Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(self-modification): activate production file editing (#2873)

prha8946bd592e35
diff --git a/.changeset/production-self-modification-a4.md b/.changeset/production-self-modification-a4.md
new file mode 100644
index 000000000..3445092cf
--- /dev/null
+++ b/.changeset/production-self-modification-a4.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Enable configured deployments to edit an agent source checkout and publish changes as draft GitHub pull requests. Registry setup installs official registry items in the disposable checkout, provisions a repository-scoped Vercel Connect GitHub connector, and can continue without secrets in headless environments; manual and self-hosted deployments can use a fine-grained GitHub PAT.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index 9b5d4c616..ffa985919 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -32,8 +32,8 @@
"name": "experimental/self-modification",
"type": "registry:item",
"title": "Self-modification (Experimental)",
- "description": "Add an experimental, development-only source editing subagent to an eve project.",
- "dependencies": ["just-bash"],
+ "description": "Add an experimental source editing subagent with local edits and official registry installation.",
+ "dependencies": ["just-bash", "@vercel/connect"],
"meta": {
"eve": {
"install": {
@@ -47,10 +47,75 @@
}
]
}
- }
+ },
+ "setup": [
+ {
+ "package": "eve",
+ "bin": "eve",
+ "args": ["integration", "setup", "self-modification"]
+ }
+ ]
}
},
"files": [
+ {
+ "path": "registry/experimental/self-modification/config.ts",
+ "type": "registry:file",
+ "target": "agent/subagents/self-modification/config.ts"
+ },
+ {
+ "path": "registry/experimental/self-modification/agent.ts",
+ "type": "registry:file",
+ "target": "agent/subagents/self-modification/agent.ts"
+ },
+ {
+ "path": "registry/experimental/self-modification/sandbox.ts",
+ "type": "registry:file",
+ "target": "agent/subagents/self-modification/sandbox.ts"
+ },
+ {
+ "path": "registry/experimental/self-modification/extension.ts",
+ "type": "registry:file",
+ "target": "agent/subagents/self-modification/extensions/selfmod.ts"
+ }
+ ]
+ },
+ {
+ "name": "experimental/self-modification/prod",
+ "type": "registry:item",
+ "title": "Self-modification production (Experimental)",
+ "description": "Add experimental self-modification with local editing and deployed draft pull requests.",
+ "dependencies": ["just-bash", "@vercel/connect"],
+ "meta": {
+ "eve": {
+ "hidden": true,
+ "install": {
+ "pnpm": {
+ "buildScripts": [
+ {
+ "packages": ["node-liblzma", "@mongodb-js/zstd"],
+ "optional": true,
+ "recommendedAction": "ignore-optional",
+ "reason": "These optional just-bash compression accelerators are not required by the self-modification agent."
+ }
+ ]
+ }
+ },
+ "setup": [
+ {
+ "package": "eve",
+ "bin": "eve",
+ "args": ["integration", "setup", "self-modification-production"]
+ }
+ ]
+ }
+ },
+ "files": [
+ {
+ "path": "registry/experimental/self-modification/config.ts",
+ "type": "registry:file",
+ "target": "agent/subagents/self-modification/config.ts"
+ },
{
"path": "registry/experimental/self-modification/agent.ts",
"type": "registry:file",
diff --git a/apps/docs/registry/experimental/self-modification/agent.ts b/apps/docs/registry/experimental/self-modification/agent.ts
index d75b02f26..b1fd88b57 100644
--- a/apps/docs/registry/experimental/self-modification/agent.ts
+++ b/apps/docs/registry/experimental/self-modification/agent.ts
@@ -1,5 +1,5 @@
import { defineSelfModificationAgent } from "eve/self-modification/agent";
-export default defineSelfModificationAgent({
- model: "openai/gpt-5.6-terra",
-});
+import config from "./config";
+
+export default defineSelfModificationAgent({ config });
diff --git a/apps/docs/registry/experimental/self-modification/config.ts b/apps/docs/registry/experimental/self-modification/config.ts
new file mode 100644
index 000000000..c3411b168
--- /dev/null
+++ b/apps/docs/registry/experimental/self-modification/config.ts
@@ -0,0 +1,3 @@
+import { defineSelfModificationConfig } from "eve/self-modification/config";
+
+export default defineSelfModificationConfig({});
diff --git a/apps/docs/registry/experimental/self-modification/extension.ts b/apps/docs/registry/experimental/self-modification/extension.ts
index 5f046d60d..1b51e3fbe 100644
--- a/apps/docs/registry/experimental/self-modification/extension.ts
+++ b/apps/docs/registry/experimental/self-modification/extension.ts
@@ -1 +1,5 @@
-export { default } from "eve/self-modification";
+import selfModification from "eve/self-modification";
+
+import config from "../config";
+
+export default selfModification(config);
diff --git a/apps/docs/registry/experimental/self-modification/sandbox.ts b/apps/docs/registry/experimental/self-modification/sandbox.ts
index 9bf669acb..27b9b9f6e 100644
--- a/apps/docs/registry/experimental/self-modification/sandbox.ts
+++ b/apps/docs/registry/experimental/self-modification/sandbox.ts
@@ -1 +1,5 @@
-export { default } from "eve/self-modification/sandbox";
+import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";
+
+import config from "./config";
+
+export default defineSelfModificationSandbox({ config });
diff --git a/packages/eve/src/cli/commands/registry-add-command.ts b/packages/eve/src/cli/commands/registry-add-command.ts
new file mode 100644
index 000000000..7d720420d
--- /dev/null
+++ b/packages/eve/src/cli/commands/registry-add-command.ts
@@ -0,0 +1,22 @@
+import { addRegistryMappings } from "./registry-project.js";
+import { runRegistryAction, type RegistryCommandLogger } from "./registry-recovery.js";
+
+/** Adds registry namespace mappings to the project's package.json. */
+export async function runRegistryAddCommand(
+ logger: RegistryCommandLogger,
+ appRoot: string,
+ mappings: readonly string[],
+): Promise<void> {
+ await runRegistryAction(logger, appRoot, async () => {
+ const result = await addRegistryMappings(appRoot, mappings);
+ for (const namespace of result.skippedBuiltIn) {
+ logger.log(`Skipped ${namespace} because it is built in.`);
+ }
+ for (const namespace of result.skippedExisting) {
+ logger.log(`Skipped ${namespace} because it is already configured.`);
+ }
+ if (result.added.length > 0) {
+ logger.log(`Added ${result.added.join(", ")} to package.json.`);
+ }
+ });
+}
diff --git a/packages/eve/src/cli/commands/registry-metadata.test.ts b/packages/eve/src/cli/commands/registry-metadata.test.ts
index 0ff6227d7..e36237902 100644
--- a/packages/eve/src/cli/commands/registry-metadata.test.ts
+++ b/packages/eve/src/cli/commands/registry-metadata.test.ts
@@ -15,12 +15,14 @@ describe("registry metadata", () => {
eve: { docs: "/docs/channels/photon", implementation: "native" },
},
},
+ { name: "experimental/self-modification/prod", meta: { eve: { hidden: true } } },
{ name: "extension/browser" },
],
});
expect([...metadata]).toEqual([
["channel/photon-imessage", { docs: "/docs/channels/photon", implementation: "native" }],
+ ["experimental/self-modification/prod", { hidden: true }],
]);
});
diff --git a/packages/eve/src/cli/commands/registry-metadata.ts b/packages/eve/src/cli/commands/registry-metadata.ts
index 279e033a3..a49538cbb 100644
--- a/packages/eve/src/cli/commands/registry-metadata.ts
+++ b/packages/eve/src/cli/commands/registry-metadata.ts
@@ -23,6 +23,7 @@ const EveRegistryMetadataSchema = z.object({
requires: z.string().optional(),
docs: z.string().min(1).optional(),
implementation: z.enum(["native", "chat-sdk"]).optional(),
+ hidden: z.literal(true).optional(),
install: z
.object({
pnpm: z.object({ buildScripts: z.array(PnpmBuildScriptPolicySchema).min(1) }).optional(),
@@ -57,7 +58,7 @@ const RegistryPresentationManifestSchema = EveRegistryItemMetadataSchema.extend(
export type RegistrySearchMetadata = Pick<
z.infer<typeof EveRegistryMetadataSchema>,
- "docs" | "implementation"
+ "docs" | "hidden" | "implementation"
>;
/** Parses eve-owned metadata from a registry item manifest. */
@@ -72,9 +73,9 @@ export function parseOfficialRegistrySearchMetadata(
const { items } = OfficialRegistryCatalogSchema.parse(input);
const metadata = new Map<string, RegistrySearchMetadata>();
for (const item of items) {
- const { docs, implementation } = item.meta?.eve ?? {};
- if (docs !== undefined || implementation !== undefined) {
- metadata.set(item.name, { docs, implementation });
+ const { docs, hidden, implementation } = item.meta?.eve ?? {};
+ if (docs !== undefined || hidden !== undefined || implementation !== undefined) {
+ metadata.set(item.name, { docs, hidden, implementation });
}
}
return metadata;
diff --git a/packages/eve/src/cli/commands/registry.test.ts b/packages/eve/src/cli/commands/registry.test.ts
index 746089be4..f6235de3f 100644
--- a/packages/eve/src/cli/commands/registry.test.ts
+++ b/packages/eve/src/cli/commands/registry.test.ts
@@ -1221,6 +1221,44 @@ describe("registry commands", () => {
);
});
+ it("omits official items marked hidden from registry search", async () => {
+ readFile.mockResolvedValue(JSON.stringify({ name: "project" }));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ items: [
+ { name: "experimental/self-modification" },
+ { name: "experimental/self-modification/prod", meta: { eve: { hidden: true } } },
+ ],
+ }),
+ ),
+ ),
+ );
+ searchRegistries.mockResolvedValue({
+ items: [
+ {
+ registry: "https://eve.dev/r/registry.json",
+ name: "experimental/self-modification",
+ addCommandArgument: "https://eve.dev/r/experimental/self-modification.json",
+ },
+ {
+ registry: "https://eve.dev/r/registry.json",
+ name: "experimental/self-modification/prod",
+ addCommandArgument: "https://eve.dev/r/experimental/self-modification/prod.json",
+ },
+ ],
+ pagination: { total: 2, offset: 0, limit: 2, hasMore: false },
+ });
+
+ await expect(browseRegistryCatalog("/project")).resolves.toMatchObject({
+ items: [{ name: "experimental/self-modification" }],
+ total: 1,
+ });
+ });
+
it("lists the official registry without configured namespaces", async () => {
const logger = createLogger();
readFile.mockResolvedValue(JSON.stringify({ name: "project" }));
diff --git a/packages/eve/src/cli/commands/registry.ts b/packages/eve/src/cli/commands/registry.ts
index 96162d1cd..3f06b372a 100644
--- a/packages/eve/src/cli/commands/registry.ts
+++ b/packages/eve/src/cli/commands/registry.ts
@@ -39,11 +39,11 @@ import {
import type { runRegistrySetupCommand } from "./registry-setup-command.js";
import { serializeHeadlessSetupEvent } from "./setup-headless.js";
import {
- addRegistryMappings,
assertCanInstallWebChat,
prepareWebRegistryProject,
readRegistryConfig,
} from "./registry-project.js";
+export { runRegistryAddCommand } from "./registry-add-command.js";
export type { RegistryCommandLogger } from "./registry-recovery.js";
export interface AddCommandOptions {
skipInstall?: boolean;
@@ -333,6 +333,14 @@ async function searchRegistryCatalog(
: new Map<string, RegistrySearchMetadata>();
const official = resultsBySource.get(OFFICIAL_CATALOG);
if (official !== undefined) {
+ const visibleItems = official.items.filter(
+ (item) => metadataByAddress.get(searchItemAddress(item))?.hidden !== true,
+ );
+ official.items = visibleItems;
+ official.pagination = {
+ ...official.pagination,
+ total: visibleItems.length,
+ };
official.items.sort((left, right) => {
const rank = (item: RegistrySearchItem) =>
metadataByAddress.get(searchItemAddress(item))?.implementation === "native" ? 0 : 1;
@@ -639,25 +647,6 @@ export async function runAddCommand(
return reportCompletion(logger, item, completion, options);
});
}
-/** Adds registry namespace mappings to the project's package.json. */
-export async function runRegistryAddCommand(
- logger: RegistryCommandLogger,
- appRoot: string,
- mappings: readonly string[],
-): Promise<void> {
- await runRegistryAction(logger, appRoot, async () => {
- const result = await addRegistryMappings(appRoot, mappings);
- for (const namespace of result.skippedBuiltIn) {
- logger.log(`Skipped ${namespace} because it is built in.`);
- }
- for (const namespace of result.skippedExisting) {
- logger.log(`Skipped ${namespace} because it is already configured.`);
- }
- if (result.added.length > 0) {
- logger.log(`Added ${result.added.join(", ")} to package.json.`);
- }
- });
-}
/** Lists registry items from every configured source or one selected source. */
export async function runRegistryListCommand(
logger: RegistryCommandLogger,
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel-options.ts b/packages/eve/src/execution/sandbox/bindings/vercel-options.ts
new file mode 100644
index 000000000..9f57fd9b0
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/vercel-options.ts
@@ -0,0 +1,73 @@
+import type { VercelCreateOptions } from "#execution/sandbox/bindings/vercel-sdk-types.js";
+import type { SandboxBackendTags } from "#public/definitions/sandbox-backend.js";
+
+const VERCEL_SANDBOX_TAG_LIMIT = 5;
+
+export function resolveVercelSandboxTags(
+ userTags: VercelCreateOptions["tags"],
+ eveTags: SandboxBackendTags | undefined,
+): Record<string, string> | undefined {
+ const tags: Record<string, string> = {};
+
+ if (userTags !== undefined) {
+ for (const [key, value] of Object.entries(userTags as Record<string, string>)) {
+ tags[key] = value;
+ }
+ }
+
+ if (eveTags !== undefined) {
+ for (const [key, value] of Object.entries(eveTags)) {
+ tags[key] = value;
+ }
+ }
+
+ const count = Object.keys(tags).length;
+ if (count === 0) return undefined;
+
+ if (count > VERCEL_SANDBOX_TAG_LIMIT) {
+ throw new Error(
+ `Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. ` +
+ 'eve reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercel().',
+ );
+ }
+
+ return tags;
+}
+
+export async function ensureVercelSandboxTags(
+ sandbox: {
+ readonly tags?: Record<string, string>;
+ update(options: { tags: Record<string, string> }): Promise<unknown>;
+ },
+ tags: Record<string, string> | undefined,
+): Promise<void> {
+ if (tags === undefined || areVercelSandboxTagsEqual(sandbox.tags, tags)) return;
+ await sandbox.update({ tags });
+}
+
+function areVercelSandboxTagsEqual(
+ current: Record<string, string> | undefined,
+ next: Record<string, string>,
+): boolean {
+ const currentTags = current ?? {};
+ const currentEntries = Object.entries(currentTags);
+ const nextEntries = Object.entries(next);
+ if (currentEntries.length !== nextEntries.length) return false;
+ return nextEntries.every(([key, value]) => currentTags[key] === value);
+}
+
+export function errorMessage(error: unknown): string {
+ if (error instanceof Error) {
+ const responseJson = (error as { readonly json?: unknown }).json;
+ const responseText = (error as { readonly text?: unknown }).text;
+ const responseBody =
+ typeof responseText === "string" && responseText.length > 0
+ ? responseText
+ : responseJson !== undefined
+ ? JSON.stringify(responseJson)
+ : undefined;
+ if (responseBody !== undefined) return `${error.message}: ${responseBody}`;
+ return error.message;
+ }
+ return String(error);
+}
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
index 3f8224a0c..ad9facd64 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts
@@ -64,7 +64,16 @@ function createMockSandbox(input: {
const content = files.get(file.path);
return content === undefined ? null : Readable.from([content]);
}),
- runCommand: vi.fn().mockResolvedValue(createMockCommandResult()),
+ runCommand: vi
+ .fn()
+ .mockImplementation(async (command: { args?: readonly string[]; cmd: string }) =>
+ command.cmd === "realpath"
+ ? {
+ ...createMockCommandResult(),
+ stdout: vi.fn().mockResolvedValue(`${command.args?.at(-1) ?? ""}\n`),
+ }
+ : createMockCommandResult(),
+ ),
snapshot: vi.fn().mockResolvedValue({ snapshotId: `${input.name}-snapshot` }),
status: input.status ?? "running",
stop: vi.fn().mockResolvedValue(undefined),
@@ -322,6 +331,34 @@ describe("createVercelSandbox", () => {
).rejects.toThrow(/The sandbox request is invalid/);
});
+ it("resolves symlinked destinations before writing files", async () => {
+ const { handle, sessionSandbox } = await createTestVercelSession();
+ vi.mocked(sessionSandbox.runCommand).mockResolvedValueOnce({
+ ...createMockCommandResult(),
+ stdout: vi.fn().mockResolvedValue("/workspace/repository/agent/instructions.md\n"),
+ });
+
+ await handle.session.writeTextFile({
+ content: "updated instructions\n",
+ path: "/source/instructions.md",
+ });
+
+ expect(sessionSandbox.runCommand).toHaveBeenLastCalledWith({
+ args: ["-m", "--", "/source/instructions.md"],
+ cmd: "realpath",
+ signal: undefined,
+ });
+ expect(sessionSandbox.writeFiles).toHaveBeenLastCalledWith(
+ [
+ {
+ content: Buffer.from("updated instructions\n"),
+ path: "/workspace/repository/agent/instructions.md",
+ },
+ ],
+ { signal: undefined },
+ );
+ });
+
it("resolves and writes all seed paths to the sandbox filesystem in one batch", async () => {
const templateSandbox = createMockSandbox({ name: "template" });
const sessionSandbox = createMockSandbox({ name: "session" });
diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.ts b/packages/eve/src/execution/sandbox/bindings/vercel.ts
index f7f99c8cd..8cad28ce1 100644
--- a/packages/eve/src/execution/sandbox/bindings/vercel.ts
+++ b/packages/eve/src/execution/sandbox/bindings/vercel.ts
@@ -40,6 +40,11 @@ import {
type CreateVercelSandbox,
type VercelSandboxCreateParams,
} from "#execution/sandbox/bindings/vercel-create-sdk.js";
+import {
+ errorMessage,
+ ensureVercelSandboxTags,
+ resolveVercelSandboxTags,
+} from "#execution/sandbox/bindings/vercel-options.js";
import {
isVercelSandboxMissingError,
isVercelSnapshotUnavailableError,
@@ -534,7 +539,8 @@ function createVercelInternalSandboxSession(
},
async writeFile(options: SandboxWriteFileOptions) {
const bytes = await streamToBuffer(options.content);
- await sandbox.writeFiles([{ content: bytes, path: options.path }]);
+ const path = await resolveVercelWritePath(sandbox, options.path, options.abortSignal);
+ await sandbox.writeFiles([{ content: bytes, path }], { signal: options.abortSignal });
},
async removePath(options: SandboxRemovePathOptions) {
await sandbox.fs.rm(options.path, {
@@ -575,6 +581,23 @@ function resolveVercelSandboxPath(path: string): string {
return `${WORKSPACE_ROOT}/${path}`;
}
+async function resolveVercelWritePath(
+ sandbox: VercelSandbox,
+ path: string,
+ signal?: AbortSignal,
+): Promise<string> {
+ const result = await sandbox.runCommand({
+ args: ["-m", "--", path],
+ cmd: "realpath",
+ signal,
+ });
+ const resolved = (await result.stdout()).trim();
+ if (result.exitCode !== 0 || !resolved.startsWith("/") || resolved.includes("\n")) {
+ throw new Error(`Failed to resolve Vercel Sandbox write path: ${path}`);
+ }
+ return resolved;
+}
+
function isUnprovisionedTerminalTemplateSandbox(
sandbox: VercelSandbox,
authorSnapshotId: string | undefined,
@@ -612,87 +635,8 @@ function getVercelSandboxName(metadata: Record<string, unknown> | undefined): st
return typeof sandboxName === "string" ? sandboxName : undefined;
}
-function resolveVercelSandboxTags(
- userTags: VercelCreateOptions["tags"],
- eveTags: SandboxBackendTags | undefined,
-): Record<string, string> | undefined {
- const tags: Record<string, string> = {};
-
- if (userTags !== undefined) {
- for (const [key, value] of Object.entries(userTags as Record<string, string>)) {
- tags[key] = value;
- }
- }
-
- if (eveTags !== undefined) {
- for (const [key, value] of Object.entries(eveTags)) {
- tags[key] = value;
- }
- }
-
- const count = Object.keys(tags).length;
- if (count === 0) {
- return undefined;
- }
-
- if (count > VERCEL_SANDBOX_TAG_LIMIT) {
- throw new Error(
- `Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. ` +
- 'eve reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercel().',
- );
- }
-
- return tags;
-}
-
-async function ensureVercelSandboxTags(
- sandbox: VercelSandbox,
- tags: Record<string, string> | undefined,
-): Promise<void> {
- if (tags === undefined || areVercelSandboxTagsEqual(sandbox.tags, tags)) {
- return;
- }
-
- await sandbox.update({ tags });
-}
-
-function areVercelSandboxTagsEqual(
- current: Record<string, string> | undefined,
- next: Record<string, string>,
-): boolean {
- const currentTags = current ?? {};
- const currentEntries = Object.entries(currentTags);
- const nextEntries = Object.entries(next);
-
- if (currentEntries.length !== nextEntries.length) {
- return false;
- }
-
- return nextEntries.every(([key, value]) => currentTags[key] === value);
-}
-
-function errorMessage(error: unknown): string {
- if (error instanceof Error) {
- const responseJson = (error as { readonly json?: unknown }).json;
- const responseText = (error as { readonly text?: unknown }).text;
- const responseBody =
- typeof responseText === "string" && responseText.length > 0
- ? responseText
- : responseJson !== undefined
- ? JSON.stringify(responseJson)
- : undefined;
- if (responseBody !== undefined) {
- return `${error.message}: ${responseBody}`;
- }
- return error.message;
- }
- return String(error);
-}
-
/**
* 30 minutes. The `@vercel/sandbox` SDK defaults to 5 minutes which is
* too short for multi-step workflows — the VM expires between steps.
*/
const DEFAULT_SANDBOX_TIMEOUT_MS = 30 * 60 * 1_000;
-
-const VERCEL_SANDBOX_TAG_LIMIT = 5;
diff --git a/packages/eve/src/internal/authored-package-boundary.test.ts b/packages/eve/src/internal/authored-package-boundary.test.ts
index 538e7c916..3294b3b95 100644
--- a/packages/eve/src/internal/authored-package-boundary.test.ts
+++ b/packages/eve/src/internal/authored-package-boundary.test.ts
@@ -4,12 +4,44 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
+ createGenerationPackageBoundaryPlugin,
createRuntimeLoaderPackageBoundaryPlugin,
type RolldownResolveContext,
} from "#internal/authored-package-boundary.js";
const PACKAGE_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
+describe("createGenerationPackageBoundaryPlugin", () => {
+ it("resolves package-private imports from the importing dependency", async () => {
+ const plugin = createGenerationPackageBoundaryPlugin({
+ externalDependencies: [],
+ packageRoot: join(PACKAGE_ROOT, "test/consumer-app"),
+ });
+ const resolveId = plugin.resolveId as (
+ this: RolldownResolveContext,
+ source: string,
+ importer: string | undefined,
+ options: { kind: string },
+ ) => Promise<unknown>;
+ const context: RolldownResolveContext = {
+ async resolve() {
+ throw new Error("package imports should resolve before delegating");
+ },
+ };
+
+ await expect(
+ resolveId.call(
+ context,
+ "#shared/git.js",
+ join(PACKAGE_ROOT, "dist/src/self-modification/agent.js"),
+ { kind: "import-statement" },
+ ),
+ ).resolves.toEqual({
+ id: join(PACKAGE_ROOT, "dist/src/shared/git.js"),
+ });
+ });
+});
+
describe("createRuntimeLoaderPackageBoundaryPlugin", () => {
it("resolves eve package imports through the published dist mapping", async () => {
const plugin = createRuntimeLoaderPackageBoundaryPlugin({
diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.ts
index 79198ec58..06d7cc598 100644
--- a/packages/eve/src/internal/authored-package-boundary.ts
+++ b/packages/eve/src/internal/authored-package-boundary.ts
@@ -56,6 +56,15 @@ export function createGenerationPackageBoundaryPlugin(input: {
return { external: true, id: resolveFrameworkRuntimeImport(source) };
}
+ // Package-private imports must be resolved before this bundle is moved
+ // into the generated host, where the owning package scope no longer exists.
+ if (source.startsWith("#")) {
+ const resolvedPackageImport = resolvePackageImport(source, importer, input.packageRoot);
+ if (resolvedPackageImport !== undefined) {
+ return { id: resolvedPackageImport };
+ }
+ }
+
const externalModule = await resolveConfiguredExternalModule.call(this, {
externalDependencies: input.externalDependencies,
importer,
@@ -99,7 +108,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {
// Resolve through Node's default package-import conditions here so a
// packed eve installation does not leak #shared/* into the bundle.
if (source.startsWith("#")) {
- const resolvedPackageImport = resolvePackageImport(source, input.packageRoot);
+ const resolvedPackageImport = resolvePackageImport(source, importer, input.packageRoot);
if (resolvedPackageImport !== undefined) {
return { id: resolvedPackageImport };
}
@@ -301,28 +310,40 @@ function packageImportName(source: string): string {
}
function nearestPackageName(filePath: string): string | undefined {
+ const packageRoot = nearestPackageRoot(filePath);
+ if (packageRoot === undefined) return undefined;
+
+ try {
+ const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) as {
+ name?: unknown;
+ };
+ return typeof manifest.name === "string" && manifest.name.length > 0
+ ? manifest.name
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function nearestPackageRoot(filePath: string): string | undefined {
let directory = dirname(toCanonicalPath(filePath));
while (true) {
- const manifestPath = join(directory, "package.json");
- if (existsSync(manifestPath)) {
- try {
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { name?: unknown };
- return typeof manifest.name === "string" && manifest.name.length > 0
- ? manifest.name
- : undefined;
- } catch {
- return undefined;
- }
- }
+ if (existsSync(join(directory, "package.json"))) return directory;
const parent = dirname(directory);
- if (parent === directory) {
- return undefined;
- }
+ if (parent === directory) return undefined;
directory = parent;
}
}
-function resolvePackageImport(source: string, packageRoot: string): string | undefined {
+function resolvePackageImport(
+ source: string,
+ importer: string | undefined,
+ fallbackPackageRoot: string,
+): string | undefined {
+ const packageRoot =
+ importer === undefined || importer.startsWith("\0")
+ ? fallbackPackageRoot
+ : (nearestPackageRoot(importer) ?? fallbackPackageRoot);
try {
const resolved = createRequire(join(packageRoot, "package.json")).resolve(source);
return isPathInsideOrEqual(toCanonicalPath(resolved), toCanonicalPath(packageRoot))
diff --git a/packages/eve/src/sandbox/backends/default.ts b/packages/eve/src/sandbox/backends/default.ts
index 97cb66227..15797333d 100644
--- a/packages/eve/src/sandbox/backends/default.ts
+++ b/packages/eve/src/sandbox/backends/default.ts
@@ -39,7 +39,8 @@ export interface DefaultSandboxProbes {
// module participates in an import cycle through the runtime resolver,
// so the probe imports may still be uninitialized live bindings when
// this object literal evaluates. Accessing them at call time is safe.
-const PRODUCTION_PROBES: DefaultSandboxProbes = {
+/** Runtime probes shared by availability-aware built-in backend selectors. @internal */
+export const SANDBOX_BACKEND_PROBES: DefaultSandboxProbes = {
isDeployedOnVercel: () => Boolean(process.env.VERCEL),
isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),
isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),
@@ -64,7 +65,7 @@ const PRODUCTION_PROBES: DefaultSandboxProbes = {
* `vercel()`).
*/
export function defaultSandbox(opts?: DefaultSandboxOptions): SandboxBackend {
- return lazyBackend(() => selectDefaultSandbox(opts, PRODUCTION_PROBES));
+ return lazyBackend(() => selectDefaultSandbox(opts, SANDBOX_BACKEND_PROBES));
}
/**
diff --git a/packages/eve/src/self-modification/agent.test.ts b/packages/eve/src/self-modification/agent.test.ts
index d1dde2507..a6393ff2b 100644
--- a/packages/eve/src/self-modification/agent.test.ts
+++ b/packages/eve/src/self-modification/agent.test.ts
@@ -3,6 +3,14 @@ import { afterEach, describe, expect, it } from "vitest";
import { DEFAULT_SELF_MODIFICATION_MODEL, defineSelfModificationAgent } from "./agent.js";
const originalEveDev = process.env.EVE_DEV;
+const originalGitHubToken = process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN;
+const deployed = {
+ deployed: {
+ source: { git: { directory: ".", repository: "github.com/acme/agent" } },
+ target: { branch: "main" },
+ credentials: { pat: true },
+ },
+} as const;
afterEach(() => {
if (originalEveDev === undefined) {
@@ -10,6 +18,11 @@ afterEach(() => {
} else {
process.env.EVE_DEV = originalEveDev;
}
+ if (originalGitHubToken === undefined) {
+ delete process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN;
+ } else {
+ process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN = originalGitHubToken;
+ }
});
describe("defineSelfModificationAgent", () => {
@@ -35,4 +48,24 @@ describe("defineSelfModificationAgent", () => {
expect(definition).toMatchObject({ model: "openai/gpt-5" });
});
+
+ it("requires configured deployment and credential preflight", async () => {
+ delete process.env.EVE_DEV;
+ const agent = defineSelfModificationAgent({ config: deployed });
+ expect(agent.events["session.started"]?.({}, {} as never)).toBeNull();
+
+ process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN = "secret";
+ const definition = await agent.events["session.started"]?.({}, {} as never);
+ expect(definition?.description).toContain("draft pull request");
+ expect(definition?.description).toContain("non-secret answers");
+ });
+
+ it("keeps configured deployment local under eve dev", async () => {
+ process.env.EVE_DEV = "1";
+ process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN = "secret";
+ const agent = defineSelfModificationAgent({ config: deployed });
+ const definition = await agent.events["session.started"]?.({}, {} as never);
+ expect(definition?.description).toContain("developer");
+ expect(definition?.description).not.toContain("draft pull request");
+ });
});
diff --git a/packages/eve/src/self-modification/agent.ts b/packages/eve/src/self-modification/agent.ts
index 7ef56bf3d..493327522 100644
--- a/packages/eve/src/self-modification/agent.ts
+++ b/packages/eve/src/self-modification/agent.ts
@@ -1,10 +1,16 @@
import { defineAgent, defineDynamic, type AgentStaticModelDefinition } from "#public/index.js";
+import { resolveSelfModificationConfig, type SelfModificationConfig } from "./config.js";
+import { hasGitHubCredential } from "./credentials.js";
+import { resolveSelfModificationMode } from "./mode.js";
+
/** Default model used by the self-modification subagent. */
export const DEFAULT_SELF_MODIFICATION_MODEL = "anthropic/claude-sonnet-5";
-/** Configuration for the development-only self-modification subagent. */
+/** Configuration for the self-modification subagent. */
export interface SelfModificationAgentOptions {
+ /** Policy shared with the sandbox and extension mount. */
+ readonly config?: SelfModificationConfig;
/**
* Model used by the self-modification subagent.
*
@@ -13,29 +19,46 @@ export interface SelfModificationAgentOptions {
readonly model?: AgentStaticModelDefinition;
}
-/** Defines the development-only self-modification dynamic subagent. */
+const localDescription =
+ "Delegate here when the developer asks to change this eve agent or its authored source. " +
+ "Describe the requested behavior change without guessing source paths or passing runtime skill paths under $HOME/.agents or /workspace/skills; the subagent discovers authored files under its /source mount. " +
+ "Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the developer does not mention files or source code. " +
+ "Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” " +
+ "For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. " +
+ "Also delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them. " +
+ "Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted. " +
+ "Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " +
+ "Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn. " +
+ "If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.";
+
+const deployedDescription =
+ "Delegate here when the user asks to change this eve agent or its authored source. " +
+ "Describe the requested behavior change without guessing source paths or passing runtime skill paths under $HOME/.agents or /workspace/skills; the subagent discovers authored files in an isolated checkout under its /source mount. " +
+ "Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the user does not mention files or source code. " +
+ "Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” " +
+ "For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. " +
+ "Also delegate requests to add integrations, channels, connections, or capabilities: the subagent searches the official eve registry and can install source changes into the draft proposal. Setup may require non-secret answers or an external action, and secret binding remains separate. " +
+ "Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " +
+ "Source edits do not affect the caller’s current turn. The subagent can publish only a draft pull request, and changes become effective only after review, merge, and redeployment. " +
+ "If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.";
+
+/** Defines the environment-aware self-modification dynamic subagent. */
export function defineSelfModificationAgent(options: SelfModificationAgentOptions = {}) {
const model = options.model ?? DEFAULT_SELF_MODIFICATION_MODEL;
+ const config = resolveSelfModificationConfig(options.config);
+
+ const resolve = () => {
+ const mode = resolveSelfModificationMode(config);
+ if (mode === "local") return defineAgent({ description: localDescription, model });
+ if (mode !== "deployed" || config.deployed === undefined) return null;
+ if (config.deployed.credentials.kind === "pat" && !hasGitHubCredential()) return null;
+ return defineAgent({ description: deployedDescription, model });
+ };
return defineDynamic({
events: {
- "session.started": () =>
- process.env.EVE_DEV === "1"
- ? defineAgent({
- description:
- "Delegate here when the developer asks to change this eve agent or its authored source. " +
- "Describe the requested behavior change without guessing source paths or passing runtime skill paths under $HOME/.agents or /workspace/skills; the subagent discovers authored files under its /source mount. " +
- "Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the developer does not mention files or source code. " +
- "Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” " +
- "For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. " +
- "Also delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them. " +
- "Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted. " +
- "Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " +
- "Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn. " +
- "If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.",
- model,
- })
- : null,
+ "session.started": resolve,
+ "turn.started": resolve,
},
});
}
diff --git a/packages/eve/src/self-modification/extension/eve-add.ts b/packages/eve/src/self-modification/extension/eve-add.ts
index 9c54fad94..bede9059f 100644
--- a/packages/eve/src/self-modification/extension/eve-add.ts
+++ b/packages/eve/src/self-modification/extension/eve-add.ts
@@ -27,11 +27,17 @@ export type EveAddOutcome =
readonly changed?: readonly string[];
};
-interface HeadlessEvent {
+export interface HeadlessEvent {
readonly version?: number;
readonly type: string;
readonly item?: string;
+ readonly completedItems?: readonly string[];
+ readonly deploymentRequired?: boolean;
+ readonly installed?: boolean;
readonly message?: string;
+ readonly question?: unknown;
+ readonly url?: string;
+ readonly userCode?: string;
readonly failureCode?: string;
readonly rolledBack?: boolean;
readonly changed?: readonly string[];
@@ -129,7 +135,8 @@ export function readTerminalHeadlessEvent(output: string): HeadlessEvent | undef
(event.type === "completed" ||
event.type === "blocked" ||
event.type === "failed" ||
- event.type === "cancelled")
+ event.type === "cancelled" ||
+ event.type === "external_action")
) {
terminal = event;
}
diff --git a/packages/eve/src/self-modification/extension/extension.ts b/packages/eve/src/self-modification/extension/extension.ts
index eb45471fd..0a24f7d93 100644
--- a/packages/eve/src/self-modification/extension/extension.ts
+++ b/packages/eve/src/self-modification/extension/extension.ts
@@ -1,3 +1,23 @@
import { defineExtension } from "eve/extension";
+import { z } from "zod";
-export default defineExtension();
+export const selfModificationConfigSchema = z.object({
+ local: z.object({ enabled: z.boolean().optional() }).optional(),
+ deployed: z
+ .object({
+ credentials: z
+ .object({
+ pat: z.literal(true).optional(),
+ vercelConnect: z.object({ connector: z.string() }).optional(),
+ })
+ .optional(),
+ source: z.object({
+ git: z.object({ directory: z.string(), repository: z.string() }),
+ }),
+ target: z.object({ branch: z.string() }),
+ })
+ .optional(),
+});
+
+/** Extension mount configured with the same policy as the agent and sandbox. */
+export default defineExtension({ config: selfModificationConfigSchema });
diff --git a/packages/eve/src/self-modification/extension/instructions.ts b/packages/eve/src/self-modification/extension/instructions.ts
index 348e860c0..0727abee6 100644
--- a/packages/eve/src/self-modification/extension/instructions.ts
+++ b/packages/eve/src/self-modification/extension/instructions.ts
@@ -1,24 +1,34 @@
import { defineDynamic, defineInstructions } from "eve/instructions";
-const instructions = `You are an expert coding assistant operating inside of an eve agent. You help users by reading files, editing code, and writing new files that shape the behavior of the agent itself.
+import { resolveSelfModificationConfig } from "../config.js";
+import { resolveSelfModificationMode } from "../mode.js";
+import selfModification from "./extension.js";
+
+const introduction = `You are an expert coding assistant operating inside of an eve agent. You help users by reading files, editing code, and writing new files that shape the behavior of the agent itself.
The source code of the eve agent is mounted read-write at /source. Use bash only for read-only discovery and available validation commands. Never modify source files with bash, sed, awk, redirection, or scripting. /source is the authored agent directory.
Use 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.
-Use selfmod__search_models to get the list of available models.
+Use selfmod__search_models to get the list of available models.`;
-Before writing an integration by hand, check whether the eve registry already ships it with selfmod__search_registry. If it has an item that fulfills the requirement, install it with selfmod__registry_add using its address. If the registry does not have any matches that will fulfill the requirement, or if the developer asks for a custom implementation, write the integration yourself.
+const workingGuidance = `Batch independent read-only tool calls and edits to different files in one response. Do not edit the same file concurrently.
-The selfmod__registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result from the tool call automatically opens the existing setup panel for the user to complete setup there. In headless development, relay the terminal command the tool names.
-
-Batch independent tool calls in one response.
+Run selfmod__registry_add separately from file edits and other registry installations. Complete all edits and registry installations before publication, and call publish by itself.
Skip task lists for simple work - only use them for complex actions. Never spend a turn only reporting status or updating the task list - batch them with other calls.
Registry installation is outside the source sandbox.
-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.
+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.`;
+
+const developmentMarkdown = `${introduction}
+
+Before writing an integration by hand, check whether the eve registry already ships it with selfmod__search_registry. If it has an item that fulfills the requirement, install it with selfmod__registry_add using its address. If the registry does not have any matches that will fulfill the requirement, or if the developer asks for a custom implementation, write the integration yourself.
+
+The selfmod__registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result from the tool call automatically opens the existing setup panel for the user to complete setup there. In headless development, relay the terminal command the tool names.
+
+${workingGuidance}
Local eve dev logs are available read-only at /logs.
@@ -28,6 +38,22 @@ Treat a successful file-edit tool result as confirmation; do not reread a file s
Local trace segments are mounted read-only at /traces when available. Inspect other traces only when the user asks about another session or broader behavior.`;
+const developmentInstructions = defineInstructions({ markdown: developmentMarkdown });
+
+const deployedInstructions = defineInstructions({
+ markdown: `${introduction}
+
+Before writing an integration by hand, check whether the official eve registry already ships it with selfmod__search_registry. If it has a suitable item, call selfmod__registry_add with the exact address. The tool may return \`completed\`, \`input-required\`, \`external-action-required\`, \`cancelled\`, or \`failed\`. Supply only non-secret structured answers when continuing an \`input-required\` setup; set \`installed: true\` so the continuation does not reinstall source. Never request, accept, or repeat secret values. External authorization and secret binding are incomplete follow-up boundaries, not evidence that an integration is active.
+
+${workingGuidance}
+
+The configured target branch is checked out as a disposable workspace under /workspace/repository. Make ordinary changes through /source, which is the writable view of the configured application's agent/ directory. Publication validates the final repository snapshot, including registry, manifest, and lockfile changes. Never modify Git refs, access GitHub directly, or use shell commands to write files. The sandbox has no reusable GitHub credential after checkout.
+
+Before publication, review and summarize the complete intended scope. Call publish once with a concise title and summary. A successful result is only a draft pull request. Return its URL and changed paths, and state that merge and deployment have not occurred.
+
+Treat a successful file-edit tool result as confirmation; do not reread a file solely to verify that the edit succeeded. Do not approximate unavailable build or test commands with broad source searches.`,
+});
+
function readTrace(
event: unknown,
): { readonly traceFlags: number; readonly traceId: string } | undefined {
@@ -43,8 +69,14 @@ function readTrace(
export default defineDynamic({
events: {
"session.started": (event) => {
+ const mode = resolveSelfModificationMode(
+ resolveSelfModificationConfig(selfModification.config),
+ );
+ if (mode === "deployed") return deployedInstructions;
+ if (mode !== "local") return null;
+
const trace = readTrace(event);
- if (trace === undefined) return defineInstructions({ markdown: instructions });
+ if (trace === undefined) return developmentInstructions;
const availability =
(trace.traceFlags & 1) === 1
@@ -52,7 +84,7 @@ export default defineDynamic({
: "This trace was not sampled, so local segments may be absent. If any are present,";
return defineInstructions({
- markdown: `${instructions}\n\nThe invoking trace has ID ${trace.traceId}. ${availability} inspect them at /traces/${trace.traceId}.`,
+ markdown: `${developmentMarkdown}\n\nThe invoking trace has ID ${trace.traceId}. ${availability} inspect them at /traces/${trace.traceId}.`,
});
},
},
diff --git a/packages/eve/src/self-modification/extension/production-registry-add.ts b/packages/eve/src/self-modification/extension/production-registry-add.ts
new file mode 100644
index 000000000..85afbecca
--- /dev/null
+++ b/packages/eve/src/self-modification/extension/production-registry-add.ts
@@ -0,0 +1,309 @@
+import type { SandboxSession } from "eve/sandbox";
+
+import { shellQuote } from "#shared/shell-quote.js";
+
+import type { PreparedSelfModificationWorkspace } from "../git-workspace.js";
+import { gitOutput, runGitCommand } from "../git.js";
+import { assertFullSha } from "../identifiers.js";
+import { readTerminalHeadlessEvent } from "./eve-add.js";
+
+const OFFICIAL_ADDRESS =
+ /^(?:(?:channel|connection|extension|instrumentation)\/)?[a-z0-9][a-z0-9._-]*$/u;
+const SAFE_PATH = "/usr/local/bin:/usr/bin:/bin";
+
+export type ProductionRegistryInstallResult =
+ | {
+ readonly kind: "completed";
+ readonly completedItems: readonly string[];
+ readonly changedPaths: readonly string[];
+ readonly deploymentRequired: boolean;
+ }
+ | { readonly kind: "input-required"; readonly installed: boolean; readonly question: unknown }
+ | {
+ readonly kind: "external-action-required";
+ readonly installed: boolean;
+ readonly message: string;
+ readonly url: string;
+ readonly userCode?: string;
+ }
+ | { readonly kind: "failed" | "cancelled"; readonly message: string };
+
+export function assertOfficialRegistryAddress(address: string): void {
+ if (!OFFICIAL_ADDRESS.test(address))
+ throw new Error(
+ "Production registry installation requires an exact official eve registry address.",
+ );
+}
+
+/** Installs only official items and rolls back this invocation's tree on terminal failure. */
+export async function installProductionRegistryItem(input: {
+ readonly address: string;
+ readonly answers?: Readonly<Record<string, unknown>>;
+ readonly installed?: boolean;
+ readonly sandbox: Pick<SandboxSession, "run">;
+ readonly signal?: AbortSignal;
+ readonly workspace: PreparedSelfModificationWorkspace;
+}): Promise<ProductionRegistryInstallResult> {
+ assertOfficialRegistryAddress(input.address);
+ const applicationRoot =
+ input.workspace.directory === "."
+ ? input.workspace.repositoryPath
+ : `${input.workspace.repositoryPath}/${input.workspace.directory}`;
+ const packageRoot = await locatePackageManagerRoot(
+ input.sandbox,
+ applicationRoot,
+ input.workspace.repositoryPath,
+ input.signal,
+ );
+ if (packageRoot === undefined)
+ return { kind: "failed", message: "The proposal checkout has no supported lockfile." };
+ if (
+ !(await runChecked(
+ input.sandbox,
+ `mkdir -p ${quote(`${input.workspace.repositoryPath}/.git/info`)} && printf '\\nnode_modules/\\n**/node_modules/\\n' >> ${quote(`${input.workspace.repositoryPath}/.git/info/exclude`)}`,
+ input.signal,
+ )) ||
+ !(await runChecked(input.sandbox, bootstrapCommand(packageRoot), input.signal))
+ ) {
+ return {
+ kind: "failed",
+ message: "Could not prepare the proposal checkout's locked dependencies.",
+ };
+ }
+ const executable = await locateEveExecutable(
+ input.sandbox,
+ applicationRoot,
+ packageRoot.root,
+ input.signal,
+ );
+ if (executable === undefined)
+ return {
+ kind: "failed",
+ message: "The proposal checkout's locked dependencies do not provide the eve CLI.",
+ };
+ const startingTree = await captureTree(input.sandbox, input.workspace.repositoryPath);
+ if (input.answers !== undefined) {
+ if (input.installed !== true) {
+ return {
+ kind: "failed",
+ message: "Setup answers require a prior installed input-required result.",
+ };
+ }
+ let probe: Awaited<ReturnType<typeof input.sandbox.run>>;
+ try {
+ probe = await input.sandbox.run({
+ abortSignal: input.signal,
+ command: isolatedCommand(
+ applicationRoot,
+ `${quote(executable)} add ${quote(input.address)} --non-interactive --skip-install`,
+ ),
+ });
+ } finally {
+ await restoreTree(input.sandbox, input.workspace.repositoryPath, startingTree);
+ }
+ const event = readTerminalHeadlessEvent(
+ `${String(probe.stdout ?? "")}\n${String(probe.stderr ?? "")}`,
+ );
+ if (event?.type !== "blocked" || event.item !== input.address) {
+ return {
+ kind: "failed",
+ message: "Setup continuation is no longer waiting for a validated question.",
+ };
+ }
+ const question = setupQuestion(event.question);
+ if (question === undefined) {
+ return {
+ kind: "failed",
+ message: "Registry setup returned an invalid continuation question.",
+ };
+ }
+ if (question.kind === "environment") {
+ return { kind: "input-required", installed: true, question: event.question };
+ }
+ if (!acceptsNonSecretSetupAnswers(question, input.answers)) {
+ return {
+ kind: "failed",
+ message: "Setup answers must contain only the current non-secret question.",
+ };
+ }
+ }
+ const answerArgs = Object.entries(input.answers ?? {}).flatMap(([key, value]) => [
+ "--answer",
+ `${key}=${JSON.stringify(value)}`,
+ ]);
+ try {
+ const command = `${quote(executable)} add ${quote(input.address)} --non-interactive ${input.installed === true ? "--skip-install " : ""}${answerArgs.map(quote).join(" ")}`;
+ const result = await input.sandbox.run({
+ abortSignal: input.signal,
+ command: isolatedCommand(applicationRoot, command),
+ });
+ const event = readTerminalHeadlessEvent(
+ `${String(result.stdout ?? "")}\n${String(result.stderr ?? "")}`,
+ );
+ if (event?.type === "completed" && event.item === input.address && result.exitCode === 0) {
+ const resultingTree = await captureTree(input.sandbox, input.workspace.repositoryPath);
+ return {
+ kind: "completed",
+ changedPaths: await changedPaths(
+ input.sandbox,
+ input.workspace.repositoryPath,
+ startingTree,
+ resultingTree,
+ ),
+ completedItems: event.completedItems?.filter((item) => OFFICIAL_ADDRESS.test(item)) ?? [],
+ deploymentRequired: event.deploymentRequired === true,
+ };
+ }
+ if (event?.type === "blocked" && event.item === input.address) {
+ return {
+ kind: "input-required",
+ installed: event.installed === true,
+ question: event.question ?? event,
+ };
+ }
+ if (
+ event?.type === "external_action" &&
+ typeof event.url === "string" &&
+ typeof event.message === "string"
+ ) {
+ const result: {
+ kind: "external-action-required";
+ installed: boolean;
+ message: string;
+ url: string;
+ userCode?: string;
+ } = {
+ kind: "external-action-required",
+ installed: input.installed === true,
+ message: event.message,
+ url: event.url,
+ };
+ if (typeof event.userCode === "string") result.userCode = event.userCode;
+ return result;
+ }
+ await restoreTree(input.sandbox, input.workspace.repositoryPath, startingTree);
+ return event?.type === "cancelled" || input.signal?.aborted === true
+ ? { kind: "cancelled", message: `Installing ${input.address} was cancelled.` }
+ : { kind: "failed", message: `Installing ${input.address} failed.` };
+ } catch (error) {
+ await restoreTree(input.sandbox, input.workspace.repositoryPath, startingTree);
+ throw error;
+ }
+}
+
+export function acceptsNonSecretSetupAnswers(
+ question: { readonly key: string; readonly kind: string },
+ answers: Readonly<Record<string, unknown>>,
+): boolean {
+ return (
+ question.kind !== "environment" &&
+ Object.keys(answers).length === 1 &&
+ answers[question.key] !== undefined
+ );
+}
+
+function setupQuestion(
+ value: unknown,
+): { readonly key: string; readonly kind: string } | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+ const question = value as { key?: unknown; kind?: unknown; sensitive?: unknown };
+ if (
+ typeof question.key !== "string" ||
+ question.key.length === 0 ||
+ typeof question.kind !== "string"
+ ) {
+ return undefined;
+ }
+ return { key: question.key, kind: question.sensitive === true ? "environment" : question.kind };
+}
+
+interface PackageRoot {
+ readonly kind: "npm" | "pnpm";
+ readonly root: string;
+}
+export async function locatePackageManagerRoot(
+ sandbox: Pick<SandboxSession, "run">,
+ applicationRoot: string,
+ repositoryRoot: string,
+ signal?: AbortSignal,
+): Promise<PackageRoot | undefined> {
+ const result = await sandbox.run({
+ abortSignal: signal,
+ command: `root=${quote(applicationRoot)}; repository=${quote(repositoryRoot)}; while :; do if test -f "$root/pnpm-lock.yaml"; then printf 'pnpm\\t%s' "$root"; exit 0; fi; if test -f "$root/package-lock.json"; then printf 'npm\\t%s' "$root"; exit 0; fi; test "$root" = "$repository" && exit 0; root=\${root%/*}; done`,
+ });
+ if (result.exitCode !== 0) throw new Error("Could not inspect the proposal package workspace.");
+ const match = /^(pnpm|npm)\t([^\n]+)$/u.exec(String(result.stdout ?? ""));
+ if (match === null) return undefined;
+ const root = match[2]!;
+ if (root !== repositoryRoot && !root.startsWith(`${repositoryRoot}/`))
+ throw new Error("Package manager root escaped the proposal repository.");
+ return { kind: match[1]! as PackageRoot["kind"], root };
+}
+export function bootstrapCommand(root: PackageRoot): string {
+ return isolatedCommand(
+ root.root,
+ root.kind === "pnpm"
+ ? `corepack pnpm --dir ${quote(root.root)} install --frozen-lockfile --ignore-scripts`
+ : `npm ci --prefix ${quote(root.root)} --ignore-scripts`,
+ );
+}
+async function locateEveExecutable(
+ sandbox: Pick<SandboxSession, "run">,
+ applicationRoot: string,
+ packageRoot: string,
+ signal?: AbortSignal,
+): Promise<string | undefined> {
+ const candidates = [
+ `${applicationRoot}/node_modules/.bin/eve`,
+ `${packageRoot}/node_modules/.bin/eve`,
+ ];
+ const result = await sandbox.run({
+ abortSignal: signal,
+ command: `for executable in ${candidates.map(quote).join(" ")}; do if test -x "$executable"; then printf '%s' "$executable"; exit 0; fi; done`,
+ });
+ if (result.exitCode !== 0) throw new Error("Could not inspect the checkout's eve executable.");
+ return candidates.includes(String(result.stdout ?? "")) ? String(result.stdout) : undefined;
+}
+async function captureTree(
+ sandbox: Pick<SandboxSession, "run">,
+ repository: string,
+): Promise<string> {
+ await runGitCommand(sandbox, `git -C ${quote(repository)} add -A -- .`);
+ const tree = await gitOutput(sandbox, `git -C ${quote(repository)} write-tree`);
+ assertFullSha(tree, "registry tree");
+ return tree;
+}
+async function restoreTree(
+ sandbox: Pick<SandboxSession, "run">,
+ repository: string,
+ tree: string,
+): Promise<void> {
+ await runGitCommand(sandbox, `git -C ${quote(repository)} read-tree --reset -u ${quote(tree)}`);
+ await runGitCommand(sandbox, `git -C ${quote(repository)} clean -fd -- .`);
+}
+async function changedPaths(
+ sandbox: Pick<SandboxSession, "run">,
+ repository: string,
+ before: string,
+ after: string,
+): Promise<readonly string[]> {
+ const raw = await gitOutput(
+ sandbox,
+ `git -C ${quote(repository)} diff-tree -r --no-commit-id --name-only -z ${quote(before)} ${quote(after)}`,
+ false,
+ );
+ return raw.split("\0").filter((path) => path.length > 0);
+}
+async function runChecked(
+ sandbox: Pick<SandboxSession, "run">,
+ command: string,
+ signal?: AbortSignal,
+): Promise<boolean> {
+ return (await sandbox.run({ abortSignal: signal, command })).exitCode === 0;
+}
+function isolatedCommand(cwd: string, command: string): string {
+ return `env -i HOME=/tmp/eve-selfmod-home PATH=${SAFE_PATH} CI=1 npm_config_ignore_scripts=true sh -c ${quote(`cd ${quote(cwd)} && ${command}`)}`;
+}
+function quote(value: string): string {
+ return shellQuote(value);
+}
diff --git a/packages/eve/src/self-modification/extension/source-lock.ts b/packages/eve/src/self-modification/extension/source-lock.ts
deleted file mode 100644
index 5cb525194..000000000
--- a/packages/eve/src/self-modification/extension/source-lock.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * 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/src/self-modification/extension/tools/edit_file.ts b/packages/eve/src/self-modification/extension/tools/edit_file.ts
index ec8a1afd3..0e46e45e6 100644
--- a/packages/eve/src/self-modification/extension/tools/edit_file.ts
+++ b/packages/eve/src/self-modification/extension/tools/edit_file.ts
@@ -1,7 +1,5 @@
import { defineTool } from "eve/tools";
-import { withAuthoredSourceLock } from "../source-lock.js";
-
const replacementSchema = {
type: "object",
additionalProperties: false,
@@ -27,7 +25,7 @@ const inputSchema = {
path: {
type: "string",
minLength: 1,
- description: "Path to the file to edit (relative or absolute).",
+ description: "Absolute path below /source to edit.",
},
edits: {
type: "array",
@@ -123,24 +121,25 @@ export default defineTool({
const sandbox = await ctx.getSandbox();
- // 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 });
+ const resolved = sandbox.resolvePath(path);
+ if (!resolved.startsWith("/source/") || resolved.split("/").some((part) => part === "..")) {
+ throw new Error("Self-modification file edits must stay below /source.");
+ }
- 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.`);
- }
+ const content = await sandbox.readTextFile({ path: resolved });
- 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.`);
+ }
- return { path: sandbox.resolvePath(path), replacements: edits.length };
+ await sandbox.writeTextFile({
+ content: applyExactEdits(content, edits),
+ path: resolved,
});
+
+ return { path: resolved, replacements: edits.length };
},
});
diff --git a/packages/eve/src/self-modification/extension/tools/publish.ts b/packages/eve/src/self-modification/extension/tools/publish.ts
new file mode 100644
index 000000000..c0900f189
--- /dev/null
+++ b/packages/eve/src/self-modification/extension/tools/publish.ts
@@ -0,0 +1,122 @@
+import { defineDynamic, defineTool, type ToolContext } from "eve/tools";
+
+import { resolveSelfModificationConfig } from "../../config.js";
+import { createGitHubCredentialProvider } from "../../credentials.js";
+import { readPreparedSelfModificationWorkspace } from "../../git-workspace.js";
+import { publishGitHubDraftPullRequest } from "../../github-publisher.js";
+import { resolveSelfModificationMode } from "../../mode.js";
+import { withSelfModificationWorkspaceLock } from "../../workspace-lock.js";
+import selfModification from "../extension.js";
+
+const inputSchema = {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ summary: {
+ type: "string",
+ minLength: 1,
+ maxLength: 10_000,
+ description: "Concise description of the proposed agent source change.",
+ },
+ title: {
+ type: "string",
+ minLength: 1,
+ maxLength: 256,
+ description: "Concise draft pull request title.",
+ },
+ },
+ required: ["summary", "title"],
+} as const;
+
+const outputSchema = {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ branch: { type: "string" },
+ changedPaths: { type: "array", items: { type: "string" } },
+ commitSha: { type: "string" },
+ deployed: { type: "boolean", const: false },
+ draft: { type: "boolean", const: true },
+ merged: { type: "boolean", const: false },
+ pullRequestUrl: { type: "string" },
+ repository: { type: "string" },
+ targetBranch: { type: "string" },
+ },
+ required: [
+ "branch",
+ "changedPaths",
+ "commitSha",
+ "deployed",
+ "draft",
+ "merged",
+ "pullRequestUrl",
+ "repository",
+ "targetBranch",
+ ],
+} as const;
+
+function resolveTool() {
+ const config = resolveSelfModificationConfig(selfModification.config);
+ if (resolveSelfModificationMode(config) !== "deployed" || config.deployed === undefined)
+ return null;
+ return defineTool({
+ description:
+ "Publish the complete validated agent source change as one draft pull request. Merge and deployment do not occur.",
+ inputSchema,
+ outputSchema,
+ execute: publish,
+ });
+}
+
+async function publish(input: unknown, toolContext: ToolContext) {
+ if (
+ typeof input !== "object" ||
+ input === null ||
+ !("summary" in input) ||
+ typeof input.summary !== "string" ||
+ input.summary.trim().length === 0 ||
+ !("title" in input) ||
+ typeof input.title !== "string" ||
+ input.title.trim().length === 0
+ ) {
+ throw new Error("Production publication requires a valid title and summary.");
+ }
+ const config = resolveSelfModificationConfig(selfModification.config);
+ if (resolveSelfModificationMode(config) !== "deployed" || config.deployed === undefined) {
+ throw new Error("Production publication requires deployed self-modification configuration.");
+ }
+ const deployed = config.deployed;
+ const summary = input.summary;
+ const title = input.title;
+ const operationId = publicationOperationId(toolContext);
+ const sandbox = await toolContext.getSandbox();
+ return await withSelfModificationWorkspaceLock(`sandbox:${sandbox.id}`, async () => {
+ const workspace = await readPreparedSelfModificationWorkspace({
+ ...deployed,
+ sandbox,
+ });
+ return await publishGitHubDraftPullRequest({
+ credentialProvider: createGitHubCredentialProvider(deployed.credentials),
+ description: summary,
+ operationId,
+ sandbox,
+ title,
+ workspace,
+ });
+ });
+}
+
+/** Derives replay identity only from eve's verified delegation lineage. */
+export function publicationOperationId(ctx: Pick<ToolContext, "session">): string {
+ const parent = ctx.session.parent;
+ if (parent === undefined) {
+ throw new Error("Production publication requires a delegated child session.");
+ }
+ return `${parent.rootSessionId}:${parent.sessionId}:${parent.turn.id}:${parent.callId}:${ctx.session.id}`;
+}
+
+export default defineDynamic({
+ events: {
+ "session.started": resolveTool,
+ },
+});
diff --git a/packages/eve/src/self-modification/extension/tools/registry_add.ts b/packages/eve/src/self-modification/extension/tools/registry_add.ts
index a270fb682..a072fa543 100644
--- a/packages/eve/src/self-modification/extension/tools/registry_add.ts
+++ b/packages/eve/src/self-modification/extension/tools/registry_add.ts
@@ -1,17 +1,40 @@
import { getLocalDevCapability, type LocalDevCapability } from "eve/local-dev";
-import { defineTool } from "eve/tools";
+import { defineDynamic, defineTool, type ToolContext } from "eve/tools";
import { once } from "eve/tools/approval";
+import {
+ resolveSelfModificationConfig,
+ type ResolvedDeployedSelfModificationConfig,
+ type ResolvedSelfModificationConfig,
+} from "../../config.js";
+import { readPreparedSelfModificationWorkspace } from "../../git-workspace.js";
+import { resolveSelfModificationMode } from "../../mode.js";
+import { withSelfModificationWorkspaceLock } from "../../workspace-lock.js";
+import selfModification from "../extension.js";
import { classifyCatalogEntry } from "../classify-registry-item.js";
import { runEveAdd, type SpawnLike } from "../eve-add.js";
-import { withAuthoredSourceLock } from "../source-lock.js";
+import {
+ assertOfficialRegistryAddress,
+ installProductionRegistryItem,
+} from "../production-registry-add.js";
import {
loadRegistryIndex,
+ officialRegistryIndexUrl,
resolveRegistryIndexUrl,
type CatalogEntry,
} from "./search_registry.js";
-const inputSchema = {
+/**
+ * Local installation mutates the developer's project through `eve dev`. It may
+ * hand setup-bearing items to the TUI or terminal, supports the configured
+ * registry, and reports any local files that could not be restored on failure.
+ *
+ * Production installation mutates only the disposable proposal checkout. It is
+ * restricted to the official registry, supports resumable non-secret setup and
+ * external authorization boundaries, and reports paths destined for the draft
+ * pull request rather than claiming that those changes are deployed.
+ */
+const localInputSchema = {
type: "object",
additionalProperties: false,
properties: {
@@ -26,16 +49,11 @@ const inputSchema = {
required: ["address"],
} as const;
-const outputSchema = {
+const localOutputSchema = {
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.",
- },
+ status: { type: "string", enum: ["installed", "needs-terminal", "failed"] },
address: { type: "string" },
title: { type: "string" },
envVars: {
@@ -44,10 +62,7 @@ const outputSchema = {
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.",
- },
+ reason: { type: "string", description: "Why the item was not installed here." },
changed: {
type: "array",
items: { type: "string" },
@@ -62,13 +77,71 @@ const outputSchema = {
required: ["status", "address", "message"],
} as const;
+const productionInputSchema = {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ address: {
+ type: "string",
+ minLength: 1,
+ maxLength: 200,
+ description:
+ "Exact official eve registry address, for example `channel/slack` or `extension/browserbase`.",
+ },
+ answers: {
+ type: "object",
+ additionalProperties: true,
+ description: "Non-secret answers to the setup question returned by the previous call.",
+ },
+ installed: {
+ type: "boolean",
+ description:
+ "Set to true with answers when the previous input-required result installed the source.",
+ },
+ },
+ required: ["address"],
+} as const;
+
+const productionOutputSchema = {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ status: {
+ type: "string",
+ enum: ["completed", "input-required", "external-action-required", "failed", "cancelled"],
+ },
+ address: { type: "string" },
+ changedPaths: {
+ type: "array",
+ items: { type: "string" },
+ description: "Repository-relative paths installed into the proposal.",
+ },
+ completedItems: { type: "array", items: { type: "string" } },
+ deploymentRequired: { type: "boolean" },
+ installed: {
+ type: "boolean",
+ description: "Whether source installation completed before setup paused.",
+ },
+ question: {
+ type: "object",
+ additionalProperties: true,
+ description:
+ "The current setup question. Supply only its non-secret answer on the next call.",
+ },
+ message: { type: "string" },
+ url: { type: "string", description: "External authorization URL the developer must open." },
+ userCode: { type: "string" },
+ },
+ required: ["status", "address"],
+} as const;
+
interface RegistryAddDependencies {
readonly getCapability?: () => LocalDevCapability | undefined;
readonly spawn?: SpawnLike;
}
-/** What the tool reports back. Mirrors {@link outputSchema}. */
-export interface RegistryAddResult {
+/** What local registry installation reports back. Mirrors {@link localOutputSchema}. */
+export interface LocalRegistryAddResult {
readonly address: string;
/** `failed` carries an explicit mutation outcome instead of implying nothing changed. */
readonly status: "installed" | "needs-terminal" | "failed";
@@ -80,6 +153,30 @@ export interface RegistryAddResult {
readonly changed?: readonly string[];
}
+type ProductionRegistryAddResult =
+ | {
+ readonly address: string;
+ readonly status: "completed";
+ readonly completedItems: readonly string[];
+ readonly changedPaths: readonly string[];
+ readonly deploymentRequired: boolean;
+ }
+ | {
+ readonly address: string;
+ readonly status: "input-required";
+ readonly installed: boolean;
+ readonly question: unknown;
+ }
+ | {
+ readonly address: string;
+ readonly status: "external-action-required";
+ readonly installed: boolean;
+ readonly message: string;
+ readonly url: string;
+ readonly userCode?: string;
+ }
+ | { readonly address: string; readonly status: "failed" | "cancelled"; readonly message: string };
+
/**
* Names the item's declared environment variables that are not set.
*
@@ -124,10 +221,10 @@ export function handoffMessage(input: {
}
/** Exported for tests; the tool's `execute` delegates here. */
-export async function addRegistryItem(
+export async function addLocalRegistryItem(
address: string,
options: RegistryAddDependencies & { readonly signal?: AbortSignal } = {},
-): Promise<RegistryAddResult> {
+): Promise<LocalRegistryAddResult> {
const capability = (options.getCapability ?? getLocalDevCapability)();
if (capability === undefined) {
throw new Error(
@@ -166,7 +263,7 @@ export async function addRegistryItem(
};
}
- const outcome = await withAuthoredSourceLock(() =>
+ const outcome = await withSelfModificationWorkspaceLock(`local:${capability.appRoot}`, async () =>
capability.withSuspendedSource(() =>
runEveAdd({
address,
@@ -225,17 +322,98 @@ export async function addRegistryItem(
};
}
-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 });
+async function addProductionRegistryItem(
+ address: string,
+ context: ToolContext,
+ deployed: ResolvedDeployedSelfModificationConfig,
+ continuation: {
+ readonly answers?: Readonly<Record<string, unknown>>;
+ readonly installed?: boolean;
+ },
+): Promise<ProductionRegistryAddResult> {
+ assertOfficialRegistryAddress(address);
+ const entries = await loadRegistryIndex({
+ nowMs: Date.now(),
+ signal: context.abortSignal,
+ url: officialRegistryIndexUrl(),
+ });
+ const entry = entries.find((candidate) => candidate.address === address);
+ if (entry === undefined) {
+ throw new Error(`No official eve registry item is published at "${address}".`);
+ }
+ const sandbox = await context.getSandbox();
+ const result = await withSelfModificationWorkspaceLock(`sandbox:${sandbox.id}`, async () => {
+ const workspace = await readPreparedSelfModificationWorkspace({ ...deployed, sandbox });
+ return await installProductionRegistryItem({
+ address,
+ answers: continuation.answers,
+ installed: continuation.installed,
+ sandbox,
+ signal: context.abortSignal,
+ workspace,
+ });
+ });
+ if (result.kind === "completed") return { address, ...result, status: "completed" };
+ if (result.kind === "input-required") return { address, ...result, status: "input-required" };
+ if (result.kind === "external-action-required")
+ return { address, ...result, status: "external-action-required" };
+ return { address, ...result, status: result.kind };
+}
+
+function localRegistryAddTool() {
+ return defineTool({
+ approval: once(),
+ description:
+ "Install an item from the configured eve registry into this project. Items that need setup are handed to the local setup flow instead. Search first, then call this with the exact item address.",
+ inputSchema: localInputSchema,
+ outputSchema: localOutputSchema,
+ 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 addLocalRegistryItem(address, { signal: ctx.abortSignal });
+ },
+ });
+}
+
+function productionRegistryAddTool(deployed: ResolvedDeployedSelfModificationConfig) {
+ return defineTool({
+ approval: once(),
+ description:
+ "Install an exact item from the official eve registry into the current production change proposal. If setup pauses, call this tool again with the non-secret answers and the installed state from its result. External authorization and secret binding must be completed by the developer.",
+ inputSchema: productionInputSchema,
+ outputSchema: productionOutputSchema,
+ 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 official eve registry.");
+ }
+ const answers =
+ "answers" in input &&
+ typeof input.answers === "object" &&
+ input.answers !== null &&
+ !Array.isArray(input.answers)
+ ? (input.answers as Record<string, unknown>)
+ : undefined;
+ const installed = "installed" in input && input.installed === true;
+ return await addProductionRegistryItem(address, ctx, deployed, { answers, installed });
+ },
+ });
+}
+
+export function resolveRegistryAddTool(config: ResolvedSelfModificationConfig) {
+ const mode = resolveSelfModificationMode(config);
+ if (mode === "local") return localRegistryAddTool();
+ if (mode === "deployed" && config.deployed !== undefined) {
+ return productionRegistryAddTool(config.deployed);
+ }
+ return null;
+}
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ resolveRegistryAddTool(resolveSelfModificationConfig(selfModification.config)),
},
});
diff --git a/packages/eve/src/self-modification/extension/tools/search_registry.ts b/packages/eve/src/self-modification/extension/tools/search_registry.ts
index 54962ddee..b0eb4b2ff 100644
--- a/packages/eve/src/self-modification/extension/tools/search_registry.ts
+++ b/packages/eve/src/self-modification/extension/tools/search_registry.ts
@@ -227,6 +227,7 @@ export function parseRegistryIndex(value: unknown): readonly CatalogEntry[] {
const address = optionalString(item.name);
if (address === undefined) continue;
const eve = eveMetadata(item);
+ if (eve.hidden === true) continue;
const entry: {
address: string;
@@ -386,8 +387,12 @@ function matchesCategory(entry: CatalogEntry, category: Category): boolean {
* rather than imported because that module reaches the registry client, which
* has no place in an agent runtime.
*/
+export function officialRegistryIndexUrl(): string {
+ return `${DEFAULT_REGISTRY_BASE}${INDEX_PATH}`;
+}
+
export function resolveRegistryIndexUrl(configured = process.env.EVE_DEV_OFFICIAL_REGISTRY_URL) {
- if (configured === undefined) return `${DEFAULT_REGISTRY_BASE}${INDEX_PATH}`;
+ if (configured === undefined) return officialRegistryIndexUrl();
let url: URL;
try {
diff --git a/packages/eve/src/self-modification/instructions.test.ts b/packages/eve/src/self-modification/instructions.test.ts
index 4687052da..2466eaf7f 100644
--- a/packages/eve/src/self-modification/instructions.test.ts
+++ b/packages/eve/src/self-modification/instructions.test.ts
@@ -1,7 +1,17 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it } from "vitest";
import instructions from "./extension/instructions.js";
+const originalEveDev = process.env.EVE_DEV;
+
+afterEach(() => {
+ if (originalEveDev === undefined) {
+ delete process.env.EVE_DEV;
+ } else {
+ process.env.EVE_DEV = originalEveDev;
+ }
+});
+
describe("self-modification instructions", () => {
const ctx = {
channel: {},
@@ -10,6 +20,7 @@ describe("self-modification instructions", () => {
};
it("points at the trace that invoked selfmod", () => {
+ process.env.EVE_DEV = "1";
const traceId = "a".repeat(32);
const definition = instructions.events["session.started"]?.(
{
@@ -26,6 +37,7 @@ describe("self-modification instructions", () => {
});
it("does not claim that trace coordinates guarantee local segments", () => {
+ process.env.EVE_DEV = "1";
const traceId = "a".repeat(32);
const definition = instructions.events["session.started"]?.(
{
diff --git a/packages/eve/src/self-modification/package-consumption.scenario.test.ts b/packages/eve/src/self-modification/package-consumption.scenario.test.ts
index 7cb781732..38f87606e 100644
--- a/packages/eve/src/self-modification/package-consumption.scenario.test.ts
+++ b/packages/eve/src/self-modification/package-consumption.scenario.test.ts
@@ -9,12 +9,15 @@ import { afterEach, describe, it } from "vitest";
const runFile = promisify(execFile);
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
-const compatibilityPackageRoot = resolve(packageRoot, "../eve-self-modification");
const temporaryRoots: string[] = [];
-async function run(command: string, args: string[], cwd: string): Promise<void> {
+async function run(
+ command: string,
+ args: string[],
+ cwd: string,
+): Promise<{ stderr: string; stdout: string }> {
try {
- await runFile(command, args, {
+ return await runFile(command, args, {
cwd,
maxBuffer: 10 * 1024 * 1024,
shell: process.platform === "win32",
@@ -73,7 +76,9 @@ describe("packed package consumption", () => {
it("builds a fresh app using only installed tarball contents", async () => {
await access(join(packageRoot, "dist/src/index.js"));
await access(join(packageRoot, "dist/src/self-modification/agent.js"));
- await access(join(packageRoot, "dist/src/self-modification/extension/extension.js"));
+ await access(join(packageRoot, "dist/src/self-modification/config.js"));
+ await access(join(packageRoot, "dist/src/self-modification/sandbox.js"));
+ await access(join(packageRoot, "dist/src/self-modification/setup.js"));
const root = await mkdtemp(join(tmpdir(), "eve-self-modification-package-"));
temporaryRoots.push(root);
@@ -82,13 +87,7 @@ describe("packed package consumption", () => {
await mkdir(tarballsRoot, { recursive: true });
await mkdir(appRoot, { recursive: true });
- await run("pnpm", ["run", "build"], compatibilityPackageRoot);
const eveTarball = await pack(packageRoot, tarballsRoot, "eve");
- const compatibilityTarball = await pack(
- compatibilityPackageRoot,
- tarballsRoot,
- "eve-self-modification",
- );
await writeAppFile(
appRoot,
"package.json",
@@ -99,7 +98,7 @@ describe("packed package consumption", () => {
type: "module",
scripts: { build: "eve build" },
dependencies: {
- "@eve/self-modification": `file:${compatibilityTarball}`,
+ "@vercel/connect": "1.0.0",
eve: `file:${eveTarball}`,
"just-bash": "3.1.0",
},
@@ -119,20 +118,25 @@ describe("packed package consumption", () => {
'import { defineAgent } from "eve";\n\nexport default defineAgent({ model: "openai/gpt-5.4" });\n',
);
await writeAppFile(appRoot, "agent/instructions.md", "You are a test agent.\n");
+ await writeAppFile(
+ appRoot,
+ "agent/subagents/self-modification/config.ts",
+ 'import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({ deployed: { source: { git: { directory: ".", repository: "github.com/acme/agent" } }, target: { branch: "main" }, credentials: { vercelConnect: { connector: "github/selfmod-acme-agent" } } } });\n',
+ );
await writeAppFile(
appRoot,
"agent/subagents/self-modification/agent.ts",
- 'import { defineSelfModificationAgent } from "@eve/self-modification/agent";\n\nexport default defineSelfModificationAgent();\n',
+ 'import { defineSelfModificationAgent } from "eve/self-modification/agent";\nimport config from "./config";\n\nexport default defineSelfModificationAgent({ config });\n',
);
await writeAppFile(
appRoot,
"agent/subagents/self-modification/sandbox.ts",
- 'export { default } from "@eve/self-modification/sandbox";\n',
+ 'import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";\nimport config from "./config";\n\nexport default defineSelfModificationSandbox({ config });\n',
);
await writeAppFile(
appRoot,
"agent/subagents/self-modification/extensions/selfmod.ts",
- 'export { default } from "@eve/self-modification";\n',
+ 'import selfModification from "eve/self-modification";\nimport config from "../config";\n\nexport default selfModification(config);\n',
);
await run(
@@ -147,7 +151,12 @@ describe("packed package consumption", () => {
appRoot,
);
await access(join(appRoot, "node_modules/eve/dist/src/self-modification/agent.js"));
- await access(join(appRoot, "node_modules/@eve/self-modification/scaffold/agent.js"));
- await run("pnpm", ["build"], appRoot);
+ const build = await run("pnpm", ["build"], appRoot);
+ const output = `${build.stdout}\n${build.stderr}`;
+ if (output.includes("Could not resolve '#shared/")) {
+ throw new Error(
+ `Packed eve leaked a package-private import into the application build:\n${output}`,
+ );
+ }
}, 120_000);
});
diff --git a/packages/eve/src/self-modification/production-registry-add.test.ts b/packages/eve/src/self-modification/production-registry-add.test.ts
new file mode 100644
index 000000000..09a7e075f
--- /dev/null
+++ b/packages/eve/src/self-modification/production-registry-add.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ acceptsNonSecretSetupAnswers,
+ assertOfficialRegistryAddress,
+ installProductionRegistryItem,
+} from "./extension/production-registry-add.js";
+
+const SHA = "a".repeat(40);
+const workspace = {
+ baseSha: SHA,
+ directory: ".",
+ repository: { owner: "acme", repo: "agent" },
+ repositoryPath: "/repository",
+ targetBranch: "main",
+} as const;
+
+describe("production registry addresses", () => {
+ it("accepts canonical official addresses", () => {
+ for (const address of ["channel/slack", "extension/browserbase", "linear"]) {
+ expect(() => assertOfficialRegistryAddress(address)).not.toThrow();
+ }
+ });
+
+ it("does not change network policy or forward an environment answer", async () => {
+ const commands: string[] = [];
+ let networkPolicyUpdates = 0;
+ const result = await installProductionRegistryItem({
+ address: "channel/slack",
+ answers: { SLACK_BOT_TOKEN: "secret" },
+ installed: true,
+ sandbox: {
+ run: async ({ command }: { readonly command: string }) => {
+ commands.push(command);
+ if (command.includes("while :")) return { exitCode: 0, stdout: "pnpm\t/repository" };
+ if (command.includes("info/exclude") || command.includes("corepack")) {
+ return { exitCode: 0 };
+ }
+ if (command.includes("for executable")) {
+ return { exitCode: 0, stdout: "/repository/node_modules/.bin/eve" };
+ }
+ if (
+ command.includes(" add -A") ||
+ command.includes("read-tree") ||
+ command.includes(" clean -fd -- .")
+ ) {
+ return { exitCode: 0 };
+ }
+ if (command.includes("write-tree")) return { exitCode: 0, stdout: SHA };
+ if (command.includes("--skip-install")) {
+ return {
+ exitCode: 2,
+ stderr: JSON.stringify({
+ version: 1,
+ type: "blocked",
+ item: "channel/slack",
+ installed: true,
+ question: { key: "SLACK_BOT_TOKEN", kind: "environment", sensitive: true },
+ }),
+ };
+ }
+ throw new Error(`Unexpected command: ${command}`);
+ },
+ setNetworkPolicy: async () => {
+ networkPolicyUpdates += 1;
+ },
+ } as never,
+ workspace,
+ });
+
+ expect(result).toMatchObject({ kind: "input-required", installed: true });
+ expect(commands.join("\n")).not.toContain("SLACK_BOT_TOKEN=secret");
+ expect(networkPolicyUpdates).toBe(0);
+ });
+
+ it("removes files created by a failed install while restoring the starting tree", async () => {
+ const commands: string[] = [];
+ const result = await installProductionRegistryItem({
+ address: "extension/browserbase",
+ sandbox: {
+ run: async ({ command }: { readonly command: string }) => {
+ commands.push(command);
+ if (command.includes("while :")) return { exitCode: 0, stdout: "pnpm\t/repository" };
+ if (command.includes("info/exclude") || command.includes("corepack")) {
+ return { exitCode: 0 };
+ }
+ if (command.includes("for executable")) {
+ return { exitCode: 0, stdout: "/repository/node_modules/.bin/eve" };
+ }
+ if (command.includes(" add -A") || command.includes("read-tree")) {
+ return { exitCode: 0 };
+ }
+ if (command.includes("write-tree")) return { exitCode: 0, stdout: SHA };
+ if (command.includes(" clean -fd -- .")) return { exitCode: 0 };
+ if (command.includes(" add ")) {
+ return {
+ exitCode: 1,
+ stderr: JSON.stringify({
+ version: 1,
+ type: "failed",
+ item: "extension/browserbase",
+ }),
+ };
+ }
+ throw new Error(`Unexpected command: ${command}`);
+ },
+ setNetworkPolicy: async () => {},
+ } as never,
+ workspace,
+ });
+
+ expect(result).toMatchObject({ kind: "failed" });
+ expect(commands.some((command) => command.includes("read-tree --reset -u"))).toBe(true);
+ expect(commands.some((command) => command.includes("clean -fd -- ."))).toBe(true);
+ });
+
+ it("accepts only the current non-secret setup answer", () => {
+ expect(
+ acceptsNonSecretSetupAnswers(
+ { key: "components", kind: "multi-select" },
+ {
+ components: ["slack"],
+ },
+ ),
+ ).toBe(true);
+ expect(
+ acceptsNonSecretSetupAnswers({ key: "API_KEY", kind: "environment" }, { API_KEY: "secret" }),
+ ).toBe(false);
+ expect(
+ acceptsNonSecretSetupAnswers(
+ { key: "components", kind: "multi-select" },
+ { components: [], API_KEY: "secret" },
+ ),
+ ).toBe(false);
+ });
+
+ it("rejects URLs, configured namespaces, and shell-shaped input", () => {
+ for (const address of [
+ "https://example.com/item.json",
+ "@acme/widget",
+ "channel/slack; touch owned",
+ "channel/slack --skip-setup",
+ "../channel/slack",
+ ]) {
+ expect(() => assertOfficialRegistryAddress(address)).toThrow("exact official");
+ }
+ });
+});
diff --git a/packages/eve/src/self-modification/publish-tool.test.ts b/packages/eve/src/self-modification/publish-tool.test.ts
new file mode 100644
index 000000000..0416987e6
--- /dev/null
+++ b/packages/eve/src/self-modification/publish-tool.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+
+import { publicationOperationId } from "./extension/tools/publish.js";
+
+describe("production publish tool", () => {
+ it("derives operation identity from trusted parent lineage", () => {
+ expect(
+ publicationOperationId({
+ session: {
+ auth: { current: null, initiator: null },
+ id: "child-session",
+ parent: {
+ callId: "delegate-call",
+ rootSessionId: "root-session",
+ sessionId: "parent-session",
+ turn: { id: "parent-turn", sequence: 2 },
+ },
+ turn: { id: "child-turn", sequence: 0 },
+ },
+ }),
+ ).toBe("root-session:parent-session:parent-turn:delegate-call:child-session");
+ });
+
+ it("rejects direct publication sessions", () => {
+ expect(() =>
+ publicationOperationId({
+ session: {
+ auth: { current: null, initiator: null },
+ id: "root-session",
+ turn: { id: "root-turn", sequence: 0 },
+ },
+ }),
+ ).toThrow("delegated child session");
+ });
+});
diff --git a/packages/eve/src/self-modification/registry-add.test.ts b/packages/eve/src/self-modification/registry-add.test.ts
index fd5e20844..9acdff89a 100644
--- a/packages/eve/src/self-modification/registry-add.test.ts
+++ b/packages/eve/src/self-modification/registry-add.test.ts
@@ -14,10 +14,16 @@ 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 {
+ addLocalRegistryItem,
+ handoffMessage,
+ resolveRegistryAddTool,
+ unsetEnvVars,
+} from "./extension/tools/registry_add.js";
import { clearRegistryIndexCache } from "./extension/tools/search_registry.js";
const APP_ROOT = "/workspace/agent";
+const originalEveDev = process.env.EVE_DEV;
const INDEX = {
items: [
@@ -110,20 +116,84 @@ beforeEach(() => {
});
afterEach(() => {
+ if (originalEveDev === undefined) delete process.env.EVE_DEV;
+ else process.env.EVE_DEV = originalEveDev;
vi.unstubAllGlobals();
vi.clearAllMocks();
});
-describe("addRegistryItem", () => {
+describe("resolveRegistryAddTool", () => {
+ it("resolves the local lifecycle with only local arguments and outcomes", () => {
+ process.env.EVE_DEV = "1";
+
+ const tool = resolveRegistryAddTool({ localEnabled: true });
+
+ expect(tool).toMatchObject({
+ description: expect.stringContaining("configured eve registry"),
+ inputSchema: {
+ properties: { address: expect.any(Object) },
+ required: ["address"],
+ },
+ outputSchema: {
+ properties: { status: { enum: ["installed", "needs-terminal", "failed"] } },
+ },
+ });
+ if (tool === null) throw new Error("Expected the local registry tool.");
+ expect(Object.keys((tool.inputSchema as { properties: object }).properties)).toEqual([
+ "address",
+ ]);
+ });
+
+ it("resolves the deployed lifecycle with continuation arguments and outcomes", () => {
+ delete process.env.EVE_DEV;
+
+ const tool = resolveRegistryAddTool({
+ localEnabled: true,
+ deployed: {
+ credentials: { kind: "pat" },
+ directory: ".",
+ repository: { owner: "acme", repo: "agent" },
+ targetBranch: "main",
+ },
+ });
+
+ expect(tool).toMatchObject({
+ description: expect.stringContaining("production change proposal"),
+ inputSchema: {
+ properties: {
+ address: expect.any(Object),
+ answers: expect.any(Object),
+ installed: expect.any(Object),
+ },
+ required: ["address"],
+ },
+ outputSchema: {
+ properties: {
+ status: {
+ enum: [
+ "completed",
+ "input-required",
+ "external-action-required",
+ "failed",
+ "cancelled",
+ ],
+ },
+ },
+ },
+ });
+ });
+});
+
+describe("addLocalRegistryItem", () => {
it("refuses to run without the development capability", async () => {
await expect(
- addRegistryItem("extension/browserbase", { getCapability: () => undefined }),
+ addLocalRegistryItem("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", {
+ const result = await addLocalRegistryItem("channel/slack", {
getCapability: () => capability(),
spawn,
});
@@ -136,7 +206,10 @@ describe("addRegistryItem", () => {
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 });
+ const result = await addLocalRegistryItem("linear", {
+ getCapability: () => capability(),
+ spawn,
+ });
expect(result.status).toBe("needs-terminal");
expect(result.reason).toContain("channel/linear-agent");
@@ -144,7 +217,7 @@ describe("addRegistryItem", () => {
});
it("leaves the automatically queued setup to an interactive client", async () => {
- const result = await addRegistryItem("channel/slack", {
+ const result = await addLocalRegistryItem("channel/slack", {
getCapability: () => capability({ interactiveClient: true }),
});
@@ -159,7 +232,7 @@ describe("addRegistryItem", () => {
code: 0,
output: JSON.stringify({ version: 1, type: "completed", item: address }),
});
- const result = await addRegistryItem(address, {
+ const result = await addLocalRegistryItem(address, {
getCapability: () => capability(),
spawn,
});
@@ -170,7 +243,7 @@ describe("addRegistryItem", () => {
it("rejects an address the registry does not publish", async () => {
await expect(
- addRegistryItem("channel/nonexistent", { getCapability: () => capability() }),
+ addLocalRegistryItem("channel/nonexistent", { getCapability: () => capability() }),
).rejects.toThrow(/No item in the configured eve registry is published/u);
});
@@ -180,7 +253,7 @@ describe("addRegistryItem", () => {
output: `Something from shadcn\n${COMPLETED}\n`,
});
const suspended: string[] = [];
- const result = await addRegistryItem("extension/browserbase", {
+ const result = await addLocalRegistryItem("extension/browserbase", {
getCapability: () =>
capability({
withSuspendedSource: async (task) => {
@@ -212,7 +285,7 @@ describe("addRegistryItem", () => {
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", {
+ const install = addLocalRegistryItem("extension/browserbase", {
getCapability: () => capability(),
spawn,
});
@@ -244,7 +317,10 @@ describe("addRegistryItem", () => {
});
await expect(
- addRegistryItem("extension/browserbase", { getCapability: () => capability(), spawn }),
+ addLocalRegistryItem("extension/browserbase", {
+ getCapability: () => capability(),
+ spawn,
+ }),
).resolves.toMatchObject({
status: "failed",
changed: ["package.json"],
@@ -288,7 +364,7 @@ describe("addRegistryItem", () => {
message: "Setup needs an answer.",
}),
});
- const result = await addRegistryItem("extension/browserbase", {
+ const result = await addLocalRegistryItem("extension/browserbase", {
getCapability: () => capability(),
spawn,
});
@@ -365,6 +441,19 @@ describe("readTerminalHeadlessEvent", () => {
).toMatchObject({ type: "completed" });
});
+ it("reads an external-action continuation", () => {
+ expect(
+ readTerminalHeadlessEvent(
+ JSON.stringify({
+ version: 1,
+ type: "external_action",
+ message: "Authorize GitHub.",
+ url: "https://github.com/login/device",
+ }),
+ ),
+ ).toMatchObject({ type: "external_action", url: "https://github.com/login/device" });
+ });
+
it("ignores lines that are not JSON", () => {
expect(readTerminalHeadlessEvent("not json\n{broken\n")).toBeUndefined();
});
diff --git a/packages/eve/src/self-modification/sandbox.test.ts b/packages/eve/src/self-modification/sandbox.test.ts
new file mode 100644
index 000000000..1371fb550
--- /dev/null
+++ b/packages/eve/src/self-modification/sandbox.test.ts
@@ -0,0 +1,108 @@
+import { docker } from "eve/sandbox/docker";
+import { justbash } from "eve/sandbox/just-bash";
+import { microsandbox } from "eve/sandbox/microsandbox";
+import { vercel } from "eve/sandbox/vercel";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { SelfModificationConfig } from "./config.js";
+import { defineSelfModificationSandbox, selectDeployedSelfModificationBackend } from "./sandbox.js";
+
+const connectConfig: SelfModificationConfig = {
+ deployed: {
+ credentials: { vercelConnect: { connector: "github/selfmod-acme-agent" } },
+ source: { git: { directory: ".", repository: "github.com/acme/agent" } },
+ target: { branch: "main" },
+ },
+};
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("self-modification sandbox", () => {
+ it("selects Vercel Sandbox for an unspecified backend on Vercel", () => {
+ expect(
+ selectDeployedSelfModificationBackend(undefined, {
+ isDeployedOnVercel: () => true,
+ isMicrosandboxSupported: () => true,
+ }).name,
+ ).toBe("vercel");
+ });
+
+ it("selects microsandbox for an unspecified backend on a supported self-hosted system", () => {
+ expect(
+ selectDeployedSelfModificationBackend(undefined, {
+ isDeployedOnVercel: () => false,
+ isMicrosandboxSupported: () => true,
+ }).name,
+ ).toBe("microsandbox");
+ });
+
+ it.each([
+ ["docker", docker()],
+ ["just-bash", justbash()],
+ ] as const)("rejects the %s backend for deployed self-modification", (name, backend) => {
+ expect(() =>
+ selectDeployedSelfModificationBackend(backend, {
+ isDeployedOnVercel: () => true,
+ isMicrosandboxSupported: () => true,
+ }),
+ ).toThrow(
+ `Deployed self-modification requires runtime credential transforms. The configured ${name} backend does not support them. Use vercel() on Vercel or microsandbox() on a supported self-hosted system.`,
+ );
+ });
+
+ it("reports the same backend guidance when automatic selection cannot find one", () => {
+ expect(() =>
+ selectDeployedSelfModificationBackend(undefined, {
+ isDeployedOnVercel: () => false,
+ isMicrosandboxSupported: () => false,
+ }),
+ ).toThrow(
+ "Deployed self-modification requires runtime credential transforms. No supported backend is available. Use vercel() on Vercel or microsandbox() on a supported self-hosted system.",
+ );
+ });
+
+ it.each([microsandbox(), vercel()])(
+ "accepts an explicitly configured $name backend",
+ (backend) => {
+ expect(
+ selectDeployedSelfModificationBackend(backend, {
+ isDeployedOnVercel: () => false,
+ isMicrosandboxSupported: () => false,
+ }),
+ ).toBe(backend);
+ },
+ );
+
+ it("does not update the just-bash network policy in local mode", async () => {
+ vi.stubEnv("EVE_DEV", "1");
+ const definition = defineSelfModificationSandbox({ config: connectConfig });
+ if (definition.onSession === undefined) throw new Error("Expected an onSession hook.");
+ const use = vi.fn();
+
+ await definition.onSession({
+ ctx: { session: { parent: undefined } } as never,
+ use,
+ });
+
+ expect(use).not.toHaveBeenCalled();
+ });
+
+ it("establishes its allow-all baseline before resolving deployed credentials", async () => {
+ vi.stubEnv("EVE_DEV", "0");
+ vi.stubEnv("VERCEL_ENV", "production");
+ const definition = defineSelfModificationSandbox({ config: connectConfig });
+ if (definition.onSession === undefined) throw new Error("Expected an onSession hook.");
+ const failure = new Error("baseline applied");
+ const setNetworkPolicy = vi.fn().mockRejectedValue(failure);
+
+ await expect(
+ definition.onSession({
+ ctx: { session: { parent: {} } } as never,
+ use: async () => ({ setNetworkPolicy }) as never,
+ }),
+ ).rejects.toBe(failure);
+ expect(setNetworkPolicy).toHaveBeenCalledWith("allow-all");
+ });
+});
diff --git a/packages/eve/src/self-modification/sandbox.ts b/packages/eve/src/self-modification/sandbox.ts
index 0fbb50968..ad7614ab2 100644
--- a/packages/eve/src/self-modification/sandbox.ts
+++ b/packages/eve/src/self-modification/sandbox.ts
@@ -1,8 +1,118 @@
-import { defineSandbox } from "#public/sandbox/index.js";
+import { shellQuote } from "#shared/shell-quote.js";
+import { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "#sandbox/backends/default.js";
+import {
+ defaultBackend,
+ defineSandbox,
+ type SandboxBackend,
+ type SandboxDefinition,
+} from "#public/sandbox/index.js";
import { justbash } from "#public/sandbox/just-bash.js";
+import { microsandbox } from "#public/sandbox/microsandbox.js";
+import { vercel } from "#public/sandbox/vercel.js";
+import { resolveSelfModificationConfig, type SelfModificationConfig } from "./config.js";
+import { createGitHubCredentialProvider } from "./credentials.js";
import { createSelfModificationFilesystem } from "./filesystem.js";
+import { prepareSelfModificationWorkspace, REPOSITORY_PATH } from "./git-workspace.js";
+import { resolveSelfModificationMode } from "./mode.js";
+import { SELF_MODIFICATION_BASELINE_NETWORK_POLICY } from "./network-policy.js";
-export default defineSandbox({
- backend: justbash({ filesystem: createSelfModificationFilesystem }),
-});
+export interface SelfModificationSandboxOptions {
+ /**
+ * Production backend. Deployed self-modification owns an allow-all network
+ * policy and temporarily adds a credential transform while checking out its
+ * source. When omitted, eve selects Vercel Sandbox on Vercel or microsandbox
+ * on a supported self-hosted system.
+ */
+ readonly backend?: SandboxBackend;
+ /** Policy shared with the agent and extension mount. */
+ readonly config?: SelfModificationConfig;
+}
+
+type SelfModificationSandboxProbes = Pick<
+ DefaultSandboxProbes,
+ "isDeployedOnVercel" | "isMicrosandboxSupported"
+>;
+
+/** Defines the local source mount or isolated production proposal workspace. */
+export function defineSelfModificationSandbox(
+ options: SelfModificationSandboxOptions = {},
+): SandboxDefinition {
+ const config = resolveSelfModificationConfig(options.config);
+
+ return defineSandbox({
+ backend: () => {
+ const mode = resolveSelfModificationMode(config);
+ if (mode === "local") return justbash({ filesystem: createSelfModificationFilesystem });
+ if (mode === "disabled") return options.backend ?? defaultBackend();
+ return selectDeployedSelfModificationBackend(options.backend, SANDBOX_BACKEND_PROBES);
+ },
+ async onSession({ ctx, use }) {
+ if (resolveSelfModificationMode(config) !== "deployed" || config.deployed === undefined)
+ return;
+ if (ctx.session.parent === undefined) {
+ throw new Error(
+ "Production self-modification workspaces require a delegated child session.",
+ );
+ }
+
+ const deployed = config.deployed;
+ const sandbox = await use();
+ await sandbox.setNetworkPolicy(SELF_MODIFICATION_BASELINE_NETWORK_POLICY);
+ const token = await createGitHubCredentialProvider(deployed.credentials).resolve({
+ capability: "checkout",
+ repository: deployed.repository,
+ });
+ await prepareSelfModificationWorkspace({
+ directory: deployed.directory,
+ repository: deployed.repository,
+ sandbox,
+ targetBranch: deployed.targetBranch,
+ token,
+ });
+ const applicationRoot =
+ deployed.directory === "." ? REPOSITORY_PATH : `${REPOSITORY_PATH}/${deployed.directory}`;
+ const mounted = await sandbox.run({
+ command: `rm -rf /source && ln -s ${shellQuote(`${applicationRoot}/agent`)} /source`,
+ });
+ if (mounted.exitCode !== 0) {
+ throw new Error("Self-modification could not mount the production agent source.");
+ }
+ },
+ });
+}
+
+/**
+ * Deployed self-modification deliberately selects a backend that can inject
+ * GitHub auth at the network boundary, keeping the credential outside the
+ * sandbox and agent. Docker and just-bash do not provide that separation.
+ * Internal—exported for tests, which inject availability probes.
+ */
+export function selectDeployedSelfModificationBackend(
+ configured: SandboxBackend | undefined,
+ probes: SelfModificationSandboxProbes,
+): SandboxBackend {
+ if (configured !== undefined) {
+ if (configured.name === "vercel" || configured.name === "microsandbox") return configured;
+ throw unsupportedBackend(configured.name);
+ }
+ if (probes.isDeployedOnVercel()) {
+ return vercel({ networkPolicy: SELF_MODIFICATION_BASELINE_NETWORK_POLICY });
+ }
+ if (probes.isMicrosandboxSupported()) {
+ return microsandbox({ networkPolicy: SELF_MODIFICATION_BASELINE_NETWORK_POLICY });
+ }
+ throw unsupportedBackend();
+}
+
+function unsupportedBackend(name?: string): Error {
+ const reason =
+ name === undefined
+ ? "No supported backend is available."
+ : `The configured ${name} backend does not support them.`;
+ return new Error(
+ `Deployed self-modification requires runtime credential transforms. ${reason} Use vercel() on Vercel or microsandbox() on a supported self-hosted system.`,
+ );
+}
+
+export default defineSelfModificationSandbox();
diff --git a/packages/eve/src/self-modification/search-registry.test.ts b/packages/eve/src/self-modification/search-registry.test.ts
index fe30c8447..63bac50f7 100644
--- a/packages/eve/src/self-modification/search-registry.test.ts
+++ b/packages/eve/src/self-modification/search-registry.test.ts
@@ -101,6 +101,17 @@ describe("parseRegistryIndex", () => {
expect(parseRegistryIndex({ items: "nope" })).toEqual([]);
});
+ it("omits items hidden from registry search", () => {
+ expect(
+ parseRegistryIndex({
+ items: [
+ { name: "experimental/self-modification" },
+ { name: "experimental/self-modification/prod", meta: { eve: { hidden: true } } },
+ ],
+ }).map((entry) => entry.address),
+ ).toEqual(["experimental/self-modification"]);
+ });
+
it("reads whether an item declares a setup flow, used by selfmod__registry_add's split rule", () => {
const entries = parseRegistryIndex({
items: [
diff --git a/packages/eve/src/self-modification/setup.test.ts b/packages/eve/src/self-modification/setup.test.ts
new file mode 100644
index 000000000..0a6ce2de3
--- /dev/null
+++ b/packages/eve/src/self-modification/setup.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+
+import { win32 } from "node:path";
+
+import {
+ classifySelfModificationConfig,
+ connectorName,
+ parseGitHubRemote,
+ renderSelfModificationConfig,
+ repositoryRelativeDirectory,
+} from "./setup.js";
+
+describe("self-modification setup", () => {
+ it("renders a generated Connect-backed deployed configuration", () => {
+ const source = renderSelfModificationConfig({
+ branch: "release/production",
+ connector: "github/selfmod-acme-agents",
+ directory: "apps/support",
+ repository: "github.com/acme/agents",
+ });
+ expect(source).toContain('repository: "github.com/acme/agents"');
+ expect(source).toContain('directory: "apps/support"');
+ expect(source).toContain('target: { branch: "release/production" }');
+ expect(source).toContain('connector: "github/selfmod-acme-agents"');
+ expect(source).not.toContain("EVE_SELF_MODIFICATION_GITHUB_TOKEN");
+ expect(classifySelfModificationConfig(source)).toBe("generated");
+ });
+
+ it("refuses altered generated configuration as authored", () => {
+ expect(
+ classifySelfModificationConfig(
+ `${renderSelfModificationConfig({ branch: "main", connector: "github/selfmod-acme-agents", directory: ".", repository: "github.com/acme/agents" })}\n// edited`,
+ ),
+ ).toBe("authored");
+ });
+
+ it("uses a stable repository-specific connector name", () => {
+ expect(connectorName("Acme", "agents_tools")).toBe("selfmod-acme-agents-tools");
+ });
+
+ it("normalizes Windows application directories", () => {
+ expect(
+ repositoryRelativeDirectory(
+ "C:\\work\\agents",
+ "C:\\work\\agents\\apps\\support",
+ win32.relative,
+ ),
+ ).toBe("apps/support");
+ });
+
+ it.each([
+ "https://github.com/acme/agents.git",
+ "[email protected]:acme/agents.git",
+ "ssh://[email protected]/acme/agents.git",
+ ])("detects GitHub remotes without retaining credentials: %s", (remote) => {
+ expect(parseGitHubRemote(remote)).toEqual({ owner: "acme", repo: "agents" });
+ });
+});
diff --git a/packages/eve/src/self-modification/setup.ts b/packages/eve/src/self-modification/setup.ts
new file mode 100644
index 000000000..c594400ed
--- /dev/null
+++ b/packages/eve/src/self-modification/setup.ts
@@ -0,0 +1,255 @@
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFile, writeFile } from "node:fs/promises";
+import { join, relative } from "node:path";
+import { promisify } from "node:util";
+
+import { SELF_MODIFICATION_CONFIG_PATH } from "./git-workspace.js";
+
+const runFile = promisify(execFile);
+const GENERATED_MARKER = "// eve-self-modification: generated-v1";
+
+export interface SelfModificationSetupValues {
+ readonly branch: string;
+ readonly connector: string;
+ readonly directory: string;
+ readonly repository: string;
+}
+export interface DetectedGitRepository {
+ readonly branch?: string;
+ readonly directory?: string;
+ readonly owner?: string;
+ readonly repo?: string;
+ readonly remoteKind: "github" | "missing" | "other";
+}
+export interface SelfModificationSetupOperations {
+ attachConnector(connector: string): Promise<void>;
+ detectGitRepository(): Promise<DetectedGitRepository>;
+ findOrCreateConnector(name: string): Promise<string>;
+ readConfig(): Promise<string | undefined>;
+ writeConfig(source: string): Promise<void>;
+}
+
+export function connectorName(owner: string, repo: string): string {
+ return `selfmod-${owner}-${repo}`.toLowerCase().replaceAll(/[^a-z0-9-]/gu, "-");
+}
+
+export function renderSelfModificationConfig(values?: SelfModificationSetupValues): string {
+ if (values === undefined) {
+ return `import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({});\n`;
+ }
+ const body = `import { defineSelfModificationConfig } from "eve/self-modification/config";
+
+export default defineSelfModificationConfig({
+ deployed: {
+ source: {
+ git: {
+ repository: ${JSON.stringify(values.repository)},
+ directory: ${JSON.stringify(values.directory)},
+ },
+ },
+ target: { branch: ${JSON.stringify(values.branch)} },
+ credentials: {
+ vercelConnect: { connector: ${JSON.stringify(values.connector)} },
+ },
+ },
+});
+`;
+ return `${GENERATED_MARKER} digest:${createHash("sha256").update(body).digest("hex")}\n${body}`;
+}
+
+/** Distinguishes resumable generated source from authored source without evaluating it. */
+export function classifySelfModificationConfig(
+ source: string | undefined,
+): "missing" | "local" | "generated" | "authored" {
+ if (source === undefined) return "missing";
+ if (source === renderSelfModificationConfig()) return "local";
+ const [marker, ...body] = source.split("\n");
+ const match = /^\/\/ eve-self-modification: generated-v1 digest:([a-f0-9]{64})$/u.exec(
+ marker ?? "",
+ );
+ return match?.[1] === createHash("sha256").update(body.join("\n")).digest("hex")
+ ? "generated"
+ : "authored";
+}
+
+export function parseGitHubRemote(remote: string): { owner: string; repo: string } | undefined {
+ const match = remote
+ .trim()
+ .match(
+ /^(?:https?:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?$/u,
+ );
+ return match?.[1] === undefined || match[2] === undefined
+ ? undefined
+ : { owner: match[1], repo: match[2] };
+}
+
+export function defaultSelfModificationSetupOperations(
+ appRoot: string,
+): SelfModificationSetupOperations {
+ const configPath = join(appRoot, SELF_MODIFICATION_CONFIG_PATH);
+ return {
+ async detectGitRepository() {
+ const remote = await gitOutput(appRoot, ["config", "--get", "remote.origin.url"]);
+ const repository = remote === undefined ? undefined : parseGitHubRemote(remote);
+ const remoteHead = await gitOutput(appRoot, [
+ "symbolic-ref",
+ "--quiet",
+ "--short",
+ "refs/remotes/origin/HEAD",
+ ]);
+ const repositoryRoot = await gitOutput(appRoot, ["rev-parse", "--show-toplevel"]);
+ return {
+ ...repository,
+ branch: remoteHead?.replace(/^origin\//u, ""),
+ directory:
+ repositoryRoot === undefined
+ ? undefined
+ : repositoryRelativeDirectory(repositoryRoot, appRoot),
+ remoteKind:
+ remote === undefined ? "missing" : repository === undefined ? "other" : "github",
+ };
+ },
+ async readConfig() {
+ try {
+ return await readFile(configPath, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ throw error;
+ }
+ },
+ writeConfig: (source) => writeFile(configPath, source, "utf8"),
+ async findOrCreateConnector(name) {
+ const listed = await vercel(appRoot, ["connect", "list", "-F", "json"]);
+ if (!listed.ok)
+ throw new Error(
+ "Vercel Connect requires an authenticated Vercel CLI linked to this project.",
+ );
+ const connectors = parseConnectors(listed.stdout);
+ const expected = `github/${name}`;
+ const existing = connectors.find((connector) => connector.uid === expected);
+ if (existing !== undefined) {
+ if (existing.type !== "github")
+ throw new Error(`The existing connector ${expected} is not a GitHub connector.`);
+ return existing.uid;
+ }
+ const created = await vercel(appRoot, [
+ "connect",
+ "create",
+ "github",
+ "--name",
+ name,
+ "-F",
+ "json",
+ ]);
+ const connector = created.ok ? parseCreatedConnector(created.stdout) : undefined;
+ if (connector === undefined || !connector.startsWith("github/"))
+ throw new Error("Could not create a GitHub Vercel Connect connector.");
+ return connector;
+ },
+ async attachConnector(connector) {
+ const link = await readLinkedProject(appRoot);
+ if (link === undefined)
+ throw new Error(
+ "Vercel Connect requires this directory to be linked to a Vercel project. Run `vercel link` and retry.",
+ );
+ const result = await vercel(appRoot, [
+ "connect",
+ "attach",
+ connector,
+ "--project",
+ link.projectId,
+ "--environment",
+ "production",
+ "--yes",
+ ]);
+ if (!result.ok)
+ throw new Error(
+ `Could not attach ${connector} to the linked Vercel project for Production.`,
+ );
+ },
+ };
+}
+
+function parseCreatedConnector(stdout: string): string | undefined {
+ try {
+ const value = JSON.parse(stdout) as { uid?: unknown };
+ return typeof value.uid === "string" ? value.uid : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function parseConnectors(stdout: string): { type: string; uid: string }[] {
+ try {
+ const parsed = JSON.parse(stdout) as { connectors?: unknown; uid?: unknown; type?: unknown };
+ const values = Array.isArray(parsed.connectors) ? parsed.connectors : [parsed];
+ return values.flatMap((value) =>
+ typeof value === "object" &&
+ value !== null &&
+ typeof (value as { uid?: unknown }).uid === "string" &&
+ typeof (value as { type?: unknown }).type === "string"
+ ? [{ uid: (value as { uid: string }).uid, type: (value as { type: string }).type }]
+ : [],
+ );
+ } catch {
+ return [];
+ }
+}
+async function vercel(cwd: string, args: string[]) {
+ try {
+ const result = await runFile("vercel", args, { cwd });
+ return { ok: true, stdout: result.stdout };
+ } catch {
+ return { ok: false, stdout: "" };
+ }
+}
+async function readLinkedProject(appRoot: string): Promise<{ projectId: string } | undefined> {
+ try {
+ const value = JSON.parse(await readFile(join(appRoot, ".vercel", "project.json"), "utf8")) as {
+ projectId?: unknown;
+ };
+ return typeof value.projectId === "string" ? { projectId: value.projectId } : undefined;
+ } catch {
+ return undefined;
+ }
+}
+export function repositoryRelativeDirectory(
+ repositoryRoot: string,
+ appRoot: string,
+ relativePath: typeof relative = relative,
+): string {
+ return relativePath(repositoryRoot, appRoot).replaceAll("\\", "/") || ".";
+}
+export function repositoryPartError(value: string): string | undefined {
+ return /^[A-Za-z0-9_.-]+$/u.test(value)
+ ? undefined
+ : "Enter a valid GitHub owner or repository name.";
+}
+export function directoryError(value: string): string | undefined {
+ return value === "." ||
+ (value.length > 0 &&
+ !value.startsWith("/") &&
+ !value.includes("\\") &&
+ value.split("/").every((part) => part !== "" && part !== "." && part !== ".."))
+ ? undefined
+ : 'Enter a safe repository-relative directory or ".".';
+}
+export function gitRefError(value: string): string | undefined {
+ return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/u.test(value) &&
+ !value.endsWith(".") &&
+ !value.endsWith("/") &&
+ !value.includes("..") &&
+ !value.includes("//") &&
+ !value.includes("@{")
+ ? undefined
+ : "Enter a valid branch name.";
+}
+async function gitOutput(appRoot: string, args: string[]): Promise<string | undefined> {
+ try {
+ const result = await runFile("git", args, { cwd: appRoot });
+ return result.stdout.trim() || undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/eve/src/self-modification/workspace-lock.test.ts b/packages/eve/src/self-modification/workspace-lock.test.ts
new file mode 100644
index 000000000..ed06b9c62
--- /dev/null
+++ b/packages/eve/src/self-modification/workspace-lock.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import { withSelfModificationWorkspaceLock } from "./workspace-lock.js";
+
+describe("self-modification workspace lock", () => {
+ it("serializes operations for the same workspace", async () => {
+ const events: string[] = [];
+ let releaseFirst!: () => void;
+ const firstBlocked = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+
+ const first = withSelfModificationWorkspaceLock("sandbox-1", async () => {
+ events.push("first:start");
+ await firstBlocked;
+ events.push("first:end");
+ });
+ const second = withSelfModificationWorkspaceLock("sandbox-1", async () => {
+ events.push("second:start");
+ events.push("second:end");
+ });
+
+ await Promise.resolve();
+ expect(events).toEqual(["first:start"]);
+ releaseFirst();
+ await Promise.all([first, second]);
+ expect(events).toEqual(["first:start", "first:end", "second:start", "second:end"]);
+ });
+
+ it("allows operations for different workspaces to overlap", async () => {
+ const started: string[] = [];
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+
+ const first = withSelfModificationWorkspaceLock("sandbox-1", async () => {
+ started.push("sandbox-1");
+ await blocked;
+ });
+ const second = withSelfModificationWorkspaceLock("sandbox-2", async () => {
+ started.push("sandbox-2");
+ });
+
+ await second;
+ expect(started).toEqual(["sandbox-1", "sandbox-2"]);
+ release();
+ await first;
+ });
+
+ it("releases the workspace after an operation fails", async () => {
+ await expect(
+ withSelfModificationWorkspaceLock("sandbox-1", async () => {
+ throw new Error("failed");
+ }),
+ ).rejects.toThrow("failed");
+
+ await expect(
+ withSelfModificationWorkspaceLock("sandbox-1", async () => "recovered"),
+ ).resolves.toBe("recovered");
+ });
+});
diff --git a/packages/eve/src/self-modification/workspace-lock.ts b/packages/eve/src/self-modification/workspace-lock.ts
new file mode 100644
index 000000000..c8969adf0
--- /dev/null
+++ b/packages/eve/src/self-modification/workspace-lock.ts
@@ -0,0 +1,23 @@
+const workspaceTails = new Map<string, Promise<void>>();
+
+/** Serializes operations that require an exclusive view of one self-modification workspace. */
+export async function withSelfModificationWorkspaceLock<T>(
+ workspaceKey: string,
+ operation: () => Promise<T>,
+): Promise<T> {
+ const previous = workspaceTails.get(workspaceKey) ?? Promise.resolve();
+ let release!: () => void;
+ const acquired = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const tail = previous.then(() => acquired);
+ workspaceTails.set(workspaceKey, tail);
+
+ await previous;
+ try {
+ return await operation();
+ } finally {
+ release();
+ if (workspaceTails.get(workspaceKey) === tail) workspaceTails.delete(workspaceKey);
+ }
+}
diff --git a/packages/eve/src/setup/integrations/registry.test.ts b/packages/eve/src/setup/integrations/registry.test.ts
index 68fc4ec45..7f8597e46 100644
--- a/packages/eve/src/setup/integrations/registry.test.ts
+++ b/packages/eve/src/setup/integrations/registry.test.ts
@@ -36,8 +36,16 @@ describe("setup integrations", () => {
label: "File memory",
});
});
- it("registers Shopify", () => {
+ it("registers Shopify and self-modification setup variants", () => {
expect(setupIntegration("shopify")).toMatchObject({ kind: "shopify", label: "Shopify" });
+ expect(setupIntegration("self-modification")).toMatchObject({
+ kind: "self-modification",
+ label: "Self-modification",
+ });
+ expect(setupIntegration("self-modification-production")).toMatchObject({
+ kind: "self-modification-production",
+ label: "Self-modification production",
+ });
});
it("rejects unknown integrations", () => {
expect(() => setupIntegration("unknown")).toThrow(
diff --git a/packages/eve/src/setup/integrations/registry.ts b/packages/eve/src/setup/integrations/registry.ts
index bf917b212..077867e7c 100644
--- a/packages/eve/src/setup/integrations/registry.ts
+++ b/packages/eve/src/setup/integrations/registry.ts
@@ -4,6 +4,10 @@ import { GITHUB_SETUP } from "./github/setup.js";
import { LINEAR_SETUP } from "./linear/setup.js";
import { LINQ_SETUP } from "./linq/setup.js";
import { PHOTON_SETUP } from "./photon/setup.js";
+import {
+ SELF_MODIFICATION_PRODUCTION_SETUP,
+ SELF_MODIFICATION_SETUP,
+} from "./self-modification/setup.js";
import { SHOPIFY_SETUP } from "./shopify/setup.js";
import { SLACK_SETUP } from "./slack/setup.js";
import type { SetupIntegration } from "./types.js";
@@ -20,6 +24,8 @@ export const SETUP_INTEGRATIONS: readonly SetupIntegration[] = [
LINQ_SETUP,
PHOTON_SETUP,
SHOPIFY_SETUP,
+ SELF_MODIFICATION_SETUP,
+ SELF_MODIFICATION_PRODUCTION_SETUP,
];
/** Resolves one built-in setup integration by its registry setup name. */
diff --git a/packages/eve/src/setup/integrations/runner.ts b/packages/eve/src/setup/integrations/runner.ts
index babc5da89..02c803f3e 100644
--- a/packages/eve/src/setup/integrations/runner.ts
+++ b/packages/eve/src/setup/integrations/runner.ts
@@ -60,7 +60,10 @@ export async function runIntegrationSetup(
]);
const project = projectResolutionFromDeployment(deployment);
const environment = integrationSetupEnvironment(authStatus, project);
- options.prompter.log.info(describeIntegrationSetupEnvironment(environment));
+ options.prompter.log.info(
+ integration.describeEnvironment?.(environment) ??
+ describeIntegrationSetupEnvironment(environment),
+ );
return integration.run(
createSetupContexts({
appRoot: options.appRoot,
diff --git a/packages/eve/src/setup/integrations/self-modification/setup.test.ts b/packages/eve/src/setup/integrations/self-modification/setup.test.ts
new file mode 100644
index 000000000..2bec7e8e2
--- /dev/null
+++ b/packages/eve/src/setup/integrations/self-modification/setup.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+import type { SelfModificationSetupOperations } from "#self-modification/setup.js";
+import { headlessAsker, withAnswers } from "#setup/ask.js";
+
+import { integrationSetupEnvironment } from "../shared/environment.js";
+import { createSetupContexts } from "../shared/ui.js";
+import {
+ applySelfModificationSetup,
+ prepareLocalSelfModificationSetup,
+ prepareSelfModificationSetup,
+ SELF_MODIFICATION_PRODUCTION_SETUP,
+ SELF_MODIFICATION_SETUP,
+} from "./setup.js";
+
+function operations(config?: string): SelfModificationSetupOperations & {
+ attachConnector: ReturnType<typeof vi.fn>;
+ findOrCreateConnector: ReturnType<typeof vi.fn>;
+ writeConfig: ReturnType<typeof vi.fn>;
+} {
+ return {
+ attachConnector: vi.fn(async () => {}),
+ detectGitRepository: vi.fn(async () => ({
+ branch: "main",
+ directory: "apps/support",
+ owner: "acme",
+ repo: "agents",
+ remoteKind: "github" as const,
+ })),
+ findOrCreateConnector: vi.fn(async () => "github/selfmod-acme-agents"),
+ readConfig: vi.fn(async () => config),
+ writeConfig: vi.fn(async () => {}),
+ };
+}
+
+function contexts(answers: Record<string, unknown>) {
+ return createSetupContexts({
+ appRoot: "/project",
+ asker: withAnswers(answers)(headlessAsker()),
+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),
+ prompter: createFakePrompter().prompter,
+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
+ });
+}
+
+describe("self-modification integration setup", () => {
+ it("keeps the default setup local without mutation", async () => {
+ const effects = operations();
+ const ctx = contexts({});
+
+ const plan = await prepareLocalSelfModificationSetup(ctx.prepare, effects);
+ await expect(applySelfModificationSetup(plan, ctx.apply, effects)).resolves.toEqual({
+ facts: [{ label: "Self-modification", value: "local editing" }],
+ });
+ expect(effects.findOrCreateConnector).not.toHaveBeenCalled();
+ expect(effects.writeConfig).not.toHaveBeenCalled();
+ });
+
+ it("prepares deployed configuration before applying connector effects", async () => {
+ const effects = operations();
+ const ctx = contexts({
+ "self-modification-repository-owner": "acme",
+ "self-modification-repository-name": "agents",
+ "self-modification-repository-directory": "apps/support",
+ "self-modification-target-branch": "main",
+ "self-modification-confirm": true,
+ });
+
+ const plan = await prepareSelfModificationSetup(ctx.prepare, effects);
+ expect(effects.findOrCreateConnector).not.toHaveBeenCalled();
+ await expect(applySelfModificationSetup(plan, ctx.apply, effects)).resolves.toMatchObject({
+ deploymentRequired: true,
+ });
+ expect(effects.attachConnector).toHaveBeenCalledWith("github/selfmod-acme-agents");
+ expect(effects.writeConfig).toHaveBeenCalledWith(
+ expect.stringContaining('repository: "github.com/acme/agents"'),
+ );
+ });
+
+ it("registers the production setup separately from local setup", () => {
+ expect(SELF_MODIFICATION_PRODUCTION_SETUP.kind).toBe("self-modification-production");
+ });
+
+ it("describes unavailable Vercel setup without suggesting portable credentials", () => {
+ const environment = integrationSetupEnvironment("cli-missing", { kind: "unresolved" });
+ expect(SELF_MODIFICATION_SETUP.describeEnvironment?.(environment)).toBe(
+ "Vercel CLI not found. Local editing remains available; deployed proposals require Vercel Connect.",
+ );
+ });
+});
diff --git a/packages/eve/src/setup/integrations/self-modification/setup.ts b/packages/eve/src/setup/integrations/self-modification/setup.ts
new file mode 100644
index 000000000..8e2e26ac0
--- /dev/null
+++ b/packages/eve/src/setup/integrations/self-modification/setup.ts
@@ -0,0 +1,196 @@
+import { confirm, text } from "#setup/ask.js";
+import {
+ classifySelfModificationConfig,
+ connectorName,
+ defaultSelfModificationSetupOperations,
+ directoryError,
+ gitRefError,
+ renderSelfModificationConfig,
+ repositoryPartError,
+ type SelfModificationSetupOperations,
+ type SelfModificationSetupValues,
+} from "#self-modification/setup.js";
+import { SELF_MODIFICATION_CONFIG_PATH } from "#self-modification/git-workspace.js";
+
+import { describeIntegrationSetupEnvironment } from "../shared/environment.js";
+import {
+ defineSetupIntegration,
+ type SetupApplyContext,
+ type SetupPrepareContext,
+} from "../types.js";
+
+type SelfModificationSetupPlan =
+ | { readonly kind: "authored" }
+ | { readonly kind: "local" }
+ | {
+ readonly kind: "deployed";
+ readonly connectorName: string;
+ readonly values: SelfModificationSetupValues;
+ };
+
+function validationResult(error: string | undefined): string | null {
+ return error ?? null;
+}
+
+export async function prepareSelfModificationSetup(
+ context: SetupPrepareContext,
+ operations: SelfModificationSetupOperations = defaultSelfModificationSetupOperations(
+ context.appRoot,
+ ),
+): Promise<SelfModificationSetupPlan> {
+ const existing = await operations.readConfig();
+ if (classifySelfModificationConfig(existing) === "authored") {
+ context.presenter.note(
+ `The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,
+ "Manual update required",
+ { tone: "warning" },
+ );
+ return { kind: "authored" };
+ }
+
+ const detected = await operations.detectGitRepository();
+ const owner = await context.asker.ask(
+ text({
+ key: "self-modification-repository-owner",
+ message: "GitHub repository owner",
+ detected: detected.owner,
+ required: true,
+ validate: (value) => validationResult(repositoryPartError(value)),
+ }),
+ );
+ const repo = await context.asker.ask(
+ text({
+ key: "self-modification-repository-name",
+ message: "GitHub repository name",
+ detected: detected.repo,
+ required: true,
+ validate: (value) => validationResult(repositoryPartError(value)),
+ }),
+ );
+ const directory = await context.asker.ask(
+ text({
+ key: "self-modification-repository-directory",
+ message: "Application directory relative to the repository root",
+ detected: detected.directory ?? ".",
+ required: true,
+ validate: (value) => validationResult(directoryError(value)),
+ }),
+ );
+ const branch = await context.asker.ask(
+ text({
+ key: "self-modification-target-branch",
+ message: "Target branch",
+ detected: detected.branch ?? "main",
+ required: true,
+ validate: (value) => validationResult(gitRefError(value)),
+ }),
+ );
+ const name = connectorName(owner, repo);
+ const values = {
+ branch,
+ connector: `github/${name}`,
+ directory,
+ repository: `github.com/${owner}/${repo}`,
+ };
+ context.presenter.note(
+ renderSelfModificationConfig(values),
+ `Generated ${SELF_MODIFICATION_CONFIG_PATH}`,
+ );
+ context.presenter.note(
+ "Vercel Connect will issue short-lived GitHub App credentials restricted to this repository. Install the managed GitHub App and select only this repository. Review, merge, and deployment remain separate operator boundaries.",
+ "Security summary",
+ );
+ const confirmed = await context.asker.ask(
+ confirm({
+ key: "self-modification-confirm",
+ message: "Create or attach this GitHub connector and write this configuration?",
+ recommended: false,
+ required: true,
+ }),
+ );
+ return confirmed ? { kind: "deployed", connectorName: name, values } : { kind: "local" };
+}
+
+export async function applySelfModificationSetup(
+ plan: SelfModificationSetupPlan,
+ context: SetupApplyContext,
+ operations: SelfModificationSetupOperations = defaultSelfModificationSetupOperations(
+ context.appRoot,
+ ),
+) {
+ if (plan.kind === "authored") {
+ return {
+ facts: [{ label: "Self-modification", value: "manual configuration update required" }],
+ };
+ }
+ if (plan.kind === "local") {
+ return { facts: [{ label: "Self-modification", value: "local editing" }] };
+ }
+
+ const connector = await operations.findOrCreateConnector(plan.connectorName);
+ await operations.attachConnector(connector);
+ await operations.writeConfig(renderSelfModificationConfig({ ...plan.values, connector }));
+ context.presenter.log.success(`Updated ${SELF_MODIFICATION_CONFIG_PATH}.`);
+ context.presenter.nextSteps([
+ "Install the managed GitHub App for the configured repository, then redeploy.",
+ ]);
+ return {
+ deploymentRequired: true as const,
+ facts: [
+ { label: "Repository", value: plan.values.repository },
+ { label: "Application directory", value: plan.values.directory },
+ { label: "Target branch", value: plan.values.branch },
+ { label: "Credential", value: connector },
+ ],
+ };
+}
+
+export async function prepareLocalSelfModificationSetup(
+ context: SetupPrepareContext,
+ operations: SelfModificationSetupOperations = defaultSelfModificationSetupOperations(
+ context.appRoot,
+ ),
+): Promise<SelfModificationSetupPlan> {
+ const existing = await operations.readConfig();
+ if (classifySelfModificationConfig(existing) === "authored") {
+ context.presenter.note(
+ `The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,
+ "Manual update required",
+ { tone: "warning" },
+ );
+ return { kind: "authored" };
+ }
+ return { kind: "local" };
+}
+
+function describeEnvironment(environment: SetupPrepareContext["environment"]): string {
+ if (environment.vercel.kind === "available") {
+ return describeIntegrationSetupEnvironment(environment);
+ }
+ switch (environment.vercel.reason) {
+ case "logged-out":
+ return "No authenticated Vercel account found. Local editing remains available; deployed proposals require Vercel Connect.";
+ case "cli-missing":
+ return "Vercel CLI not found. Local editing remains available; deployed proposals require Vercel Connect.";
+ case "unavailable":
+ return "Could not verify the Vercel account. Local editing remains available; deployed proposals require Vercel Connect.";
+ }
+}
+
+export const SELF_MODIFICATION_SETUP = defineSetupIntegration({
+ kind: "self-modification",
+ label: "Self-modification",
+ hint: "Local source editing is enabled",
+ describeEnvironment,
+ prepare: prepareLocalSelfModificationSetup,
+ apply: applySelfModificationSetup,
+});
+
+export const SELF_MODIFICATION_PRODUCTION_SETUP = defineSetupIntegration({
+ kind: "self-modification-production",
+ label: "Self-modification production",
+ hint: "Configure deployed draft pull requests",
+ describeEnvironment,
+ prepare: prepareSelfModificationSetup,
+ apply: applySelfModificationSetup,
+});
diff --git a/packages/eve/src/setup/integrations/types.ts b/packages/eve/src/setup/integrations/types.ts
index 04a7ce66f..64c38f310 100644
--- a/packages/eve/src/setup/integrations/types.ts
+++ b/packages/eve/src/setup/integrations/types.ts
@@ -44,6 +44,7 @@ interface SetupIntegrationDefinition<Plan> {
readonly kind: string;
readonly label: string;
readonly hint?: string;
+ describeEnvironment?(environment: IntegrationSetupEnvironment): string;
prepare(context: SetupPrepareContext): Promise<Plan>;
apply(plan: Plan, context: SetupApplyContext): Promise<RegistrySetupCompletion>;
}
@@ -52,6 +53,7 @@ export interface SetupIntegration {
readonly kind: string;
readonly label: string;
hint?: string;
+ describeEnvironment?(environment: IntegrationSetupEnvironment): string;
run(input: {
prepare: SetupPrepareContext;
apply: SetupApplyContext;
@@ -76,5 +78,7 @@ export function defineSetupIntegration<Plan>(
},
};
if (definition.hint !== undefined) registered.hint = definition.hint;
+ if (definition.describeEnvironment !== undefined)
+ registered.describeEnvironment = definition.describeEnvironment;
return registered;
}