The Open Framework for Building Agents
Resolve CLI commands from the enclosing eve application (#2084)
OwenKephartabcd06d541a8
diff --git a/.changeset/tidy-roots-resolve.md b/.changeset/tidy-roots-resolve.mdnew file mode 100644index 000000000..adaed55cf--- /dev/null+++ b/.changeset/tidy-roots-resolve.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Resolve project-scoped CLI commands from the nearest enclosing eve application when run from a nested directory.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex d2ae2b605..f04ab471d 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -3,7 +3,7 @@ title: "CLI"description: "Reference for every eve CLI command: init, set, info, build, start, dev, logs, trace, link, deploy, eval, channels, and extension."----The `eve` binary (`bin: eve`) runs from your app root. Every command first loads `.env`/`.env.local` from that root. Running `eve` with no command runs `eve init` when the current directory is not an eve project, or `eve dev` when it is.+Relevant `eve` commands can run from the application root or any directory beneath it. Running `eve` with no command runs `eve init` when the current directory is not an eve project, or `eve dev` when it is.## Commandsdiff --git a/packages/eve/src/cli/acp/command.ts b/packages/eve/src/cli/acp/command.tsindex 6a27a8b65..e31e673c1 100644--- a/packages/eve/src/cli/acp/command.ts+++ b/packages/eve/src/cli/acp/command.ts@@ -1,4 +1,5 @@import { Command } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";import {parseDevelopmentHeaderOption,@@ -23,7 +24,7 @@ export type ResolveVerifiedRemoteDevelopmentClient =typeof import("#setup/verified-remote-client.js").resolveVerifiedRemoteDevelopmentClient;export interface RegisterAcpCommandOptions {- readonly appRoot: string;+ readonly applicationContext: CliApplicationContext;readonly eveVersion: string;readonly program: Command;readonly resolveVerifiedRemoteDevelopmentClient?: ResolveVerifiedRemoteDevelopmentClient;@@ -33,8 +34,15 @@ export interface RegisterAcpCommandOptions {/** Registers the ACP stdio bridge for local and deployed eve agents. */export function registerAcpCommand(options: RegisterAcpCommandOptions): void {- options.program- .command("acp")+ applicationCommand(options.program.command("acp"), options.applicationContext, (command) => {+ const commandOptions = command.opts<AcpCliOptions>();+ return (+ resolveDevelopmentUrlTarget(+ commandOptions,+ command.processedArgs[0] as string | undefined,+ ) === undefined+ );+ }).description("Serve an eve agent through stable ACP v1 over stdio.").argument("[url]", "Connect to an existing server URL", parseDevelopmentServerUrl).option("-u, --url <url>", "Connect to an existing server URL", parseDevelopmentServerUrl)@@ -50,7 +58,7 @@ export function registerAcpCommand(options: RegisterAcpCommandOptions): void {).action(async (positionalUrl: string | undefined, commandOptions: AcpCliOptions) => {const target = resolveDevelopmentUrlTarget(commandOptions, positionalUrl);- loadDevelopmentEnvironmentFiles(options.appRoot);+ loadDevelopmentEnvironmentFiles(options.applicationContext.root);const lifecycle = installShutdownSignal({ exitAfterMs: FORCED_EXIT_BACKSTOP_MS });if (target !== undefined) {@@ -79,7 +87,7 @@ export function registerAcpCommand(options: RegisterAcpCommandOptions): void {try {const startHost = options.startHost ?? (await loadStartHost());- server = startHost(options.appRoot, {+ server = startHost(options.applicationContext.root, {existing: "reject",host: "127.0.0.1",output: "stderr",@@ -133,7 +141,7 @@ async function runAcp(serverUrl: serverInput.serverUrl,signal: serverInput.signal,vercelScope,- workspaceRoot: options.appRoot,+ workspaceRoot: options.applicationContext.root,});await run({auth: clientOptions.auth,diff --git a/packages/eve/src/cli/application-command.test.ts b/packages/eve/src/cli/application-command.test.tsnew file mode 100644index 000000000..b4f23aeca--- /dev/null+++ b/packages/eve/src/cli/application-command.test.ts@@ -0,0 +1,36 @@+import { Command } from "#compiled/commander/index.js";+import { describe, expect, it, vi } from "vitest";++import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";++function context(): CliApplicationContext & { resolve: ReturnType<typeof vi.fn> } {+ return { root: "/workspace", resolve: vi.fn(async () => {}) };+}++describe("applicationCommand", () => {+ it("resolves the application root before running the action", async () => {+ const applicationContext = context();+ const action = vi.fn();+ const program = new Command().exitOverride();+ applicationCommand(program.command("build"), applicationContext).action(action);++ await program.parseAsync(["build"], { from: "user" });++ expect(applicationContext.resolve).toHaveBeenCalledOnce();+ expect(action).toHaveBeenCalledOnce();+ });++ it("supports command-local conditional resolution", async () => {+ const applicationContext = context();+ const program = new Command().exitOverride();+ applicationCommand(+ program.command("invoke").option("--url <url>"),+ applicationContext,+ (command) => command.opts<{ url?: string }>().url === undefined,+ ).action(vi.fn());++ await program.parseAsync(["invoke", "--url", "https://example.com"], { from: "user" });++ expect(applicationContext.resolve).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/cli/application-command.ts b/packages/eve/src/cli/application-command.tsnew file mode 100644index 000000000..4d93ee0ed--- /dev/null+++ b/packages/eve/src/cli/application-command.ts@@ -0,0 +1,19 @@+import type { Command } from "#compiled/commander/index.js";++export interface CliApplicationContext {+ root: string;+ resolve(): Promise<void>;+}++export type CliApplicationRootRequirement = (command: Command) => boolean;++/** Adds application-root resolution to a project-scoped CLI command. */+export function applicationCommand(+ command: Command,+ applicationContext: CliApplicationContext,+ requirement: CliApplicationRootRequirement = () => true,+): Command {+ return command.hook("preAction", async (_command, actionCommand) => {+ if (requirement(actionCommand)) await applicationContext.resolve();+ });+}diff --git a/packages/eve/src/cli/application-root.test.ts b/packages/eve/src/cli/application-root.test.tsnew file mode 100644index 000000000..8f1c9d230--- /dev/null+++ b/packages/eve/src/cli/application-root.test.ts@@ -0,0 +1,80 @@+import { resolve } from "node:path";++import { describe, expect, it, vi } from "vitest";++import {+ findCliApplicationRoot,+ resolveCliApplicationRoot,+ type ResolveCliApplicationRootDependencies,+} from "#cli/application-root.js";+import {+ createDiscoverErrorDiagnostic,+ DISCOVER_PROJECT_NOT_FOUND,+} from "#discover/diagnostics.js";+import { DiscoveryProjectResolutionError } from "#discover/project.js";++function projectNotFound(path: string): DiscoveryProjectResolutionError {+ return new DiscoveryProjectResolutionError(+ createDiscoverErrorDiagnostic({+ code: DISCOVER_PROJECT_NOT_FOUND,+ message: `Could not resolve an eve agent root from "${path}".`,+ sourcePath: path,+ }),+ );+}++function dependencies(+ implementation: ResolveCliApplicationRootDependencies["resolveDiscoveryProject"],+): ResolveCliApplicationRootDependencies {+ return { resolveDiscoveryProject: vi.fn(implementation) };+}++describe("resolveCliApplicationRoot", () => {+ it("uses the application root resolved by project discovery", async () => {+ const deps = dependencies(async () => ({+ agentRoot: "/repo/agent",+ appRoot: "/repo",+ layout: "nested",+ }));++ await expect(resolveCliApplicationRoot("/repo/agent/tools", deps)).resolves.toBe("/repo");+ });++ it("finds flat application roots", async () => {+ const deps = dependencies(async () => ({+ agentRoot: "/repo/agents/billing",+ appRoot: "/repo/agents/billing",+ layout: "flat",+ }));++ await expect(findCliApplicationRoot("/repo/agents/billing", deps)).resolves.toBe(+ "/repo/agents/billing",+ );+ });++ it("returns undefined when finding from outside an application", async () => {+ const deps = dependencies(async (path) => {+ throw projectNotFound(path ?? process.cwd());+ });++ await expect(findCliApplicationRoot("/workspace/packages", deps)).resolves.toBeUndefined();+ });++ it("preserves cwd when resolving from outside an application", async () => {+ const deps = dependencies(async (path) => {+ throw projectNotFound(path ?? process.cwd());+ });++ await expect(resolveCliApplicationRoot("./workspace/packages", deps)).resolves.toBe(+ resolve("./workspace/packages"),+ );+ });++ it("does not hide unexpected discovery failures", async () => {+ const deps = dependencies(async () => {+ throw new Error("read failed");+ });++ await expect(resolveCliApplicationRoot("/workspace", deps)).rejects.toThrow("read failed");+ });+});diff --git a/packages/eve/src/cli/application-root.ts b/packages/eve/src/cli/application-root.tsnew file mode 100644index 000000000..36fd6e9af--- /dev/null+++ b/packages/eve/src/cli/application-root.ts@@ -0,0 +1,32 @@+import { resolve } from "node:path";++import { DiscoveryProjectResolutionError, resolveDiscoveryProject } from "#discover/project.js";++export interface ResolveCliApplicationRootDependencies {+ readonly resolveDiscoveryProject: typeof resolveDiscoveryProject;+}++const defaultDependencies: ResolveCliApplicationRootDependencies = {+ resolveDiscoveryProject,+};++/** Finds the nearest enclosing eve application. */+export async function findCliApplicationRoot(+ cwd: string = process.cwd(),+ dependencies: ResolveCliApplicationRootDependencies = defaultDependencies,+): Promise<string | undefined> {+ try {+ return (await dependencies.resolveDiscoveryProject(cwd)).appRoot;+ } catch (error) {+ if (error instanceof DiscoveryProjectResolutionError) return undefined;+ throw error;+ }+}++/** Uses the nearest enclosing eve application, or preserves cwd when none exists. */+export async function resolveCliApplicationRoot(+ cwd: string = process.cwd(),+ dependencies: ResolveCliApplicationRootDependencies = defaultDependencies,+): Promise<string> {+ return (await findCliApplicationRoot(cwd, dependencies)) ?? resolve(cwd);+}diff --git a/packages/eve/src/cli/commands/build.ts b/packages/eve/src/cli/commands/build.tsindex d7684dcaa..37fe325fa 100644--- a/packages/eve/src/cli/commands/build.ts+++ b/packages/eve/src/cli/commands/build.ts@@ -1,6 +1,7 @@import { resolve } from "node:path";import type { Command } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";import { resolveInternalVercelServiceOutput } from "#cli/vercel-service-output.js";import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";import type { ApplicationBuildOptions } from "#internal/nitro/host/types.js";@@ -22,15 +23,14 @@ interface BuildCliOptions {/** Registers the production application build command. */export function registerBuildCommand(input: {- readonly appRoot: string;+ readonly applicationContext: CliApplicationContext;readonly buildHost?: BuildHost;readonly logger: BuildCommandLogger;readonly program: Command;}): void {const theme = createCliTheme();- input.program- .command("build")+ applicationCommand(input.program.command("build"), input.applicationContext).description("Build the current eve application.").option("--profile <path>", "Write best-effort timing and output-size profile JSON to a file").option(@@ -40,12 +40,14 @@ export function registerBuildCommand(input: {.action(async (options: BuildCliOptions) => {const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");- loadDevelopmentEnvironmentFiles(input.appRoot);+ loadDevelopmentEnvironmentFiles(input.applicationContext.root);const buildHost =input.buildHost ?? (await import("#internal/nitro/host.js")).buildApplication;const profileOutputPath =- options.profile === undefined ? undefined : resolve(input.appRoot, options.profile);+ options.profile === undefined+ ? undefined+ : resolve(input.applicationContext.root, options.profile);const buildOptions: {profileOutputPath?: string;readonly publicRoutePrefix: ApplicationBuildOptions["publicRoutePrefix"];@@ -54,12 +56,12 @@ export function registerBuildCommand(input: {} = {publicRoutePrefix: normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]),skipVercelSandboxPrewarm: options.skipSandboxPrewarm === true,- vercelServiceOutput: resolveInternalVercelServiceOutput(input.appRoot),+ vercelServiceOutput: resolveInternalVercelServiceOutput(input.applicationContext.root),};if (profileOutputPath !== undefined) {buildOptions.profileOutputPath = profileOutputPath;}- const outputDir = await buildHost(input.appRoot, buildOptions);+ const outputDir = await buildHost(input.applicationContext.root, buildOptions);input.logger.log(renderCliTaggedLine(theme, {message: `built output at ${outputDir}`,diff --git a/packages/eve/src/cli/commands/register-integration-commands.ts b/packages/eve/src/cli/commands/register-integration-commands.tsindex 48c15ccab..c3bf0e18c 100644--- a/packages/eve/src/cli/commands/register-integration-commands.ts+++ b/packages/eve/src/cli/commands/register-integration-commands.ts@@ -1,4 +1,5 @@import type { Command } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";import { parseSetupAnswer } from "./setup-answers.js";@@ -11,14 +12,13 @@ interface IntegrationCommandLogger {export function registerIntegrationCommands(input: {program: Command;logger: IntegrationCommandLogger;- appRoot: string;+ applicationContext: CliApplicationContext;}): void {- const { appRoot, logger, program } = input;+ const { applicationContext, logger, program } = input;const integration = program.command("integration", { hidden: true });- integration- .command("setup <kind>")+ applicationCommand(integration.command("setup <kind>"), applicationContext).option("-y, --yes").option("--non-interactive",@@ -40,7 +40,7 @@ export function registerIntegrationCommands(input: {},) => {const { runIntegrationSetupCommand } = await import("./integration-setup.js");- await runIntegrationSetupCommand(logger, appRoot, kind, {+ await runIntegrationSetupCommand(logger, applicationContext.root, kind, {yes: options.yes,nonInteractive: options.nonInteractive,answers: options.answer,@@ -48,8 +48,10 @@ export function registerIntegrationCommands(input: {},);- integration- .command("connect <slug> <service> [canonical-name]")+ applicationCommand(+ integration.command("connect <slug> <service> [canonical-name]"),+ applicationContext,+ ).option("-y, --yes").option("--non-interactive",@@ -63,7 +65,14 @@ export function registerIntegrationCommands(input: {options: { nonInteractive?: boolean },) => {const { runIntegrationConnectCommand } = await import("./integration-connect.js");- await runIntegrationConnectCommand(logger, appRoot, slug, service, canonicalName, options);+ await runIntegrationConnectCommand(+ logger,+ applicationContext.root,+ slug,+ service,+ canonicalName,+ options,+ );},);}diff --git a/packages/eve/src/cli/commands/register-project-commands.ts b/packages/eve/src/cli/commands/register-project-commands.tsindex 6c28c3607..9890cb1df 100644--- a/packages/eve/src/cli/commands/register-project-commands.ts+++ b/packages/eve/src/cli/commands/register-project-commands.ts@@ -1,4 +1,5 @@import type { Command } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";interface ProjectCommandLogger {error(message: string): void;@@ -9,21 +10,19 @@ interface ProjectCommandLogger {export function registerProjectCommands(input: {program: Command;logger: ProjectCommandLogger;- appRoot: string;+ applicationContext: CliApplicationContext;}): void {- input.program- .command("link")+ applicationCommand(input.program.command("link"), input.applicationContext).description("Link this directory to a Vercel project and pull AI Gateway credentials.").action(async () => {const { runLinkCommand } = await import("./link.js");- await runLinkCommand(input.logger, input.appRoot);+ await runLinkCommand(input.logger, input.applicationContext.root);});- input.program- .command("deploy")+ applicationCommand(input.program.command("deploy"), input.applicationContext).description("Deploy the agent to Vercel production (links first if needed).").action(async () => {const { runDeployCommand } = await import("./deploy.js");- await runDeployCommand(input.logger, input.appRoot);+ await runDeployCommand(input.logger, input.applicationContext.root);});}diff --git a/packages/eve/src/cli/commands/register-registry-commands.ts b/packages/eve/src/cli/commands/register-registry-commands.tsindex 9582c6ec9..3912f235b 100644--- a/packages/eve/src/cli/commands/register-registry-commands.ts+++ b/packages/eve/src/cli/commands/register-registry-commands.ts@@ -1,4 +1,5 @@import { InvalidArgumentError, type Command } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";import { parseSetupAnswer } from "./setup-answers.js";@@ -28,12 +29,11 @@ function parseSearchLimit(value: string): number {export function registerRegistryCommands(input: {program: Command;logger: RegistryCommandLogger;- appRoot: string;+ applicationContext: CliApplicationContext;}): void {- const { appRoot, logger, program } = input;+ const { applicationContext, logger, program } = input;- program- .command("add <item>")+ applicationCommand(program.command("add <item>"), applicationContext).description("Install a registry item; relative paths use the official eve registry.").option("-o, --overwrite", "Overwrite existing files.").option("--skip-install", "Run the item's setup flow without installing it.")@@ -64,7 +64,10 @@ export function registerRegistryCommands(input: {throw new InvalidArgumentError("--answer requires --non-interactive.");}const { runAddCommand } = await import("./registry.js");- await runAddCommand(logger, appRoot, item, { ...options, answers: options.answer });+ await runAddCommand(logger, applicationContext.root, item, {+ ...options,+ answers: options.answer,+ });},);@@ -72,26 +75,23 @@ export function registerRegistryCommands(input: {.command("registry").description("Configure and browse extension and agent registry catalogs.");- registry- .command("add <registries...>")+ applicationCommand(registry.command("add <registries...>"), applicationContext).description("Add registry namespace mappings to package.json.").action(async (registries: string[]) => {const { runRegistryAddCommand } = await import("./registry.js");- await runRegistryAddCommand(logger, appRoot, registries);+ await runRegistryAddCommand(logger, applicationContext.root, registries);});- registry- .command("list")+ applicationCommand(registry.command("list"), applicationContext).description("List items from all registries or one source.").option("-r, --registry <source>", "List items from one registry.").option("--json", "Output as JSON").action(async (options: { json?: boolean; registry?: string }) => {const { runRegistryListCommand } = await import("./registry.js");- await runRegistryListCommand(logger, appRoot, options.registry, options);+ await runRegistryListCommand(logger, applicationContext.root, options.registry, options);});- registry- .command("search <query>")+ applicationCommand(registry.command("search <query>"), applicationContext).description("Search all registries or one source.").option("-r, --registry <source>", "Search one registry.").option(@@ -104,16 +104,21 @@ export function registerRegistryCommands(input: {.action(async (query: string, options: { json?: boolean; limit: number; registry?: string }) => {const { runRegistrySearchCommand } = await import("./registry.js");- await runRegistrySearchCommand(logger, appRoot, query, options.registry, options);+ await runRegistrySearchCommand(+ logger,+ applicationContext.root,+ query,+ options.registry,+ options,+ );},);- registry- .command("view <item>")+ applicationCommand(registry.command("view <item>"), applicationContext).description("Inspect one registry item.").option("--json", "Output the raw registry item as JSON.").action(async (item: string, options: { json?: boolean }) => {const { runRegistryViewCommand } = await import("./registry.js");- await runRegistryViewCommand(logger, appRoot, item, options);+ await runRegistryViewCommand(logger, applicationContext.root, item, options);});}diff --git a/packages/eve/src/cli/invoke/command.ts b/packages/eve/src/cli/invoke/command.tsindex 4a51cda34..d0c788893 100644--- a/packages/eve/src/cli/invoke/command.ts+++ b/packages/eve/src/cli/invoke/command.ts@@ -1,4 +1,5 @@import { type Command, InvalidArgumentError } from "#compiled/commander/index.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";import {parseDevelopmentHeaderOption,resolveDevelopmentUrlTarget,@@ -37,7 +38,7 @@ interface InvokeCommandLogger {/** Registers the invoke command with lazily loaded production dependencies. */export function registerRuntimeInvokeCommand(input: {- readonly appRoot: string;+ readonly applicationContext: CliApplicationContext;readonly logger: InvokeCommandLogger;readonly program: Command;readonly runtime: Partial<InvokeCliRuntimeDependencies>;@@ -60,13 +61,15 @@ export function registerRuntimeInvokeCommand(input: {/** Registers the non-interactive invoke command. */export function registerInvokeCommand(input: {- readonly appRoot: string;+ readonly applicationContext: CliApplicationContext;readonly deps: InvokeCommandDependencies;readonly logger: InvokeCommandLogger;readonly program: Command;}): void {- input.program- .command("invoke")+ applicationCommand(input.program.command("invoke"), input.applicationContext, (command) => {+ const options = command.opts<InvokeCliOptions>();+ return options.url === undefined && options.jsonSchema !== true;+ }).description("Invoke an eve agent without a terminal UI.").argument("[prompt]", "Prompt, follow-up message, or answer to a pending input").option("-u, --url <url>", "Invoke an existing server URL", parseDevelopmentServerUrl)@@ -84,7 +87,7 @@ export function registerInvokeCommand(input: {}async function runInvokeCommand(input: {- readonly appRoot: string;+ readonly applicationContext: CliApplicationContext;readonly deps: InvokeCommandDependencies;readonly logger: InvokeCommandLogger;readonly options: InvokeCliOptions;@@ -124,14 +127,14 @@ async function runInvokeCommand(input: {}const operation = resolveInvokeOperation({ previous, prompt: input.prompt });- await input.deps.loadEnvironment(input.appRoot);+ await input.deps.loadEnvironment(input.applicationContext.root);if (remoteTarget !== undefined) {await executeWithSignals(input,{kind: "remote",serverUrl: remoteTarget.serverUrl,- workspaceRoot: input.appRoot,+ workspaceRoot: input.applicationContext.root,},remoteTarget.headers,operation,@@ -140,7 +143,7 @@ async function runInvokeCommand(input: {return;}- const server = await input.deps.startHost(input.appRoot);+ const server = await input.deps.startHost(input.applicationContext.root);try {const handle = await server.start();await executeWithSignals(diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.tsindex 9a34439aa..a61063733 100644--- a/packages/eve/src/cli/run.test.ts+++ b/packages/eve/src/cli/run.test.ts@@ -12,6 +12,9 @@ const { runInitCommand, runSetCommand } = vi.hoisted(() => ({runSetCommand: vi.fn(async () => {}),}));+vi.mock("#cli/application-root.js", () => ({+ resolveCliApplicationRoot: vi.fn(async (cwd: string) => cwd),+}));vi.mock("#cli/commands/init.js", () => ({ runInitCommand }));vi.mock("#cli/commands/set.js", () => ({ runSetCommand }));@@ -77,6 +80,36 @@ describe("CLI command registration", () => {});});+ it("runs project commands with the resolved application root", async () => {+ const logger = { error: vi.fn(), log: vi.fn() };+ const resolveRoot = vi.fn(async () => "/workspace/weather");+ runSetCommand.mockClear();++ await runCli(["set", "--model", "openai/gpt-5.6-sol"], logger, {+ resolveApplicationRoot: resolveRoot,+ });++ expect(resolveRoot).toHaveBeenCalledWith(resolve(process.cwd()));+ expect(runSetCommand).toHaveBeenCalledWith(logger, "/workspace/weather", {+ model: "openai/gpt-5.6-sol",+ reasoning: undefined,+ });+ });++ it("does not resolve an application root for command help", async () => {+ const resolveRoot = vi.fn(async () => "/workspace/weather");++ await runCli(+ ["set", "--help"],+ { error: vi.fn(), log: vi.fn() },+ {+ resolveApplicationRoot: resolveRoot,+ },+ );++ expect(resolveRoot).not.toHaveBeenCalled();+ });+it("lists model and reasoning options for the set command", async () => {const output: string[] = [];@@ -185,12 +218,12 @@ describe("CLI command registration", () => {describe("bare eve command", () => {it("runs init in the current directory when no eve project is detected", async () => {const logger = { error: vi.fn(), log: vi.fn() };- const isEveProject = vi.fn(async () => false);+ const findApplicationRoot = vi.fn(async () => undefined);runInitCommand.mockClear();- await runCli([], logger, { isEveProject });+ await runCli([], logger, { findApplicationRoot });- expect(isEveProject).toHaveBeenCalledWith(resolve(process.cwd()));+ expect(findApplicationRoot).toHaveBeenCalledWith(resolve(process.cwd()));expect(runInitCommand).toHaveBeenCalledWith(logger, resolve(process.cwd()), undefined, {channelWebNextjs: undefined,model: undefined,@@ -198,9 +231,9 @@ describe("bare eve command", () => {});});- it("runs dev when an eve project is detected", async () => {+ it("runs dev from the enclosing eve application", async () => {const logger = { error: vi.fn(), log: vi.fn() };- const isEveProject = vi.fn(async () => true);+ const findApplicationRoot = vi.fn(async () => "/resolved/app");const close = vi.fn(async () => {});const startHost = vi.fn(() => ({start: async () => ({@@ -214,11 +247,11 @@ describe("bare eve command", () => {runInitCommand.mockClear();await withInteractiveTerminal(() =>- runCli([], logger, { isEveProject, runDevelopmentTui, startHost }),+ runCli([], logger, { findApplicationRoot, runDevelopmentTui, startHost }),);- expect(isEveProject).toHaveBeenCalledWith(resolve(process.cwd()));- expect(startHost).toHaveBeenCalledWith(resolve(process.cwd()), {+ expect(findApplicationRoot).toHaveBeenCalledWith(resolve(process.cwd()));+ expect(startHost).toHaveBeenCalledWith("/resolved/app", {existing: "attach-if-unconfigured",host: undefined,onBootProgress: expect.any(Function),@@ -232,11 +265,11 @@ describe("bare eve command", () => {it("does not inspect the project when a command is explicit", async () => {const logger = { error: vi.fn(), log: vi.fn() };- const isEveProject = vi.fn(async () => false);+ const findApplicationRoot = vi.fn(async () => undefined);- await runCli(["init"], logger, { isEveProject });+ await runCli(["init"], logger, { findApplicationRoot });- expect(isEveProject).not.toHaveBeenCalled();+ expect(findApplicationRoot).not.toHaveBeenCalled();});});@@ -443,16 +476,18 @@ describe("eve invoke", () => {);});- it("prints the JSON schema without invoking an agent", async () => {+ it("prints the JSON schema without resolving or invoking an agent", async () => {const runInvoke = vi.fn();+ const resolveRoot = vi.fn(async () => "/workspace/weather");const output: string[] = [];await runCli(["invoke", "--json-schema"],{ error: () => {}, log: (message) => output.push(message) },- { runInvoke },+ { resolveApplicationRoot: resolveRoot, runInvoke },);+ expect(resolveRoot).not.toHaveBeenCalled();expect(runInvoke).not.toHaveBeenCalled();expect(JSON.parse(output[0]!)).toMatchObject({ title: "eve invoke result" });});@@ -468,6 +503,16 @@ describe("eve invoke", () => {});describe("eve dev --url protocol", () => {+ it("does not resolve a local application for a remote URL", async () => {+ const resolveRoot = vi.fn(async () => "/workspace/weather");++ await runInteractiveDev(["dev", "https://example.com"], {+ resolveApplicationRoot: resolveRoot,+ });++ expect(resolveRoot).not.toHaveBeenCalled();+ });+it("preserves query parameters on the remote target URL", async () => {const runDevelopmentTui = await runInteractiveDev(["dev",diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 73fb32018..8c6ae4133 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -4,6 +4,8 @@ import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-pimport { resolveApplicationRoot } from "#internal/application/paths.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isCodingAgentLaunch } from "#cli/agent-detection.js";+import { applicationCommand, type CliApplicationContext } from "#cli/application-command.js";+import { findCliApplicationRoot, resolveCliApplicationRoot } from "#cli/application-root.js";import { eveCliBanner } from "#cli/banner.js";import { registerIntegrationCommands } from "#cli/commands/register-integration-commands.js";import { registerProjectCommands } from "#cli/commands/register-project-commands.js";@@ -62,7 +64,7 @@ interface CliLogger {interface CliRuntimeDependencies {isCodingAgentLaunch(): Promise<boolean>;- isEveProject(appRoot: string): Promise<boolean>;+ findApplicationRoot(cwd: string): Promise<string | undefined>;isActiveDevelopmentServerForApp(input: {readonly appRoot: string;readonly serverUrl: string;@@ -81,8 +83,10 @@ interface CliRuntimeDependencies {evalIds: readonly string[],options: EvalCliOptions,logger: CliLogger,+ appRoot: string,): Promise<void>;startHost(appRoot: string, options?: DevelopmentServerOptions): DevelopmentServer;+ resolveApplicationRoot(cwd: string): Promise<string>;startProductionHost(appRoot: string,options?: {@@ -135,10 +139,6 @@ async function loadStartHost(): Promise<CliRuntimeDependencies["startHost"]> {return (await import("#cli/dev/local-server-process.js")).createDevelopmentServer;}-async function loadIsEveProject(): Promise<CliRuntimeDependencies["isEveProject"]> {- return (await import("#setup/scaffold/index.js")).isEveProject;-}-const loadIsActiveDevelopmentServerForApp = async () =>(await import("#internal/nitro/host.js")).isActiveDevelopmentServerForApp;@@ -153,7 +153,7 @@ function hasInteractiveTerminal(): boolean {function createCliProgram(logger: CliLogger,runtime: CliRuntimeOverrides,- appRoot: string,+ applicationContext: CliApplicationContext,): Command {const packageVersion = resolveInstalledPackageInfo().version;const program = new Command();@@ -179,18 +179,21 @@ function createCliProgram(},});- program- .command("channels")- .description("Manage user-authored channels in the current project.")- .command("list")+ applicationCommand(+ program+ .command("channels")+ .description("Manage user-authored channels in the current project.")+ .command("list"),+ applicationContext,+ ).description("List user-authored channels in the current project.").option("--json", "Output as JSON").action(async (options: { json?: boolean }) => {const { runChannelsListCommand } = await import("#cli/commands/channels.js");- await runChannelsListCommand(logger, appRoot, options);+ await runChannelsListCommand(logger, applicationContext.root, options);});- registerIntegrationCommands({ program, logger, appRoot });+ registerIntegrationCommands({ program, logger, applicationContext });const extension = program.command("extension")@@ -208,7 +211,7 @@ function createCliProgram(}const { runExtensionInitCommand } = await import("#cli/commands/extension-init.js");- await runExtensionInitCommand(logger, appRoot, target);+ await runExtensionInitCommand(logger, applicationContext.root, target);});extension@@ -216,13 +219,13 @@ function createCliProgram(.description("Build the current package as an eve extension.").action(async () => {const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");- loadDevelopmentEnvironmentFiles(appRoot);+ loadDevelopmentEnvironmentFiles(applicationContext.root);const { runExtensionBuildCommand } = await import("#cli/commands/extension-build.js");- await runExtensionBuildCommand(logger, appRoot);+ await runExtensionBuildCommand(logger, applicationContext.root);});- registerRegistryCommands({ program, logger, appRoot });+ registerRegistryCommands({ program, logger, applicationContext });program// Optional: a missing target scaffolds or updates the current directory,@@ -252,7 +255,7 @@ function createCliProgram(}const { runInitCommand } = await import("#cli/commands/init.js");- await runInitCommand(logger, appRoot, target, {+ await runInitCommand(logger, applicationContext.root, target, {channelWebNextjs: options.channelWebNextjs,model: options.model,reasoning: options.reasoning,@@ -260,8 +263,7 @@ function createCliProgram(},);- program- .command("set")+ applicationCommand(program.command("set"), applicationContext).description("Change root agent model settings.").option("--model <model>", "Set the agent model (provider/model-id)").option(@@ -271,30 +273,29 @@ function createCliProgram().action(async (options: { model?: string; reasoning?: AgentReasoningDefinition }) => {const { runSetCommand } = await import("#cli/commands/set.js");- await runSetCommand(logger, appRoot, options);+ await runSetCommand(logger, applicationContext.root, options);});- registerProjectCommands({ program, logger, appRoot });+ registerProjectCommands({ program, logger, applicationContext });registerBuildCommand({- appRoot,+ applicationContext,buildHost: runtime.buildHost,logger,program,});- program- .command("start")+ applicationCommand(program.command("start"), applicationContext).description("Start a built eve application.").option("--host <host>", "Host interface to bind").option("--port <port>", "Port to listen on (defaults to $PORT, then 3000)", parsePortOption).action(async (options: ProductionCliOptions) => {const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");- loadDevelopmentEnvironmentFiles(appRoot);+ loadDevelopmentEnvironmentFiles(applicationContext.root);const startProductionHost = runtime.startProductionHost ?? (await loadStartProductionHost());- const server = await startProductionHost(appRoot, {+ const server = await startProductionHost(applicationContext.root, {host: options.host,port: options.port,});@@ -310,10 +311,10 @@ function createCliProgram(await waitForShutdownSignal({ close: () => server.close(), wait: () => server.wait() });});- registerRuntimeInvokeCommand({ appRoot, logger, program, runtime });+ registerRuntimeInvokeCommand({ applicationContext, logger, program, runtime });registerAcpCommand({- appRoot,+ applicationContext,eveVersion: packageVersion,program,resolveVerifiedRemoteDevelopmentClient: runtime.resolveVerifiedRemoteDevelopmentClient,@@ -321,8 +322,13 @@ function createCliProgram(startHost: runtime.startHost,});- program- .command("dev")+ applicationCommand(program.command("dev"), applicationContext, (command) => {+ const options = command.opts<DevelopmentCliOptions>();+ return (+ resolveDevelopmentUrlTarget(options, command.processedArgs[0] as string | undefined) ===+ undefined+ );+ }).description("Start the eve development server or connect to an existing URL.").argument("[url]", "Connect to an existing server URL", parseDevelopmentServerUrl).option("--host <host>", "Host interface to bind")@@ -387,7 +393,10 @@ function createCliProgram(if (remoteServerUrl !== undefined) {const isActive =runtime.isActiveDevelopmentServerForApp ?? (await loadIsActiveDevelopmentServerForApp());- existingLocalDevelopmentServer = await isActive({ appRoot, serverUrl: remoteServerUrl });+ existingLocalDevelopmentServer = await isActive({+ appRoot: applicationContext.root,+ serverUrl: remoteServerUrl,+ });}const runInteractiveUi = async (input: {@@ -408,9 +417,13 @@ function createCliProgram(? {kind: "local",serverUrl: input.serverUrl,- workspaceRoot: input.appRoot ?? appRoot,+ workspaceRoot: input.appRoot ?? applicationContext.root,}- : { kind: "remote", serverUrl: input.serverUrl, workspaceRoot: appRoot };+ : {+ kind: "remote",+ serverUrl: input.serverUrl,+ workspaceRoot: applicationContext.root,+ };const title = resolveTuiTitle({ name: options.name, target });if (title !== undefined) display.name = title;const tuiInput: RunDevelopmentTuiInput = {@@ -447,7 +460,7 @@ function createCliProgram(if (remoteServerUrl) {const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");- loadDevelopmentEnvironmentFiles(appRoot);+ loadDevelopmentEnvironmentFiles(applicationContext.root);logger.log(`↗ ${existingLocalDevelopmentServer ? "local" : "remote"} mode targeting ${theme.info(new URL(remoteServerUrl).host)}`,);@@ -495,7 +508,7 @@ function createCliProgram(try {const startHost = runtime.startHost ?? (await loadStartHost());- server = startHost(appRoot, {+ server = startHost(applicationContext.root, {existing: mode === "tui" ? "attach-if-unconfigured" : "reject",host: options.host,onBootProgress,@@ -555,27 +568,24 @@ function createCliProgram(.command("logs").description("Inspect local `eve dev` diagnostic logs (.eve/logs).");- logs- .command("show [logid]", { isDefault: true })+ applicationCommand(logs.command("show [logid]", { isDefault: true }), applicationContext).description("Print a diagnostic log (the most recent when logid is omitted).").option("--dump", "Prepend the log's environment dump (.dump sibling)").option("--events", "Interleave session events from the local workflow store").action(async (logId: string | undefined, options: { dump?: boolean; events?: boolean }) => {const { runLogsShowCommand } = await import("#cli/commands/logs.js");- await runLogsShowCommand(logger, appRoot, logId, options);+ await runLogsShowCommand(logger, applicationContext.root, logId, options);});- logs- .command("ls")+ applicationCommand(logs.command("ls"), applicationContext).description("List diagnostic logs, most recent first.").option("--json", "Output as JSON").action(async (options: { json?: boolean }) => {const { runLogsListCommand } = await import("#cli/commands/logs.js");- await runLogsListCommand(logger, appRoot, options);+ await runLogsListCommand(logger, applicationContext.root, options);});- const traces = program- .command("traces [trace]")+ const traces = applicationCommand(program.command("traces [trace]"), applicationContext).usage("[options] [trace]\n eve traces ls [options]").description("Show a local `eve dev` trace (the most recent when trace is omitted).").option("--verbose", "Expand every span with all attributes and events")@@ -583,7 +593,7 @@ function createCliProgram(.action(async (reference: string | undefined, options: { json?: boolean; verbose?: boolean }) => {const { runTraceShowCommand } = await import("#cli/commands/trace.js");- await runTraceShowCommand(logger, appRoot, reference, options);+ await runTraceShowCommand(logger, applicationContext.root, reference, options);},);@@ -593,21 +603,19 @@ function createCliProgram(.option("--json", "Output as JSON").action(async (options: { json?: boolean }) => {const { runTraceListCommand } = await import("#cli/commands/trace.js");- await runTraceListCommand(logger, appRoot, options);+ await runTraceListCommand(logger, applicationContext.root, options);});- program- .command("info")+ applicationCommand(program.command("info"), applicationContext).description("Print resolved application information.").option("--json", "Output as JSON").action(async (options: { json?: boolean }) => {const printApplicationInfo =runtime.printApplicationInfo ?? (await loadPrintApplicationInfo());- await printApplicationInfo(logger, appRoot, options);+ await printApplicationInfo(logger, applicationContext.root, options);});- program- .command("eval")+ applicationCommand(program.command("eval"), applicationContext).description("Run evals against an eve agent.").argument("[evalIds...]",@@ -626,7 +634,7 @@ function createCliProgram(.option("--verbose", "Stream per-eval t.log lines to stdout").action(async (evalIds: string[], options: EvalCliOptions) => {const runEvalCommand = runtime.runEvalCommand ?? (await loadRunEvalCommand());- await runEvalCommand(evalIds, options, logger);+ await runEvalCommand(evalIds, options, logger, applicationContext.root);});return program;@@ -640,12 +648,25 @@ export async function runCli(logger: CliLogger = console,runtime: CliRuntimeOverrides = {},): Promise<void> {- const appRoot = resolveApplicationRoot();- const program = createCliProgram(logger, runtime, appRoot);+ const applicationContext: CliApplicationContext = {+ root: resolveApplicationRoot(),+ async resolve() {+ applicationContext.root = await (runtime.resolveApplicationRoot ?? resolveCliApplicationRoot)(+ applicationContext.root,+ );+ },+ };+ const program = createCliProgram(logger, runtime, applicationContext);let input = argv;if (input.length === 0) {- const detectEveProject = runtime.isEveProject ?? (await loadIsEveProject());- input = [(await detectEveProject(appRoot)) ? "dev" : "init"];+ const findApplicationRoot = runtime.findApplicationRoot ?? findCliApplicationRoot;+ const appRoot = await findApplicationRoot(applicationContext.root);+ if (appRoot === undefined) {+ input = ["init"];+ } else {+ applicationContext.root = appRoot;+ input = ["dev"];+ }}try {diff --git a/packages/eve/src/evals/cli/eval.ts b/packages/eve/src/evals/cli/eval.tsindex 2ed4991ac..6dd54ed0b 100644--- a/packages/eve/src/evals/cli/eval.ts+++ b/packages/eve/src/evals/cli/eval.ts@@ -8,7 +8,6 @@ import {EVE_EVALUATION_ENV_FLAG,EVE_EVALUATION_RUN_ID_ENV,} from "#internal/application/dev-environment.js";-import { resolveApplicationRoot } from "#internal/application/paths.js";import { createDevelopmentServer, type DevelopmentServer } from "#internal/nitro/host.js";import { createEvalClient } from "#evals/cli/eval-client.js";import { filterEvalsByTags } from "#evals/cli/filter.js";@@ -54,9 +53,8 @@ export async function runEvalCommand(evalIds: readonly string[],options: EvalCliOptions,logger: EvalCliLogger,+ appRoot: string = process.cwd(),): Promise<void> {- const appRoot = resolveApplicationRoot();-loadDevelopmentEnvironmentFiles(appRoot);const requestedEvalIds = evalIds.length > 0 ? evalIds : undefined;diff --git a/packages/eve/test/scenarios/cli.scenario.test.ts b/packages/eve/test/scenarios/cli.scenario.test.tsindex 55726c922..4177e3d15 100644--- a/packages/eve/test/scenarios/cli.scenario.test.ts+++ b/packages/eve/test/scenarios/cli.scenario.test.ts@@ -283,7 +283,7 @@ describe("runCli", () => {error: vi.fn(),log: vi.fn(),};- const isEveProject = vi.fn(async () => true);+ const findApplicationRoot = vi.fn(async () => process.cwd());const startHost = vi.fn(() => ({start: async () => {throw new Error("dev started");@@ -293,12 +293,12 @@ describe("runCli", () => {await expect(runCli([], logger, {- isEveProject,+ findApplicationRoot,startHost,}),).rejects.toThrow("dev started");- expect(isEveProject).toHaveBeenCalledOnce();+ expect(findApplicationRoot).toHaveBeenCalledOnce();expect(startHost).toHaveBeenCalledOnce();});