Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): support named Next agents (#655)

JJ Kasperf00f08423209
diff --git a/.changeset/named-next-agents.md b/.changeset/named-next-agents.md
new file mode 100644
index 000000000..6a22efa99
--- /dev/null
+++ b/.changeset/named-next-agents.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add named multi-agent routing to `withEve` and `useEveAgent`. Next.js apps can now configure multiple eve roots with `agents`, then target one from the frontend with `useEveAgent({ agent: "name" })`.
diff --git a/apps/frameworks/README.md b/apps/frameworks/README.md
index f36feef15..50ad9c7fc 100644
--- a/apps/frameworks/README.md
+++ b/apps/frameworks/README.md
@@ -3,6 +3,7 @@
These apps verify eve's frontend framework integrations and act as runnable examples for maintainers.
- `framework-next` covers `eve/next` and `withEve()`.
+- `framework-next-multi-agent` covers `withEve({ agents })` and named `useEveAgent({ agent })` calls.
- `framework-nuxt` covers the `eve/nuxt` module.
- `framework-sveltekit` covers the `eve/sveltekit` Vite plugin.
diff --git a/apps/frameworks/next-multi-agent/README.md b/apps/frameworks/next-multi-agent/README.md
new file mode 100644
index 000000000..2c6f8e88b
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/README.md
@@ -0,0 +1,16 @@
+# Next.js multi-agent eve demo
+
+This app demonstrates `withEve({ agents })` with three independent eve agents
+mounted into one Next.js app:
+
+- `support` at `/eve/agents/support/eve/v1/*`
+- `billing` at `/eve/agents/billing/eve/v1/*`
+- `research` at `/eve/agents/research/eve/v1/*`
+
+Run it locally with:
+
+```sh
+pnpm --filter framework-next-multi-agent dev
+```
+
+The page calls each agent with `useEveAgent({ agent: "<name>" })`.
diff --git a/apps/frameworks/next-multi-agent/agents/billing/agent.ts b/apps/frameworks/next-multi-agent/agents/billing/agent.ts
new file mode 100644
index 000000000..af4b36659
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/billing/agent.ts
@@ -0,0 +1,5 @@
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "anthropic/claude-opus-4.6",
+});
diff --git a/apps/frameworks/next-multi-agent/agents/billing/instructions.md b/apps/frameworks/next-multi-agent/agents/billing/instructions.md
new file mode 100644
index 000000000..f83fefeba
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/billing/instructions.md
@@ -0,0 +1,4 @@
+You are the billing agent in the Next.js multi-agent fixture.
+
+Keep replies to one or two short sentences. Help with invoices, plans, refunds,
+and payment status.
diff --git a/apps/frameworks/next-multi-agent/agents/billing/tools/identify_agent.ts b/apps/frameworks/next-multi-agent/agents/billing/tools/identify_agent.ts
new file mode 100644
index 000000000..10288c5b3
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/billing/tools/identify_agent.ts
@@ -0,0 +1,11 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Return the identity and focus area of this fixture agent.",
+ inputSchema: z.object({}),
+ execute: async () => ({
+ agent: "billing",
+ focus: "Invoices, plans, and payment questions",
+ }),
+});
diff --git a/apps/frameworks/next-multi-agent/agents/research/agent.ts b/apps/frameworks/next-multi-agent/agents/research/agent.ts
new file mode 100644
index 000000000..af4b36659
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/research/agent.ts
@@ -0,0 +1,5 @@
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "anthropic/claude-opus-4.6",
+});
diff --git a/apps/frameworks/next-multi-agent/agents/research/instructions.md b/apps/frameworks/next-multi-agent/agents/research/instructions.md
new file mode 100644
index 000000000..bb480b174
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/research/instructions.md
@@ -0,0 +1,4 @@
+You are the research agent in the Next.js multi-agent fixture.
+
+Keep replies to one or two short sentences. Help turn research questions into a
+clear next step or brief summary.
diff --git a/apps/frameworks/next-multi-agent/agents/research/tools/identify_agent.ts b/apps/frameworks/next-multi-agent/agents/research/tools/identify_agent.ts
new file mode 100644
index 000000000..7f7b3bcad
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/research/tools/identify_agent.ts
@@ -0,0 +1,11 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Return the identity and focus area of this fixture agent.",
+ inputSchema: z.object({}),
+ execute: async () => ({
+ agent: "research",
+ focus: "Research summaries and source planning",
+ }),
+});
diff --git a/apps/frameworks/next-multi-agent/agents/support/agent.ts b/apps/frameworks/next-multi-agent/agents/support/agent.ts
new file mode 100644
index 000000000..af4b36659
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/support/agent.ts
@@ -0,0 +1,5 @@
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "anthropic/claude-opus-4.6",
+});
diff --git a/apps/frameworks/next-multi-agent/agents/support/instructions.md b/apps/frameworks/next-multi-agent/agents/support/instructions.md
new file mode 100644
index 000000000..393dabeed
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/support/instructions.md
@@ -0,0 +1,4 @@
+You are the support agent in the Next.js multi-agent fixture.
+
+Keep replies to one or two short sentences. Help triage product issues and ask
+for only the next missing detail.
diff --git a/apps/frameworks/next-multi-agent/agents/support/tools/identify_agent.ts b/apps/frameworks/next-multi-agent/agents/support/tools/identify_agent.ts
new file mode 100644
index 000000000..29c05aacc
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/agents/support/tools/identify_agent.ts
@@ -0,0 +1,11 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Return the identity and focus area of this fixture agent.",
+ inputSchema: z.object({}),
+ execute: async () => ({
+ agent: "support",
+ focus: "Customer-facing triage and troubleshooting",
+ }),
+});
diff --git a/apps/frameworks/next-multi-agent/app/layout.tsx b/apps/frameworks/next-multi-agent/app/layout.tsx
new file mode 100644
index 000000000..844e0080d
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/app/layout.tsx
@@ -0,0 +1,19 @@
+import type { Metadata } from "next";
+import "./styles.css";
+
+export const metadata: Metadata = {
+ title: "eve multi-agent Next.js fixture",
+ description: "Next.js fixture for withEve named agents.",
+};
+
+export default function RootLayout({
+ children,
+}: Readonly<{
+ children: React.ReactNode;
+}>) {
+ return (
+ <html lang="en">
+ <body>{children}</body>
+ </html>
+ );
+}
diff --git a/apps/frameworks/next-multi-agent/app/page.tsx b/apps/frameworks/next-multi-agent/app/page.tsx
new file mode 100644
index 000000000..009fba6df
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/app/page.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useState, type ComponentProps } from "react";
+import { useEveAgent } from "eve/react";
+
+const AGENTS = [
+ {
+ description: "Customer-facing triage and troubleshooting",
+ initialPrompt: "My checkout page is failing.",
+ name: "support",
+ },
+ {
+ description: "Invoices, plans, and payment questions",
+ initialPrompt: "Why did my invoice increase?",
+ name: "billing",
+ },
+ {
+ description: "Research summaries and source planning",
+ initialPrompt: "Compare two options briefly.",
+ name: "research",
+ },
+] as const;
+
+type AgentName = (typeof AGENTS)[number]["name"];
+
+export default function Home() {
+ return (
+ <main>
+ <header>
+ <p>Next.js named agents fixture</p>
+ <h1>Three eve agents mounted through one Next.js app</h1>
+ </header>
+ <section className="grid">
+ {AGENTS.map((agent) => (
+ <AgentPanel key={agent.name} agent={agent} />
+ ))}
+ </section>
+ </main>
+ );
+}
+
+function AgentPanel({
+ agent,
+}: {
+ readonly agent: {
+ readonly description: string;
+ readonly initialPrompt: string;
+ readonly name: AgentName;
+ };
+}) {
+ const eve = useEveAgent({ agent: agent.name });
+ const [message, setMessage] = useState(agent.initialPrompt);
+ const isBusy = eve.status === "submitted" || eve.status === "streaming";
+
+ const submit: ComponentProps<"form">["onSubmit"] = async (event) => {
+ event.preventDefault();
+ const trimmed = message.trim();
+ if (trimmed.length === 0 || isBusy) return;
+ setMessage("");
+ await eve.send({ message: trimmed });
+ };
+
+ return (
+ <article>
+ <div className="panel-header">
+ <div>
+ <h2>{agent.name}</h2>
+ <p>{agent.description}</p>
+ </div>
+ <span>{eve.status}</span>
+ </div>
+
+ <div className="messages">
+ {eve.data.messages.length === 0 ? (
+ <p className="empty">Send a short prompt to the {agent.name} agent.</p>
+ ) : (
+ eve.data.messages.map((item) => (
+ <div className="message" data-role={item.role} key={item.id}>
+ <strong>{item.role}</strong>
+ {item.parts.map((part, index) =>
+ part.type === "text" ? <p key={index}>{part.text}</p> : null,
+ )}
+ </div>
+ ))
+ )}
+ </div>
+
+ <form onSubmit={submit}>
+ <textarea
+ aria-label={`Message ${agent.name} agent`}
+ onChange={(event) => setMessage(event.currentTarget.value)}
+ value={message}
+ />
+ <button disabled={isBusy || message.trim().length === 0} type="submit">
+ Send to {agent.name}
+ </button>
+ </form>
+ </article>
+ );
+}
diff --git a/apps/frameworks/next-multi-agent/app/styles.css b/apps/frameworks/next-multi-agent/app/styles.css
new file mode 100644
index 000000000..3752c5fe0
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/app/styles.css
@@ -0,0 +1,173 @@
+:root {
+ color: #171717;
+ background: #f7f7f5;
+ font-family:
+ Inter,
+ ui-sans-serif,
+ system-ui,
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ sans-serif;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+}
+
+main {
+ width: min(1180px, calc(100vw - 48px));
+ margin: 0 auto;
+ padding: 40px 0;
+}
+
+header {
+ margin-bottom: 28px;
+}
+
+header p {
+ margin: 0 0 8px;
+ color: #5f656f;
+ font-size: 14px;
+ font-weight: 600;
+ text-transform: uppercase;
+}
+
+h1 {
+ max-width: 760px;
+ margin: 0;
+ font-size: 36px;
+ line-height: 1.1;
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 16px;
+}
+
+article {
+ display: flex;
+ min-height: 620px;
+ flex-direction: column;
+ border: 1px solid #deded8;
+ border-radius: 8px;
+ background: #ffffff;
+}
+
+.panel-header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ border-bottom: 1px solid #ebebe6;
+ padding: 16px;
+}
+
+h2 {
+ margin: 0 0 4px;
+ font-size: 18px;
+}
+
+.panel-header p {
+ margin: 0;
+ color: #626873;
+ font-size: 14px;
+ line-height: 1.4;
+}
+
+.panel-header span {
+ border-radius: 999px;
+ background: #eef2ff;
+ color: #32458f;
+ font-size: 12px;
+ font-weight: 700;
+ padding: 4px 8px;
+}
+
+.messages {
+ flex: 1;
+ overflow: auto;
+ padding: 16px;
+}
+
+.empty {
+ margin: 0;
+ color: #737780;
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+.message {
+ border-radius: 8px;
+ margin-bottom: 12px;
+ padding: 12px;
+}
+
+.message[data-role="user"] {
+ background: #f2f3f5;
+}
+
+.message[data-role="assistant"] {
+ background: #eff8f4;
+}
+
+.message strong {
+ display: block;
+ margin-bottom: 6px;
+ font-size: 12px;
+ text-transform: uppercase;
+}
+
+.message p {
+ margin: 0 0 8px;
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+.message p:last-child {
+ margin-bottom: 0;
+}
+
+form {
+ display: grid;
+ gap: 10px;
+ border-top: 1px solid #ebebe6;
+ padding: 16px;
+}
+
+textarea {
+ min-height: 92px;
+ resize: vertical;
+ border: 1px solid #cfd1d5;
+ border-radius: 8px;
+ color: inherit;
+ font: inherit;
+ padding: 10px 12px;
+}
+
+button {
+ border: 0;
+ border-radius: 8px;
+ background: #171717;
+ color: #ffffff;
+ cursor: pointer;
+ font: inherit;
+ font-weight: 700;
+ padding: 10px 12px;
+}
+
+button:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+}
+
+@media (max-width: 900px) {
+ .grid {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/apps/frameworks/next-multi-agent/next-env.d.ts b/apps/frameworks/next-multi-agent/next-env.d.ts
new file mode 100644
index 000000000..c4b7818fb
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/next-env.d.ts
@@ -0,0 +1,6 @@
+/// <reference types="next" />
+/// <reference types="next/image-types/global" />
+import "./.next/dev/types/routes.d.ts";
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/apps/frameworks/next-multi-agent/next.config.ts b/apps/frameworks/next-multi-agent/next.config.ts
new file mode 100644
index 000000000..ed2c6d2c1
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/next.config.ts
@@ -0,0 +1,16 @@
+import type { NextConfig } from "next";
+import { withEve } from "eve/next";
+
+const nextConfig: NextConfig = {};
+
+export default withEve(nextConfig, {
+ agents: {
+ support: "./agents/support",
+ billing: {
+ root: "./agents/billing",
+ buildCommand: "pnpm --dir ../.. build:billing-agent",
+ servicePrefix: "/_eve_internal/billing",
+ },
+ research: "./agents/research",
+ },
+});
diff --git a/apps/frameworks/next-multi-agent/package.json b/apps/frameworks/next-multi-agent/package.json
new file mode 100644
index 000000000..053e20a6e
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "framework-next-multi-agent",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "pnpm --filter eve build && next build",
+ "build:billing-agent": "cd agents/billing && eve build",
+ "dev": "next dev",
+ "typecheck": "tsc --noEmit -p tsconfig.json"
+ },
+ "dependencies": {
+ "ai": "catalog:",
+ "eve": "workspace:*",
+ "next": "catalog:",
+ "react": "catalog:",
+ "react-dom": "catalog:",
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "typescript": "6.0.3"
+ }
+}
diff --git a/apps/frameworks/next-multi-agent/tsconfig.json b/apps/frameworks/next-multi-agent/tsconfig.json
new file mode 100644
index 000000000..388ee8cab
--- /dev/null
+++ b/apps/frameworks/next-multi-agent/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "extends": "../../../tsconfig.json",
+ "compilerOptions": {
+ "allowJs": true,
+ "incremental": true,
+ "jsx": "preserve",
+ "lib": ["dom", "dom.iterable", "es2024"],
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "noEmit": true,
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "resolveJsonModule": true,
+ "target": "es2024"
+ },
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdx
index 2972efa51..c26371884 100644
--- a/docs/guides/frontend/nextjs.mdx
+++ b/docs/guides/frontend/nextjs.mdx
@@ -30,16 +30,41 @@ export default withEve(nextConfig, {
});
```
+For multiple agents, use `agents`. String values are agent roots; object values can override the build command or private production service prefix for that agent:
+
+```ts
+export default withEve(nextConfig, {
+ agents: {
+ support: "./agents/support",
+ billing: {
+ root: "./agents/billing",
+ buildCommand: "pnpm build:billing-agent",
+ servicePrefix: "/_eve_internal/billing",
+ },
+ },
+});
+```
+
+Named agents mount under `/eve/agents/<name>/eve/v1/*`. Call the matching agent from React with `agent`:
+
+```tsx
+const support = useEveAgent({ agent: "support" });
+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/*`.
+
### `withEve` options
All fields are optional.
-| Option | Type | Default | Purpose |
-| -------------------- | -------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `eveRoot` | `string` | Next.js app root | Path to the eve app root, relative to `process.cwd()` unless absolute. Set it when the agent lives outside the Next.js project. |
-| `eveBuildCommand` | `string` | `"eve build"` | Build command for the generated eve Vercel service. Use it when the eve service needs project-specific prework, without changing the Next.js build. |
-| `servicePrefix` | `string` | `"/_eve_internal/eve"` | Private route namespace for legacy manual Vercel service configs and non-Vercel production proxying. Generated Vercel configs use service routes instead. |
-| `devServerTimeoutMs` | `number` | `180000` | Maximum time to wait for the eve development server to become available. |
+| Option | Type | Default | Purpose |
+| -------------------- | --------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `eveRoot` | `string` | Next.js app root | Path to one unnamed eve app root, relative to `process.cwd()` unless absolute. Do not combine with `agents`. |
+| `agents` | `Record<string, ...>` | unset | Named eve agents to mount under `/eve/agents/<name>/eve/v1/*`. Each value is a root string or `{ root, buildCommand?, servicePrefix? }`. |
+| `eveBuildCommand` | `string` | generated | Build command for generated eve Vercel services. In multi-agent mode this is the default for agents without their own `buildCommand`. |
+| `servicePrefix` | `string` | `"/_eve_internal/eve"` | Private route namespace for legacy manual Vercel service configs and non-Vercel production proxying. Named agents derive unique defaults from this prefix. |
+| `devServerTimeoutMs` | `number` | `180000` | Maximum time to wait for each eve development server to become available. |
For slow cold starts, increase the development timeout:
@@ -75,7 +100,7 @@ For a public demo, use `none()` (also from `eve/channels/auth`) to skip authenti
## Dev vs deploy topology
- **Local dev.** `npm run dev` boots the eve dev server next to `next dev` and rewrites the eve routes over to it. The browser only ever talks to the Next.js origin.
-- **Vercel.** The web app and the eve runtime deploy as a single project. `withEve()` writes Build Output `services` for eve and `routes` that send `/eve/v1/**` to that service before filesystem routing; the Next.js app itself remains the default app. When the agent needs its own build step, set `eveBuildCommand`:
+- **Vercel.** The web app and the eve runtime deploy as a single project. `withEve()` writes Build Output `services` for eve and `routes` that send `/eve/v1/**` to that service before filesystem routing; the Next.js app itself remains the default app. By default, generated services run the installed eve binary from the agent root, so the agent directory does not need its own `package.json`. When the agent needs its own build step, set `eveBuildCommand`:
```ts
export default withEve(nextConfig, {
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index c3a31e7d1..d15a51181 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -254,7 +254,7 @@ const agent = useEveAgent({
Store the full `session` object (`sessionId`, `continuationToken`, `streamIndex`), not a single field. The session cursor lets eve continue the durable conversation; the event log lets your UI render historical messages without replaying the whole stream. A database-backed chat app should usually persist stream events as they arrive with `onEvent` and then save a final snapshot in `onFinish`.
-For multiple chat threads, keep one saved event log and session cursor per thread. `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, `maxReconnectAttempts`, and `optimistic` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`.
+For multiple chat threads, keep one saved event log and session cursor per thread. `agent`, `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, `maxReconnectAttempts`, and `optimistic` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`.
If the user can refresh or navigate immediately after pressing send, create your app-level chat row and store the pending user message before calling `send()`. After the request starts, persist the session state as soon as it contains a `sessionId`, then reconnect an interrupted in-flight turn with `session.stream({ startIndex: savedEvents.length })` from the lower-level client.
@@ -271,6 +271,12 @@ const agent = useEveAgent({
});
```
+When a framework integration mounts multiple named agents, pass `agent` instead of `host`:
+
+```tsx
+const support = useEveAgent({ agent: "support" });
+```
+
## Per-framework integration
| Framework | Integration | Hook |
diff --git a/packages/eve/src/client/agent-host.test.ts b/packages/eve/src/client/agent-host.test.ts
new file mode 100644
index 000000000..afcfa489b
--- /dev/null
+++ b/packages/eve/src/client/agent-host.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveEveAgentHost } from "#client/agent-host.js";
+
+describe("resolveEveAgentHost", () => {
+ it("defaults to same-origin root eve routes", () => {
+ expect(resolveEveAgentHost({})).toBe("");
+ });
+
+ it("preserves explicit hosts", () => {
+ expect(resolveEveAgentHost({ host: "/api" })).toBe("/api");
+ });
+
+ it("maps a named agent to the same-origin named route prefix", () => {
+ expect(resolveEveAgentHost({ agent: "support" })).toBe("/eve/agents/support");
+ });
+
+ it("rejects host and agent together", () => {
+ expect(() => resolveEveAgentHost({ agent: "support", host: "/api" })).toThrow(
+ "cannot combine agent and host",
+ );
+ });
+
+ it("rejects names that are not safe route segments", () => {
+ expect(() => resolveEveAgentHost({ agent: "Support" })).toThrow("eve agent name");
+ });
+});
diff --git a/packages/eve/src/client/agent-host.ts b/packages/eve/src/client/agent-host.ts
new file mode 100644
index 000000000..7cc6d6f99
--- /dev/null
+++ b/packages/eve/src/client/agent-host.ts
@@ -0,0 +1,28 @@
+const AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
+const EVE_NAMED_AGENT_ROUTE_PREFIX = "/eve/agents";
+
+export function resolveEveAgentHost(input: {
+ readonly agent?: string;
+ readonly host?: string;
+}): string {
+ if (input.agent === undefined) {
+ return input.host ?? "";
+ }
+
+ if (input.host !== undefined) {
+ throw new Error("useEveAgent cannot combine agent and host. Use one target option.");
+ }
+
+ assertValidAgentName(input.agent);
+ return `${EVE_NAMED_AGENT_ROUTE_PREFIX}/${input.agent}`;
+}
+
+function assertValidAgentName(name: string): void {
+ if (!AGENT_NAME_PATTERN.test(name)) {
+ throw new Error(
+ `eve agent name ${JSON.stringify(
+ name,
+ )} is invalid. Use lowercase letters, numbers, underscores, or hyphens, starting with a letter or number.`,
+ );
+ }
+}
diff --git a/packages/eve/src/discover/agent.integration.test.ts b/packages/eve/src/discover/agent.integration.test.ts
index 24302c877..448c3a3f0 100644
--- a/packages/eve/src/discover/agent.integration.test.ts
+++ b/packages/eve/src/discover/agent.integration.test.ts
@@ -471,6 +471,33 @@ describe("discoverAgent (memory)", () => {
]);
});
+ it("silently ignores generated runtime directories", async () => {
+ const project = buildMemoryAgentProject({
+ agentDirectories: [".eve", ".next", ".output", ".vercel", ".workflow-data", "node_modules"],
+ agentFiles: {
+ "instructions.md": "You are a precise assistant.",
+ },
+ });
+
+ const result = await discoverAgent({
+ agentRoot: project.agentRoot,
+ appRoot: project.appRoot,
+ source: project.source,
+ });
+
+ expect(result.diagnostics).toEqual([]);
+ expect(result.manifest.instructions).toEqual([
+ {
+ definition: {
+ markdown: "You are a precise assistant.",
+ },
+ sourceKind: "markdown",
+ logicalPath: "instructions.md",
+ sourceId: "instructions.md",
+ },
+ ]);
+ });
+
it("rejects authored tool filenames that violate the tool-name charset", async () => {
const project = buildMemoryAgentProject({
agentFiles: {
diff --git a/packages/eve/src/discover/filesystem.ts b/packages/eve/src/discover/filesystem.ts
index dd755abb0..16cfa3bea 100644
--- a/packages/eve/src/discover/filesystem.ts
+++ b/packages/eve/src/discover/filesystem.ts
@@ -20,6 +20,14 @@ export const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS = [
export const PROJECT_MARKER_FILE_NAMES = ["package.json", "vercel.json"] as const;
const PROJECT_MARKER_FILE_NAME_SET = new Set<string>(PROJECT_MARKER_FILE_NAMES);
+const GENERATED_AGENT_DIRECTORY_NAMES = new Set<string>([
+ ".eve",
+ ".next",
+ ".output",
+ ".vercel",
+ ".workflow-data",
+ "node_modules",
+]);
/**
* Filesystem entry type used by discovery classifiers.
@@ -35,6 +43,7 @@ export type AgentRootEntryKind =
| "connections-directory"
| "extensions-directory"
| "hooks-directory"
+ | "ignored-directory"
| "instructions-directory"
| "instructions-markdown"
| "instructions-module"
@@ -55,6 +64,7 @@ export type LocalSubagentEntryKind =
| "agent-config-module"
| "connections-directory"
| "hooks-directory"
+ | "ignored-directory"
| "instructions-directory"
| "instructions-markdown"
| "instructions-module"
@@ -143,6 +153,10 @@ export function classifyAgentRootEntry(
}
if (entryType === "directory") {
+ if (GENERATED_AGENT_DIRECTORY_NAMES.has(name)) {
+ return "ignored-directory";
+ }
+
if (name === "channels") {
return "channels-directory";
}
@@ -223,6 +237,10 @@ export function classifyLocalSubagentEntry(
}
if (entryType === "directory") {
+ if (GENERATED_AGENT_DIRECTORY_NAMES.has(name)) {
+ return "ignored-directory";
+ }
+
if (name === "connections") {
return "connections-directory";
}
diff --git a/packages/eve/src/discover/project.ts b/packages/eve/src/discover/project.ts
index 7f57cf225..66ff6876b 100644
--- a/packages/eve/src/discover/project.ts
+++ b/packages/eve/src/discover/project.ts
@@ -160,7 +160,9 @@ async function isFlatAgentRoot(source: ProjectSource, directoryPath: string): Pr
return Array.from(entries.entries()).some(([name, entryType]) => {
const entryKind = classifyAgentRootEntry(name, entryType);
- return entryKind !== "unknown" && entryKind !== "lib-directory";
+ return (
+ entryKind !== "unknown" && entryKind !== "ignored-directory" && entryKind !== "lib-directory"
+ );
});
}
diff --git a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
index 5936a3108..c0352827f 100644
--- a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
@@ -273,14 +273,8 @@ describe("buildApplication", () => {
const vercelConfig = JSON.parse(
await readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
) as {
- routes: Array<{ dest?: string; handle?: string; src?: string }>;
+ routes: unknown[];
};
- const sharedFunctionConfig = JSON.parse(
- await readFile(
- join(appRoot, ".vercel", "output", "functions", "eve", "__server.func", ".vc-config.json"),
- "utf8",
- ),
- ) as { handler?: string };
await expect(
lstat(join(appRoot, ".vercel", "output", "functions", "index.func")),
@@ -304,30 +298,12 @@ describe("buildApplication", () => {
).resolves.toContain("export default");
expect(vercelConfig.routes).toEqual([
{ handle: "filesystem" },
- { dest: "/eve/__server", src: "/_eve_internal/eve/eve/v1/health" },
+ { dest: "/eve/__server", src: "/eve/v1/health" },
{
dest: "/eve/__server",
- src: "^/_eve_internal/eve/eve/v1/session/(?<sessionId>[^/]+)/stream$",
+ src: "^/eve/v1/session/(?<sessionId>[^/]+)/stream$",
},
]);
- expect(sharedFunctionConfig.handler).toBe("index.__eve_service_route_prefix.mjs");
- const sharedFunctionWrapper = await readFile(
- join(
- appRoot,
- ".vercel",
- "output",
- "functions",
- "eve",
- "__server.func",
- "index.__eve_service_route_prefix.mjs",
- ),
- "utf8",
- );
- expect(sharedFunctionWrapper).toContain('const SERVICE_PREFIX = "/_eve_internal/eve";');
- expect(sharedFunctionWrapper).toContain('event === "request" || event === "upgrade"');
- expect(sharedFunctionWrapper).toContain(
- "export const handleUpgrade = originalModule.handleUpgrade",
- );
await expect(readFile(staleFlowOutputPath, "utf8")).rejects.toThrow();
expect(runVercelBuildPrewarmMock).toHaveBeenCalledWith({
appRoot,
@@ -399,13 +375,131 @@ describe("buildApplication", () => {
await expect(
lstat(join(appRoot, ".vercel", "output", "functions", "index.func")),
).rejects.toThrow();
- const sharedFunctionConfig = JSON.parse(
- await readFile(
- join(appRoot, ".vercel", "output", "functions", "eve", "__server.func", ".vc-config.json"),
- "utf8",
- ),
- ) as { handler?: string };
- expect(sharedFunctionConfig.handler).toBe("index.__eve_service_route_prefix.mjs");
+ const vercelConfig = JSON.parse(
+ await readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
+ ) as {
+ routes: unknown[];
+ };
+ expect(vercelConfig.routes).toContainEqual({
+ dest: "/eve/__server",
+ src: "/eve/v1/health",
+ });
+ });
+
+ it("normalizes eve function output behind a host service from a service array", async () => {
+ vi.stubEnv("VERCEL", "1");
+ const appRoot = await createScratchDirectory("eve-build-application-vercel-service-array-");
+
+ prepareApplicationHostMock.mockResolvedValueOnce(createPreparedHost(appRoot));
+ createApplicationNitroMock.mockImplementation(
+ async (
+ _preparedHost: PreparedApplicationHost,
+ _dev: boolean,
+ options: { outputDir?: string; surface?: string } = {},
+ ) => createNitroStub(options.outputDir ?? join(appRoot, ".vercel", "output")),
+ );
+ await mkdir(join(appRoot, ".vercel", "output"), { recursive: true });
+ await writeFile(
+ join(appRoot, ".vercel", "output", "config.json"),
+ `${JSON.stringify(
+ {
+ version: 3,
+ services: [
+ {
+ entrypoint: "package.json",
+ framework: "nextjs",
+ name: "web",
+ root: ".",
+ },
+ {
+ entrypoint: "package.json",
+ framework: "eve",
+ name: "eve-support",
+ root: ".",
+ routePrefix: "/eve/agents/support",
+ },
+ ],
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+
+ const { buildApplication } = await import("#internal/nitro/host/build-application.js");
+ await buildApplication(appRoot);
+
+ const vercelConfig = JSON.parse(
+ await readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
+ ) as {
+ routes: unknown[];
+ };
+ expect(vercelConfig.routes).toContainEqual({
+ dest: "/eve/__server",
+ src: "/eve/v1/health",
+ });
+ });
+
+ it("resolves service roots relative to a linked Vercel root directory", async () => {
+ vi.stubEnv("VERCEL", "1");
+ const projectRoot = await createScratchDirectory("eve-build-application-vercel-root-dir-");
+ const appRoot = join(projectRoot, "apps", "web", "agents", "support");
+
+ prepareApplicationHostMock.mockResolvedValueOnce(createPreparedHost(appRoot));
+ createApplicationNitroMock.mockImplementation(
+ async (
+ _preparedHost: PreparedApplicationHost,
+ _dev: boolean,
+ options: { outputDir?: string; surface?: string } = {},
+ ) => createNitroStub(options.outputDir ?? join(appRoot, ".vercel", "output")),
+ );
+ await mkdir(join(projectRoot, ".vercel", "output"), { recursive: true });
+ await writeFile(
+ join(projectRoot, ".vercel", "project.json"),
+ `${JSON.stringify(
+ {
+ settings: {
+ rootDirectory: "apps/web",
+ },
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ await writeFile(join(projectRoot, ".vercel", "output", "builds.json"), "{}\n");
+ await writeFile(
+ join(projectRoot, ".vercel", "output", "config.json"),
+ `${JSON.stringify(
+ {
+ experimentalServicesV2: {
+ web: {
+ framework: "nextjs",
+ root: ".",
+ },
+ "eve-support": {
+ framework: "eve",
+ root: "agents/support",
+ routePrefix: "/eve/agents/support",
+ },
+ },
+ version: 3,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+
+ const { buildApplication } = await import("#internal/nitro/host/build-application.js");
+ await buildApplication(appRoot);
+
+ const vercelConfig = JSON.parse(
+ await readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
+ ) as {
+ routes: unknown[];
+ };
+ expect(vercelConfig.routes).toContainEqual({
+ dest: "/eve/__server",
+ src: "/eve/v1/health",
+ });
});
it("builds isolated Vercel Nitro surfaces from legacy root service config", async () => {
@@ -456,27 +550,15 @@ describe("buildApplication", () => {
const outputDir = await buildApplication(appRoot);
expect(outputDir).toBe(join(appRoot, ".vercel", "output"));
- const sharedFunctionConfig = JSON.parse(
- await readFile(
- join(appRoot, ".vercel", "output", "functions", "eve", "__server.func", ".vc-config.json"),
- "utf8",
- ),
- ) as { handler?: string };
- expect(sharedFunctionConfig.handler).toBe("index.__eve_service_route_prefix.mjs");
- await expect(
- readFile(
- join(
- appRoot,
- ".vercel",
- "output",
- "functions",
- "eve",
- "__server.func",
- "index.__eve_service_route_prefix.mjs",
- ),
- "utf8",
- ),
- ).resolves.toContain('const SERVICE_PREFIX = "/_eve_internal/eve";');
+ const vercelConfig = JSON.parse(
+ await readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
+ ) as {
+ routes: unknown[];
+ };
+ expect(vercelConfig.routes).toContainEqual({
+ dest: "/eve/__server",
+ src: "/eve/v1/health",
+ });
});
it("leaves standalone Vercel Nitro output routable at the root", async () => {
diff --git a/packages/eve/src/internal/nitro/host/build-application.ts b/packages/eve/src/internal/nitro/host/build-application.ts
index 4dcbc59b4..b3f88e89f 100644
--- a/packages/eve/src/internal/nitro/host/build-application.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.ts
@@ -39,6 +39,14 @@ function normalizeEntrypoint(rootDir: string, entrypoint: unknown): string | nul
return resolve(rootDir, entrypoint);
}
+function normalizeServiceRoot(rootDir: string, service: Record<string, unknown>): string | null {
+ if (typeof service.root === "string" && service.root.trim().length > 0) {
+ return resolve(rootDir, service.root);
+ }
+
+ return normalizeEntrypoint(rootDir, service.entrypoint);
+}
+
function normalizeServicePrefix(service: Record<string, unknown>): string {
if (typeof service.routePrefix === "string") {
return service.routePrefix.trim();
@@ -59,6 +67,20 @@ function normalizeServicePrefix(service: Record<string, unknown>): string {
return "";
}
+function normalizeServiceCollection(
+ value: unknown,
+): readonly Record<string, unknown>[] | undefined {
+ if (isRecord(value)) {
+ return Object.values(value).filter(isRecord);
+ }
+
+ if (Array.isArray(value)) {
+ return value.filter(isRecord);
+ }
+
+ return undefined;
+}
+
/**
* Resolve the route prefix an eve service is mounted under when it is
* co-deployed behind a host web service (Next.js, Nuxt, SvelteKit etc.).
@@ -68,31 +90,41 @@ function normalizeServicePrefix(service: Record<string, unknown>): string {
* service) returns `undefined` so its output stays routable at the root.
*/
function resolveCoDeployedEveServicePrefix(input: {
- appRoot: string;
+ appRoots: readonly string[];
configRoot: string;
config: unknown;
}): string | undefined {
- if (!isRecord(input.config) || !isRecord(input.config.experimentalServices)) {
+ if (!isRecord(input.config)) {
+ return undefined;
+ }
+
+ const services =
+ normalizeServiceCollection(input.config.experimentalServices) ??
+ normalizeServiceCollection(input.config.experimentalServicesV2) ??
+ normalizeServiceCollection(input.config.services);
+
+ if (services === undefined) {
return undefined;
}
let hasHostService = false;
let servicePrefix: string | undefined;
- for (const service of Object.values(input.config.experimentalServices)) {
- if (!isRecord(service)) {
- continue;
- }
-
+ for (const service of services) {
if (service.framework !== "eve") {
hasHostService = true;
continue;
}
- const eveEntrypoint = normalizeEntrypoint(input.configRoot, service.entrypoint);
+ const eveEntrypoint = normalizeServiceRoot(input.configRoot, service);
const routePrefix = normalizeServicePrefix(service);
- if (eveEntrypoint === input.appRoot && routePrefix.length > 0 && routePrefix !== "/") {
+ if (
+ eveEntrypoint !== null &&
+ input.appRoots.includes(eveEntrypoint) &&
+ routePrefix.length > 0 &&
+ routePrefix !== "/"
+ ) {
servicePrefix = routePrefix;
}
}
@@ -102,7 +134,9 @@ function resolveCoDeployedEveServicePrefix(input: {
async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
appRoot: string,
+ agentRoot: string,
): Promise<string | undefined> {
+ const appRoots = Array.from(new Set([resolve(appRoot), resolve(agentRoot)]));
const outputDirectory = await findClosestVercelOutputDirectory(appRoot);
if (outputDirectory !== undefined) {
@@ -111,8 +145,8 @@ async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
await readFile(join(outputDirectory, "config.json"), "utf8"),
) as unknown;
const servicePrefix = resolveCoDeployedEveServicePrefix({
- appRoot,
- configRoot: appRoot,
+ appRoots,
+ configRoot: await resolveVercelOutputConfigRoot(outputDirectory),
config,
});
@@ -135,10 +169,12 @@ async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
]) {
try {
const config = JSON.parse(await readFile(configPath, "utf8")) as unknown;
- const configRoot = configPath.endsWith("vercel.json") ? currentDir : appRoot;
+ const configRoot = configPath.endsWith("vercel.json")
+ ? currentDir
+ : await resolveVercelOutputConfigRoot(dirname(configPath));
const servicePrefix = resolveCoDeployedEveServicePrefix({
- appRoot,
+ appRoots,
configRoot,
config,
});
@@ -176,6 +212,31 @@ async function readVercelServerRuntime(outputDir: string): Promise<string | unde
}
}
+async function resolveVercelOutputConfigRoot(outputDirectory: string): Promise<string> {
+ const projectRoot = dirname(dirname(outputDirectory));
+
+ try {
+ const projectConfig = JSON.parse(
+ await readFile(join(projectRoot, ".vercel", "project.json"), "utf8"),
+ ) as unknown;
+
+ if (
+ isRecord(projectConfig) &&
+ isRecord(projectConfig.settings) &&
+ typeof projectConfig.settings.rootDirectory === "string" &&
+ projectConfig.settings.rootDirectory.trim().length > 0
+ ) {
+ return resolve(projectRoot, projectConfig.settings.rootDirectory);
+ }
+ } catch (error) {
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
+ throw error;
+ }
+ }
+
+ return projectRoot;
+}
+
async function emitVercelWorkflowFunctions(input: {
agentName: string;
appRoot: string;
@@ -258,6 +319,7 @@ export async function buildApplication(rootDir: string): Promise<string> {
const servicePrefix = await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(
preparedHost.appRoot,
+ preparedHost.compileResult.project.agentRoot,
);
const nitro = await createApplicationNitro(preparedHost, false, {
surface: "app",
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index 7ce13c155..5a52ced1c 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -18,6 +18,7 @@ import {
} from "#compiler/manifest.js";
import {
resolvePackageSourceDirectoryPath,
+ resolvePackageRoot,
resolveInstalledPackageInfo,
resolveWorkflowModulePath,
} from "#internal/application/package.js";
@@ -656,6 +657,13 @@ describe("createApplicationNitro", () => {
const importedModulesDir = join(workflowBuildDir, "imports");
const stepModulePath = join(importedModulesDir, "step-module.js");
const bootstrapModulePath = join(importedModulesDir, "bootstrap.mjs");
+ const packageDistStepModulePath = join(
+ resolvePackageRoot(),
+ "dist",
+ "src",
+ "execution",
+ "create-session-step.js",
+ );
await mkdir(importedModulesDir, { recursive: true });
await Promise.all([
@@ -667,6 +675,7 @@ describe("createApplicationNitro", () => {
'import "workflow/internal/builtins";',
'import "./imports/step-module.js";',
'import "./imports/bootstrap.mjs";',
+ `import ${JSON.stringify(packageDistStepModulePath)};`,
"export const __steps_registered = true;",
"",
].join("\n"),
@@ -725,6 +734,12 @@ describe("createApplicationNitro", () => {
code: "transformed-step-module",
map: null,
});
+ expect(
+ await stepTransformPlugin.transform("package dist source", packageDistStepModulePath),
+ ).toEqual({
+ code: "transformed-step-module",
+ map: null,
+ });
await expect(
stepModuleSideEffectsPlugin.resolveId(
"./imports/step-module.js",
@@ -761,7 +776,15 @@ describe("createApplicationNitro", () => {
expect(
await stepTransformPlugin.transform("other source", "/tmp/not-imported.js"),
).toBeNull();
- expect(applyWorkflowTransform).toHaveBeenCalledTimes(3);
+ expect(applyWorkflowTransform).toHaveBeenCalledTimes(4);
+ expect(applyWorkflowTransform).toHaveBeenNthCalledWith(
+ 4,
+ "src/execution/create-session-step.js",
+ "package dist source",
+ "step",
+ packageDistStepModulePath,
+ "/tmp/weather-agent",
+ );
} finally {
await rm(workflowBuildDir, { force: true, recursive: true });
await rm(nitroBuildDir, { force: true, recursive: true });
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index 027d6b893..5a1cc2c52 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -6,6 +6,7 @@ import { createNitro } from "nitro/builder";
import type { Nitro } from "nitro/types";
import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
import {
+ resolvePackageRoot,
resolvePackageSourceDirectoryPath,
resolvePackageSourceFilePath,
resolveWorkflowModulePath,
@@ -318,6 +319,11 @@ async function addNitroStepNoExternals(nitro: Nitro, stepEntrypointPath: string)
}
function createRelativeTransformFilename(workingDir: string, path: string): string {
+ const packageRelativePath = createPackageRelativeTransformFilename(path);
+ if (packageRelativePath !== undefined) {
+ return packageRelativePath;
+ }
+
const normalizedWorkingDir = normalizePath(workingDir).replace(/\/$/, "");
const normalizedPath = normalizePath(path);
const lowerWorkingDir = normalizedWorkingDir.toLowerCase();
@@ -348,6 +354,27 @@ function createRelativeTransformFilename(workingDir: string, path: string): stri
return relativePath;
}
+function createPackageRelativeTransformFilename(path: string): string | undefined {
+ const normalizedPackageRoot = normalizePath(resolvePackageRoot()).replace(/\/$/, "");
+ const normalizedPath = normalizePath(path);
+ const lowerPackageRoot = normalizedPackageRoot.toLowerCase();
+ const lowerPath = normalizedPath.toLowerCase();
+ const packageSourcePrefix = `${normalizedPackageRoot}/src/`;
+ const lowerPackageSourcePrefix = `${lowerPackageRoot}/src/`;
+ const packageDistSourcePrefix = `${normalizedPackageRoot}/dist/src/`;
+ const lowerPackageDistSourcePrefix = `${lowerPackageRoot}/dist/src/`;
+
+ if (lowerPath.startsWith(lowerPackageSourcePrefix)) {
+ return `src/${normalizedPath.slice(packageSourcePrefix.length)}`;
+ }
+
+ if (lowerPath.startsWith(lowerPackageDistSourcePrefix)) {
+ return `src/${normalizedPath.slice(packageDistSourcePrefix.length)}`;
+ }
+
+ return undefined;
+}
+
function addWorkflowModuleSideEffectsPlugin(nitro: Nitro, workflowBuildDir: string): void {
const workflowBundleDirectories = [
workflowBuildDir,
diff --git a/packages/eve/src/internal/workflow-bundle/eve-service-route-output.ts b/packages/eve/src/internal/workflow-bundle/eve-service-route-output.ts
index b311d4493..9304245da 100644
--- a/packages/eve/src/internal/workflow-bundle/eve-service-route-output.ts
+++ b/packages/eve/src/internal/workflow-bundle/eve-service-route-output.ts
@@ -1,10 +1,6 @@
-import { readFile, writeFile } from "node:fs/promises";
-import { join } from "node:path";
-
export const EVE_SHARED_SERVER_FUNCTION_PATH = "eve/__server.func";
const EVE_SHARED_SERVER_ROUTE_DESTINATION = "/eve/__server";
-const EVE_SERVICE_ROUTE_PREFIX_WRAPPER = "index.__eve_service_route_prefix.mjs";
const EVE_VERCEL_FUNCTION_PREFIXES = ["eve/", ".well-known/workflow/"] as const;
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -17,11 +13,9 @@ export function isEveVercelFunctionPath(path: string): boolean {
export function normalizeEveVercelRoutes(
routes: readonly unknown[],
- servicePrefix: string | undefined,
+ _servicePrefix: string | undefined,
): unknown[] {
- return routes
- .filter(isEveVercelRoute)
- .map((route) => normalizeEveVercelRoute(route, servicePrefix));
+ return routes.filter(isEveVercelRoute).map(normalizeEveVercelRoute);
}
function isEveVercelRoute(route: unknown): boolean {
@@ -47,7 +41,7 @@ function isEveProtocolRoutePath(path: string): boolean {
return path.includes("/eve/v1");
}
-function normalizeEveVercelRoute(route: unknown, servicePrefix: string | undefined): unknown {
+function normalizeEveVercelRoute(route: unknown): unknown {
if (!isRecord(route) || "handle" in route || typeof route.src !== "string") {
return route;
}
@@ -57,7 +51,6 @@ function normalizeEveVercelRoute(route: unknown, servicePrefix: string | undefin
(typeof route.dest === "string" && isEveProtocolRoutePath(route.dest));
const nextRoute: Record<string, unknown> = {
...route,
- src: prefixEveVercelRoutePath(route.src, servicePrefix),
};
if (shouldUseSharedServerFunction) {
@@ -66,122 +59,3 @@ function normalizeEveVercelRoute(route: unknown, servicePrefix: string | undefin
return nextRoute;
}
-
-function prefixEveVercelRoutePath(path: string, servicePrefix: string | undefined): string {
- if (
- servicePrefix === undefined ||
- servicePrefix === "/" ||
- !isEveVercelRoutePath(path) ||
- path.includes(servicePrefix)
- ) {
- return path;
- }
-
- const normalizedPrefix = servicePrefix.endsWith("/") ? servicePrefix.slice(0, -1) : servicePrefix;
- const escapedPrefix = normalizedPrefix.replaceAll("/", "\\/");
-
- if (path.includes(escapedPrefix)) {
- return path;
- }
-
- if (path.startsWith("^(?:/")) {
- return `^(?:${normalizedPrefix}${path.slice(4)}`;
- }
-
- if (path.startsWith("^/")) {
- return `^${normalizedPrefix}${path.slice(1)}`;
- }
-
- if (path.startsWith("/")) {
- return `${normalizedPrefix}${path}`;
- }
-
- return path;
-}
-
-export async function applyEveServiceRoutePrefixWrapper(
- functionPath: string,
- servicePrefix: string,
-): Promise<void> {
- const configPath = join(functionPath, ".vc-config.json");
- const wrapperPath = join(functionPath, EVE_SERVICE_ROUTE_PREFIX_WRAPPER);
- const rawConfig = JSON.parse(await readFile(configPath, "utf8")) as unknown;
- const config = isRecord(rawConfig) ? rawConfig : {};
-
- await writeFile(wrapperPath, createEveServiceRoutePrefixWrapper(servicePrefix));
- await writeFile(
- configPath,
- `${JSON.stringify(
- {
- ...config,
- handler: EVE_SERVICE_ROUTE_PREFIX_WRAPPER,
- },
- null,
- 2,
- )}\n`,
- );
-}
-
-function createEveServiceRoutePrefixWrapper(servicePrefix: string): string {
- return `
-import { Server } from "node:http";
-
-const SERVICE_PREFIX = ${JSON.stringify(normalizeServiceRoutePrefix(servicePrefix))};
-const PATCH_SYMBOL = Symbol.for("eve.service.route-prefix-strip.patch");
-
-function stripServiceRoutePrefix(requestUrl) {
- if (typeof requestUrl !== "string" || requestUrl === "*") {
- return requestUrl;
- }
-
- const queryIndex = requestUrl.indexOf("?");
- const rawPath = queryIndex === -1 ? requestUrl : requestUrl.slice(0, queryIndex);
- const query = queryIndex === -1 ? "" : requestUrl.slice(queryIndex);
- const path = rawPath.startsWith("/") ? rawPath : \`/\${rawPath}\`;
-
- if (path === SERVICE_PREFIX) {
- return \`/\${query}\`;
- }
-
- if (path.startsWith(\`\${SERVICE_PREFIX}/\`)) {
- return path.slice(SERVICE_PREFIX.length) + query;
- }
-
- return path + query;
-}
-
-if (!globalThis[PATCH_SYMBOL]) {
- globalThis[PATCH_SYMBOL] = true;
- const originalEmit = Server.prototype.emit;
- Server.prototype.emit = function patchedEmit(event, request, ...args) {
- if ((event === "request" || event === "upgrade") && request && typeof request.url === "string") {
- request.url = stripServiceRoutePrefix(request.url);
- }
-
- return originalEmit.call(this, event, request, ...args);
- };
-}
-
-const originalModule = await import("./index.mjs");
-const entrypoint = originalModule?.default ?? originalModule;
-
-export const handleUpgrade = originalModule.handleUpgrade
- ? (request, socket, head) => {
- if (request && typeof request.url === "string") {
- request.url = stripServiceRoutePrefix(request.url);
- }
-
- return originalModule.handleUpgrade(request, socket, head);
- }
- : undefined;
-
-export default entrypoint;
-`.trimStart();
-}
-
-function normalizeServiceRoutePrefix(servicePrefix: string): string {
- const prefixed = servicePrefix.startsWith("/") ? servicePrefix : `/${servicePrefix}`;
- const normalized = prefixed.replace(/\/+$/, "");
-
- return normalized.length === 0 ? "/" : normalized;
-}
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 8e2220e17..6a4bd48b3 100644
--- a/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts
+++ b/packages/eve/src/internal/workflow-bundle/vercel-workflow-output.ts
@@ -18,7 +18,6 @@ import {
type RolldownBuild,
} from "#internal/bundler/nitro-rolldown.js";
import {
- applyEveServiceRoutePrefixWrapper,
EVE_SHARED_SERVER_FUNCTION_PATH,
isEveVercelFunctionPath,
normalizeEveVercelRoutes,
@@ -133,9 +132,6 @@ export async function normalizeEveVercelFunctionOutput(
const sharedFunctionPath = await prepareSharedEveServerFunction(functionsDir);
if (sharedFunctionPath !== null) {
- if (options.servicePrefix !== undefined) {
- await applyEveServiceRoutePrefixWrapper(sharedFunctionPath, options.servicePrefix);
- }
await repointEveFunctionSymlinksInDirectory(functionsDir, sharedFunctionPath);
}
await pruneNonEveFunctionEntries(functionsDir, functionsDir);
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index 8d6a001ae..f62cbdc75 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -73,9 +73,20 @@ describe("withEve Vercel config", () => {
],
services: {
eve: {
- buildCommand: "eve build",
- entrypoint: "package.json",
+ buildCommand: "node 'node_modules/eve/bin/eve.js' build",
framework: "eve",
+ routes: [
+ {
+ src: "^/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
root: ".",
},
},
@@ -111,9 +122,20 @@ describe("withEve Vercel config", () => {
],
services: {
eve: {
- buildCommand: "eve build",
- entrypoint: "package.json",
+ buildCommand: "node 'node_modules/eve/bin/eve.js' build",
framework: "eve",
+ routes: [
+ {
+ src: "^/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
root: ".",
},
},
@@ -212,6 +234,18 @@ describe("withEve Vercel config", () => {
agent: {
entrypoint: "package.json",
framework: "eve",
+ routes: [
+ {
+ src: "^/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
root: "agent",
},
},
@@ -248,6 +282,209 @@ describe("withEve Vercel config", () => {
});
});
+ it("writes one Build Output service and route for each named agent", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_URL", "preview.example.com");
+
+ const config = await resolveConfig(
+ withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ billing: {
+ buildCommand: "pnpm build:billing-agent",
+ root: "./agents/billing",
+ servicePrefix: "/_eve_internal/billing",
+ },
+ support: "./agents/support",
+ },
+ },
+ ),
+ );
+ const rewrites = await config.rewrites?.();
+ const outputConfig = await readJsonFile(join(appRoot, ".vercel", "output", "config.json"));
+
+ expect(outputConfig).toEqual({
+ routes: [
+ {
+ destination: {
+ service: "eve-billing",
+ type: "service",
+ },
+ src: "^/eve/agents/billing/eve/v1/(.*)$",
+ },
+ {
+ destination: {
+ service: "eve-support",
+ type: "service",
+ },
+ src: "^/eve/agents/support/eve/v1/(.*)$",
+ },
+ ],
+ services: {
+ "eve-billing": {
+ buildCommand: "pnpm build:billing-agent",
+ framework: "eve",
+ routes: [
+ {
+ src: "^/eve/agents/billing/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
+ root: "agents/billing",
+ routePrefix: "/eve/agents/billing",
+ },
+ "eve-support": {
+ buildCommand: "node '../../node_modules/eve/bin/eve.js' build",
+ framework: "eve",
+ routes: [
+ {
+ src: "^/eve/agents/support/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
+ root: "agents/support",
+ routePrefix: "/eve/agents/support",
+ },
+ },
+ version: 3,
+ });
+ expect(rewrites).toBeUndefined();
+ });
+
+ it("normalizes existing Build Output service arrays before adding named agents", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ await mkdir(join(appRoot, ".vercel", "output"), { recursive: true });
+ await writeFile(join(appRoot, ".vercel", "project.json"), "{}\n");
+ await writeFile(join(appRoot, ".vercel", "output", "builds.json"), "{}\n");
+ await writeFile(
+ join(appRoot, ".vercel", "output", "config.json"),
+ `${JSON.stringify(
+ {
+ version: 3,
+ routes: [
+ {
+ destination: {
+ service: "eve-billing",
+ type: "service",
+ },
+ src: "^/eve/agents/billing/eve/v1/(.*)$",
+ },
+ { handle: "filesystem" },
+ ],
+ services: [
+ {
+ buildCommand: "eve build:support",
+ entrypoint: "package.json",
+ framework: "eve",
+ name: "eve-support",
+ root: "agents/support",
+ routePrefix: "/eve/agents/support",
+ schema: "experimentalServicesV2",
+ },
+ ],
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_URL", "preview.example.com");
+
+ const config = await resolveConfig(
+ withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ billing: "./agents/billing",
+ support: "./agents/support",
+ },
+ },
+ ),
+ );
+ const rewrites = await config.rewrites?.();
+ const outputConfig = await readJsonFile(join(appRoot, ".vercel", "output", "config.json"));
+
+ expect(outputConfig).toEqual({
+ routes: [
+ {
+ destination: {
+ service: "eve-billing",
+ type: "service",
+ },
+ src: "^/eve/agents/billing/eve/v1/(.*)$",
+ },
+ {
+ destination: {
+ service: "eve-support",
+ type: "service",
+ },
+ src: "^/eve/agents/support/eve/v1/(.*)$",
+ },
+ { handle: "filesystem" },
+ ],
+ services: {
+ "eve-billing": {
+ buildCommand: "node '../../node_modules/eve/bin/eve.js' build",
+ framework: "eve",
+ routes: [
+ {
+ src: "^/eve/agents/billing/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
+ root: "agents/billing",
+ routePrefix: "/eve/agents/billing",
+ },
+ "eve-support": {
+ buildCommand: "eve build:support",
+ entrypoint: "package.json",
+ framework: "eve",
+ routes: [
+ {
+ src: "^/eve/agents/support/eve/v1/(.*)$",
+ transforms: [
+ {
+ args: "/eve/v1/$1",
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ },
+ ],
+ root: "agents/support",
+ routePrefix: "/eve/agents/support",
+ schema: "experimentalServicesV2",
+ },
+ },
+ version: 3,
+ });
+ expect(rewrites).toBeUndefined();
+ });
+
it("does not start a local eve build while Next.js is building", async () => {
const appRoot = await createTempAppRoot();
process.chdir(appRoot);
diff --git a/packages/eve/src/public/next/index.test.ts b/packages/eve/src/public/next/index.test.ts
index bf3fb68f8..95b1ea9b0 100644
--- a/packages/eve/src/public/next/index.test.ts
+++ b/packages/eve/src/public/next/index.test.ts
@@ -1,11 +1,33 @@
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("./vercel-output-config.js", () => ({
- ensureEveVercelOutputConfig: vi.fn(async (input: { readonly servicePrefix: string }) => ({
- servicePrefix: input.servicePrefix,
- })),
+ ensureEveVercelOutputConfig: vi.fn(
+ async (input: {
+ readonly agents: readonly {
+ readonly name?: string;
+ readonly servicePrefix: string;
+ }[];
+ }) => ({
+ agents: input.agents.map((agent) => ({
+ name: agent.name,
+ servicePrefix: agent.servicePrefix,
+ })),
+ }),
+ ),
}));
+const { ensureEveVercelOutputConfig } = await import("./vercel-output-config.js");
+
+vi.mock("./server.js", async (importOriginal) => {
+ const original = await importOriginal<typeof import("./server.js")>();
+ return {
+ ...original,
+ resolveEveDestinationPrefix: vi.fn(original.resolveEveDestinationPrefix),
+ };
+});
+
+const { resolveEveDestinationPrefix } = await import("./server.js");
+
import {
EVE_NEXT_SERVICE_PREFIX,
withEve,
@@ -25,6 +47,8 @@ async function resolveConfig(config: ReturnType<typeof withEve<TestConfig>>): Pr
describe("withEve", () => {
afterEach(() => {
+ vi.mocked(resolveEveDestinationPrefix).mockClear();
+ vi.mocked(ensureEveVercelOutputConfig).mockClear();
vi.unstubAllEnvs();
});
@@ -275,6 +299,117 @@ describe("withEve", () => {
source: "/eve/v1/:path+",
});
});
+
+ it("adds named agent rewrites with derived and per-agent service prefixes", async () => {
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("EVE_NEXT_PRODUCTION_ORIGIN", "https://agent.example.com");
+
+ const config = await resolveConfig(
+ withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ billing: {
+ buildCommand: "pnpm build:billing-agent",
+ root: "./agents/billing",
+ servicePrefix: "/_eve_internal/billing",
+ },
+ support: "./agents/support",
+ },
+ },
+ ),
+ );
+ const rewrites = await config.rewrites?.();
+
+ expect(getBeforeFiles(rewrites)).toEqual(
+ expect.arrayContaining([
+ {
+ destination: `https://agent.example.com${EVE_NEXT_SERVICE_PREFIX}/support/eve/v1/:path+`,
+ source: "/eve/agents/support/eve/v1/:path+",
+ },
+ {
+ destination: "https://agent.example.com/_eve_internal/billing/eve/v1/:path+",
+ source: "/eve/agents/billing/eve/v1/:path+",
+ },
+ ]),
+ );
+ expect(ensureEveVercelOutputConfig).toHaveBeenCalledWith({
+ agents: [
+ {
+ appRoot: expect.stringContaining("/agents/billing"),
+ buildCommand: "pnpm build:billing-agent",
+ name: "billing",
+ publicRoutePrefix: "/eve/agents/billing",
+ servicePrefix: "/_eve_internal/billing",
+ },
+ {
+ appRoot: expect.stringContaining("/agents/support"),
+ buildCommand: "node '../../node_modules/eve/bin/eve.js' build",
+ name: "support",
+ publicRoutePrefix: "/eve/agents/support",
+ servicePrefix: `${EVE_NEXT_SERVICE_PREFIX}/support`,
+ },
+ ],
+ nextRoot: process.cwd(),
+ });
+ });
+
+ it("uses adjacent stable local production ports for named agents", async () => {
+ vi.stubEnv("NODE_ENV", "production");
+
+ const config = await withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ billing: "./agents/billing",
+ support: "./agents/support",
+ },
+ },
+ )("phase-production-build", {
+ defaultConfig: {},
+ });
+ const rewrites = await config.rewrites?.();
+
+ expect(getBeforeFiles(rewrites)).toEqual(
+ expect.arrayContaining([
+ {
+ destination: "http://127.0.0.1:4274/eve/v1/:path+",
+ source: "/eve/agents/billing/eve/v1/:path+",
+ },
+ {
+ destination: "http://127.0.0.1:4275/eve/v1/:path+",
+ source: "/eve/agents/support/eve/v1/:path+",
+ },
+ ]),
+ );
+ });
+
+ it("rejects eveRoot when named agents are configured", () => {
+ expect(() =>
+ withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ support: "./agents/support",
+ },
+ eveRoot: "./agent",
+ },
+ ),
+ ).toThrow("withEve cannot combine eveRoot with agents");
+ });
+
+ it("rejects invalid named agent route segments", () => {
+ expect(() =>
+ withEve<TestConfig>(
+ {},
+ {
+ agents: {
+ Support: "./agents/support",
+ },
+ },
+ ),
+ ).toThrow("eve Next.js agent name");
+ });
});
function getBeforeFiles(
diff --git a/packages/eve/src/public/next/index.ts b/packages/eve/src/public/next/index.ts
index 20cbdaf26..ef9418e99 100644
--- a/packages/eve/src/public/next/index.ts
+++ b/packages/eve/src/public/next/index.ts
@@ -1,4 +1,4 @@
-import { isAbsolute, resolve } from "node:path";
+import { isAbsolute, join, relative, resolve } from "node:path";
import type { NextConfig } from "next";
@@ -14,9 +14,9 @@ export const EVE_NEXT_SERVICE_PREFIX = "/_eve_internal/eve";
const EVE_NEXT_PRODUCTION_ORIGIN_ENV = "EVE_NEXT_PRODUCTION_ORIGIN";
const EVE_NEXT_PRODUCTION_PORT_ENV = "EVE_NEXT_PRODUCTION_PORT";
-const DEFAULT_EVE_BUILD_COMMAND = "eve build";
const DEFAULT_EVE_NEXT_PRODUCTION_PORT = 4274;
-const EVE_PROXY_REWRITE_SOURCES: readonly string[] = [`${EVE_ROUTE_PREFIX}/:path+`];
+const EVE_NAMED_AGENT_ROUTE_PREFIX = "/eve/agents";
+const AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
type ArrayElement<T> = T extends readonly (infer TElement)[] ? TElement : never;
type NextRewrites = Awaited<ReturnType<NonNullable<NextConfig["rewrites"]>>>;
@@ -69,6 +69,33 @@ export type EveNextConfigInput<TConfig extends EveNextConfig = EveNextConfig> =
| EveNextConfigFunction<TConfig>
| TConfig;
+/**
+ * Configuration for one named eve agent mounted by {@link withEve}.
+ */
+export interface WithEveAgentOptions {
+ /**
+ * Path to the eve application root, relative to `process.cwd()` unless
+ * absolute.
+ */
+ readonly root: string;
+ /**
+ * Build command for this generated eve Vercel service. Defaults to
+ * {@link WithEveOptions.eveBuildCommand}, then a generated command that runs
+ * the installed eve binary from this agent root.
+ */
+ readonly buildCommand?: string;
+ /**
+ * Private route namespace for this agent's legacy manually configured Vercel
+ * service and non-Vercel production proxying.
+ */
+ readonly servicePrefix?: string;
+}
+
+/**
+ * Map of agent names to roots or per-agent configuration.
+ */
+export type WithEveAgentsConfig = Record<string, string | WithEveAgentOptions>;
+
/**
* Options for {@link withEve}.
*/
@@ -85,9 +112,19 @@ export interface WithEveOptions {
*/
readonly eveRoot?: string;
/**
- * Build command for the generated eve Vercel service. Defaults to `eve build`.
- * Use this when the eve service needs project-specific prework before the
- * framework build, without changing the Next.js service build command.
+ * Named eve agents to mount under `/eve/agents/<name>/eve/v1/*`.
+ *
+ * Use this when one Next.js app needs to talk to multiple eve agents. When
+ * set, do not also set {@link eveRoot}; the single-agent form remains the
+ * shorthand for one unnamed agent mounted at `/eve/v1/*`.
+ */
+ readonly agents?: WithEveAgentsConfig;
+ /**
+ * Build command for the generated eve Vercel service. In multi-agent mode
+ * this is the default for agents without their own `buildCommand`.
+ *
+ * When omitted, withEve generates a command that runs the installed eve
+ * binary from the agent root.
*/
readonly eveBuildCommand?: string;
/**
@@ -100,6 +137,15 @@ export interface WithEveOptions {
readonly servicePrefix?: string;
}
+interface ResolvedEveNextAgent {
+ readonly appRoot: string;
+ readonly buildCommand: string;
+ readonly localProductionPortOffset: number;
+ readonly name?: string;
+ readonly publicRoutePrefix: string;
+ readonly servicePrefix: string;
+}
+
function resolveApplicationRoot(appPath: string | undefined): string {
if (appPath === undefined || appPath.length === 0) {
return process.cwd();
@@ -135,33 +181,56 @@ function joinRoutePrefix(prefix: string, path: string): string {
return `${prefix.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
}
+function createNamedAgentRoutePrefix(name: string): string {
+ return joinRoutePrefix(EVE_NAMED_AGENT_ROUTE_PREFIX, name);
+}
+
+function createNamedAgentServicePrefix(basePrefix: string, name: string): string {
+ return joinRoutePrefix(basePrefix, name);
+}
+
+function createAgentRewriteSource(publicRoutePrefix: string): string {
+ return joinRoutePrefix(publicRoutePrefix, `${EVE_ROUTE_PREFIX}/:path+`);
+}
+
function normalizeOrigin(origin: string): string {
return new URL(origin.trim()).origin;
}
-function readLocalProductionPort(): number {
+function readLocalProductionPort(portOffset: number): number {
const configuredPort = process.env[EVE_NEXT_PRODUCTION_PORT_ENV];
- if (configuredPort === undefined || configuredPort.trim().length === 0) {
- return DEFAULT_EVE_NEXT_PRODUCTION_PORT;
- }
-
- const port = Number.parseInt(configuredPort, 10);
+ const basePort =
+ configuredPort === undefined || configuredPort.trim().length === 0
+ ? DEFAULT_EVE_NEXT_PRODUCTION_PORT
+ : Number.parseInt(configuredPort, 10);
- if (String(port) !== configuredPort.trim() || port < 1 || port > 65_535) {
+ if (
+ configuredPort !== undefined &&
+ configuredPort.trim().length > 0 &&
+ String(basePort) !== configuredPort.trim()
+ ) {
throw new Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} must be an integer between 1 and 65535.`);
}
+ const port = basePort + portOffset;
+ if (port < 1 || port > 65_535) {
+ throw new Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} plus the eve agent count exceeds 65535.`);
+ }
+
return port;
}
-function resolveProductionDestination(servicePrefix: string): {
+function resolveProductionDestination(input: {
+ readonly localProductionPortOffset: number;
+ readonly servicePrefix: string;
+}): {
readonly destinationPrefix: string;
readonly localServerOrigin?: string;
} {
if (process.env.VERCEL) {
return {
- destinationPrefix: servicePrefix,
+ destinationPrefix: input.servicePrefix,
};
}
@@ -169,26 +238,28 @@ function resolveProductionDestination(servicePrefix: string): {
if (configuredOrigin !== undefined && configuredOrigin.trim().length > 0) {
return {
- destinationPrefix: joinRoutePrefix(normalizeOrigin(configuredOrigin), servicePrefix),
+ destinationPrefix: joinRoutePrefix(normalizeOrigin(configuredOrigin), input.servicePrefix),
};
}
- const localServerOrigin = `http://127.0.0.1:${String(readLocalProductionPort())}`;
+ const localServerOrigin = `http://127.0.0.1:${String(
+ readLocalProductionPort(input.localProductionPortOffset),
+ )}`;
return {
destinationPrefix: localServerOrigin,
localServerOrigin,
};
}
-function createEveRewriteRules(destinationPrefix: string): EveNextRewriteRule[] {
- return EVE_PROXY_REWRITE_SOURCES.map((source) => {
- const rule: EveNextRewriteRule = {
- destination: joinRoutePrefix(destinationPrefix, source),
- source,
- };
-
- return rule;
- });
+function createEveRewriteRule(input: {
+ readonly destinationPrefix: string;
+ readonly publicRoutePrefix: string;
+}): EveNextRewriteRule {
+ const source = createAgentRewriteSource(input.publicRoutePrefix);
+ return {
+ destination: joinRoutePrefix(input.destinationPrefix, `${EVE_ROUTE_PREFIX}/:path+`),
+ source,
+ };
}
async function resolveExistingRewrites(
@@ -236,6 +307,83 @@ async function resolveNextConfig<TConfig extends EveNextConfig>(
: configOrFunction;
}
+function assertValidAgentName(name: string): void {
+ if (!AGENT_NAME_PATTERN.test(name)) {
+ throw new Error(
+ `eve Next.js agent name ${JSON.stringify(
+ name,
+ )} is invalid. Use lowercase letters, numbers, underscores, or hyphens, starting with a letter or number.`,
+ );
+ }
+}
+
+function quoteShellArg(value: string): string {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+}
+
+function toPosixPath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
+
+function createDefaultBuildCommand(input: {
+ readonly agentRoot: string;
+ readonly nextRoot: string;
+}): string {
+ const eveBinaryPath = toPosixPath(
+ relative(input.agentRoot, join(input.nextRoot, "node_modules", "eve", "bin", "eve.js")),
+ );
+ return `node ${quoteShellArg(eveBinaryPath)} build`;
+}
+
+function normalizeAgentsConfig(
+ options: WithEveOptions,
+ nextRoot: string,
+): readonly ResolvedEveNextAgent[] {
+ const servicePrefixBase = normalizeRoutePrefix(options.servicePrefix ?? EVE_NEXT_SERVICE_PREFIX);
+ const resolveBuildCommand = (agentRoot: string, buildCommand: string | undefined) =>
+ buildCommand ?? options.eveBuildCommand ?? createDefaultBuildCommand({ agentRoot, nextRoot });
+
+ if (options.agents === undefined) {
+ const appRoot = resolveApplicationRoot(options.eveRoot);
+ return [
+ {
+ appRoot,
+ buildCommand: resolveBuildCommand(appRoot, undefined),
+ localProductionPortOffset: 0,
+ publicRoutePrefix: "",
+ servicePrefix: servicePrefixBase,
+ },
+ ];
+ }
+
+ if (options.eveRoot !== undefined) {
+ throw new Error("withEve cannot combine eveRoot with agents. Use one configuration form.");
+ }
+
+ const entries = Object.entries(options.agents);
+ if (entries.length === 0) {
+ throw new Error("withEve agents must contain at least one named eve agent.");
+ }
+
+ return entries.map(([name, config], index) => {
+ assertValidAgentName(name);
+
+ const agentConfig = typeof config === "string" ? { root: config } : config;
+ const appRoot = resolveApplicationRoot(agentConfig.root);
+
+ return {
+ appRoot,
+ buildCommand: resolveBuildCommand(appRoot, agentConfig.buildCommand),
+ localProductionPortOffset: index,
+ name,
+ publicRoutePrefix: createNamedAgentRoutePrefix(name),
+ servicePrefix: normalizeRoutePrefix(
+ agentConfig.servicePrefix ?? createNamedAgentServicePrefix(servicePrefixBase, name),
+ ),
+ };
+ });
+}
+
/**
* Wraps a Next.js config so same-origin eve endpoints proxy to a separate eve
* service.
@@ -253,41 +401,68 @@ export function withEve<TConfig extends EveNextConfig>(
options: WithEveOptions = {},
): EveNextConfigFunction<TConfig> {
const nextRoot = process.cwd();
- const appRoot = resolveApplicationRoot(options.eveRoot);
const devServerTimeoutMs = resolveDevServerTimeout(options.devServerTimeoutMs);
- const servicePrefixInput = normalizeRoutePrefix(options.servicePrefix ?? EVE_NEXT_SERVICE_PREFIX);
+ const agents = normalizeAgentsConfig(options, nextRoot);
return async function eveNextConfig(phase, context) {
const nextConfig = await resolveNextConfig(configOrFunction, phase, context);
const existingRewrites = nextConfig.rewrites;
const configuredVercel = await ensureEveVercelOutputConfig({
- appRoot,
- eveBuildCommand: options.eveBuildCommand ?? DEFAULT_EVE_BUILD_COMMAND,
+ agents: agents.map((agent) => ({
+ appRoot: agent.appRoot,
+ buildCommand: agent.buildCommand,
+ name: agent.name,
+ publicRoutePrefix: agent.publicRoutePrefix,
+ servicePrefix: agent.servicePrefix,
+ })),
nextRoot,
- servicePrefix: servicePrefixInput,
});
if (process.env.VERCEL) {
return nextConfig;
}
- const productionDestination = resolveProductionDestination(configuredVercel.servicePrefix);
+ const configuredAgentByName = new Map(
+ configuredVercel.agents.map((agent) => [agent.name, agent] as const),
+ );
+ const agentsWithDestinations = agents.map((agent) => {
+ const configuredAgent = configuredAgentByName.get(agent.name);
+ const productionDestination = resolveProductionDestination({
+ localProductionPortOffset: agent.localProductionPortOffset,
+ servicePrefix: configuredAgent?.servicePrefix ?? agent.servicePrefix,
+ });
+
+ return {
+ ...agent,
+ productionDestination,
+ };
+ });
return {
...nextConfig,
async rewrites() {
- const [existing, destinationPrefix] = await Promise.all([
+ const [existing, eveRules] = await Promise.all([
resolveExistingRewrites(existingRewrites),
- resolveEveDestinationPrefix({
- appRoot,
- devServerTimeoutMs,
- phase,
- productionDestinationPrefix: productionDestination.destinationPrefix,
- productionServerOrigin: productionDestination.localServerOrigin,
- }),
+ Promise.all(
+ agentsWithDestinations.map(async (agent) => {
+ const destinationPrefix = await resolveEveDestinationPrefix({
+ appRoot: agent.appRoot,
+ devServerTimeoutMs,
+ logLabel: agent.name,
+ phase,
+ productionDestinationPrefix: agent.productionDestination.destinationPrefix,
+ productionServerOrigin: agent.productionDestination.localServerOrigin,
+ });
+
+ return createEveRewriteRule({
+ destinationPrefix,
+ publicRoutePrefix: agent.publicRoutePrefix,
+ });
+ }),
+ ),
]);
- return mergeRewriteRules(existing, createEveRewriteRules(destinationPrefix));
+ return mergeRewriteRules(existing, eveRules);
},
};
};
diff --git a/packages/eve/src/public/next/server.integration.test.ts b/packages/eve/src/public/next/server.integration.test.ts
index e8ec83db1..7668fbc5f 100644
--- a/packages/eve/src/public/next/server.integration.test.ts
+++ b/packages/eve/src/public/next/server.integration.test.ts
@@ -39,6 +39,7 @@ function createMockChildProcess(): MockChildProcess {
describe("resolveEveDestinationPrefix", () => {
afterEach(async () => {
spawnMock.mockReset();
+ vi.restoreAllMocks();
vi.unstubAllEnvs();
await Promise.all(
tempRoots.splice(0).map((root) =>
@@ -54,10 +55,21 @@ describe("resolveEveDestinationPrefix", () => {
vi.stubEnv("NODE_ENV", "development");
const appRoot = await createTempAppRoot();
const child = createMockChildProcess();
+ const stderrWrites: string[] = [];
+ const stdoutWrites: string[] = [];
+ vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ stderrWrites.push(String(chunk));
+ return true;
+ });
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdoutWrites.push(String(chunk));
+ return true;
+ });
spawnMock.mockReturnValue(child);
const destination = resolveEveDestinationPrefix({
appRoot,
+ logLabel: "support",
phase: "phase-development-server",
productionDestinationPrefix: "/internal/eve",
});
@@ -74,6 +86,46 @@ describe("resolveEveDestinationPrefix", () => {
await expect(destination).resolves.toBe("http://127.0.0.1:33449");
await expect(readRegisteredOrigin(appRoot)).resolves.toBe("http://127.0.0.1:33449");
+ expect(stdoutWrites).toContain(
+ '[eve:dev:support] dependency metadata: "homepage": "https://rolldown.rs/"\n',
+ );
+ expect(stderrWrites).toContain(
+ "[eve:dev:support] server listening at http://127.0.0.1:33449\n",
+ );
+ });
+
+ it("suppresses low-signal eve dev startup output", async () => {
+ vi.stubEnv("NODE_ENV", "development");
+ const appRoot = await createTempAppRoot();
+ const child = createMockChildProcess();
+ const stdoutWrites: string[] = [];
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdoutWrites.push(String(chunk));
+ return true;
+ });
+ spawnMock.mockReturnValue(child);
+
+ const destination = resolveEveDestinationPrefix({
+ appRoot,
+ logLabel: "billing",
+ phase: "phase-development-server",
+ productionDestinationPrefix: "/internal/eve",
+ });
+
+ await vi.waitFor(() => {
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ });
+ child.stdout.emit(
+ "data",
+ Buffer.from(
+ "☰eve v0.0.0\nCONFIGURATION_FIELD_CONFLICT\n\u001b[33m[CONFIGURATION_FIELD_CONFLICT] \u001b[0mnoisy\n[dev] server listening at http://127.0.0.1:33450\n",
+ ),
+ );
+
+ await expect(destination).resolves.toBe("http://127.0.0.1:33450");
+ expect(stdoutWrites).toEqual([
+ "[eve:dev:billing] server listening at http://127.0.0.1:33450\n",
+ ]);
});
});
diff --git a/packages/eve/src/public/next/server.ts b/packages/eve/src/public/next/server.ts
index 91cd25778..cceaf6bd7 100644
--- a/packages/eve/src/public/next/server.ts
+++ b/packages/eve/src/public/next/server.ts
@@ -14,6 +14,7 @@ const DEV_SERVER_STALE_LOCK_MS = 30_000;
const EVE_CACHE_DIRECTORY_NAME = ".eve";
const EVE_NEXT_DEV_SERVER_FILE_NAME = "next-dev-server.json";
const EVE_NEXT_DEV_SERVER_LOCK_FILE_NAME = "next-dev-server.lock";
+const ANSI_ESCAPE_PATTERN = /\u001b\[[0-?]*[ -/]*[@-~]/g;
const SERVER_URL_CANDIDATE_PATTERN = /https?:\/\/[^\s"'<>]+/g;
const NEXT_PHASE_PRODUCTION_BUILD = "phase-production-build";
@@ -151,7 +152,6 @@ async function readUsableEveDevServerRegistry(appRoot: string): Promise<string |
return undefined;
}
- process.env[EVE_BASE_URL_ENV] = registry.origin;
return registry.origin;
} catch (error) {
if (isNodeErrorWithCode(error, "ENOENT")) {
@@ -284,11 +284,71 @@ function findLocalServerOrigin(output: string): string | undefined {
return undefined;
}
+function formatEveDevOutputLine(line: string, logLabel: string | undefined): string | undefined {
+ const normalizedLine = line.replace(/\r$/, "");
+ const trimmedLine = normalizedLine.replace(ANSI_ESCAPE_PATTERN, "").trim();
+
+ if (
+ trimmedLine.length === 0 ||
+ /^☰eve\b/.test(trimmedLine) ||
+ trimmedLine === "CONFIGURATION_FIELD_CONFLICT" ||
+ /^\[CONFIGURATION_FIELD_CONFLICT\]/.test(trimmedLine)
+ ) {
+ return undefined;
+ }
+
+ const tag = logLabel === undefined ? "[eve:dev]" : `[eve:dev:${logLabel}]`;
+ const serverMatch = /server listening at\s+(https?:\/\/[^\s]+)/i.exec(normalizedLine);
+ if (serverMatch !== null) {
+ return `${tag} server listening at ${serverMatch[1]}`;
+ }
+
+ return `${tag} ${normalizedLine}`;
+}
+
+function createEveDevOutputWriter(input: {
+ readonly logLabel?: string;
+ readonly stream: NodeJS.WriteStream;
+}): {
+ readonly flush: () => void;
+ readonly write: (chunk: Buffer) => void;
+} {
+ let pendingLine = "";
+
+ const writeLine = (line: string) => {
+ const formattedLine = formatEveDevOutputLine(line, input.logLabel);
+ if (formattedLine !== undefined) {
+ input.stream.write(`${formattedLine}\n`);
+ }
+ };
+
+ return {
+ flush() {
+ if (pendingLine.length === 0) {
+ return;
+ }
+
+ writeLine(pendingLine);
+ pendingLine = "";
+ },
+ write(chunk) {
+ pendingLine += chunk.toString("utf8");
+ const lines = pendingLine.split("\n");
+ pendingLine = lines.pop() ?? "";
+
+ for (const line of lines) {
+ writeLine(line);
+ }
+ },
+ };
+}
+
function startServerProcess(input: {
readonly args: readonly string[];
readonly command: string;
readonly cwd: string;
readonly env?: Record<string, string>;
+ readonly logLabel?: string;
readonly timeoutMs?: number;
}): Promise<EveProcessHandle> {
return new Promise((resolvePromise, reject) => {
@@ -300,6 +360,14 @@ function startServerProcess(input: {
},
stdio: ["ignore", "pipe", "pipe"],
});
+ const stderrWriter = createEveDevOutputWriter({
+ logLabel: input.logLabel,
+ stream: process.stderr,
+ });
+ const stdoutWriter = createEveDevOutputWriter({
+ logLabel: input.logLabel,
+ stream: process.stdout,
+ });
const timeout = setTimeout(() => {
child.kill();
reject(
@@ -314,11 +382,17 @@ function startServerProcess(input: {
child.off("error", handleError);
child.off("exit", handleEarlyExit);
};
+ const flushOutput = () => {
+ stdoutWriter.flush();
+ stderrWriter.flush();
+ };
const handleError = (error: Error) => {
+ flushOutput();
cleanup();
reject(error);
};
const handleEarlyExit = (code: number | null, signal: NodeJS.Signals | null) => {
+ flushOutput();
cleanup();
reject(
new Error(
@@ -340,11 +414,11 @@ function startServerProcess(input: {
});
};
const handleStdout = (chunk: Buffer) => {
- process.stdout.write(chunk);
+ stdoutWriter.write(chunk);
handleOutput(chunk);
};
const handleStderr = (chunk: Buffer) => {
- process.stderr.write(chunk);
+ stderrWriter.write(chunk);
handleOutput(chunk);
};
@@ -374,14 +448,18 @@ function installProcessShutdown(handle: EveProcessHandle): EveProcessHandle {
return handle;
}
-function startEveDevServer(appRoot: string, timeoutMs: number): Promise<EveProcessHandle> {
+function startEveDevServer(
+ appRoot: string,
+ timeoutMs: number,
+ logLabel: string | undefined,
+): Promise<EveProcessHandle> {
return startServerProcess({
args: [createEveBinaryPath(), "dev", "--no-ui", "--port", "0"],
command: process.execPath,
cwd: appRoot,
+ logLabel,
timeoutMs,
}).then((handle) => {
- process.env[EVE_BASE_URL_ENV] = handle.origin;
return installProcessShutdown(handle);
});
}
@@ -414,6 +492,7 @@ function startEveProductionServer(input: {
async function resolveSharedEveDevServer(
appRoot: string,
timeoutMs: number,
+ logLabel: string | undefined,
): Promise<EveProcessHandle> {
const registeredOrigin = await readUsableEveDevServerRegistry(appRoot);
if (registeredOrigin !== undefined) {
@@ -432,7 +511,7 @@ async function resolveSharedEveDevServer(
};
}
- const handle = await startEveDevServer(appRoot, timeoutMs);
+ const handle = await startEveDevServer(appRoot, timeoutMs, logLabel);
await writeEveDevServerRegistry(appRoot, handle);
return handle;
} finally {
@@ -443,6 +522,7 @@ async function resolveSharedEveDevServer(
export async function resolveEveDestinationPrefix(input: {
readonly appRoot: string;
readonly devServerTimeoutMs?: number;
+ readonly logLabel?: string;
readonly phase: string;
readonly productionDestinationPrefix: string;
readonly productionServerOrigin?: string;
@@ -496,6 +576,7 @@ export async function resolveEveDestinationPrefix(input: {
server = resolveSharedEveDevServer(
input.appRoot,
input.devServerTimeoutMs ?? DEV_SERVER_REGISTRY_TIMEOUT_MS,
+ input.logLabel,
).catch((error) => {
state.servers.delete(key);
throw error;
diff --git a/packages/eve/src/public/next/vercel-output-config.ts b/packages/eve/src/public/next/vercel-output-config.ts
index 8676387f1..6284d0b24 100644
--- a/packages/eve/src/public/next/vercel-output-config.ts
+++ b/packages/eve/src/public/next/vercel-output-config.ts
@@ -11,6 +11,7 @@ const VERCEL_OUTPUT_CONFIG_FILE_NAME = ".vercel/output/config.json";
const VERCEL_BUILD_OUTPUT_VERSION = 3;
const EVE_SERVICE_NAME = "eve";
const EVE_SERVICE_ROUTE_SRC = "^/eve/v1/(.*)$";
+const EVE_SERVICE_ROUTE_PATH = "/eve/v1/$1";
interface VercelServiceMount {
readonly path?: string;
@@ -22,26 +23,50 @@ interface VercelServiceConfig {
readonly entrypoint?: string;
readonly framework?: string;
readonly mount?: string | VercelServiceMount;
+ readonly routes?: readonly VercelRouteConfig[];
readonly routePrefix?: string;
readonly root?: string;
readonly type?: string;
}
+interface MutableGeneratedVercelServiceConfig {
+ buildCommand: string;
+ framework: "eve";
+ routePrefix?: string;
+ routes: readonly VercelRouteConfig[];
+ root: string;
+}
+
+interface VercelNamedServiceConfig extends VercelServiceConfig {
+ readonly name?: string;
+}
+
+type VercelServicesCollection =
+ | Record<string, VercelServiceConfig>
+ | readonly VercelNamedServiceConfig[];
+
interface VercelServiceRouteDestination {
readonly service?: string;
readonly type?: string;
}
+interface VercelRequestPathTransform {
+ readonly args: string;
+ readonly op: "set";
+ readonly type: "request.path";
+}
+
interface VercelRouteConfig {
readonly destination?: string | VercelServiceRouteDestination;
readonly handle?: string;
readonly src?: string;
+ readonly transforms?: readonly VercelRequestPathTransform[];
readonly [key: string]: unknown;
}
interface VercelServicesConfig {
readonly routes?: readonly VercelRouteConfig[];
- readonly services?: Record<string, VercelServiceConfig>;
+ readonly services?: VercelServicesCollection;
readonly [key: string]: unknown;
}
@@ -50,6 +75,19 @@ interface VercelOutputConfig extends VercelServicesConfig {
}
export interface EnsureVercelOutputConfigResult {
+ readonly agents: readonly EnsureVercelOutputConfigAgentResult[];
+}
+
+export interface EnsureVercelOutputConfigAgentInput {
+ readonly appRoot: string;
+ readonly buildCommand: string;
+ readonly name?: string;
+ readonly publicRoutePrefix: string;
+ readonly servicePrefix: string;
+}
+
+export interface EnsureVercelOutputConfigAgentResult {
+ readonly name?: string;
readonly servicePrefix: string;
}
@@ -58,9 +96,38 @@ function isRecord(value: unknown): value is Record<string, unknown> {
}
function hasServices(
- services: Record<string, VercelServiceConfig> | undefined,
-): services is Record<string, VercelServiceConfig> {
- return services !== undefined && Object.keys(services).length > 0;
+ services: VercelServicesCollection | undefined,
+): services is VercelServicesCollection {
+ return services !== undefined && Object.keys(createServiceConfigRecord(services)).length > 0;
+}
+
+function isNamedServiceConfigArray(
+ services: VercelServicesCollection,
+): services is readonly VercelNamedServiceConfig[] {
+ return Array.isArray(services);
+}
+
+function createServiceConfigRecord(
+ services: VercelServicesCollection | undefined,
+): Record<string, VercelServiceConfig> {
+ if (services === undefined) {
+ return {};
+ }
+
+ if (isNamedServiceConfigArray(services)) {
+ const record: Record<string, VercelServiceConfig> = {};
+
+ for (const service of services) {
+ if (typeof service.name === "string" && service.name.trim().length > 0) {
+ const { name, ...serviceConfig } = service;
+ record[name] = serviceConfig;
+ }
+ }
+
+ return record;
+ }
+
+ return services;
}
function resolveRelativeEntrypoint(fromRoot: string, toRoot: string): string {
@@ -112,8 +179,18 @@ function normalizeVercelServicesConfig(value: unknown, fileName: string): Vercel
const services = value.services;
- if (services !== undefined && !isRecord(services)) {
- throw new Error(`${fileName} services must be a JSON object.`);
+ if (
+ services !== undefined &&
+ !isRecord(services) &&
+ !(
+ Array.isArray(services) &&
+ services.every(
+ (service) =>
+ isRecord(service) && typeof service.name === "string" && service.name.trim().length > 0,
+ )
+ )
+ ) {
+ throw new Error(`${fileName} services must be a JSON object or named service array.`);
}
const routes = value.routes;
@@ -143,13 +220,6 @@ async function readVercelServicesConfig(
}
}
-function findServiceByFramework(
- services: Record<string, VercelServiceConfig>,
- framework: string,
-): VercelServiceConfig | undefined {
- return findServiceEntryByFramework(services, framework)?.service;
-}
-
function findServiceEntryByFramework(
services: Record<string, VercelServiceConfig>,
framework: string,
@@ -159,6 +229,14 @@ function findServiceEntryByFramework(
.find((entry) => entry.service.framework === framework);
}
+function findServiceEntryByName(
+ services: Record<string, VercelServiceConfig>,
+ name: string,
+): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
+ const service = services[name];
+ return service === undefined ? undefined : { name, service };
+}
+
function resolveServicePrefix(service: VercelServiceConfig | undefined): string | undefined {
if (service === undefined) {
return undefined;
@@ -184,76 +262,158 @@ function resolveServicePrefix(service: VercelServiceConfig | undefined): string
}
function resolveConfiguredServicePrefix(input: {
+ readonly agent: EnsureVercelOutputConfigAgentInput;
readonly services: Record<string, VercelServiceConfig>;
- readonly servicePrefix: string;
}): string {
- const configuredEveService = findServiceByFramework(input.services, "eve");
- return resolveServicePrefix(configuredEveService) ?? input.servicePrefix;
+ const configuredEveService = findConfiguredEveServiceEntry(input.services, input.agent)?.service;
+ return resolveServicePrefix(configuredEveService) ?? input.agent.servicePrefix;
+}
+
+function findConfiguredEveServiceEntry(
+ services: Record<string, VercelServiceConfig>,
+ agent: EnsureVercelOutputConfigAgentInput,
+): { readonly name: string; readonly service: VercelServiceConfig } | undefined {
+ if (agent.name !== undefined) {
+ const namedService = findServiceEntryByName(services, createEveServiceName(agent.name));
+ if (namedService?.service.framework === "eve") {
+ return namedService;
+ }
+ }
+
+ return agent.name === undefined ? findServiceEntryByFramework(services, "eve") : undefined;
}
function assertRootServicesIncludeEve(input: {
+ readonly agents: readonly EnsureVercelOutputConfigAgentInput[];
readonly services: Record<string, VercelServiceConfig>;
- readonly servicePrefix: string;
-}): string {
- const configuredEveService = findServiceByFramework(input.services, "eve");
+}): readonly EnsureVercelOutputConfigAgentResult[] {
+ const results: EnsureVercelOutputConfigAgentResult[] = [];
+
+ for (const agent of input.agents) {
+ const configuredEveService = findConfiguredEveServiceEntry(input.services, agent)?.service;
- if (configuredEveService !== undefined) {
- return resolveServicePrefix(configuredEveService) ?? input.servicePrefix;
+ if (configuredEveService === undefined) {
+ throw new Error(
+ `${VERCEL_JSON_FILE_NAME} already defines services, so withEve cannot add generated eve services through ${VERCEL_OUTPUT_CONFIG_FILE_NAME}. Add the eve service for ${agent.name ?? "the default agent"} to ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`,
+ );
+ }
+
+ results.push({
+ name: agent.name,
+ servicePrefix: resolveServicePrefix(configuredEveService) ?? agent.servicePrefix,
+ });
}
- throw new Error(
- `${VERCEL_JSON_FILE_NAME} already defines services, so withEve cannot add a generated eve service through ${VERCEL_OUTPUT_CONFIG_FILE_NAME}. Add the eve service to ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`,
- );
+ return results;
}
-function isEveServiceRoute(route: VercelRouteConfig, serviceName: string): boolean {
+function createEveServiceRouteSrc(publicRoutePrefix: string): string {
+ if (publicRoutePrefix.length === 0) {
+ return EVE_SERVICE_ROUTE_SRC;
+ }
+
+ const normalizedPrefix = publicRoutePrefix.startsWith("/")
+ ? publicRoutePrefix
+ : `/${publicRoutePrefix}`;
+ return `^${escapeRegExp(normalizedPrefix)}/eve/v1/(.*)$`;
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function createEveServiceName(name: string | undefined): string {
+ return name === undefined ? EVE_SERVICE_NAME : `${EVE_SERVICE_NAME}-${name}`;
+}
+
+function isEveServiceRoute(
+ route: VercelRouteConfig,
+ serviceName: string,
+ routeSrc: string,
+): boolean {
const destination = route.destination;
return (
- route.src === EVE_SERVICE_ROUTE_SRC &&
+ route.src === routeSrc &&
isRecord(destination) &&
destination.type === "service" &&
destination.service === serviceName
);
}
-function createEveServiceRoute(serviceName: string): VercelRouteConfig {
+function createEveServiceRoute(serviceName: string, routeSrc: string): VercelRouteConfig {
return {
destination: {
service: serviceName,
type: "service",
},
- src: EVE_SERVICE_ROUTE_SRC,
+ src: routeSrc,
};
}
-function insertEveServiceRoute(
+function isEveServiceRequestPathRoute(route: VercelRouteConfig, routeSrc: string): boolean {
+ return route.src === routeSrc;
+}
+
+function createEveServiceRequestPathRoute(routeSrc: string): VercelRouteConfig {
+ return {
+ src: routeSrc,
+ transforms: [
+ {
+ args: EVE_SERVICE_ROUTE_PATH,
+ op: "set",
+ type: "request.path",
+ },
+ ],
+ };
+}
+
+function insertEveServiceRequestPathRoute(
+ routes: readonly VercelRouteConfig[] | undefined,
+ routeSrc: string,
+): readonly VercelRouteConfig[] {
+ const existingRoutes = routes ?? [];
+ const routesWithoutGeneratedRoute = existingRoutes.filter(
+ (route) => !isEveServiceRequestPathRoute(route, routeSrc),
+ );
+
+ return [createEveServiceRequestPathRoute(routeSrc), ...routesWithoutGeneratedRoute];
+}
+
+function insertEveServiceRoutes(
routes: readonly VercelRouteConfig[],
- serviceName: string,
+ eveRoutes: readonly {
+ readonly routeSrc: string;
+ readonly serviceName: string;
+ }[],
): readonly VercelRouteConfig[] {
- const existingRoute = routes.find((route) => isEveServiceRoute(route, serviceName));
- const routesWithoutEveRoute = routes.filter((route) => !isEveServiceRoute(route, serviceName));
- const filesystemRouteIndex = routesWithoutEveRoute.findIndex(
+ const routesWithoutEveRoutes = routes.filter(
+ (route) =>
+ !eveRoutes.some((eveRoute) =>
+ isEveServiceRoute(route, eveRoute.serviceName, eveRoute.routeSrc),
+ ),
+ );
+ const filesystemRouteIndex = routesWithoutEveRoutes.findIndex(
(route) => route.handle === "filesystem",
);
- const eveRoute = existingRoute ?? createEveServiceRoute(serviceName);
+ const nextEveRoutes = eveRoutes.map((eveRoute) =>
+ createEveServiceRoute(eveRoute.serviceName, eveRoute.routeSrc),
+ );
if (filesystemRouteIndex === -1) {
- return [eveRoute, ...routesWithoutEveRoute];
+ return [...nextEveRoutes, ...routesWithoutEveRoutes];
}
return [
- ...routesWithoutEveRoute.slice(0, filesystemRouteIndex),
- eveRoute,
- ...routesWithoutEveRoute.slice(filesystemRouteIndex),
+ ...routesWithoutEveRoutes.slice(0, filesystemRouteIndex),
+ ...nextEveRoutes,
+ ...routesWithoutEveRoutes.slice(filesystemRouteIndex),
];
}
export async function ensureEveVercelOutputConfig(input: {
- readonly appRoot: string;
- readonly eveBuildCommand: string;
+ readonly agents: readonly EnsureVercelOutputConfigAgentInput[];
readonly nextRoot: string;
- readonly servicePrefix: string;
}): Promise<EnsureVercelOutputConfigResult> {
const { canWriteGeneratedOutput, outputConfigPath, projectRoot } =
await resolveVercelOutputConfigLocation(input.nextRoot);
@@ -265,9 +425,9 @@ export async function ensureEveVercelOutputConfig(input: {
if (hasServices(rootServices)) {
return {
- servicePrefix: assertRootServicesIncludeEve({
- services: rootServices,
- servicePrefix: input.servicePrefix,
+ agents: assertRootServicesIncludeEve({
+ agents: input.agents,
+ services: createServiceConfigRecord(rootServices),
}),
};
}
@@ -276,39 +436,67 @@ export async function ensureEveVercelOutputConfig(input: {
outputConfigPath,
VERCEL_OUTPUT_CONFIG_FILE_NAME,
)) as VercelOutputConfig;
- const eveEntrypoint = resolveRelativeEntrypoint(input.nextRoot, input.appRoot);
- const existingServices = existingConfig.services ?? {};
- const configuredEveServiceEntry = findServiceEntryByFramework(existingServices, "eve");
- const servicePrefix = resolveConfiguredServicePrefix({
- services: existingServices,
- servicePrefix: input.servicePrefix,
- });
+ const existingServices = createServiceConfigRecord(existingConfig.services);
+ const agentResults = input.agents.map((agent) => ({
+ name: agent.name,
+ servicePrefix: resolveConfiguredServicePrefix({
+ agent,
+ services: existingServices,
+ }),
+ }));
if (!canWriteGeneratedOutput) {
return {
- servicePrefix,
+ agents: agentResults,
};
}
const services: Record<string, VercelServiceConfig> = {
...existingServices,
};
- let eveServiceName = configuredEveServiceEntry?.name ?? EVE_SERVICE_NAME;
-
- if (configuredEveServiceEntry === undefined) {
- services[EVE_SERVICE_NAME] = {
- buildCommand: input.eveBuildCommand,
- entrypoint: "package.json",
- framework: "eve",
- root: eveEntrypoint,
- };
- eveServiceName = EVE_SERVICE_NAME;
+ const eveRoutes: {
+ routeSrc: string;
+ serviceName: string;
+ }[] = [];
+
+ for (const agent of input.agents) {
+ const configuredEveServiceEntry = findConfiguredEveServiceEntry(existingServices, agent);
+ const serviceName = configuredEveServiceEntry?.name ?? createEveServiceName(agent.name);
+ const routeSrc = createEveServiceRouteSrc(agent.publicRoutePrefix);
+
+ if (configuredEveServiceEntry === undefined) {
+ const serviceConfig: MutableGeneratedVercelServiceConfig = {
+ buildCommand: agent.buildCommand,
+ framework: "eve",
+ routes: insertEveServiceRequestPathRoute(undefined, routeSrc),
+ root: resolveRelativeEntrypoint(input.nextRoot, agent.appRoot),
+ };
+
+ if (agent.publicRoutePrefix.length > 0) {
+ serviceConfig.routePrefix = agent.publicRoutePrefix;
+ }
+
+ services[serviceName] = serviceConfig;
+ } else {
+ services[serviceName] = {
+ ...configuredEveServiceEntry.service,
+ routes: insertEveServiceRequestPathRoute(
+ configuredEveServiceEntry.service.routes,
+ routeSrc,
+ ),
+ };
+ }
+
+ eveRoutes.push({
+ routeSrc,
+ serviceName,
+ });
}
const { services: _services, ...configWithoutLegacyServices } = existingConfig;
const vercelConfig: VercelOutputConfig = {
...configWithoutLegacyServices,
- routes: insertEveServiceRoute(existingConfig.routes ?? [], eveServiceName),
+ routes: insertEveServiceRoutes(existingConfig.routes ?? [], eveRoutes),
services,
version: VERCEL_BUILD_OUTPUT_VERSION,
};
@@ -319,6 +507,6 @@ export async function ensureEveVercelOutputConfig(input: {
}
return {
- servicePrefix,
+ agents: agentResults,
};
}
diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.ts
index befa01524..e4b871fa8 100644
--- a/packages/eve/src/react/use-eve-agent.test.ts
+++ b/packages/eve/src/react/use-eve-agent.test.ts
@@ -275,6 +275,43 @@ describe("useEveAgent", () => {
});
});
+ it("targets named agent routes when agent is configured", async () => {
+ const startResponse = createDeferred<Response>();
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockReturnValueOnce(startResponse.promise)
+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));
+
+ let helpers: UseEveAgentHelpers<EveMessageData> | undefined;
+
+ function TestComponent() {
+ helpers = useEveAgent({
+ agent: "support",
+ });
+ return null;
+ }
+
+ await act(async () => {
+ create(createElement(TestComponent));
+ });
+
+ let sendPromise: Promise<void> | undefined;
+ await act(async () => {
+ sendPromise = helpers?.send({ message: "Hello" });
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ startResponse.resolve(createStartedMessageResponse("session_1", "http:session_1"));
+ await sendPromise;
+ });
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe("/eve/agents/support/eve/v1/session");
+ expect(fetchMock.mock.calls[1]?.[0]).toBe(
+ "/eve/agents/support/eve/v1/session/session_1/stream",
+ );
+ });
+
it("marks an optimistic message as failed when send fails before confirmation", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));
diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.ts
index fc102795a..1093ee6e5 100644
--- a/packages/eve/src/react/use-eve-agent.ts
+++ b/packages/eve/src/react/use-eve-agent.ts
@@ -7,6 +7,7 @@ import {
type EveAgentStoreStatus,
type PrepareSend,
} from "#client/eve-agent-store.js";
+import { resolveEveAgentHost } from "#client/agent-host.js";
import type { EveAgentReducer } from "#client/reducer.js";
import type { ClientSession } from "#client/session.js";
import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";
@@ -55,10 +56,17 @@ export interface UseEveAgentHelpers<TData> extends UseEveAgentSnapshot<TData> {
* values to `auth` or `headers`; the client resolves those before each request.
*/
export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData> {
+ /**
+ * Named agent mounted by a framework integration such as `withEve({ agents })`.
+ *
+ * `agent: "support"` targets same-origin routes under
+ * `/eve/agents/support/eve/v1/...`. Do not combine with `host`.
+ */
+ readonly agent?: string;
readonly auth?: ClientAuth;
readonly headers?: HeadersValue;
/**
- * Base URL for eve client requests.
+ * Base URL for eve client requests. Do not combine with `agent`.
*
* Defaults to same-origin eve routes such as `/eve/v1/...`. Pass a same-origin
* prefix such as `/api` for an app-owned proxy, or an absolute origin to talk
@@ -117,7 +125,7 @@ export function useEveAgent<TData>(
storeRef.current = new EveAgentStore({
auth: options.auth,
headers: options.headers,
- host: options.host,
+ host: resolveEveAgentHost({ agent: options.agent, host: options.host }),
initialEvents: options.initialEvents,
initialSession: options.initialSession,
maxReconnectAttempts: options.maxReconnectAttempts,
diff --git a/packages/eve/src/svelte/use-eve-agent.ts b/packages/eve/src/svelte/use-eve-agent.ts
index c454e05bb..44969ba29 100644
--- a/packages/eve/src/svelte/use-eve-agent.ts
+++ b/packages/eve/src/svelte/use-eve-agent.ts
@@ -7,6 +7,7 @@ import {
type EveAgentStoreStatus,
type PrepareSend,
} from "#client/eve-agent-store.js";
+import { resolveEveAgentHost } from "#client/agent-host.js";
import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";
import type { EveAgentReducer } from "#client/reducer.js";
import type { ClientSession } from "#client/session.js";
@@ -64,6 +65,13 @@ export interface UseEveAgentReturn<TData> {
* the client resolves before each HTTP request.
*/
export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData> {
+ /**
+ * Named agent mounted by a framework integration such as `withEve({ agents })`.
+ *
+ * `agent: "support"` targets same-origin routes under
+ * `/eve/agents/support/eve/v1/...`. Do not combine with `host`.
+ */
+ readonly agent?: string;
/**
* Credentials for the auto-created session. Pass function values to refresh
* per request. Ignored when `session` is supplied.
@@ -75,7 +83,7 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>
*/
readonly headers?: HeadersValue;
/**
- * Base URL for eve client requests. Empty targets same-origin eve routes
+ * Base URL for eve client requests. Do not combine with `agent`. Empty targets same-origin eve routes
* such as `/eve/v1/...`; a same-origin prefix like `/api` routes through an
* app-owned proxy; an absolute origin hits an eve server directly.
*
@@ -198,7 +206,7 @@ export function useEveAgent<TData>(
const store = new EveAgentStore<TData>({
auth: options.auth,
headers: options.headers,
- host: options.host,
+ host: resolveEveAgentHost({ agent: options.agent, host: options.host }),
initialEvents: options.initialEvents,
initialSession: options.initialSession,
maxReconnectAttempts: options.maxReconnectAttempts,
diff --git a/packages/eve/src/vue/use-eve-agent.ts b/packages/eve/src/vue/use-eve-agent.ts
index 22645ea52..4ff3641ee 100644
--- a/packages/eve/src/vue/use-eve-agent.ts
+++ b/packages/eve/src/vue/use-eve-agent.ts
@@ -7,6 +7,7 @@ import {
type EveAgentStoreStatus,
type PrepareSend,
} from "#client/eve-agent-store.js";
+import { resolveEveAgentHost } from "#client/agent-host.js";
import type { EveAgentReducer } from "#client/reducer.js";
import type { ClientSession } from "#client/session.js";
import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";
@@ -66,12 +67,19 @@ export interface UseEveAgentReturn<TData> {
* every render.
*/
export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData> {
+ /**
+ * Named agent mounted by a framework integration such as `withEve({ agents })`.
+ *
+ * `agent: "support"` targets same-origin routes under
+ * `/eve/agents/support/eve/v1/...`. Do not combine with `host`.
+ */
+ readonly agent?: string;
/** Authentication configuration; a function value is resolved per request. */
readonly auth?: ClientAuth;
/** Custom headers; a function value is resolved per request. */
readonly headers?: HeadersValue;
/**
- * Base URL used for eve client requests.
+ * Base URL used for eve client requests. Do not combine with `agent`.
*
* By default, requests target same-origin eve routes such as `/eve/v1/...`.
* Pass a same-origin prefix such as `/api` to use an app-owned proxy, or an
@@ -137,7 +145,7 @@ export function useEveAgent<TData>(
const store = new EveAgentStore<TData>({
auth: options.auth,
headers: options.headers,
- host: options.host,
+ host: resolveEveAgentHost({ agent: options.agent, host: options.host }),
initialEvents: options.initialEvents,
initialSession: options.initialSession,
maxReconnectAttempts: options.maxReconnectAttempts,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d9faddc66..f44481cc0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -381,6 +381,40 @@ importers:
specifier: 6.0.3
version: 6.0.3
+ apps/frameworks/next-multi-agent:
+ dependencies:
+ ai:
+ specifier: 'catalog:'
+ version: 7.0.0([email protected])
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ next:
+ specifier: 'catalog:'
+ react:
+ specifier: 'catalog:'
+ version: 19.2.6
+ react-dom:
+ specifier: 'catalog:'
+ version: 19.2.6([email protected])
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ '@types/react':
+ specifier: 'catalog:'
+ version: 19.2.15
+ '@types/react-dom':
+ specifier: 'catalog:'
+ version: 19.2.3(@types/[email protected])
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
+
apps/frameworks/nuxt:
dependencies:
'@tailwindcss/vite':