Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): start managed agents under next start (#3457)

roboeve[bot]394ed22ecf3e
diff --git a/.changeset/quiet-shrimps-walk.md b/.changeset/quiet-shrimps-walk.md
new file mode 100644
index 000000000..4cdf53756
--- /dev/null
+++ b/.changeset/quiet-shrimps-walk.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Start built, managed eve agents when a local production Next.js server loads its configuration, so `next start` can serve eve routes.
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index 4efd70d74..19c55d620 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -1,3 +1,4 @@
+import { EventEmitter } from "node:events";
import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -15,6 +16,19 @@ vi.mock("#shared/resolve-eve-binary.js", async () => {
};
});
+interface SpawnOptions {
+ readonly cwd: string;
+ readonly env: Record<string, string | undefined>;
+}
+
+const spawnMock = vi.hoisted(() =>
+ vi.fn<(command: string, args: readonly string[], options: SpawnOptions) => EventEmitter>(),
+);
+
+vi.mock("node:child_process", () => ({
+ spawn: spawnMock,
+}));
+
import { withEve, type EveNextConfig, type EveNextRewriteSections } from "./index.js";
interface TestConfig extends EveNextConfig {
@@ -39,25 +53,99 @@ describe("withEve Vercel config", () => {
const originalCwd = process.cwd();
afterEach(() => {
+ spawnMock.mockReset();
process.chdir(originalCwd);
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
- it("requires a local eve build outside Vercel", async () => {
+ it("requires a local eve build when next start loads config outside Vercel", async () => {
const appRoot = await createTempAppRoot();
process.chdir(appRoot);
vi.stubEnv("NODE_ENV", "production");
- const config = await resolveConfig(withEve<TestConfig>({}));
- await expect(config.rewrites?.()).rejects.toThrow(
- /Run eve build from .+ before starting Next\.js\./u,
- );
+ await expect(
+ withEve<TestConfig>({})("phase-production-server", { defaultConfig: {} }),
+ ).rejects.toThrow(/Run eve build from .+ before starting Next\.js\./u);
+ expect(spawnMock).not.toHaveBeenCalled();
await expect(
readFile(join(appRoot, ".vercel", "output", "config.json"), "utf8"),
).rejects.toThrow();
});
+ it("starts each managed agent once when next start loads config, without rewrites()", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ const resolvedAppRoot = process.cwd();
+ vi.stubEnv("NODE_ENV", "production");
+ await writeBuiltAgent(join(resolvedAppRoot, "agents", "billing"));
+ await writeBuiltAgent(join(resolvedAppRoot, "agents", "support"));
+ spawnListeningServer();
+ const config = withEve<TestConfig>(
+ {},
+ { agents: { billing: "./agents/billing", support: "./agents/support" } },
+ );
+
+ await config("phase-production-server", { defaultConfig: {} });
+ expect(spawnedServers()).toEqual([
+ { cwd: join(resolvedAppRoot, "agents", "billing"), port: "4274" },
+ { cwd: join(resolvedAppRoot, "agents", "support"), port: "4275" },
+ ]);
+
+ const reloaded = await config("phase-production-server", { defaultConfig: {} });
+ const rewrites = await reloaded.rewrites?.();
+
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ expect(getBeforeFiles(rewrites)).toEqual([
+ { destination: "http://127.0.0.1:4274/eve/v1/:path+", source: "/eve/billing/v1/:path+" },
+ { destination: "http://127.0.0.1:4275/eve/v1/:path+", source: "/eve/support/v1/:path+" },
+ ]);
+ });
+
+ it("starts one managed server per port when named agents share a root", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ const sharedRoot = join(process.cwd(), "agents", "shared");
+ vi.stubEnv("NODE_ENV", "production");
+ await writeBuiltAgent(sharedRoot);
+ spawnListeningServer();
+ const config = withEve<TestConfig>(
+ {},
+ { agents: { billing: "./agents/shared", support: "./agents/shared" } },
+ );
+
+ await config("phase-production-server", { defaultConfig: {} });
+ const reloaded = await config("phase-production-server", { defaultConfig: {} });
+ const rewrites = await reloaded.rewrites?.();
+
+ expect(spawnedServers()).toEqual([
+ { cwd: sharedRoot, port: "4274" },
+ { cwd: sharedRoot, port: "4275" },
+ ]);
+ expect(getBeforeFiles(rewrites)).toEqual([
+ { destination: "http://127.0.0.1:4274/eve/v1/:path+", source: "/eve/billing/v1/:path+" },
+ { destination: "http://127.0.0.1:4275/eve/v1/:path+", source: "/eve/support/v1/:path+" },
+ ]);
+ });
+
+ it("does not start a managed agent on Vercel, for a hosted origin, or while building", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ vi.stubEnv("NODE_ENV", "production");
+ await writeBuiltAgent(process.cwd());
+ spawnListeningServer();
+
+ await withEve<TestConfig>({})("phase-production-build", { defaultConfig: {} });
+ vi.stubEnv("EVE_NEXT_PRODUCTION_ORIGIN", "https://agent.example.com");
+ await withEve<TestConfig>({})("phase-production-server", { defaultConfig: {} });
+ vi.stubEnv("EVE_NEXT_PRODUCTION_ORIGIN", "");
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_URL", "preview.example.com");
+ await withEve<TestConfig>({})("phase-production-server", { defaultConfig: {} });
+
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
it("writes Build Output config in Vercel even when no linked project is detected", async () => {
const appRoot = await createTempAppRoot();
process.chdir(appRoot);
@@ -696,6 +784,38 @@ describe("withEve Vercel config", () => {
});
});
+async function writeBuiltAgent(agentRoot: string): Promise<void> {
+ await mkdir(join(agentRoot, ".output", "server"), { recursive: true });
+ await writeFile(join(agentRoot, ".output", "server", "index.mjs"), "// built agent\n");
+}
+
+/** Each spawned child reports it is listening on the port it was given. */
+function spawnListeningServer(): void {
+ spawnMock.mockImplementation((_command, _args, options) => {
+ const child = Object.assign(new EventEmitter(), {
+ killed: false,
+ kill: () => undefined,
+ pid: 12345,
+ stderr: new EventEmitter(),
+ stdout: new EventEmitter(),
+ });
+ setImmediate(() => {
+ child.stdout.emit(
+ "data",
+ Buffer.from(`Listening on: http://127.0.0.1:${options.env.PORT ?? ""}/\n`),
+ );
+ });
+ return child;
+ });
+}
+
+function spawnedServers(): readonly { readonly cwd: string; readonly port: string }[] {
+ return spawnMock.mock.calls.map(([, , options]) => ({
+ cwd: options.cwd,
+ port: options.env.PORT ?? "",
+ }));
+}
+
function getBeforeFiles(
rewrites: Awaited<ReturnType<NonNullable<TestConfig["rewrites"]>>> | undefined,
): readonly NonNullable<EveNextRewriteSections["beforeFiles"]>[number][] {
diff --git a/packages/eve/src/public/next/index.ts b/packages/eve/src/public/next/index.ts
index 0f3f2680a..b87f3e6bb 100644
--- a/packages/eve/src/public/next/index.ts
+++ b/packages/eve/src/public/next/index.ts
@@ -11,7 +11,9 @@ import { resolveDevServerTimeout } from "#shared/framework-eve-server.js";
import { resolveEveBinaryPath } from "#shared/resolve-eve-binary.js";
import {
EVE_NEXT_HOST,
+ ensureEveProductionServer,
NEXT_PHASE_PRODUCTION_BUILD,
+ NEXT_PHASE_PRODUCTION_SERVER,
resolveEveDestinationPrefix,
} from "./server.js";
import { ensureEveVercelOutputConfig } from "./vercel-output-config.js";
@@ -487,6 +489,18 @@ export function withEve<TConfig extends EveNextConfig>(
productionDestination,
};
});
+ if (phase === NEXT_PHASE_PRODUCTION_SERVER) {
+ await Promise.all(
+ agentsWithDestinations.map(async ({ appRoot, productionDestination }) => {
+ if (productionDestination.localServerOrigin !== undefined) {
+ await ensureEveProductionServer({
+ appRoot,
+ origin: productionDestination.localServerOrigin,
+ });
+ }
+ }),
+ );
+ }
return {
...nextConfig,
@@ -499,9 +513,7 @@ export function withEve<TConfig extends EveNextConfig>(
appRoot: agent.appRoot,
devServerTimeoutMs,
logLabel: agent.name,
- phase,
productionDestinationPrefix: agent.productionDestination.destinationPrefix,
- productionServerOrigin: agent.productionDestination.localServerOrigin,
workspaceAgentName: agent.workspaceMember === true ? agent.name : undefined,
});
diff --git a/packages/eve/src/public/next/server.integration.test.ts b/packages/eve/src/public/next/server.integration.test.ts
index 3a87c4203..7aa677fa9 100644
--- a/packages/eve/src/public/next/server.integration.test.ts
+++ b/packages/eve/src/public/next/server.integration.test.ts
@@ -11,7 +11,7 @@ vi.mock("node:child_process", () => ({
spawn: spawnMock,
}));
-import { resolveEveDestinationPrefix } from "./server.js";
+import { ensureEveProductionServer, resolveEveDestinationPrefix } from "./server.js";
const tempRoots: string[] = [];
@@ -56,11 +56,9 @@ describe("resolveEveDestinationPrefix", () => {
const appRoot = await createTempAppRoot();
await expect(
- resolveEveDestinationPrefix({
+ ensureEveProductionServer({
appRoot,
- phase: "phase-production-server",
- productionDestinationPrefix: "http://127.0.0.1:4274",
- productionServerOrigin: "http://127.0.0.1:4274",
+ origin: "http://127.0.0.1:4274",
}),
).rejects.toThrow(`Run eve build from ${appRoot} before starting Next.js.`);
expect(spawnMock).not.toHaveBeenCalled();
@@ -85,7 +83,6 @@ describe("resolveEveDestinationPrefix", () => {
const destination = resolveEveDestinationPrefix({
appRoot,
logLabel: "support",
- phase: "phase-development-server",
productionDestinationPrefix: "/internal/eve",
});
@@ -119,7 +116,6 @@ describe("resolveEveDestinationPrefix", () => {
const destination = resolveEveDestinationPrefix({
appRoot,
logLabel: "support",
- phase: "phase-development-server",
productionDestinationPrefix: "/internal/eve",
workspaceAgentName: "support",
});
@@ -148,7 +144,6 @@ describe("resolveEveDestinationPrefix", () => {
const destination = resolveEveDestinationPrefix({
appRoot,
logLabel: "billing",
- phase: "phase-development-server",
productionDestinationPrefix: "/internal/eve",
});
diff --git a/packages/eve/src/public/next/server.ts b/packages/eve/src/public/next/server.ts
index 987afca05..8031d0501 100644
--- a/packages/eve/src/public/next/server.ts
+++ b/packages/eve/src/public/next/server.ts
@@ -7,6 +7,7 @@ import {
const EVE_BASE_URL_ENV = "EVE_BASE_URL";
export const NEXT_PHASE_PRODUCTION_BUILD = "phase-production-build";
+export const NEXT_PHASE_PRODUCTION_SERVER = "phase-production-server";
export const EVE_NEXT_HOST: EveFrameworkHost = { label: "Next.js", slug: "next" };
interface EveNextGlobalState {
@@ -37,47 +38,42 @@ function readEveBaseUrlEnvironment(): string | undefined {
return new URL(configuredUrl).origin;
}
+/**
+ * Start the built eve server for `appRoot` on `origin` once per process. Named
+ * agents may share a root, each on its own port, so both identify the server.
+ * `next start` calls this while loading config, because Next serves the
+ * rewrites saved by `next build` and never calls `rewrites()` again.
+ */
+export async function ensureEveProductionServer(input: {
+ readonly appRoot: string;
+ readonly origin: string;
+}): Promise<void> {
+ const state = getGlobalState();
+ const key = `production:${input.appRoot}:${input.origin}`;
+ let server = state.servers.get(key);
+ if (server === undefined) {
+ server = startEveProductionServer({
+ appRoot: input.appRoot,
+ host: EVE_NEXT_HOST,
+ origin: input.origin,
+ }).catch((error: unknown) => {
+ state.servers.delete(key);
+ throw error;
+ });
+ state.servers.set(key, server);
+ }
+ await server;
+}
+
export async function resolveEveDestinationPrefix(input: {
readonly appRoot: string;
readonly devServerTimeoutMs?: number;
readonly logLabel?: string;
- readonly phase: string;
readonly productionDestinationPrefix: string;
- readonly productionServerOrigin?: string;
/** Workspace member selected when spawning the local eve dev server. */
readonly workspaceAgentName?: string;
}): Promise<string> {
- const state = getGlobalState();
-
if (process.env.NODE_ENV === "production") {
- if (input.phase === NEXT_PHASE_PRODUCTION_BUILD) {
- return input.productionDestinationPrefix;
- }
-
- const key = `production:${input.appRoot}`;
- let productionServer = state.servers.get(key);
- if (productionServer === undefined) {
- productionServer =
- process.env.VERCEL || input.productionServerOrigin === undefined
- ? undefined
- : startEveProductionServer({
- appRoot: input.appRoot,
- host: EVE_NEXT_HOST,
- origin: input.productionServerOrigin,
- });
- if (productionServer !== undefined) {
- productionServer = productionServer.catch((error) => {
- state.servers.delete(key);
- throw error;
- });
- state.servers.set(key, productionServer);
- }
- }
-
- if (productionServer !== undefined) {
- return (await productionServer).origin;
- }
-
return input.productionDestinationPrefix;
}
@@ -90,6 +86,7 @@ export async function resolveEveDestinationPrefix(input: {
return input.productionDestinationPrefix;
}
+ const state = getGlobalState();
const key = `dev:${input.appRoot}`;
let server = state.servers.get(key);