The Open Framework for Building Agents
feat(selfmod): install registry items from the subagent (#2639)
prhab7ac28401cab
diff --git a/.changeset/selfmod-registry-add.md b/.changeset/selfmod-registry-add.mdnew file mode 100644index 000000000..20de73336--- /dev/null+++ b/.changeset/selfmod-registry-add.md@@ -0,0 +1,15 @@+---+"@eve/self-modification": patch+"eve": patch+---++The self-modification subagent can now install items from the configured eve+registry. A new `selfmod__registry_add` tool runs `eve add <address>+--non-interactive --skip-setup` in the application root under `eve dev`,+pausing the authored-source watcher for the whole install and reporting the+item's declared environment variables that are still unset. Failed dependency+installs restore tracked project files and return a sanitized, structured reason+instead of implying the project was untouched. Items that declare a setup flow+or multiple components are never partially installed: they are reported back+untouched with the command that finishes them, so no setup question is ever+answered by the model.diff --git a/packages/eve-self-modification/README.md b/packages/eve-self-modification/README.mdindex cc2e93101..a0fc7a646 100644--- a/packages/eve-self-modification/README.md+++ b/packages/eve-self-modification/README.md@@ -37,4 +37,12 @@ Set `model` in the agent definition to choose the self-modification subagent's mThe extension contributes `selfmod__edit_file` for one or more exact targeted edits to an existing file without rewriting it. Its instructions direct independent discovery calls to run concurrently and reserve `write_file` for new files or complete rewrites.-The extension also provides `selfmod__search_registry` to search the eve registry for channels, connections, extensions, and other integrations the project can add. Registry search is read-only: it reports each item's address, whether the authored tree already holds it, and the eve version it requires. Registry installation is outside the source sandbox. In a local `eve dev` session, the subagent recommends `/add channel/slack`; you enter the command, review the item and its changes, and complete its setup prompts.+The extension also provides `selfmod__search_registry` to search the eve registry for channels, connections, extensions, and other integrations the project can add. Registry search is read-only: it reports each item's address, whether the authored tree already holds it, and the eve version it requires.++## Installing registry items++`selfmod__registry_add` installs an item from the configured eve registry — `eve add <address> --non-interactive --skip-setup` in the application root — so the subagent can add an existing integration instead of hand-writing one. It runs only under `eve dev`, requires approval the first time per session, and holds the authored-source watcher suspended for the whole install.++It installs only items that declare no setup command and no components. An item that declares either is reported back untouched, with the command that completes it: setup flows ask for credentials and open browser authorizations, and neither can be answered from a chat turn. No setup question ever reaches the model, and no secret ever enters the transcript.++An installed item's result names the environment variables it declares that are not set, so an item that installed cleanly but cannot yet work is reported as such rather than as bare success.diff --git a/packages/eve-self-modification/extension/classify-registry-item.ts b/packages/eve-self-modification/extension/classify-registry-item.tsnew file mode 100644index 000000000..853401713--- /dev/null+++ b/packages/eve-self-modification/extension/classify-registry-item.ts@@ -0,0 +1,31 @@+import type { CatalogEntry } from "./tools/search_registry.js";++/**+ * The split rule.+ *+ * An item that declares no setup and no components is installed by the tool. An+ * item that declares either is handed to the terminal whole, before anything is+ * installed — every question a setup flow asks, and every browser+ * authorization or secret it needs, belongs to the surface built to ask.+ *+ * The rule reads catalog metadata only. It never predicts whether a particular+ * setup would in fact ask something, because a wrong prediction installs half+ * an item and reports success.+ */+export function classifyCatalogEntry(+ entry: CatalogEntry,+): { readonly kind: "installable" } | { readonly kind: "needs-terminal"; readonly reason: string } {+ if (entry.components !== undefined && entry.components.length > 0) {+ return {+ kind: "needs-terminal",+ reason: `${entry.address} is a bundle of ${entry.components.join(", ")}. Choosing which components to install is a question, so the whole bundle goes to the terminal.`,+ };+ }+ if (entry.declaresSetup === true) {+ return {+ kind: "needs-terminal",+ reason: `${entry.address} declares a setup flow, which can ask for credentials or open a browser authorization. Neither can be answered from a chat turn.`,+ };+ }+ return { kind: "installable" };+}diff --git a/packages/eve-self-modification/extension/eve-add.ts b/packages/eve-self-modification/extension/eve-add.tsnew file mode 100644index 000000000..9c54fad94--- /dev/null+++ b/packages/eve-self-modification/extension/eve-add.ts@@ -0,0 +1,272 @@+import { spawn as nodeSpawn, spawnSync } from "node:child_process";+import { readFile } from "node:fs/promises";+import { findPackageJSON } from "node:module";+import { dirname, isAbsolute, relative, resolve } from "node:path";+import { pathToFileURL } from "node:url";++/**+ * An install runs the project's package manager, which is slow but not+ * unbounded. The cap exists so a wedged child cannot hold the authored-source+ * watcher suspended for the rest of the session.+ */+const INSTALL_TIMEOUT_MS = 10 * 60_000;+const TERMINATION_GRACE_MS = 5_000;+/** Enough to retain the terminal protocol event without accumulating child output indefinitely. */+const OUTPUT_LIMIT = 64_000;++/** Minimal spawn surface, injectable so tests need no real child process. */+export type SpawnLike = typeof nodeSpawn;++export type EveAddOutcome =+ | { readonly kind: "installed" }+ /** The child ended in a state that needs a terminal (a setup question). */+ | { readonly kind: "blocked"; readonly message: string }+ | {+ readonly kind: "failed";+ readonly message: string;+ readonly changed?: readonly string[];+ };++interface HeadlessEvent {+ readonly version?: number;+ readonly type: string;+ readonly item?: string;+ readonly message?: string;+ readonly failureCode?: string;+ readonly rolledBack?: boolean;+ readonly changed?: readonly string[];+}++function terminateChildTree(child: ReturnType<SpawnLike>, signal: NodeJS.Signals): void {+ if (child.pid !== undefined) {+ if (process.platform === "win32") {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (systemRoot !== undefined && systemRoot !== "") {+ const result = spawnSync(+ resolve(systemRoot, "System32", "taskkill.exe"),+ ["/pid", String(child.pid), "/t", ...(signal === "SIGKILL" ? ["/f"] : [])],+ { stdio: "ignore", windowsHide: true },+ );+ if (result.status === 0) return;+ }+ } else {+ try {+ process.kill(-child.pid, signal);+ return;+ } catch {}+ }+ }+ child.kill(signal);+}++function isChildTreeAlive(child: ReturnType<SpawnLike>): boolean {+ if (process.platform === "win32" || child.pid === undefined) return false;+ try {+ process.kill(-child.pid, 0);+ return true;+ } catch {+ return false;+ }+}++/**+ * Resolves the `eve` executable the way eve already resolves setup binaries:+ * from the application's own dependency graph and the package's declared bin,+ * never a `PATH` lookup. A `PATH` hit could be any version, or not eve at all.+ */+export async function resolveEveExecutable(appRoot: string): Promise<string> {+ const packageJsonPath = findPackageJSON("eve", pathToFileURL(resolve(appRoot, "package.json")));+ if (packageJsonPath === undefined) {+ throw new Error(+ `The "eve" package is not installed under ${appRoot}, so registry items cannot be installed from here.`,+ );+ }+ const packageRoot = dirname(packageJsonPath);+ const manifest: unknown = JSON.parse(await readFile(packageJsonPath, "utf8"));+ const bin =+ typeof manifest === "object" && manifest !== null+ ? (manifest as { bin?: unknown }).bin+ : undefined;+ const declared =+ typeof bin === "string"+ ? bin+ : typeof bin === "object" && bin !== null+ ? (bin as Record<string, unknown>).eve+ : undefined;+ if (typeof declared !== "string" || declared.length === 0) {+ throw new Error(`The installed "eve" package does not declare an "eve" binary.`);+ }++ const executable = resolve(packageRoot, declared);+ const packageRelativePath = relative(packageRoot, executable);+ if (packageRelativePath.startsWith("..") || isAbsolute(packageRelativePath)) {+ throw new Error(`The installed "eve" package declares its binary outside the package.`);+ }+ return executable;+}++/**+ * Reads the one terminal event `eve add --non-interactive` prints.+ *+ * The registry SDK writes its own progress to the same streams, so this scans+ * for the JSON line rather than assuming the output is only NDJSON.+ */+export function readTerminalHeadlessEvent(output: string): HeadlessEvent | undefined {+ let terminal: HeadlessEvent | undefined;+ for (const line of output.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed.startsWith("{")) continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ continue;+ }+ if (typeof parsed !== "object" || parsed === null) continue;+ const event = parsed as HeadlessEvent;+ if (+ event.version === 1 &&+ (event.type === "completed" ||+ event.type === "blocked" ||+ event.type === "failed" ||+ event.type === "cancelled")+ ) {+ terminal = event;+ }+ }+ return terminal;+}++/**+ * Runs `eve add <address> --non-interactive --skip-setup` in `appRoot`.+ *+ * The argv shape is fixed here rather than composed by a caller: the+ * subcommand, the interaction mode, and the setup opt-out are the constraints+ * that make this safe to expose, so none of them is a parameter.+ *+ * `--skip-setup` is redundant given the split rule, which reads the cached+ * catalog index while the manifest is fetched fresh at install. If the two ever+ * disagree, this flag is what keeps a setup flow from starting in a process+ * with no way to answer it.+ */+export async function runEveAdd(input: {+ readonly address: string;+ readonly appRoot: string;+ readonly signal?: AbortSignal | undefined;+ readonly spawn?: SpawnLike | undefined;+}): Promise<EveAddOutcome> {+ const executable = await resolveEveExecutable(input.appRoot);+ const spawn = input.spawn ?? nodeSpawn;++ return await new Promise<EveAddOutcome>((settle) => {+ const child = spawn(+ process.execPath,+ [executable, "add", input.address, "--non-interactive", "--skip-setup"],+ {+ cwd: input.appRoot,+ detached: process.platform !== "win32",+ env: process.env,+ stdio: ["ignore", "pipe", "pipe"],+ },+ );++ let output = "";+ const collect = (chunk: Buffer | string) => {+ output = `${output}${String(chunk)}`.slice(-OUTPUT_LIMIT);+ };+ child.stdout?.on("data", collect);+ child.stderr?.on("data", collect);++ let settled = false;+ let stopOutcome: EveAddOutcome | undefined;+ let hardKill: NodeJS.Timeout | undefined;+ let treePoll: NodeJS.Timeout | undefined;+ const finish = (outcome: EveAddOutcome) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (hardKill !== undefined) clearTimeout(hardKill);+ if (treePoll !== undefined) clearTimeout(treePoll);+ input.signal?.removeEventListener("abort", abort);+ settle(outcome);+ };+ const finishAfterTreeExits = (outcome: EveAddOutcome) => {+ if (isChildTreeAlive(child)) {+ treePoll = setTimeout(() => finishAfterTreeExits(outcome), 25);+ treePoll.unref?.();+ return;+ }+ finish(stopOutcome ?? outcome);+ };+ const stop = (outcome: EveAddOutcome) => {+ if (stopOutcome !== undefined) return;+ stopOutcome = outcome;+ terminateChildTree(child, "SIGTERM");+ hardKill = setTimeout(() => terminateChildTree(child, "SIGKILL"), TERMINATION_GRACE_MS);+ hardKill.unref?.();+ };+ const abort = () => {+ stop({ kind: "failed", message: `Installing ${input.address} was cancelled.` });+ };+ const timer = setTimeout(() => {+ stop({+ kind: "failed",+ message: `Installing ${input.address} did not finish within ${INSTALL_TIMEOUT_MS / 60_000} minutes.`,+ });+ }, INSTALL_TIMEOUT_MS);+ timer.unref?.();+ if (input.signal?.aborted === true) abort();+ else input.signal?.addEventListener("abort", abort, { once: true });++ child.on("error", () => {+ stop({+ kind: "failed",+ message: `Could not run \`eve add ${input.address}\`. Run the command in a terminal for details.`,+ });+ });+ child.on("close", (code: number | null) => {+ let outcome: EveAddOutcome;+ const event = readTerminalHeadlessEvent(output);+ if (code === 0 && event?.type === "completed" && event.item === input.address) {+ outcome = { kind: "installed" };+ } else if (event?.type === "blocked" && event.item === input.address) {+ outcome = {+ kind: "blocked",+ message: `Installing ${input.address} stopped for input that only a terminal can supply.`,+ };+ } else if (+ event?.type === "failed" &&+ event.item === input.address &&+ typeof event.message === "string"+ ) {+ const reason =+ event.failureCode === "pnpm_build_policy"+ ? "Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command."+ : "Dependency installation failed. Retry the eve add command in a terminal for details.";+ const changed = Array.isArray(event.changed)+ ? event.changed.filter(+ (path): path is string =>+ typeof path === "string" &&+ path.length <= 300 &&+ !path.includes("..") &&+ /^[\w@+./ -]+$/u.test(path),+ )+ : [];+ const message =+ event.rolledBack === true+ ? `${reason} Project files were restored.`+ : changed.length === 0+ ? `${reason} The install may have partially changed the project.`+ : `${reason} The install partially changed: ${changed.join(", ")}. Restore those files, then retry.`;+ outcome =+ changed.length === 0 ? { kind: "failed", message } : { kind: "failed", message, changed };+ } else {+ outcome = {+ kind: "failed",+ message: `\`eve add ${input.address}\` failed and may have partially changed the project. Run it in a terminal for details.`,+ };+ }+ finishAfterTreeExits(outcome);+ });+ });+}diff --git a/packages/eve-self-modification/extension/instructions.ts b/packages/eve-self-modification/extension/instructions.tsindex 7a423c466..212e5b57b 100644--- a/packages/eve-self-modification/extension/instructions.ts+++ b/packages/eve-self-modification/extension/instructions.ts@@ -7,9 +7,11 @@ The source code of the eve agent is mounted read-write at /source. Use bash onlyUse selfmod__edit_file for precise changes to existing files; every edits[].oldText must match exactly. When changing multiple separate locations in one file, use one call with multiple entries in edits[]. Each oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits; merge nearby changes into one edit. Keep oldText as small as possible while still being unique. Use write_file only for new files or complete rewrites.+Before writing an integration by hand, check whether the eve registry already ships it, and install it with selfmod__registry_add using the exact item address (for example \`channel/slack\`). The tool installs only items that need no setup. When it reports \`needs-terminal\`, nothing was installed: relay its message and the command it names, and do not attempt to reproduce the item's setup by editing files. Never ask the developer for a credential and never repeat one; report the names of unset environment variables and stop there.+Group independent calls, including bash and reads, in one response.-Registry installation is outside the source sandbox. When the developer asks what this agent can integrate with, or asks for a capability an existing integration may already provide, call selfmod__search_registry before writing anything by hand. Prefer a registry item. When you find an exact item, report its address and stop: in a local eve dev session, tell the developer to run \`/add <address>\`, review its source and changes, and complete its setup prompts. Do not claim to have run the command, try to invoke it, or edit files as a substitute for installation. Say when the project already has an item. Write an integration yourself only when the registry has nothing that fits, or the developer asks for a custom implementation.+Registry installation is outside the source sandbox. When the developer asks what this agent can integrate with, or asks for a capability an existing integration may already provide, call selfmod__search_registry before writing anything by hand. Prefer a registry item. When you find an exact item, install it with selfmod__registry_add unless the project already has it. Write an integration yourself only when the registry has nothing that fits, or the developer asks for a custom implementation.The eve framework documentation is mounted read-only at /eve-docs. Read the eve guide directly relevant to an unfamiliar public API. Prefer an existing local implementation pattern over broad documentation research.diff --git a/packages/eve-self-modification/extension/source-lock.ts b/packages/eve-self-modification/extension/source-lock.tsnew file mode 100644index 000000000..5cb525194--- /dev/null+++ b/packages/eve-self-modification/extension/source-lock.ts@@ -0,0 +1,18 @@+/**+ * Serializes every authored-source mutation this extension performs.+ *+ * The model may call `selfmod__edit_file` and `selfmod__registry_add` in the+ * same response. An install rewrites `package.json`, runs the package manager,+ * and holds the authored-source watcher suspended for its whole duration, so an+ * edit landing in the middle of one is compiled against a tree that is being+ * replaced underneath it. The extension bundle emits shared imports as one+ * chunk, so both tools observe this single queue.+ */+let queue: Promise<unknown> = Promise.resolve();++/** Runs `task` after every previously queued authored-source mutation settles. */+export async function withAuthoredSourceLock<T>(task: () => Promise<T>): Promise<T> {+ const run = queue.then(task, task);+ queue = run.catch(() => undefined);+ return await run;+}diff --git a/packages/eve-self-modification/extension/tools/edit_file.ts b/packages/eve-self-modification/extension/tools/edit_file.tsindex f0636991a..ec8a1afd3 100644--- a/packages/eve-self-modification/extension/tools/edit_file.ts+++ b/packages/eve-self-modification/extension/tools/edit_file.ts@@ -1,5 +1,7 @@import { defineTool } from "eve/tools";+import { withAuthoredSourceLock } from "../source-lock.js";+const replacementSchema = {type: "object",additionalProperties: false,@@ -120,20 +122,25 @@ export default defineTool({}const sandbox = await ctx.getSandbox();- const content = await sandbox.readTextFile({ path });- if (content === null) {- throw new Error(`File not found: ${path}.`);- }- if (content.includes("\0")) {- throw new Error(`File "${path}" contains NUL bytes and appears to be binary.`);- }+ // Serialized against a concurrent registry install, which rewrites+ // package.json and the authored tree out of process.+ return await withAuthoredSourceLock(async () => {+ const content = await sandbox.readTextFile({ path });- await sandbox.writeTextFile({- content: applyExactEdits(content, edits),- path,- });+ if (content === null) {+ throw new Error(`File not found: ${path}.`);+ }+ if (content.includes("\0")) {+ throw new Error(`File "${path}" contains NUL bytes and appears to be binary.`);+ }++ await sandbox.writeTextFile({+ content: applyExactEdits(content, edits),+ path,+ });- return { path: sandbox.resolvePath(path), replacements: edits.length };+ return { path: sandbox.resolvePath(path), replacements: edits.length };+ });},});diff --git a/packages/eve-self-modification/extension/tools/registry_add.ts b/packages/eve-self-modification/extension/tools/registry_add.tsnew file mode 100644index 000000000..d30715467--- /dev/null+++ b/packages/eve-self-modification/extension/tools/registry_add.ts@@ -0,0 +1,240 @@+import { getLocalDevCapability, type LocalDevCapability } from "eve/local-dev";+import { defineTool } from "eve/tools";+import { once } from "eve/tools/approval";++import { classifyCatalogEntry } from "../classify-registry-item.js";+import { runEveAdd, type SpawnLike } from "../eve-add.js";+import { withAuthoredSourceLock } from "../source-lock.js";+import {+ loadRegistryIndex,+ resolveRegistryIndexUrl,+ type CatalogEntry,+} from "./search_registry.js";++const inputSchema = {+ type: "object",+ additionalProperties: false,+ properties: {+ address: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ description:+ "Exact address of an item in the configured eve registry, for example `channel/slack` or `extension/browserbase`.",+ },+ },+ required: ["address"],+} as const;++const outputSchema = {+ type: "object",+ additionalProperties: false,+ properties: {+ status: {+ type: "string",+ enum: ["installed", "needs-terminal", "failed"],+ description:+ "`installed` means the item is present. `needs-terminal` means nothing was installed. `failed` means installation stopped; read `message` and `changed` before retrying.",+ },+ address: { type: "string" },+ title: { type: "string" },+ envVars: {+ type: "array",+ items: { type: "string" },+ description:+ "Environment variables the item needs that are not set. The item is installed but will not work until the developer sets them. Never ask for or repeat their values.",+ },+ reason: {+ type: "string",+ description: "Why the item was not installed here.",+ },+ changed: {+ type: "array",+ items: { type: "string" },+ description: "Project-relative paths a failed install could not restore.",+ },+ nextCommand: {+ type: "string",+ description: "The command that completes a `needs-terminal` item.",+ },+ message: { type: "string", description: "One-line summary to relay to the developer." },+ },+ required: ["status", "address", "message"],+} as const;++interface RegistryAddDependencies {+ readonly getCapability?: () => LocalDevCapability | undefined;+ readonly spawn?: SpawnLike;+}++/** What the tool reports back. Mirrors {@link outputSchema}. */+export interface RegistryAddResult {+ readonly address: string;+ /** `failed` carries an explicit mutation outcome instead of implying nothing changed. */+ readonly status: "installed" | "needs-terminal" | "failed";+ readonly message: string;+ readonly title?: string;+ readonly envVars?: readonly string[];+ readonly reason?: string;+ readonly nextCommand?: string;+ readonly changed?: readonly string[];+}++/**+ * Names the item's declared environment variables that are not set.+ *+ * Naming a required variable is not a secret, and an installed item can still+ * be non-functional through unset variables, so this is the difference between+ * reporting outstanding work and reporting bare success. Values are never read.+ */+export function unsetEnvVars(+ entry: CatalogEntry,+ environment: Readonly<Record<string, string | undefined>> = process.env,+): readonly string[] {+ return (entry.envVars ?? []).filter((name) => {+ const value = environment[name];+ return value === undefined || value === "";+ });+}++/**+ * Builds the handoff a `needs-terminal` item carries.+ *+ * `/add <address>` (`runRegistryFlow`'s `initialAddress`) skips the category+ * and search screens and opens that item's confirmation directly, so an+ * interactive client is offered the address-specific command rather than bare+ * `/add`, which would make the developer re-find the item in the category+ * browser. Headless `eve dev` has no TUI to dispatch a slash command into, so+ * the shell command is the only honest answer there.+ */+export function handoffMessage(input: {+ readonly address: string;+ readonly interactiveClient: boolean;+ readonly reason: string;+ readonly title: string;+}): { readonly message: string; readonly nextCommand: string } {+ const nextCommand = input.interactiveClient+ ? `/add ${input.address}`+ : `eve add ${input.address}`;+ return {+ message: `${input.title} was not installed. ${input.reason} Run \`${nextCommand}\` ${input.interactiveClient ? "here" : "in a terminal"} to finish it.`,+ nextCommand,+ };+}++/** Exported for tests; the tool's `execute` delegates here. */+export async function addRegistryItem(+ address: string,+ options: RegistryAddDependencies & { readonly signal?: AbortSignal } = {},+): Promise<RegistryAddResult> {+ const capability = (options.getCapability ?? getLocalDevCapability)();+ if (capability === undefined) {+ throw new Error(+ "Registry items can only be installed while `eve dev` is running. Report the item address to the developer instead of installing it.",+ );+ }++ // Shares the catalog fetch and its five-minute cache with+ // `selfmod__search_registry`, rather than reading the registry index twice.+ const entries = await loadRegistryIndex({+ nowMs: Date.now(),+ signal: options.signal,+ url: resolveRegistryIndexUrl(),+ });+ const entry = entries.find((candidate) => candidate.address === address);+ if (entry === undefined) {+ throw new Error(+ `No item in the configured eve registry is published at "${address}". Check the address before trying again.`,+ );+ }++ const classification = classifyCatalogEntry(entry);+ if (classification.kind === "needs-terminal") {+ const handoff = handoffMessage({+ address,+ interactiveClient: capability.interactiveClient,+ reason: classification.reason,+ title: entry.title,+ });+ return {+ address,+ reason: classification.reason,+ status: "needs-terminal",+ title: entry.title,+ ...handoff,+ };+ }++ const outcome = await withAuthoredSourceLock(() =>+ capability.withSuspendedSource(() =>+ runEveAdd({+ address,+ appRoot: capability.appRoot,+ signal: options.signal,+ spawn: options.spawn,+ }),+ ),+ );++ if (outcome.kind === "blocked") {+ const handoff = handoffMessage({+ address,+ interactiveClient: capability.interactiveClient,+ reason: outcome.message,+ title: entry.title,+ });+ return {+ address,+ reason: outcome.message,+ status: "needs-terminal",+ title: entry.title,+ ...handoff,+ };+ }+ if (outcome.kind === "failed") {+ if (outcome.changed === undefined) {+ return {+ address,+ status: "failed",+ title: entry.title,+ reason: outcome.message,+ message: outcome.message,+ };+ }+ return {+ address,+ status: "failed",+ title: entry.title,+ reason: outcome.message,+ message: outcome.message,+ changed: outcome.changed,+ };+ }++ const envVars = unsetEnvVars(entry);+ return {+ address,+ envVars: [...envVars],+ message:+ envVars.length === 0+ ? `Installed ${entry.title}.`+ : `Installed ${entry.title}. It will not work until ${envVars.join(", ")} ${envVars.length === 1 ? "is" : "are"} set.`,+ status: "installed",+ title: entry.title,+ };+}++export default defineTool({+ approval: once(),+ description:+ "Install an item from the configured eve registry into this project, for example `channel/slack` or `extension/browserbase`. Only items that need no setup are installed here; an item with a setup flow or multiple components is reported back with the command that completes it, and nothing is installed. Development only. Search first, then call this with the exact item address.",+ inputSchema,+ outputSchema,+ async execute(input, ctx) {+ const { address } = input;+ if (typeof address !== "string" || address.length === 0) {+ throw new Error("address must be an exact item address from the configured eve registry.");+ }+ return await addRegistryItem(address, { signal: ctx.abortSignal });+ },+});diff --git a/packages/eve-self-modification/extension/tools/search_registry.ts b/packages/eve-self-modification/extension/tools/search_registry.tsindex f6bad695c..1dc2ed975 100644--- a/packages/eve-self-modification/extension/tools/search_registry.ts+++ b/packages/eve-self-modification/extension/tools/search_registry.ts@@ -101,6 +101,10 @@ export interface CatalogEntry {readonly requires?: string;/** Authored path this item installs, used to detect an existing install. */readonly authoredTarget?: string;+ /** Whether `meta.eve.setup` declares one or more setup commands. */+ readonly declaresSetup?: boolean;+ /** Names of environment variables the item declares. */+ readonly envVars?: readonly string[];}/** One row returned to the model. */@@ -202,6 +206,12 @@ function authoredTargetOf(entry: Record<string, unknown>): string | undefined {return undefined;}+/** Names of environment variables the item declares, used to report unset ones after install. */+function declaredEnvVars(entry: Record<string, unknown>): readonly string[] {+ const envVars = entry.envVars;+ return isRecord(envVars) ? Object.keys(envVars) : [];+}+/*** Narrows the published registry index into catalog entries.*@@ -224,7 +234,9 @@ export function parseRegistryIndex(value: unknown): readonly CatalogEntry[] {category?: Category;componentSearchTerms?: readonly string[];components?: readonly string[];+ declaresSetup?: boolean;description?: string;+ envVars?: readonly string[];requires?: string;title: string;} = { address, title: optionalString(item.title) ?? titleFromAddress(address) };@@ -242,6 +254,9 @@ export function parseRegistryIndex(value: unknown): readonly CatalogEntry[] {if (requires !== undefined) entry.requires = requires;const authoredTarget = authoredTargetOf(item);if (authoredTarget !== undefined) entry.authoredTarget = authoredTarget;+ if (eve.setup !== undefined && eve.setup !== null) entry.declaresSetup = true;+ const envVars = declaredEnvVars(item);+ if (envVars.length > 0) entry.envVars = envVars;entries.push(entry);}@@ -407,7 +422,7 @@ export function clearRegistryIndexCache(): void {cache = undefined;}-async function loadRegistryIndex(input: {+export async function loadRegistryIndex(input: {readonly nowMs: number;readonly signal?: AbortSignal;readonly url: string;@@ -481,7 +496,7 @@ async function annotateInstalled(input: {export default defineTool({description:- "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, and report the item address (for example `channel/slack`) so the developer can install it with `/add`.",+ "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact result address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(input, ctx) {diff --git a/packages/eve-self-modification/src/classify-registry-item.test.ts b/packages/eve-self-modification/src/classify-registry-item.test.tsnew file mode 100644index 000000000..cc29dc386--- /dev/null+++ b/packages/eve-self-modification/src/classify-registry-item.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";++import { classifyCatalogEntry } from "../extension/classify-registry-item.js";+import type { CatalogEntry } from "../extension/tools/search_registry.js";++function entry(overrides: Partial<CatalogEntry> = {}): CatalogEntry {+ return {+ address: "extension/browserbase",+ title: "Browserbase",+ ...overrides,+ };+}++describe("classifyCatalogEntry", () => {+ it("installs an item that declares no setup and no components", () => {+ expect(classifyCatalogEntry(entry())).toEqual({ kind: "installable" });+ });++ it("hands a setup-bearing item to the terminal", () => {+ const result = classifyCatalogEntry(entry({ address: "channel/slack", declaresSetup: true }));+ expect(result.kind).toBe("needs-terminal");+ expect(result).toHaveProperty("reason", expect.stringContaining("setup flow"));+ });++ it("hands a bundle to the terminal and names its components", () => {+ const result = classifyCatalogEntry(+ entry({ address: "linear", components: ["channel/linear-agent", "connection/linear"] }),+ );+ expect(result.kind).toBe("needs-terminal");+ expect(result).toHaveProperty("reason", expect.stringContaining("channel/linear-agent"));+ });++ it("hands over a bundle that also declares setup", () => {+ expect(+ classifyCatalogEntry(entry({ components: ["channel/x"], declaresSetup: true })).kind,+ ).toBe("needs-terminal");+ });++ it("treats an empty components list as no bundle", () => {+ expect(classifyCatalogEntry(entry({ components: [] })).kind).toBe("installable");+ });+});diff --git a/packages/eve-self-modification/src/registry-add.test.ts b/packages/eve-self-modification/src/registry-add.test.tsnew file mode 100644index 000000000..9ff98ce0f--- /dev/null+++ b/packages/eve-self-modification/src/registry-add.test.ts@@ -0,0 +1,385 @@+import { EventEmitter } from "node:events";+import { Readable } from "node:stream";++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { LocalDevCapability } from "eve/local-dev";++const { findPackageJSON, readFile } = vi.hoisted(() => ({+ findPackageJSON: vi.fn(),+ readFile: vi.fn(),+}));++vi.mock("node:module", () => ({ findPackageJSON }));+vi.mock("node:fs/promises", () => ({ readFile }));++import { readTerminalHeadlessEvent, runEveAdd } from "../extension/eve-add.js";+import { addRegistryItem, handoffMessage, unsetEnvVars } from "../extension/tools/registry_add.js";+import { clearRegistryIndexCache } from "../extension/tools/search_registry.js";++const APP_ROOT = "/workspace/agent";++const INDEX = {+ items: [+ {+ name: "extension/browserbase",+ title: "Browserbase",+ envVars: { BROWSERBASE_API_KEY: "", BROWSERBASE_PROJECT_ID: "" },+ files: [{ target: "agent/extensions/browserbase.ts" }],+ },+ {+ name: "channel/slack",+ title: "Slack",+ meta: {+ eve: { setup: { package: "eve", bin: "eve", args: ["integration", "setup", "slack"] } },+ },+ },+ {+ name: "linear",+ title: "Linear",+ meta: {+ eve: { components: [{ item: "channel/linear-agent" }, { item: "connection/linear" }] },+ },+ },+ {+ name: "@acme/widget",+ title: "Acme Widget",+ },+ ],+};++function capability(overrides: Partial<LocalDevCapability> = {}): LocalDevCapability {+ return {+ appRoot: APP_ROOT,+ interactiveClient: false,+ withSuspendedSource: async (task) => await task(),+ ...overrides,+ };+}++/** A child process that emits the given output and exit code. */+function fakeSpawn(input: { code: number; output: string }) {+ const calls: { command: string; args: readonly string[]; options: unknown }[] = [];+ const spawn = vi.fn((command: string, args: readonly string[], options: unknown) => {+ calls.push({ args, command, options });+ const child = new EventEmitter() as EventEmitter & {+ stdout: Readable;+ stderr: Readable;+ kill: () => void;+ };+ child.stdout = Readable.from([input.output]);+ child.stderr = Readable.from([]);+ child.kill = () => {};+ queueMicrotask(() => {+ child.stdout.on("end", () => child.emit("close", input.code));+ child.stdout.resume();+ });+ return child;+ });+ return { calls, spawn: spawn as never };+}++function controlledSpawn() {+ const child = new EventEmitter() as EventEmitter & {+ stdout: Readable;+ stderr: Readable;+ kill: ReturnType<typeof vi.fn>;+ };+ child.stdout = Readable.from([]);+ child.stderr = Readable.from([]);+ child.kill = vi.fn();+ return { child, spawn: vi.fn(() => child) as never };+}++const COMPLETED = JSON.stringify({+ version: 1,+ type: "completed",+ item: "extension/browserbase",+ completedItems: ["extension/browserbase"],+});++beforeEach(() => {+ clearRegistryIndexCache();+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify(INDEX), { status: 200 })),+ );+ // The eve bin is resolved from the app's own dependency graph, never PATH.+ findPackageJSON.mockReturnValue(`${APP_ROOT}/node_modules/eve/package.json`);+ readFile.mockResolvedValue(JSON.stringify({ name: "eve", bin: { eve: "./bin/eve.js" } }));+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++describe("addRegistryItem", () => {+ it("refuses to run without the development capability", async () => {+ await expect(+ addRegistryItem("extension/browserbase", { getCapability: () => undefined }),+ ).rejects.toThrow(/only be installed while `eve dev` is running/u);+ });++ it("hands a setup-bearing item over without installing anything", async () => {+ const { calls, spawn } = fakeSpawn({ code: 0, output: COMPLETED });+ const result = await addRegistryItem("channel/slack", {+ getCapability: () => capability(),+ spawn,+ });++ expect(result.status).toBe("needs-terminal");+ expect(result.title).toBe("Slack");+ expect(result.nextCommand).toBe("eve add channel/slack");+ expect(calls).toHaveLength(0);+ });++ it("hands a bundle over without installing anything", async () => {+ const { calls, spawn } = fakeSpawn({ code: 0, output: COMPLETED });+ const result = await addRegistryItem("linear", { getCapability: () => capability(), spawn });++ expect(result.status).toBe("needs-terminal");+ expect(result.reason).toContain("channel/linear-agent");+ expect(calls).toHaveLength(0);+ });++ it("offers the address-specific /add command when an interactive client owns the terminal", async () => {+ const result = await addRegistryItem("channel/slack", {+ getCapability: () => capability({ interactiveClient: true }),+ });++ // `/add <address>` (runRegistryFlow's initialAddress) jumps straight to+ // that item's confirmation screen, skipping the category browser bare+ // `/add` would otherwise require.+ expect(result.nextCommand).toBe("/add channel/slack");+ expect(result.message).toContain("/add channel/slack");+ });++ it("installs an exact item from a configured registry without restricting its address", async () => {+ const address = "@acme/widget";+ const { calls, spawn } = fakeSpawn({+ code: 0,+ output: JSON.stringify({ version: 1, type: "completed", item: address }),+ });+ const result = await addRegistryItem(address, {+ getCapability: () => capability(),+ spawn,+ });++ expect(result.status).toBe("installed");+ expect(calls[0]?.args).toContain(address);+ });++ it("rejects an address the registry does not publish", async () => {+ await expect(+ addRegistryItem("channel/nonexistent", { getCapability: () => capability() }),+ ).rejects.toThrow(/No item in the configured eve registry is published/u);+ });++ it("installs a no-setup item with a fixed argv and reports unset envVars", async () => {+ const { calls, spawn } = fakeSpawn({+ code: 0,+ output: `Something from shadcn\n${COMPLETED}\n`,+ });+ const suspended: string[] = [];+ const result = await addRegistryItem("extension/browserbase", {+ getCapability: () =>+ capability({+ withSuspendedSource: async (task) => {+ suspended.push("suspend");+ try {+ return await task();+ } finally {+ suspended.push("resume");+ }+ },+ }),+ spawn,+ });++ expect(result.status).toBe("installed");+ expect(result.envVars).toEqual(["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"]);+ expect(result.message).toContain("BROWSERBASE_API_KEY");+ expect(suspended).toEqual(["suspend", "resume"]);++ expect(calls).toHaveLength(1);+ expect(calls[0]?.args.slice(1)).toEqual([+ "add",+ "extension/browserbase",+ "--non-interactive",+ "--skip-setup",+ ]);+ expect(calls[0]?.options).toMatchObject({ cwd: APP_ROOT });+ });++ it("does not relay child output when the child does not report completion", async () => {+ const { spawn } = fakeSpawn({ code: 1, output: "secret-child-output\n" });+ const install = addRegistryItem("extension/browserbase", {+ getCapability: () => capability(),+ spawn,+ });++ await expect(install).resolves.toMatchObject({+ status: "failed",+ message: expect.stringMatching(/may have partially changed the project/u),+ });+ await expect(install).resolves.not.toMatchObject({+ message: expect.stringContaining("secret-child-output"),+ });+ });++ it("returns a sanitized structured failure and its partial changes", async () => {+ const { spawn } = fakeSpawn({+ code: 1,+ output: [+ "token=secret-child-output",+ JSON.stringify({+ version: 1,+ type: "failed",+ item: "extension/browserbase",+ completedItems: [],+ message: "untrusted child message",+ failureCode: "pnpm_build_policy",+ changed: ["package.json"],+ }),+ ].join("\n"),+ });++ await expect(+ addRegistryItem("extension/browserbase", { getCapability: () => capability(), spawn }),+ ).resolves.toMatchObject({+ status: "failed",+ changed: ["package.json"],+ message: expect.stringContaining("pnpm requires build-script decisions"),+ });+ });++ it("waits for a cancelled child to close before releasing the install", async () => {+ const { child, spawn } = controlledSpawn();+ const controller = new AbortController();+ const install = runEveAdd({+ address: "extension/browserbase",+ appRoot: APP_ROOT,+ signal: controller.signal,+ spawn,+ });+ controller.abort();++ await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith("SIGTERM"));+ let settled = false;+ void install.then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);++ child.emit("close", null);+ await expect(install).resolves.toEqual({+ kind: "failed",+ message: "Installing extension/browserbase was cancelled.",+ });+ });++ it("hands over an install the child reports as blocked", async () => {+ const { spawn } = fakeSpawn({+ code: 2,+ output: JSON.stringify({+ version: 1,+ type: "blocked",+ item: "extension/browserbase",+ message: "Setup needs an answer.",+ }),+ });+ const result = await addRegistryItem("extension/browserbase", {+ getCapability: () => capability(),+ spawn,+ });++ expect(result.status).toBe("needs-terminal");+ expect(result.reason).toBe(+ "Installing extension/browserbase stopped for input that only a terminal can supply.",+ );+ expect(result.reason).not.toContain("Setup needs an answer.");+ });+});++describe("unsetEnvVars", () => {+ const entry = {+ address: "extension/browserbase",+ envVars: ["A", "B"],+ title: "Browserbase",+ } as const;++ it("names only the variables that are not set", () => {+ expect(unsetEnvVars(entry, { A: "value" })).toEqual(["B"]);+ expect(unsetEnvVars(entry, { A: "value", B: "value" })).toEqual([]);+ });++ it("treats an empty value as unset", () => {+ expect(unsetEnvVars(entry, { A: "", B: "value" })).toEqual(["A"]);+ });++ it("treats a missing envVars field as declaring none", () => {+ expect(unsetEnvVars({ address: "linear", title: "Linear" }, {})).toEqual([]);+ });+});++describe("handoffMessage", () => {+ it("names the shell command with no interactive client", () => {+ expect(+ handoffMessage({+ address: "channel/slack",+ interactiveClient: false,+ reason: "It declares a setup flow.",+ title: "Slack",+ }),+ ).toEqual({+ message: expect.stringContaining("`eve add channel/slack`"),+ nextCommand: "eve add channel/slack",+ });+ });++ it("names the address-specific /add command with an interactive client", () => {+ expect(+ handoffMessage({+ address: "channel/slack",+ interactiveClient: true,+ reason: "It declares a setup flow.",+ title: "Slack",+ }),+ ).toEqual({+ message: expect.stringContaining("`/add channel/slack`"),+ nextCommand: "/add channel/slack",+ });+ });+});++describe("readTerminalHeadlessEvent", () => {+ it("finds the terminal event among the registry SDK's own output", () => {+ expect(+ readTerminalHeadlessEvent(+ [+ "Checking registry.",+ `{"version":1,"type":"progress","message":"Installed x"}`,+ COMPLETED,+ "+ KEY",+ ].join("\n"),+ ),+ ).toMatchObject({ type: "completed" });+ });++ it("ignores lines that are not JSON", () => {+ expect(readTerminalHeadlessEvent("not json\n{broken\n")).toBeUndefined();+ });++ it("keeps the last terminal event", () => {+ expect(+ readTerminalHeadlessEvent(+ [+ `{"version":1,"type":"cancelled","item":"a"}`,+ `{"version":1,"type":"failed","item":"a","message":"boom"}`,+ ].join("\n"),+ ),+ ).toMatchObject({ type: "failed", message: "boom" });+ });+});diff --git a/packages/eve-self-modification/src/search-registry.test.ts b/packages/eve-self-modification/src/search-registry.test.tsindex 85d5db795..b24a49678 100644--- a/packages/eve-self-modification/src/search-registry.test.ts+++ b/packages/eve-self-modification/src/search-registry.test.ts@@ -100,6 +100,43 @@ describe("parseRegistryIndex", () => {expect(parseRegistryIndex(null)).toEqual([]);expect(parseRegistryIndex({ items: "nope" })).toEqual([]);});++ it("reads whether an item declares a setup flow, used by selfmod__registry_add's split rule", () => {+ const entries = parseRegistryIndex({+ items: [+ {+ name: "channel/slack",+ meta: {+ eve: { setup: { package: "eve", bin: "eve", args: ["integration", "setup", "slack"] } },+ },+ },+ { name: "extension/browserbase" },+ ],+ });++ expect(entries.find((entry) => entry.address === "channel/slack")?.declaresSetup).toBe(true);+ expect(+ entries.find((entry) => entry.address === "extension/browserbase")?.declaresSetup,+ ).toBeUndefined();+ });++ it("reads an item's declared environment variable names", () => {+ const entries = parseRegistryIndex({+ items: [+ {+ name: "extension/browserbase",+ envVars: { BROWSERBASE_API_KEY: "", BROWSERBASE_PROJECT_ID: "" },+ },+ { name: "channel/discord", envVars: {} },+ ],+ });++ expect(entries.find((entry) => entry.address === "extension/browserbase")?.envVars).toEqual([+ "BROWSERBASE_API_KEY",+ "BROWSERBASE_PROJECT_ID",+ ]);+ expect(entries.find((entry) => entry.address === "channel/discord")?.envVars).toBeUndefined();+ });});describe("selectIntegrations", () => {diff --git a/packages/eve/src/cli/commands/registry-install-transaction.ts b/packages/eve/src/cli/commands/registry-install-transaction.tsnew file mode 100644index 000000000..524d15a37--- /dev/null+++ b/packages/eve/src/cli/commands/registry-install-transaction.ts@@ -0,0 +1,122 @@+import { readFile, unlink, writeFile } from "node:fs/promises";+import { isAbsolute, relative, resolve } from "node:path";++import { serializeHeadlessSetupEvent, type HeadlessSetupEvent } from "./setup-headless.js";++interface Snapshot {+ readonly path: string;+ readonly contents?: Buffer;+}++// Package-manager state under node_modules is disposable and deliberately not+// restored; manifests and lock/policy files remain the source of truth on retry.+const PROJECT_INSTALL_FILES = [+ "package.json",+ "pnpm-lock.yaml",+ "pnpm-workspace.yaml",+ "package-lock.json",+ "npm-shrinkwrap.json",+ "yarn.lock",+ "bun.lock",+ "bun.lockb",+ ".env.example",+ ".env.local",+] as const;++function registryTargets(appRoot: string, item: unknown): string[] {+ if (typeof item !== "object" || item === null || !("files" in item)) return [];+ const files = (item as { files?: unknown }).files;+ if (!Array.isArray(files)) return [];+ return files.flatMap((file) => {+ if (typeof file !== "object" || file === null || !("target" in file)) return [];+ const target = (file as { target?: unknown }).target;+ if (typeof target !== "string" || target.length === 0) return [];+ const absolute = resolve(appRoot, target);+ const projectRelative = relative(appRoot, absolute);+ if (isAbsolute(projectRelative) || projectRelative.startsWith("..")) return [];+ return [projectRelative];+ });+}++async function snapshotFile(path: string): Promise<Snapshot> {+ try {+ return { path, contents: await readFile(path) };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path };+ throw error;+ }+}++export async function snapshotRegistryInstall(+ appRoot: string,+ item: unknown,+): Promise<readonly Snapshot[]> {+ const paths = [...new Set([...PROJECT_INSTALL_FILES, ...registryTargets(appRoot, item)])];+ return await Promise.all(paths.map((path) => snapshotFile(resolve(appRoot, path))));+}++export async function rollbackRegistryInstall(+ appRoot: string,+ snapshots: readonly Snapshot[],+): Promise<{ readonly restored: boolean; readonly changed: readonly string[] }> {+ const changed: string[] = [];+ for (const snapshot of snapshots) {+ try {+ if (snapshot.contents === undefined)+ await unlink(snapshot.path).catch((error: unknown) => {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ });+ else await writeFile(snapshot.path, snapshot.contents);+ } catch {+ changed.push(relative(appRoot, snapshot.path));+ }+ }+ return { restored: changed.length === 0, changed };+}++export type RegistryInstallFailureCode = "pnpm_build_policy" | "dependency_install";++export function registryInstallFailureCode(error: unknown): RegistryInstallFailureCode {+ const message = error instanceof Error ? error.message : String(error);+ return message.includes("ERR_PNPM_IGNORED_BUILDS") || message.includes("Ignored build scripts")+ ? "pnpm_build_policy"+ : "dependency_install";+}++export function registryInstallFailureMessage(code: RegistryInstallFailureCode): string {+ return code === "pnpm_build_policy"+ ? "Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command."+ : "Dependency installation failed. Retry the eve add command in a terminal for details.";+}++export async function installRegistryItemTransaction(input: {+ readonly appRoot: string;+ readonly item: string;+ readonly registryItem: unknown;+ readonly nonInteractive: boolean | undefined;+ readonly logger: { log(message: string): void };+ readonly install: () => Promise<void>;+}): Promise<void> {+ const snapshot = await snapshotRegistryInstall(input.appRoot, input.registryItem);+ try {+ await input.install();+ } catch (error) {+ const rollback = await rollbackRegistryInstall(input.appRoot, snapshot);+ const failureCode = registryInstallFailureCode(error);+ const message = registryInstallFailureMessage(failureCode);+ if (input.nonInteractive) {+ const failureEvent: Extract<HeadlessSetupEvent, { type: "failed" }> = {+ version: 1,+ type: "failed",+ item: input.item,+ completedItems: [],+ message,+ failureCode,+ rolledBack: rollback.restored,+ };+ if (rollback.changed.length > 0) failureEvent.changed = rollback.changed;+ input.logger.log(serializeHeadlessSetupEvent(failureEvent));+ }+ throw new Error(message, { cause: error });+ }+}diff --git a/packages/eve/src/cli/commands/registry.test.ts b/packages/eve/src/cli/commands/registry.test.tsindex 3200090d8..df049bcbe 100644--- a/packages/eve/src/cli/commands/registry.test.ts+++ b/packages/eve/src/cli/commands/registry.test.ts@@ -25,6 +25,7 @@ const {isEveProject,readFile,resolveInstalledPackageInfo,+ unlink,searchRegistries,writeFile,} = vi.hoisted(() => ({@@ -34,6 +35,7 @@ const {isEveProject: vi.fn(),readFile: vi.fn(),resolveInstalledPackageInfo: vi.fn(() => ({ name: "eve", version: "0.27.8" })),+ unlink: vi.fn(),searchRegistries: vi.fn(),writeFile: vi.fn(),}));@@ -47,7 +49,7 @@ vi.mock("#compiled/shadcn-registry/index.js", () => ({vi.mock("#setup/scaffold/index.js", () => ({ isEveProject }));vi.mock("#setup/scaffold/workspace-root.js", () => ({ applyPackageManagerWorkspaceConfiguration }));vi.mock("#internal/application/package.js", () => ({ resolveInstalledPackageInfo }));-vi.mock("node:fs/promises", () => ({ readFile, writeFile }));+vi.mock("node:fs/promises", () => ({ readFile, unlink, writeFile }));function createLogger(): RegistryCommandLogger & { errors: string[]; logs: string[] } {const errors: string[] = [];@@ -142,6 +144,60 @@ describe("registry commands", () => {});});+ it("rolls back project files and reports a sanitized headless install failure", async () => {+ const logger = createLogger();+ getRegistryItems.mockResolvedValue([+ {+ name: "extension/browser",+ type: "registry:item",+ files: [{ target: "agent/extensions/browser.ts" }],+ },+ ]);+ addRegistryItems.mockRejectedValueOnce(+ new Error("ERR_PNPM_IGNORED_BUILDS token=secret-child-output"),+ );++ await runAddCommand(logger, "/project", "extension/browser", { nonInteractive: true });++ expect(JSON.parse(logger.logs[0]!)).toEqual({+ version: 1,+ type: "failed",+ item: "extension/browser",+ completedItems: [],+ message:+ "Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command.",+ failureCode: "pnpm_build_policy",+ rolledBack: true,+ });+ expect(logger.logs.join("\n")).not.toContain("secret-child-output");+ expect(writeFile).toHaveBeenCalledWith("/project/package.json", expect.any(String));+ expect(logger.errors).toEqual([+ "Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command.",+ ]);+ });++ it("reports only paths that rollback could not restore", async () => {+ const logger = createLogger();+ getRegistryItems.mockResolvedValue([{ name: "extension/browser", type: "registry:item" }]);+ addRegistryItems.mockRejectedValueOnce(new Error("arbitrary secret stderr"));+ writeFile.mockRejectedValueOnce(new Error("disk full"));++ await runAddCommand(logger, "/project", "extension/browser", { nonInteractive: true });++ expect(JSON.parse(logger.logs[0]!)).toEqual({+ version: 1,+ type: "failed",+ item: "extension/browser",+ completedItems: [],+ message:+ "Dependency installation failed. Retry the eve add command in a terminal for details.",+ failureCode: "dependency_install",+ rolledBack: false,+ changed: ["package.json"],+ });+ expect(logger.logs.join("\n")).not.toContain("arbitrary secret stderr");+ });+it("suggests matching registry items when an item is not found", async () => {const logger = createLogger();getRegistryItems.mockRejectedValue(diff --git a/packages/eve/src/cli/commands/registry.ts b/packages/eve/src/cli/commands/registry.tsindex 7436994f8..f7510ae24 100644--- a/packages/eve/src/cli/commands/registry.ts+++ b/packages/eve/src/cli/commands/registry.ts@@ -12,6 +12,7 @@ import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js"import { WizardCancelledError } from "#setup/step.js";import { hasInteractiveTerminal } from "./preconditions.js";+import { installRegistryItemTransaction } from "./registry-install-transaction.js";import { runDeclaredSetups } from "./registry-declared-setups.js";import {errorMessage,@@ -543,15 +544,23 @@ export async function runAddCommand(if (address === itemAddress("channel/web")) {await (dependencies.prepareWebRegistryProject ?? prepareWebRegistryProject)(appRoot);}- await addRegistryItems([address], {- config,- cwd: appRoot,- overwrite: options.overwrite,- silent: options.silent,+ await installRegistryItemTransaction({+ appRoot,+ item,+ registryItem,+ nonInteractive: options.nonInteractive,+ logger,+ install: async () => {+ await addRegistryItems([address], {+ config,+ cwd: appRoot,+ overwrite: options.overwrite,+ silent: options.silent,+ });+ },});if (eveMetadata?.setup === undefined)return reportCompletion(logger, item, { facts: [] }, options);-const interactive =dependencies.hasInteractiveTerminal?.() ??defaultAddCommandDependencies.hasInteractiveTerminal!();@@ -630,7 +639,6 @@ function reportCompletion(nonInteractive: options.nonInteractive,});}-/** Adds registry namespace mappings to the project's package.json. */export async function runRegistryAddCommand(logger: RegistryCommandLogger,@@ -650,7 +658,6 @@ export async function runRegistryAddCommand(}});}-/** Lists registry items from every configured source or one selected source. */export async function runRegistryListCommand(logger: RegistryCommandLogger,@@ -662,7 +669,6 @@ export async function runRegistryListCommand(browseRegistryItems(logger, appRoot, undefined, source, options),);}-/** Searches registry items across every configured source or one selected source. */export async function runRegistrySearchCommand(logger: RegistryCommandLogger,@@ -678,7 +684,6 @@ export async function runRegistrySearchCommand(}),);}-/** Inspects one official, configured, or URL-addressed registry item. */export async function runRegistryViewCommand(logger: RegistryCommandLogger,diff --git a/packages/eve/src/cli/commands/setup-headless.ts b/packages/eve/src/cli/commands/setup-headless.tsindex 0aa066519..7ba5e203f 100644--- a/packages/eve/src/cli/commands/setup-headless.ts+++ b/packages/eve/src/cli/commands/setup-headless.ts@@ -42,6 +42,11 @@ export type HeadlessSetupEvent =item: string;completedItems: readonly string[];message: string;+ failureCode?: "pnpm_build_policy" | "dependency_install";+ /** True when every project file tracked by the installer was restored. */+ rolledBack?: boolean;+ /** Project-relative paths that could not be restored. Never contains file contents. */+ changed?: readonly string[];next?: HeadlessSetupCommand;}| {