The Open Framework for Building Agents
fix(selfmod): resolve Vercel project for production setup (#3399)
prhaa08e4bba60d5
diff --git a/.changeset/self-modification-vercel-scope.md b/.changeset/self-modification-vercel-scope.mdnew file mode 100644index 000000000..15755455c--- /dev/null+++ b/.changeset/self-modification-vercel-scope.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Prompt for and resolve the target Vercel project before configuring production self-modification, and scope GitHub connector creation and attachment to that project's owner.diff --git a/packages/eve/src/self-modification/setup.test.ts b/packages/eve/src/self-modification/setup.test.tsindex 2e043e485..fc9e5d719 100644--- a/packages/eve/src/self-modification/setup.test.ts+++ b/packages/eve/src/self-modification/setup.test.ts@@ -1,16 +1,20 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { win32 } from "node:path";import { runInNewContext } from "node:vm";import { defineSelfModificationConfig } from "./config.js";+import { captureVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";+import {classifySelfModificationConfig,connectorName,+ defaultSelfModificationSetupOperations,parseGitHubRemote,renderSelfModificationConfig,repositoryRelativeDirectory,+ type SelfModificationSetupDependencies,} from "./setup.js";describe("self-modification setup", () => {@@ -130,6 +134,68 @@ describe("self-modification setup", () => {).toBe("authored");});+ it("finds a connector on a later Vercel list page", async () => {+ const capture = vi.fn<typeof captureVercel>();+ capture.mockResolvedValueOnce({+ ok: true,+ stdout: JSON.stringify({+ connectors: [{ type: "github", uid: "github/other" }],+ cursor: "next-page",+ }),+ });+ capture.mockResolvedValueOnce({+ ok: true,+ stdout: JSON.stringify({+ connectors: [{ type: "github", uid: "github/selfmod-acme-agents" }],+ }),+ });+ const deps: SelfModificationSetupDependencies = {+ captureVercel: capture,+ runVercelCaptureStdout: vi.fn<typeof runVercelCaptureStdout>(),+ };+ const operations = defaultSelfModificationSetupOperations("/project", deps);++ await expect(+ operations.findOrCreateConnector("selfmod-acme-agents", {+ orgId: "team_acme",+ projectId: "prj_agent",+ }),+ ).resolves.toBe("github/selfmod-acme-agents");+ expect(capture).toHaveBeenNthCalledWith(+ 1,+ [+ "connect",+ "list",+ "--all-projects",+ "--service",+ "github",+ "-F",+ "json",+ "--scope",+ "team_acme",+ ],+ { cwd: "/project" },+ );+ expect(capture).toHaveBeenNthCalledWith(+ 2,+ [+ "connect",+ "list",+ "--all-projects",+ "--service",+ "github",+ "-F",+ "json",+ "--scope",+ "team_acme",+ "--next",+ "next-page",+ ],+ { cwd: "/project" },+ );+ expect(deps.runVercelCaptureStdout).not.toHaveBeenCalled();+ });+it("uses a stable repository-specific connector name", () => {expect(connectorName("Acme", "agents_tools")).toBe("selfmod-acme-agents-tools");});diff --git a/packages/eve/src/self-modification/setup.ts b/packages/eve/src/self-modification/setup.tsindex 228c70b7c..98d576dca 100644--- a/packages/eve/src/self-modification/setup.ts+++ b/packages/eve/src/self-modification/setup.ts@@ -6,6 +6,12 @@ import { promisify } from "node:util";import { discoverAgent } from "#discover/discover-agent.js";import { stripLogicalPathExtension } from "#discover/filesystem.js";+import {+ captureVercel,+ runVercelCaptureStdout,+ type VercelCaptureResult,+} from "#setup/primitives/run-vercel.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { SELF_MODIFICATION_CONFIG_PATH } from "./git-workspace.js";@@ -30,14 +36,24 @@ export interface DetectedGitRepository {readonly remoteKind: "github" | "missing" | "other";}export interface SelfModificationSetupOperations {- attachConnector(connector: string): Promise<void>;+ attachConnector(connector: string, project: VercelProjectReference): Promise<void>;detectChannelNames(): Promise<readonly string[]>;detectGitRepository(): Promise<DetectedGitRepository>;- findOrCreateConnector(name: string): Promise<string>;+ findOrCreateConnector(name: string, project: VercelProjectReference): Promise<string>;readConfig(): Promise<string | undefined>;writeConfig(source: string): Promise<void>;}+export interface SelfModificationSetupDependencies {+ captureVercel: typeof captureVercel;+ runVercelCaptureStdout: typeof runVercelCaptureStdout;+}++const defaultDependencies: SelfModificationSetupDependencies = {+ captureVercel,+ runVercelCaptureStdout,+};+export function connectorName(owner: string, repo: string): string {return `selfmod-${owner}-${repo}`.toLowerCase().replaceAll(/[^a-z0-9-]/gu, "-");}@@ -124,6 +140,7 @@ export function parseGitHubRemote(remote: string): { owner: string; repo: stringexport function defaultSelfModificationSetupOperations(appRoot: string,+ deps: SelfModificationSetupDependencies = defaultDependencies,): SelfModificationSetupOperations {const configPath = join(appRoot, SELF_MODIFICATION_CONFIG_PATH);return {@@ -163,13 +180,8 @@ export function defaultSelfModificationSetupOperations(}},writeConfig: (source) => writeFile(configPath, source, "utf8"),- async findOrCreateConnector(name) {- const listed = await vercel(appRoot, ["connect", "list", "-F", "json"]);- if (!listed.ok)- throw new Error(- "Vercel Connect requires an authenticated Vercel CLI linked to this project.",- );- const connectors = parseConnectors(listed.stdout);+ async findOrCreateConnector(name, project) {+ const connectors = await listGitHubConnectors(appRoot, project, deps.captureVercel);const expected = `github/${name}`;const existing = connectors.find((connector) => connector.uid === expected);if (existing !== undefined) {@@ -177,39 +189,34 @@ export function defaultSelfModificationSetupOperations(throw new Error(`The existing connector ${expected} is not a GitHub connector.`);return existing.uid;}- const created = await vercel(appRoot, [- "connect",- "create",- "github",- "--name",- name,- "-F",- "json",- ]);+ const created = await deps.runVercelCaptureStdout(+ ["connect", "create", "github", "--name", name, "-F", "json", "--scope", project.orgId],+ { cwd: appRoot },+ );const connector = created.ok ? parseCreatedConnector(created.stdout) : undefined;if (connector === undefined || !connector.startsWith("github/"))throw new Error("Could not create a GitHub Vercel Connect connector.");return connector;},- async attachConnector(connector) {- const link = await readLinkedProject(appRoot);- if (link === undefined)- throw new Error(- "Vercel Connect requires this directory to be linked to a Vercel project. Run `vercel link` and retry.",- );- const result = await vercel(appRoot, [- "connect",- "attach",- connector,- "--project",- link.projectId,- "--environment",- "production",- "--yes",- ]);+ async attachConnector(connector, project) {+ const result = await deps.runVercelCaptureStdout(+ [+ "connect",+ "attach",+ connector,+ "--project",+ project.projectId,+ "--environment",+ "production",+ "--yes",+ "--scope",+ project.orgId,+ ],+ { cwd: appRoot },+ );if (!result.ok)throw new Error(- `Could not attach ${connector} to the linked Vercel project for Production.`,+ `Could not attach ${connector} to the selected Vercel project for Production.`,);},};@@ -224,11 +231,13 @@ function parseCreatedConnector(stdout: string): string | undefined {}}-function parseConnectors(stdout: string): { type: string; uid: string }[] {+function parseConnectorListPage(+ stdout: string,+): { connectors: { type: string; uid: string }[]; cursor?: string } | undefined {try {- const parsed = JSON.parse(stdout) as { connectors?: unknown; uid?: unknown; type?: unknown };- const values = Array.isArray(parsed.connectors) ? parsed.connectors : [parsed];- return values.flatMap((value) =>+ const parsed = JSON.parse(stdout) as { connectors?: unknown; cursor?: unknown };+ if (!Array.isArray(parsed.connectors)) return undefined;+ const connectors = parsed.connectors.flatMap((value) =>typeof value === "object" &&value !== null &&typeof (value as { uid?: unknown }).uid === "string" &&@@ -236,28 +245,51 @@ function parseConnectors(stdout: string): { type: string; uid: string }[] {? [{ uid: (value as { uid: string }).uid, type: (value as { type: string }).type }]: [],);- } catch {- return [];- }-}-async function vercel(cwd: string, args: string[]) {- try {- const result = await runFile("vercel", args, { cwd });- return { ok: true, stdout: result.stdout };- } catch {- return { ok: false, stdout: "" };- }-}-async function readLinkedProject(appRoot: string): Promise<{ projectId: string } | undefined> {- try {- const value = JSON.parse(await readFile(join(appRoot, ".vercel", "project.json"), "utf8")) as {- projectId?: unknown;- };- return typeof value.projectId === "string" ? { projectId: value.projectId } : undefined;+ return typeof parsed.cursor === "string"+ ? { connectors, cursor: parsed.cursor }+ : { connectors };} catch {return undefined;}}++async function listGitHubConnectors(+ appRoot: string,+ project: VercelProjectReference,+ capture: typeof captureVercel,+): Promise<{ type: string; uid: string }[]> {+ const connectors: { type: string; uid: string }[] = [];+ const seenCursors = new Set<string>();+ let cursor: string | undefined;+ do {+ const args = [+ "connect",+ "list",+ "--all-projects",+ "--service",+ "github",+ "-F",+ "json",+ "--scope",+ project.orgId,+ ];+ if (cursor !== undefined) args.push("--next", cursor);+ const result: VercelCaptureResult = await capture(args, { cwd: appRoot });+ if (!result.ok)+ throw new Error(+ `Could not list GitHub connectors for the selected Vercel project. ${result.failure.message}`,+ );+ const page = parseConnectorListPage(result.stdout);+ if (page === undefined)+ throw new Error("Vercel returned an invalid GitHub connector list for the selected project.");+ connectors.push(...page.connectors);+ if (page.cursor !== undefined && seenCursors.has(page.cursor))+ throw new Error(`The GitHub connector list repeated cursor ${page.cursor}.`);+ if (page.cursor !== undefined) seenCursors.add(page.cursor);+ cursor = page.cursor;+ } while (cursor !== undefined);+ return connectors;+}export function repositoryRelativeDirectory(repositoryRoot: string,appRoot: string,diff --git a/packages/eve/src/setup/integrations/self-modification/setup.test.ts b/packages/eve/src/setup/integrations/self-modification/setup.test.tsindex cef02a4d6..ada5c87d9 100644--- a/packages/eve/src/setup/integrations/self-modification/setup.test.ts+++ b/packages/eve/src/setup/integrations/self-modification/setup.test.ts@@ -41,15 +41,17 @@ function contexts(project: ProjectResolution = { kind: "unresolved" },) {const fake = createFakePrompter();+ const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));return {...createSetupContexts({appRoot: "/project",asker: withAnswers(answers)(headlessAsker()),environment: integrationSetupEnvironment("authenticated", project),prompter: fake.prompter,- resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),+ resolveVercelProject,}),note: fake.prompter.note,+ resolveVercelProject,};}@@ -114,7 +116,15 @@ describe("self-modification integration setup", () => {await expect(applySelfModificationSetup(plan, ctx.apply, effects)).resolves.toMatchObject({deploymentRequired: true,});- expect(effects.attachConnector).toHaveBeenCalledWith("github/selfmod-acme-agents");+ expect(ctx.resolveVercelProject).toHaveBeenCalledWith("self-modification");+ expect(effects.findOrCreateConnector).toHaveBeenCalledWith("selfmod-acme-agents", {+ orgId: "team",+ projectId: "project",+ });+ expect(effects.attachConnector).toHaveBeenCalledWith("github/selfmod-acme-agents", {+ orgId: "team",+ projectId: "project",+ });expect(effects.writeConfig).toHaveBeenCalledWith(expect.stringContaining('repository: "github.com/acme/agents"'),);@@ -131,7 +141,7 @@ describe("self-modification integration setup", () => {);});- it("omits Vercel authorization when no Vercel backend is configured", async () => {+ it("resolves a Vercel project before configuring deployed self-modification", async () => {const effects = operations();const ctx = contexts({"self-modification-mode": "deployed",@@ -145,17 +155,8 @@ describe("self-modification integration setup", () => {const plan = await prepareSelfModificationSetup(ctx.prepare, effects);await applySelfModificationSetup(plan, ctx.apply, effects);- expect(effects.writeConfig).toHaveBeenCalledWith(expect.not.stringContaining('case "http"'));- expect(effects.writeConfig).toHaveBeenCalledWith(- expect.stringContaining(- "switch (channel.kind) {\n default:\n // Add another branch when you add a trusted channel.",- ),- );- expect(ctx.note).toHaveBeenCalledWith(- expect.stringContaining("configure `deployed.authorize`"),- "Next steps",- { tone: "success" },- );+ expect(ctx.resolveVercelProject).toHaveBeenCalledWith("self-modification");+ expect(effects.writeConfig).toHaveBeenCalledWith(expect.stringContaining('case "http"'));});it("registers the production setup separately from local setup", () => {diff --git a/packages/eve/src/setup/integrations/self-modification/setup.ts b/packages/eve/src/setup/integrations/self-modification/setup.tsindex 0ebea2993..bd1675cf7 100644--- a/packages/eve/src/setup/integrations/self-modification/setup.ts+++ b/packages/eve/src/setup/integrations/self-modification/setup.ts@@ -11,6 +11,7 @@ import {type SelfModificationSetupValues,} from "#self-modification/setup.js";import { SELF_MODIFICATION_CONFIG_PATH } from "#self-modification/git-workspace.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { describeIntegrationSetupEnvironment } from "../shared/environment.js";import {@@ -25,6 +26,7 @@ type SelfModificationSetupPlan =| {readonly kind: "deployed";readonly connectorName: string;+ readonly project: VercelProjectReference;readonly values: SelfModificationSetupValues;};@@ -72,7 +74,8 @@ export async function prepareSelfModificationSetup();if (mode === "local") return { kind: "local" };- const [detected, channelNames] = await Promise.all([+ const [project, detected, channelNames] = await Promise.all([+ context.resolveVercelProject("self-modification"),operations.detectGitRepository(),operations.detectChannelNames(),]);@@ -119,9 +122,7 @@ export async function prepareSelfModificationSetup(connector: `github/${name}`,directory,repository: `github.com/${owner}/${repo}`,- vercelBackend:- context.environment.vercel.kind === "available" &&- context.environment.vercel.project.kind !== "unresolved",+ vercelBackend: true,};context.presenter.note(renderSelfModificationConfig(values),@@ -139,7 +140,7 @@ export async function prepareSelfModificationSetup(required: true,}),);- return confirmed ? { kind: "deployed", connectorName: name, values } : { kind: "local" };+ return confirmed ? { kind: "deployed", connectorName: name, project, values } : { kind: "local" };}export async function applySelfModificationSetup(@@ -158,8 +159,8 @@ export async function applySelfModificationSetup(return { facts: [] };}- const connector = await operations.findOrCreateConnector(plan.connectorName);- await operations.attachConnector(connector);+ const connector = await operations.findOrCreateConnector(plan.connectorName, plan.project);+ await operations.attachConnector(connector, plan.project);await operations.writeConfig(renderSelfModificationConfig({ ...plan.values, connector }));context.presenter.log.success(`Updated ${SELF_MODIFICATION_CONFIG_PATH}.`);context.presenter.nextSteps([