The Open Framework for Building Agents
feat(eve): migrate self-modification to extension subagent (#3501)
prha9d394faa3ae2
diff --git a/.changeset/bright-self-modification.md b/.changeset/bright-self-modification.mdnew file mode 100644index 000000000..bb3fce48d--- /dev/null+++ b/.changeset/bright-self-modification.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Package self-modification as an extension-owned subagent and retire the legacy scaffolded self-modification capability. Registry installation uses local-only setup, while deployed-aware setup remains available separately.diff --git a/apps/docs/registry.json b/apps/docs/registry.jsonindex fdeeb6911..611352d05 100644--- a/apps/docs/registry.json+++ b/apps/docs/registry.json@@ -8,7 +8,7 @@"type": "registry:item","title": "Self-modification","description": "Add a source editing subagent with local edits and official registry installation.",- "dependencies": ["just-bash", "@vercel/connect"],+ "dependencies": ["just-bash"],"meta": {"eve": {"requires": ">=0.54.4",@@ -28,31 +28,16 @@{"package": "eve","bin": "eve",- "args": ["integration", "setup", "self-modification-production"]+ "args": ["integration", "setup", "self-modification"]}]}},"files": [- {- "path": "registry/eve/self-modification/config.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/config.ts"- },- {- "path": "registry/eve/self-modification/agent.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/agent.ts"- },- {- "path": "registry/eve/self-modification/sandbox.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/sandbox.ts"- },{"path": "registry/eve/self-modification/extension.ts","type": "registry:file",- "target": "agent/subagents/self-modification/extensions/selfmod.ts"+ "target": "agent/extensions/self-modification/extension.ts"}]},@@ -61,7 +46,7 @@"type": "registry:item","title": "Self-modification (Experimental)","description": "Add an experimental source editing subagent with local edits and official registry installation.",- "dependencies": ["just-bash", "@vercel/connect"],+ "dependencies": ["just-bash"],"meta": {"eve": {"hidden": true,@@ -87,25 +72,10 @@}},"files": [- {- "path": "registry/eve/self-modification/config.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/config.ts"- },- {- "path": "registry/eve/self-modification/agent.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/agent.ts"- },- {- "path": "registry/eve/self-modification/sandbox.ts",- "type": "registry:file",- "target": "agent/subagents/self-modification/sandbox.ts"- },{"path": "registry/eve/self-modification/extension.ts","type": "registry:file",- "target": "agent/subagents/self-modification/extensions/selfmod.ts"+ "target": "agent/extensions/self-modification/extension.ts"}]},diff --git a/apps/docs/registry.staged-requirements.json b/apps/docs/registry.staged-requirements.jsonnew file mode 100644index 000000000..923c5b664--- /dev/null+++ b/apps/docs/registry.staged-requirements.json@@ -0,0 +1,3 @@+{+ "items": ["eve/self-modification", "experimental/self-modification"]+}diff --git a/apps/docs/registry/eve/self-modification/agent.ts b/apps/docs/registry/eve/self-modification/agent.tsdeleted file mode 100644index 574eaa1f5..000000000--- a/apps/docs/registry/eve/self-modification/agent.ts+++ /dev/null@@ -1,10 +0,0 @@-import { defineSelfModificationAgent } from "eve/self-modification/agent";--import config from "./config";--export default defineSelfModificationAgent({- config,-- // To use a specific model instead of eve's default, add:- // model: "provider/model",-});diff --git a/apps/docs/registry/eve/self-modification/config.ts b/apps/docs/registry/eve/self-modification/config.tsdeleted file mode 100644index 0d2dcbd58..000000000--- a/apps/docs/registry/eve/self-modification/config.ts+++ /dev/null@@ -1,5 +0,0 @@-import { defineSelfModificationConfig } from "eve/self-modification/config";--export default defineSelfModificationConfig({- local: { enabled: true },-});diff --git a/apps/docs/registry/eve/self-modification/extension.ts b/apps/docs/registry/eve/self-modification/extension.tsindex 1b51e3fbe..1bb436a3f 100644--- a/apps/docs/registry/eve/self-modification/extension.ts+++ b/apps/docs/registry/eve/self-modification/extension.ts@@ -1,5 +1,6 @@import selfModification from "eve/self-modification";-import config from "../config";--export default selfModification(config);+export default selfModification({+ // model: "provider/model",+ // reasoning: "high",+});diff --git a/apps/docs/registry/eve/self-modification/sandbox.ts b/apps/docs/registry/eve/self-modification/sandbox.tsdeleted file mode 100644index 27b9b9f6e..000000000--- a/apps/docs/registry/eve/self-modification/sandbox.ts+++ /dev/null@@ -1,5 +0,0 @@-import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";--import config from "./config";--export default defineSelfModificationSandbox({ config });diff --git a/e2e/fixtures/agent-self-modification/.gitignore b/e2e/fixtures/agent-self-modification/.gitignoreindex 6801a5b04..11aab2e59 100644--- a/e2e/fixtures/agent-self-modification/.gitignore+++ b/e2e/fixtures/agent-self-modification/.gitignore@@ -9,5 +9,5 @@ dist.DS_Store*.tsbuildinfo.env*.local-/agent/subagents/self-modification/+/agent/extensions/self-modification//.eve-self-modification-eval.lock/diff --git a/e2e/fixtures/agent-self-modification/README.md b/e2e/fixtures/agent-self-modification/README.mdindex 18e32b79a..2b30a190c 100644--- a/e2e/fixtures/agent-self-modification/README.md+++ b/e2e/fixtures/agent-self-modification/README.md@@ -8,7 +8,7 @@ Routing-only cases remain in [`agent-subagents`](../agent-subagents/evals/self-m## Fixture preparation-`pnpm run e2e:prepare` copies the `eve/self-modification` scaffold from this checkout using the source and target paths in `apps/docs/registry.json`. The generated `agent/subagents/self-modification/` directory is gitignored and replaced on each preparation; no registry fetch, dependency installation, or credential setup runs.+`pnpm run e2e:prepare` copies the `eve/self-modification` scaffold from this checkout using the source and target paths in `apps/docs/registry.json`. The generated `agent/extensions/self-modification/` directory is gitignored and replaced on each preparation; no registry fetch, dependency installation, or credential setup runs.The fixture's `build`, `dev`, `typecheck`, and `test:e2e` scripts prepare the scaffold before starting eve. The local e2e CI workflow also runs `e2e:prepare` before invoking `eve eval` directly. For a direct CLI invocation, prepare first. Do not prepare while an eval or dev server is running: preparation replaces the generated subtree.diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.tsindex 563ac6f45..d469afca1 100644--- a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts+++ b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts@@ -15,7 +15,7 @@ import { dirname, join } from "node:path";import type { EveEvalContext, EveEvalLiveTurn, EveEvalSession, EveEvalTurn } from "eve/evals";-const SELF_MODIFICATION_AGENT = "self-modification";+const SELF_MODIFICATION_AGENT = "self-modification__agent";const CLEANUP_TIMEOUT_MS = 30_000;const LOCK_DIRECTORY = ".eve-self-modification-eval.lock";// Each eval entry bundles its relative imports separately. Share the lock across those copies.diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.tsindex c92094676..3754df3f9 100644--- a/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts+++ b/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts@@ -65,7 +65,7 @@ export default defineEval({authored.session,"That recommendation is wrong. Incoming stock should count toward the target, so it should recommend 50 units, not 80. What should we do?",);- offered.notEvent("subagent.called", { data: { name: "self-modification" } });+ offered.notEvent("subagent.called", { data: { name: "self-modification__agent" } });t.judge.autoevals.closedQA("The response offers to delegate a repair of the incorrect tool and asks the user to confirm before starting it.",{ on: offered.message },diff --git a/e2e/fixtures/agent-self-modification/scripts/prepare.mjs b/e2e/fixtures/agent-self-modification/scripts/prepare.mjsindex 785a05a94..49e0d396b 100644--- a/e2e/fixtures/agent-self-modification/scripts/prepare.mjs+++ b/e2e/fixtures/agent-self-modification/scripts/prepare.mjs@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";const fixtureRoot = fileURLToPath(new URL("../", import.meta.url));const repoRoot = resolve(fixtureRoot, "../../..");-const targetDirectory = "agent/subagents/self-modification";+const targetDirectory = "agent/extensions/self-modification";/** Materialize the checkout's registry scaffold without network access or installer setup. */export async function prepareSelfModification(options = {}) {diff --git a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjsindex 16e5d84d5..bf920dc2e 100644--- a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs+++ b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs@@ -113,7 +113,7 @@ test("close retires every session before restoring the complete source tree", asconst verification = liveTurn("verification");const parentEvent = {type: "subagent.called",- data: { name: "self-modification", childSessionId: child.sessionId },+ data: { name: "self-modification__agent", childSessionId: child.sessionId },};const parent = liveTurn("parent", [parentEvent]);@@ -194,7 +194,7 @@ test("one reset failure still retires other sessions and leaves unsafe source un};const parentEvent = {type: "subagent.called",- data: { name: "self-modification", childSessionId: "bad" },+ data: { name: "self-modification__agent", childSessionId: "bad" },};// The public request path is used to populate both tracked sessions.const liveParent = {@@ -358,10 +358,7 @@ test("request falls back to a parent-boundary watch when the initial event is misessionId: "parent",events: [],async waitForEvent() {- return {- type: "subagent.called",- data: { name: "self-modification", childSessionId: "child" },- };+ return { data: { name: "self-modification__agent", childSessionId: "child" } };},async result() {return completedTurn("parent");@@ -398,7 +395,7 @@ for (const emitsCalled of [false, true]) {test(`request follows a reused agent past stale turns (new called event: ${emitsCalled})`, async () => {const called = {type: "subagent.called",- data: { name: "self-modification", agentId: "agent-1", childSessionId: "child" },+ data: { name: "self-modification__agent", agentId: "agent-1", childSessionId: "child" },};const initialParent = liveTurn("parent", [called]);initialParent.waitForEvent = async () => called;diff --git a/e2e/fixtures/agent-self-modification/test/prepare.scenario.test.mjs b/e2e/fixtures/agent-self-modification/test/prepare.scenario.test.mjsindex 49af1022b..030e10cab 100644--- a/e2e/fixtures/agent-self-modification/test/prepare.scenario.test.mjs+++ b/e2e/fixtures/agent-self-modification/test/prepare.scenario.test.mjs@@ -35,7 +35,7 @@ test("preparation copies the canonical registry targets and removes stale generaconst registry = JSON.parse(await readFile(join(repoRoot, "apps/docs/registry.json"), "utf8"));const item = registry.items.find((item) => item.name === "eve/self-modification");await put(fixtureRoot, "agent/tools/keep.ts", "authored tool");- await put(fixtureRoot, "agent/subagents/self-modification/instructions.md", "stale override");+ await put(fixtureRoot, "agent/extensions/self-modification/instructions.md", "stale override");await prepareSelfModification({ fixtureRoot });for (const file of item.files) {@@ -45,8 +45,8 @@ test("preparation copies the canonical registry targets and removes stale genera);}assert.deepEqual(- await files(join(fixtureRoot, "agent/subagents/self-modification")),- item.files.map((file) => file.target.replace("agent/subagents/self-modification/", "")).sort(),+ await files(join(fixtureRoot, "agent/extensions/self-modification")),+ item.files.map((file) => file.target.replace("agent/extensions/self-modification/", "")).sort(),);assert.equal(await readFile(join(fixtureRoot, "agent/tools/keep.ts"), "utf8"), "authored tool");@@ -62,7 +62,7 @@ test("invalid registry targets fail before replacing the existing scaffold", asyconst root = await temporaryFixture(t);const fixtureRoot = join(root, "fixture");const sourceRepo = join(root, "repo");- await put(fixtureRoot, "agent/subagents/self-modification/agent.ts", "existing");+ await put(fixtureRoot, "agent/extensions/self-modification/agent.ts", "existing");await put(sourceRepo, "apps/docs/registry/example.ts", "source");await put(sourceRepo,@@ -78,7 +78,7 @@ test("invalid registry targets fail before replacing the existing scaffold", asy);await assert.rejects(prepareSelfModification({ fixtureRoot, repoRoot: sourceRepo }), /outside/);assert.equal(- await readFile(join(fixtureRoot, "agent/subagents/self-modification/agent.ts"), "utf8"),+ await readFile(join(fixtureRoot, "agent/extensions/self-modification/agent.ts"), "utf8"),"existing",);});@@ -87,7 +87,7 @@ test("missing source files fail before replacing the existing scaffold", async (const root = await temporaryFixture(t);const fixtureRoot = join(root, "fixture");const sourceRepo = join(root, "repo");- await put(fixtureRoot, "agent/subagents/self-modification/agent.ts", "existing");+ await put(fixtureRoot, "agent/extensions/self-modification/agent.ts", "existing");await put(sourceRepo,"apps/docs/registry.json",@@ -96,7 +96,7 @@ test("missing source files fail before replacing the existing scaffold", async ({name: "eve/self-modification",files: [- { path: "registry/missing.ts", target: "agent/subagents/self-modification/agent.ts" },+ { path: "registry/missing.ts", target: "agent/extensions/self-modification/agent.ts" },],},],@@ -104,7 +104,7 @@ test("missing source files fail before replacing the existing scaffold", async ();await assert.rejects(prepareSelfModification({ fixtureRoot, repoRoot: sourceRepo }), /ENOENT/);assert.equal(- await readFile(join(fixtureRoot, "agent/subagents/self-modification/agent.ts"), "utf8"),+ await readFile(join(fixtureRoot, "agent/extensions/self-modification/agent.ts"), "utf8"),"existing",);});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/self-modification/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/self-modification/agent.tsindex 472248972..16314d4b5 100644--- a/e2e/fixtures/agent-subagents/agent/subagents/self-modification/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/subagents/self-modification/agent.ts@@ -1,4 +1,8 @@import { e2eSubagentConfig } from "@eve-e2e/config";-import { defineSelfModificationAgent } from "eve/self-modification/agent";+import { defineAgent } from "eve";-export default defineSelfModificationAgent({ model: e2eSubagentConfig().model });+export default defineAgent({+ ...e2eSubagentConfig(),+ description:+ "Delegate requests to change the eve agent, add reusable actions, or install and connect named capabilities. This acceptance-only child does not modify source or call tools.",+});diff --git a/packages/eve-self-modification/README.md b/packages/eve-self-modification/README.mdindex 22a2abe76..ed7934593 100644--- a/packages/eve-self-modification/README.md+++ b/packages/eve-self-modification/README.md@@ -1,19 +1,34 @@# @eve/self-modification-`@eve/self-modification` is a compatibility package. It forwards its entrypoints to the implementation included with `eve`.+`@eve/self-modification` is a compatibility package. New applications should install the self-modification extension included with `eve`:-Update imports to use `eve` directly:+```sh+eve add eve/self-modification+```++The command creates `agent/extensions/self-modification/extension.ts`:```ts-import { defineSelfModificationAgent } from "eve/self-modification/agent";+import selfModification from "eve/self-modification";-export default defineSelfModificationAgent();+export default selfModification({+ // model: "provider/model",+ // reasoning: "high",+});```-```ts-export { default } from "eve/self-modification/sandbox";-```+Local source editing is available while `eve dev` is running, and registry installation adds only `just-bash`. The registry command runs local-only setup; deployed-aware setup remains a separate integration. Keep the generated mount at `agent/extensions/self-modification/extension.ts`; alternate mount paths and namespaces are not supported by the self-modification setup and TUI flows.-```ts-export { default } from "eve/self-modification";+## Migrate a scaffolded subagent++Older installations placed self-modification under `agent/subagents/self-modification/`. That scaffold is retired: its agent helper is unavailable, and its sandbox helper is inert.++Run the registry command to install the packaged extension:++```sh+eve add eve/self-modification```++When setup detects a retired scaffold, it offers to remove the entire legacy directory and selects **Yes** by default. Decline the prompt if you need to inspect those files before removing them.++The legacy `eve/self-modification/agent`, `eve/self-modification/sandbox`, and `eve/self-modification/config` entrypoints remain available so the standard scaffold can build during migration. Do not use the retired agent or sandbox helpers for new installations.diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 6856bfbf5..d6c3e9c7c 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -55,19 +55,25 @@ const VERCEL_SSO_URL =describe("registryHandoffAddress", () => {it("accepts only a terminal handoff from the self-modification registry tool", () => {expect(- registryHandoffAddress("selfmod__registry_add", {+ registryHandoffAddress("self-modification__agent", "registry_add", {status: "needs-terminal",address: "channel/slack",}),).toBe("channel/slack");expect(- registryHandoffAddress("selfmod__registry_add", {+ registryHandoffAddress("other__agent", "registry_add", {+ status: "needs-terminal",+ address: "channel/slack",+ }),+ ).toBeUndefined();+ expect(+ registryHandoffAddress("self-modification__agent", "registry_add", {status: "installed",address: "extension/browserbase",}),).toBeUndefined();expect(- registryHandoffAddress("other_tool", {+ registryHandoffAddress("self-modification__agent", "other_tool", {status: "needs-terminal",address: "channel/slack",}),@@ -261,7 +267,7 @@ describe("registryHandoffAddress", () => {callId: "registry-add",input: { address: "channel/slack" },kind: "tool-call",- toolName: "selfmod__registry_add",+ toolName: "registry_add",},],sequence: 1,@@ -281,7 +287,7 @@ describe("registryHandoffAddress", () => {callId: "registry-add",input: { address: "channel/slack" },kind: "tool-call",- toolName: "selfmod__registry_add",+ toolName: "registry_add",},display: "confirmation",kind: "tool-approval",@@ -289,7 +295,7 @@ describe("registryHandoffAddress", () => {{ id: "approve", label: "Approve" },{ id: "cancel", label: "Cancel" },],- prompt: "Approve tool call: selfmod__registry_add",+ prompt: "Approve tool call: registry_add",requestId: "approval-1",},],@@ -321,7 +327,7 @@ describe("registryHandoffAddress", () => {callId: "registry-add",input: { address: "channel/slack" },kind: "tool-call",- toolName: "selfmod__registry_add",+ toolName: "registry_add",},],sequence: 3,@@ -339,7 +345,7 @@ describe("registryHandoffAddress", () => {callId: "registry-add",kind: "tool-result",output: { status: "needs-terminal", address: "channel/slack" },- toolName: "selfmod__registry_add",+ toolName: "registry_add",},sequence: 4,status: "completed",@@ -387,7 +393,7 @@ describe("registryHandoffAddress", () => {callId: "selfmod-call",childSessionId: "child-session",childStreamPath: "/eve/v1/session/child-session/stream",- name: "self-modification",+ name: "self-modification__agent",sequence: 0,turnId: "parent-turn",},diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 5cf76c5d1..7f1978c79 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -633,8 +633,8 @@ export class EveTUIRunner {if (this.#client !== undefined) pumpOptions.client = this.#client;if (this.#renderer.subagents !== undefined) pumpOptions.view = this.#renderer.subagents;if (options.appRoot !== undefined) {- pumpOptions.onToolCompleted = async (toolName, output) => {- const address = registryHandoffAddress(toolName, output);+ pumpOptions.onToolCompleted = async (subagentName, toolName, output) => {+ const address = registryHandoffAddress(subagentName, toolName, output);if (address !== undefined) this.#queueRegistrySetup(address);};}@@ -2163,14 +2163,16 @@ type EveStreamTranslatorInput = {failureHintOverride?: (event: FailureStreamEvent) => string | undefined;};-const SELFMOD_REGISTRY_ADD_TOOL = "selfmod__registry_add";--/** Returns the registry address carried by a self-modification terminal handoff. */+/** Returns the registry address carried by a packaged self-modification terminal handoff. */export function registryHandoffAddress(+ subagentName: string | undefined,toolName: string | undefined,output: unknown,): string | undefined {- if (toolName !== SELFMOD_REGISTRY_ADD_TOOL || typeof output !== "object" || output === null) {+ const isPackagedChild =+ subagentName === "self-modification__agent" && toolName === "registry_add";+ const isLegacyRoot = subagentName === undefined && toolName === "selfmod__registry_add";+ if ((!isPackagedChild && !isLegacyRoot) || typeof output !== "object" || output === null) {return undefined;}const result = output as { address?: unknown; status?: unknown };@@ -2475,7 +2477,7 @@ async function* eveEventsToTUIStream(toolCallId: callId,output,};- const address = registryHandoffAddress(toolNames.get(callId), output);+ const address = registryHandoffAddress(undefined, toolNames.get(callId), output);if (address !== undefined) await onRegistryHandoff?.(address);break;}diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsindex cf842ce7f..1591ed0a9 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts@@ -343,7 +343,7 @@ describe("SubagentPump child stream transport", () => {callId: "registry-add",input: { address: "channel/slack" },kind: "tool-call",- toolName: "selfmod__registry_add",+ toolName: "registry_add",},],sequence: 1,@@ -361,7 +361,7 @@ describe("SubagentPump child stream transport", () => {callId: "registry-add",kind: "tool-result",output: { status: "needs-terminal", address: "channel/slack" },- toolName: "selfmod__registry_add",+ toolName: "registry_add",},sequence: 2,status: "completed",@@ -384,8 +384,10 @@ describe("SubagentPump child stream transport", () => {});const first = subagentCalled("call-1");first.data.childSessionId = "conversation-child";+ first.data.name = "self-modification__agent";const second = subagentCalled("call-2", "turn-2");second.data.childSessionId = "conversation-child";+ second.data.name = "self-modification__agent";pump.begin(first);await vi.waitFor(() =>@@ -399,7 +401,7 @@ describe("SubagentPump child stream transport", () => {"/eve/v1/children/call-2/stream?startIndex=1",expect.objectContaining({ signal: expect.any(AbortSignal) }),);- expect(onToolCompleted).toHaveBeenCalledWith("selfmod__registry_add", {+ expect(onToolCompleted).toHaveBeenCalledWith("self-modification__agent", "registry_add", {status: "needs-terminal",address: "channel/slack",});diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex 9f754d562..690ab5e41 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -126,14 +126,16 @@ export interface SubagentPumpOptions {view?: SubagentView;formatActionResultError: (event: ActionResultStreamEvent) => string;/** Runs TUI-owned handling after a child tool result becomes visible. */- onToolCompleted?: (toolName: string, output: unknown) => Promise<void>;+ onToolCompleted?: (subagentName: string, toolName: string, output: unknown) => Promise<void>;}export class SubagentPump {readonly #client: Client | undefined;readonly #view: SubagentView | undefined;readonly #formatActionResultError: (event: ActionResultStreamEvent) => string;- readonly #onToolCompleted: ((toolName: string, output: unknown) => Promise<void>) | undefined;+ readonly #onToolCompleted:+ | ((subagentName: string, toolName: string, output: unknown) => Promise<void>)+ | undefined;readonly #runs = new Map<string, SubagentRun>();readonly #pumps = new Map<string, AbortController>();/** Durable child cursor shared by repeated calls into one conversation subagent. */@@ -584,7 +586,7 @@ export class SubagentPump {if (tool.errorText !== undefined) update.errorText = tool.errorText;view?.upsertTool(update);if (event.data.status === "completed") {- return this.#onToolCompleted?.(tool.toolName, result.output);+ return this.#onToolCompleted?.(run.name, tool.toolName, result.output);}break;}diff --git a/packages/eve/src/internal/authored-package-boundary.test.ts b/packages/eve/src/internal/authored-package-boundary.test.tsindex c0bbc79fc..082337900 100644--- a/packages/eve/src/internal/authored-package-boundary.test.ts+++ b/packages/eve/src/internal/authored-package-boundary.test.ts@@ -35,6 +35,16 @@ describe("createGenerationPackageBoundaryPlugin", () => {kind: "import-statement",}),).resolves.toEqual({ external: true, id: "eve/tools" });+ await expect(+ resolveId.call(+ context,+ "eve/self-modification",+ join(PACKAGE_ROOT, "agent/extensions/edit.ts"),+ {+ kind: "import-statement",+ },+ ),+ ).resolves.toBeUndefined();});it("resolves package-private imports from the importing dependency", async () => {@@ -89,7 +99,10 @@ describe("createRuntimeLoaderPackageBoundaryPlugin", () => {resolveId.call(context,"eve/tools",- join(PACKAGE_ROOT, "dist/src/self-modification/extension/tools/edit_file.js"),+ join(+ PACKAGE_ROOT,+ "dist/src/self-modification/extension/subagents/agent/tools/edit_file.js",+ ),{ kind: "import-statement" },),).resolves.toEqual({diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.tsindex 5e8e7083d..09e4408cc 100644--- a/packages/eve/src/internal/authored-package-boundary.ts+++ b/packages/eve/src/internal/authored-package-boundary.ts@@ -397,6 +397,8 @@ export function isPathImport(source: string): boolean {}function isFrameworkRuntimeImport(source: string, importer: string | undefined): boolean {+ // The packaged extension is authored code: its mount and child must share a scoped handle.+ if (source === "eve/self-modification") return false;if (source === "eve" || source.startsWith("eve/")) {return true;}diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.tsindex 516625adc..48af9c529 100644--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts@@ -255,6 +255,56 @@ describe("development generation artifacts", () => {expect(tool.default.execute()).toBe("configured");});+ it("honors disabled local self-modification in the materialized development graph", async () => {+ const previousDev = process.env.EVE_DEV;+ process.env.EVE_DEV = "1";+ try {+ const app = await scenarioApp({+ files: {+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',+ "agent/instructions.md": "Use the available tools.",+ "agent/extensions/self-modification.mjs": [+ 'import selfModification from "eve/self-modification";',+ "export default selfModification({ local: { enabled: false } });",+ "",+ ].join("\n"),+ },+ name: "disabled-local-self-modification-generation",+ });+ await mkdir(join(app.appRoot, "node_modules"), { recursive: true });+ await symlink(resolvePackageRoot(), join(app.appRoot, "node_modules", "eve"), "junction");++ const compileResult = await compileAgent({ startPath: app.appRoot });+ const snapshot = await stageDevelopmentGeneration(compileResult);+ const moduleMap = await loadCompiledModuleMapFromAuthoredSource({+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(+ snapshot.runtimeAppRoot,+ ),+ });+ const child = compileResult.manifest.subagents[0];+ if (child?.configResolver === undefined) throw new Error("expected a dynamic subagent");+ const modules = moduleMap.nodes[child.nodeId]!.modules;+ const agent = modules[child.configResolver.sourceId] as {+ default: { events: Record<string, Function> };+ };+ for (const event of ["session.started", "turn.started"]) {+ await expect(agent.default.events[event]!({}, { model: null })).resolves.toBeNull();+ }++ const sandbox = modules[child.agent.sandbox.sourceId] as {+ defineSelfModificationSandbox(options: { backend: { name: string } }): {+ backend(): { name: string };+ };+ };+ const backend = { name: "disabled-local-test" };+ // Local mode ignores this backend and installs the writable host filesystem instead.+ expect(sandbox.defineSelfModificationSandbox({ backend }).backend()).toBe(backend);+ } finally {+ if (previousDev === undefined) delete process.env.EVE_DEV;+ else process.env.EVE_DEV = previousDev;+ }+ });+it("materializes a mounted extension from a physical installed directory", async () => {const packageName = "@acme/physical-extension";const app = await scenarioApp({diff --git a/packages/eve/src/sandbox/backends/default.ts b/packages/eve/src/sandbox/backends/default.tsindex 15797333d..5b23e0865 100644--- a/packages/eve/src/sandbox/backends/default.ts+++ b/packages/eve/src/sandbox/backends/default.ts@@ -1,7 +1,4 @@-import {- isLinuxDockerDaemonAvailableSync,- isMicrosandboxPlatformSupported,-} from "#execution/sandbox/bindings/local.js";+import { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "./probes.js";import { lazyBackend } from "#execution/sandbox/lazy-backend.js";import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";import { docker } from "#sandbox/backends/docker.js";@@ -13,6 +10,8 @@ import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandimport { vercel } from "#sandbox/backends/vercel.js";import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";+export { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "./probes.js";+/*** Input to {@link defaultSandbox}: a separate options bag per inner* backend. The framework picks one backend at runtime based on@@ -25,27 +24,6 @@ export interface DefaultSandboxOptions {readonly vercel?: VercelSandboxCreateOptions;}-/**- * Availability probes behind {@link defaultSandbox}'s selection chain.- * Injectable so selection logic is testable without touching the host.- */-export interface DefaultSandboxProbes {- readonly isDeployedOnVercel: () => boolean;- readonly isDockerAvailable: () => boolean;- readonly isMicrosandboxSupported: () => boolean;-}--// Wrapped in arrows (not captured by reference) deliberately: this-// 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.-/** 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(),-};-/*** Constructs an availability-aware sandbox backend. On first use it* picks the best backend the host supports, in priority order:diff --git a/packages/eve/src/sandbox/backends/probes.ts b/packages/eve/src/sandbox/backends/probes.tsnew file mode 100644index 000000000..8b0b6563a--- /dev/null+++ b/packages/eve/src/sandbox/backends/probes.ts@@ -0,0 +1,16 @@+import { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/docker-cli.js";+import { isMicrosandboxPlatformSupported } from "#execution/sandbox/bindings/microsandbox-platform.js";++/** Availability probes shared by built-in backend selectors. */+export interface DefaultSandboxProbes {+ readonly isDeployedOnVercel: () => boolean;+ readonly isDockerAvailable: () => boolean;+ readonly isMicrosandboxSupported: () => boolean;+}++// Keep probes separate from backend factories so authored selectors do not bundle engines.+export const SANDBOX_BACKEND_PROBES: DefaultSandboxProbes = {+ isDeployedOnVercel: () => Boolean(process.env.VERCEL),+ isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),+ isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),+};diff --git a/packages/eve/src/self-modification/agent.test.ts b/packages/eve/src/self-modification/agent.test.tsindex b142fdcac..f97a276e8 100644--- a/packages/eve/src/self-modification/agent.test.ts+++ b/packages/eve/src/self-modification/agent.test.ts@@ -1,53 +1,51 @@import type { DynamicResolveContext } from "#dynamic/definition.js";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { defineSelfModificationAgent } from "./agent.js";+const context: DynamicResolveContext = {+ channel: {},+ messages: [],+ model: null,+ session: { auth: { current: null, initiator: null }, id: "session" },+};+afterEach(() => {delete process.env.EVE_DEV;+ vi.restoreAllMocks();});-describe("self-modification agent", () => {- it("forwards the configured reasoning effort to the subagent", async () => {- process.env.EVE_DEV = "1";- const agent = defineSelfModificationAgent({ reasoning: "high" });- const context: DynamicResolveContext = {- channel: {},- messages: [],- model: null,- session: {- auth: { current: null, initiator: null },- id: "session",- },- };-- const resolved = await agent.events["session.started"]?.({}, context);-- expect(resolved).toMatchObject({ reasoning: "high" });- });+describe("retired self-modification agent scaffold", () => {+ it.each(["session.started", "turn.started"] as const)(+ "resolves to null on %s regardless of options",+ async (eventName) => {+ const agent = defineSelfModificationAgent({+ config: { deployed: { authorize: vi.fn() } },+ model: "provider/model",+ reasoning: "high",+ });++ await expect(agent.events[eventName]?.({}, context)).resolves.toBeNull();+ },+ );- it("offers repairs and delegates only after confirmation", async () => {+ it("warns once in development across both lifecycle events", async () => {process.env.EVE_DEV = "1";+ const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);const agent = defineSelfModificationAgent();- const resolved = await agent.events["session.started"]?.(- {},- {- channel: {},- messages: [],- model: null,- session: { auth: { current: null, initiator: null }, id: "session" },- },- );- expect(resolved).toMatchObject({- description: expect.stringContaining(- "If a tool or capability created or changed by this subagent later fails",- ),- });- const description = (resolved as { description: string }).description;- expect(description).toContain("Do not start the repair until the user confirms.");- expect(description).toContain(- "Treat that confirmation as a source-modification request and delegate it immediately",+ await agent.events["session.started"]?.({}, context);+ await agent.events["turn.started"]?.({}, context);++ expect(warning).toHaveBeenCalledTimes(1);+ expect(warning).toHaveBeenCalledWith(+ "[self-modification/retired-scaffold] The scaffolded self-modification subagent is disabled. Migrate to the new self-modification extension by running `/add eve/self-modification`.",);});++ it("does not warn in production", async () => {+ const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ await defineSelfModificationAgent().events["session.started"]?.({}, context);+ expect(warning).not.toHaveBeenCalled();+ });});diff --git a/packages/eve/src/self-modification/agent.ts b/packages/eve/src/self-modification/agent.tsindex 7daff3801..4033e9445 100644--- a/packages/eve/src/self-modification/agent.ts+++ b/packages/eve/src/self-modification/agent.ts@@ -1,6 +1,5 @@import type { DynamicResolveContext } from "#dynamic/definition.js";import {- defineAgent,defineDynamic,type AgentReasoningDefinition,type AgentStaticModelDefinition,@@ -8,111 +7,34 @@ import {type DynamicSubagentDefinition,} from "#public/index.js";-import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";--import { resolveSelfModificationConfig, type SelfModificationConfig } from "./config.js";-import { hasGitHubCredential } from "./credentials.js";-import { resolveSelfModificationMode } from "./mode.js";--/** Fallback model when neither the self-modification agent nor its parent configures one. */-export const FALLBACK_SELF_MODIFICATION_MODEL = DEFAULT_AGENT_MODEL_ID;--/** Configuration for the self-modification subagent. */+/** Options retained for source compatibility with the retired scaffold. */export interface SelfModificationAgentOptions {- /** Policy shared with the sandbox and extension mount. */- readonly config?: SelfModificationConfig;- /** Model used by the self-modification subagent; defaults to the effective parent model. */+ readonly config?: unknown;readonly model?: AgentStaticModelDefinition;- /**- * Reasoning effort used by the self-modification subagent.- */readonly reasoning?: AgentReasoningDefinition;}-function renderDescription(sections: readonly string[]): string {- return sections.filter((section) => section.length > 0).join(" ");+let warned = false;+function warnRetiredScaffold(): void {+ if (warned || process.env.EVE_DEV !== "1") return;+ warned = true;+ console.warn(+ "[self-modification/retired-scaffold] The scaffolded self-modification subagent is disabled. Migrate to the new self-modification extension by running `/add eve/self-modification`.",+ );}-const sourceDelegation =- "If the requested change references a tool or skill, include the exact identifier. " +- "Do not infer source paths; let the child resolve the appropriate file under /source. " +- "Delegate the requested change and existing constraints without adding unrequested features, implementation steps, or reporting requirements.";--const persistenceDelegation =- "Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the requester 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.";--const namedInstallationDelegation =- "Treat questions phrased as whether you can install, add, enable, or connect to a named product or service as requests to extend this eve agent and delegate immediately. Do not assume they refer to device software, ask what kind of installation they mean, or deny them because you lack access to the user's device. The subagent determines whether the request maps to an integration, channel, connection, or other capability, then checks registry availability and any required setup.";--const followUpDelegation =- "Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " +- "If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.";--const repairDelegation =- "If a tool or capability created or changed by this subagent later fails or behaves incorrectly, explain the observed problem and offer to delegate a repair. " +- "Do not start the repair until the user confirms. Treat that confirmation as a source-modification request and delegate it immediately, including the exact identifier, failing behavior, expected behavior, and existing constraints.";--const localIntegrationDelegation =- "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.";--const deployedIntegrationDelegation =- "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.";--const localTraceDelegation =- "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.";--const localEffectiveEdits =- "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.";-const deployedEffectiveEdits =- "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.";--/** Defines the environment-aware self-modification dynamic subagent. */+/** @deprecated Use the packaged `eve/self-modification` extension. */export function defineSelfModificationAgent(- options: SelfModificationAgentOptions = {},+ _options: SelfModificationAgentOptions = {},): DynamicSentinel<DynamicSubagentDefinition | null> {- const reasoning = options.reasoning;- const config = resolveSelfModificationConfig(options.config);-- const resolve = async (_event: unknown, ctx: DynamicResolveContext) => {- const mode = resolveSelfModificationMode(config);- const model = options.model ?? ctx.model?.id ?? FALLBACK_SELF_MODIFICATION_MODEL;- const description = renderDescription([- "Delegate here when the user asks to change this eve agent or its authored source.",- sourceDelegation,- persistenceDelegation,- namedInstallationDelegation,- mode === "local" ? localIntegrationDelegation : deployedIntegrationDelegation,- mode === "local" ? localTraceDelegation : "",- followUpDelegation,- repairDelegation,- mode === "local" ? localEffectiveEdits : deployedEffectiveEdits,- ]);- if (mode === "local") return defineAgent({ description, model, reasoning });- if (mode !== "deployed" || config.deployed === undefined) return null;- if (config.deployed.credentials.kind === "pat" && !hasGitHubCredential()) return null;- try {- if (- !(await config.deployed.authorize({- channel: ctx.channel,- principal: ctx.session.auth.current,- }))- ) {- return null;- }- } catch {- return null;- }- return defineAgent({ description, model, reasoning });+ const resolve = async (_event: unknown, _ctx: DynamicResolveContext): Promise<null> => {+ warnRetiredScaffold();+ return null;};-return defineDynamic({- events: {- "session.started": resolve,- "turn.started": resolve,- },+ events: { "session.started": resolve, "turn.started": resolve },});}+/** @deprecated Use the packaged `eve/self-modification` extension. */export default defineSelfModificationAgent();diff --git a/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts b/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.tsnew file mode 100644index 000000000..66071d576--- /dev/null+++ b/packages/eve/src/self-modification/authored-runtime-boundary.scenario.test.ts@@ -0,0 +1,33 @@+import { fileURLToPath } from "node:url";++import { describe, expect, it } from "vitest";++import { bundleAuthoredModuleForGeneration } from "#internal/authored-module-loader.js";++describe("self-modification authored runtime boundary", () => {+ it.each(["agent", "sandbox"])(+ "keeps runtime implementations out of the %s generation",+ async (entry) => {+ const code = await bundleAuthoredModuleForGeneration(+ fileURLToPath(new URL(`./extension/subagents/agent/${entry}.ts`, import.meta.url)),+ );++ expect(code).not.toContain("node-liblzma");+ expect(code).not.toContain("@mongodb-js/zstd");+ expect(code).not.toContain("createJustBashSandboxBackend");+ expect(code).not.toContain("loadJustBashModule");+ if (entry === "sandbox") {+ for (const specifier of [+ "eve/sandbox",+ "eve/sandbox/just-bash",+ "eve/sandbox/microsandbox",+ "eve/sandbox/vercel",+ ]) {+ expect(code).toContain(`from "${specifier}"`);+ }+ } else {+ expect(code).toContain('from "eve"');+ }+ },+ );+});diff --git a/packages/eve/src/self-modification/classify-registry-item.test.ts b/packages/eve/src/self-modification/classify-registry-item.test.tsindex 2be246cc5..50d5ccd89 100644--- a/packages/eve/src/self-modification/classify-registry-item.test.ts+++ b/packages/eve/src/self-modification/classify-registry-item.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { classifyCatalogEntry } from "./extension/classify-registry-item.js";-import type { CatalogEntry } from "./extension/tools/search_registry.js";+import type { CatalogEntry } from "./extension/subagents/agent/tools/search_registry.js";function entry(overrides: Partial<CatalogEntry> = {}): CatalogEntry {return {diff --git a/packages/eve/src/self-modification/edit-file.test.ts b/packages/eve/src/self-modification/edit-file.test.tsindex 3c1b227a9..60756ca5f 100644--- a/packages/eve/src/self-modification/edit-file.test.ts+++ b/packages/eve/src/self-modification/edit-file.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import editFile, { applyExactEdits } from "./extension/tools/edit_file.js";+import editFile, { applyExactEdits } from "./extension/subagents/agent/tools/edit_file.js";describe("applyExactEdits", () => {it("describes exact matching and JSON-safe encoding", () => {diff --git a/packages/eve/src/self-modification/extension/classify-registry-item.ts b/packages/eve/src/self-modification/extension/classify-registry-item.tsindex ef3e867d9..e11dda9b5 100644--- a/packages/eve/src/self-modification/extension/classify-registry-item.ts+++ b/packages/eve/src/self-modification/extension/classify-registry-item.ts@@ -1,4 +1,4 @@-import type { CatalogEntry } from "./tools/search_registry.js";+import type { CatalogEntry } from "./subagents/agent/tools/search_registry.js";/*** The split rule.diff --git a/packages/eve/src/self-modification/extension/extension.test.ts b/packages/eve/src/self-modification/extension/extension.test.tsindex f0d680aff..87a1f1623 100644--- a/packages/eve/src/self-modification/extension/extension.test.ts+++ b/packages/eve/src/self-modification/extension/extension.test.ts@@ -1,3 +1,4 @@+import { MockLanguageModelV3 } from "ai/test";import { describe, expect, it } from "vitest";import { selfModificationConfigSchema } from "./extension.js";@@ -15,6 +16,24 @@ class StatefulCredentialProvider {}describe("self-modification extension config", () => {+ it("accepts the same static model and reasoning values as agent configuration", () => {+ const languageModel = new MockLanguageModelV3();++ expect(+ selfModificationConfigSchema.parse({ model: "provider/model", reasoning: "high" }),+ ).toMatchObject({ model: "provider/model", reasoning: "high" });+ expect(selfModificationConfigSchema.parse({ model: languageModel }).model).toBe(languageModel);+ });++ it.each([+ { model: 42 },+ { model: { provider: "test", modelId: "model" } },+ { reasoning: "maximum" },+ { reasoning: {} },+ ])("rejects invalid agent options: %j", (config) => {+ expect(() => selfModificationConfigSchema.parse(config)).toThrow();+ });+it("preserves application-supplied credential providers", async () => {const credentials = new StatefulCredentialProvider("github-token");const parsed = selfModificationConfigSchema.parse({diff --git a/packages/eve/src/self-modification/extension/extension.ts b/packages/eve/src/self-modification/extension/extension.tsindex 97e907f45..29270272d 100644--- a/packages/eve/src/self-modification/extension/extension.ts+++ b/packages/eve/src/self-modification/extension/extension.ts@@ -1,9 +1,17 @@import { defineExtension } from "eve/extension";import { z } from "zod";+import { isAgentReasoningDefinition, isRuntimeLanguageModel } from "#internal/runtime-model.js";+import type { AgentReasoningDefinition, AgentStaticModelDefinition } from "#public/index.js";import type { GitHubCredentialProvider, SelfModificationAuthorization } from "../config.js";export const selfModificationConfigSchema = z.object({+ model: z+ .custom<AgentStaticModelDefinition>(+ (value) => typeof value === "string" || isRuntimeLanguageModel(value),+ )+ .optional(),+ reasoning: z.custom<AgentReasoningDefinition>(isAgentReasoningDefinition).optional(),local: z.object({ enabled: z.boolean().optional() }).optional(),deployed: z.object({diff --git a/packages/eve/src/self-modification/extension/subagents/agent/agent.ts b/packages/eve/src/self-modification/extension/subagents/agent/agent.tsnew file mode 100644index 000000000..ad1af572a--- /dev/null+++ b/packages/eve/src/self-modification/extension/subagents/agent/agent.ts@@ -0,0 +1,119 @@+import type { DynamicResolveContext } from "#dynamic/definition.js";+import {+ defineAgent,+ defineDynamic,+ type AgentReasoningDefinition,+ type AgentStaticModelDefinition,+ type DynamicSentinel,+ type DynamicSubagentDefinition,+} from "eve";++import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";++import selfModification from "../../extension.js";+import { resolveSelfModificationConfig, type SelfModificationConfig } from "../../../config.js";+import { hasGitHubCredential } from "../../../credentials.js";+import { resolveSelfModificationMode } from "../../../mode.js";++/** Fallback model when neither the self-modification agent nor its parent configures one. */+export const FALLBACK_SELF_MODIFICATION_MODEL = DEFAULT_AGENT_MODEL_ID;++/** 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; defaults to the effective parent model. */+ readonly model?: AgentStaticModelDefinition;+ /**+ * Reasoning effort used by the self-modification subagent.+ */+ readonly reasoning?: AgentReasoningDefinition;+}++function renderDescription(sections: readonly string[]): string {+ return sections.filter((section) => section.length > 0).join(" ");+}++const sourceDelegation =+ "If the requested change references a tool or skill, include the exact identifier. " ++ "Do not infer source paths; let the child resolve the appropriate file under /source. " ++ "Delegate the requested change and existing constraints without adding unrequested features, implementation steps, or reporting requirements.";++const persistenceDelegation =+ "Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the requester 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.";++const namedInstallationDelegation =+ "Treat questions phrased as whether you can install, add, enable, or connect to a named product or service as requests to extend this eve agent and delegate immediately. Do not assume they refer to device software, ask what kind of installation they mean, or deny them because you lack access to the user's device. The subagent determines whether the request maps to an integration, channel, connection, or other capability, then checks registry availability and any required setup.";++const followUpDelegation =+ "Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " ++ "If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.";++const repairDelegation =+ "If a tool or capability created or changed by this subagent later fails or behaves incorrectly, explain the observed problem and offer to delegate a repair. " ++ "Do not start the repair until the user confirms. Treat that confirmation as a source-modification request and delegate it immediately, including the exact identifier, failing behavior, expected behavior, and existing constraints.";++const localIntegrationDelegation =+ "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.";++const deployedIntegrationDelegation =+ "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.";++const localTraceDelegation =+ "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.";++const localEffectiveEdits =+ "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.";+const deployedEffectiveEdits =+ "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.";++/** Defines the environment-aware self-modification dynamic subagent. */+export function defineSelfModificationAgent(+ options: SelfModificationAgentOptions = {},+): DynamicSentinel<DynamicSubagentDefinition | null> {+ const resolve = async (_event: unknown, ctx: DynamicResolveContext) => {+ const bound = selfModification.config;+ const reasoning = options.reasoning ?? bound.reasoning;+ const config = resolveSelfModificationConfig(options.config ?? bound);+ const mode = resolveSelfModificationMode(config);+ const model = options.model ?? bound.model ?? ctx.model?.id ?? FALLBACK_SELF_MODIFICATION_MODEL;+ const description = renderDescription([+ "Delegate here when the user asks to change this eve agent or its authored source.",+ sourceDelegation,+ persistenceDelegation,+ namedInstallationDelegation,+ mode === "local" ? localIntegrationDelegation : deployedIntegrationDelegation,+ mode === "local" ? localTraceDelegation : "",+ followUpDelegation,+ repairDelegation,+ mode === "local" ? localEffectiveEdits : deployedEffectiveEdits,+ ]);+ if (mode === "local") return defineAgent({ description, model, reasoning });+ if (mode !== "deployed" || config.deployed === undefined) return null;+ if (config.deployed.credentials.kind === "pat" && !hasGitHubCredential()) return null;+ try {+ if (+ !(await config.deployed.authorize({+ channel: ctx.channel,+ principal: ctx.session.auth.current,+ }))+ ) {+ return null;+ }+ } catch {+ return null;+ }+ return defineAgent({ description, model, reasoning });+ };++ return defineDynamic({+ events: {+ "session.started": resolve,+ "turn.started": resolve,+ },+ });+}++export default defineSelfModificationAgent();diff --git a/packages/eve/src/self-modification/extension/instructions.ts b/packages/eve/src/self-modification/extension/subagents/agent/instructions.tssimilarity index 69%rename from packages/eve/src/self-modification/extension/instructions.tsrename to packages/eve/src/self-modification/extension/subagents/agent/instructions.tsindex f472b8794..ee0323b15 100644--- a/packages/eve/src/self-modification/extension/instructions.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/instructions.ts@@ -1,8 +1,8 @@import { defineDynamic, defineInstructions } from "eve/instructions";-import { resolveSelfModificationConfig } from "../config.js";-import { resolveSelfModificationMode } from "../mode.js";-import selfModification from "./extension.js";+import { resolveSelfModificationConfig } from "../../../config.js";+import { resolveSelfModificationMode } from "../../../mode.js";+import selfModification from "../../extension.js";const role = `## Role@@ -10,13 +10,13 @@ You are an expert coding assistant operating inside of an eve agent. You help usconst sourceWorkspace = `## Source workspace-The source code of the eve agent is mounted read-write at /source. /source is the authored agent directory. Locate source files with bash. Read source contents with read_file, not shell commands. Before generating an overwrite, ensure read_file has succeeded for that path. Shell reads do not satisfy write_file's read-before-write requirement. selfmod__edit_file instead validates exact matches against current contents. Never modify source files with bash, sed, awk, redirection, or scripting.+The source code of the eve agent is mounted read-write at /source. /source is the authored agent directory. Locate source files with bash. Read source contents with read_file, not shell commands. Before generating an overwrite, ensure read_file has succeeded for that path. Shell reads do not satisfy write_file's read-before-write requirement. edit_file instead validates exact matches against current contents. Never modify source files with bash, sed, awk, redirection, or scripting.Resolve named tools by filename under /source/tools before searching contents. Tool identifiers derive from filenames and may not occur in the implementation.`;const sourceEditing = `## Implement changes-Use selfmod__edit_file for localized changes; include only the unique matching text. For a complete rewrite, use read_file then write_file; do not encode the whole old file as one replacement. If tool arguments fail argument parsing, retry the same tool with corrected encoding.+Use edit_file for localized changes; include only the unique matching text. For a complete rewrite, use read_file then write_file; do not encode the whole old file as one replacement. If tool arguments fail argument parsing, retry the same tool with corrected encoding.Once paths are known, batch independent file reads and edits to different files. Never edit the same file concurrently.`;@@ -28,9 +28,9 @@ Do not substitute a loose Python, shell, or JavaScript file for a model-callableconst registryWorkflow = `## Add integrations-Before adding a new eve-managed channel, connection, extension, instrumentation, or memory integration, call selfmod__search_registry alongside source discovery. If an item fulfills the requirement, install it with selfmod__registry_add using its exact address. If no matching item fulfills the requirement, or if the developer asks for a custom implementation, write the integration yourself.+Before adding a new eve-managed channel, connection, extension, instrumentation, or memory integration, call search_registry alongside source discovery. If an item fulfills the requirement, install it with registry_add using its exact address. If no matching item fulfills the requirement, or if the developer asks for a custom implementation, write the integration yourself.-Modifying the behavior of an existing skill or tool does not require a registry search. Registry search blocks implementation, not source inspection. Serialize registry installation and dependent edits. Run selfmod__registry_add separately from file edits and other registry installations.+Modifying the behavior of an existing skill or tool does not require a registry search. Registry search blocks implementation, not source inspection. Serialize registry installation and dependent edits. Run registry_add separately from file edits and other registry installations.Registry installation is outside the source sandbox.`;@@ -58,31 +58,28 @@ For investigation tasks, report the findings and supporting evidence requested bconst localGuidance = `## Local environment-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, if a \`needs-terminal\` result includes \`nextCommand\`, present that exact value as the only shell command in your response. Never infer, construct, or rewrite a command: installing an item uses \`eve add <item>\`; \`eve registry add\` configures registry namespace mappings and does not install items.+The 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, if a \`needs-terminal\` result includes \`nextCommand\`, present that exact value as the only shell command in your response. Never infer, construct, or rewrite a command: installing an item uses \`eve add <item>\`; \`eve registry add\` configures registry namespace mappings and does not install items.Local eve dev logs are available read-only at /logs.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.-The application package.json is not mounted. Do not search outside /source for application files. You cannot run host binaries such as git, node, pnpm, or tsc. Use existing imports and selfmod__registry_add for supported registry installations.`;+The application package.json is not mounted. Do not search outside /source for application files. You cannot run host binaries such as git, node, pnpm, or tsc. Use existing imports and registry_add for supported registry installations.`;const deployedGuidance = `## Deployed environment-The selfmod__registry_add 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.+The registry_add 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.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.Complete all edits and registry installations before publication, and call publish by itself. 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.`;-function readSubagentSourceGuidance(event: unknown): string {+function packagedSubagentGuidance(event: unknown): string {const invocation = (- event as {- readonly data?: { readonly invocation?: { readonly kind?: string; readonly name?: string } };- }+ event as { readonly data?: { readonly invocation?: { readonly kind?: string } } }).data?.invocation;- if (invocation?.kind !== "subagent" || invocation.name === undefined) return "";+ if (invocation?.kind !== "subagent") return "";- const sourcePath = `/source/subagents/${invocation.name}`;- return `Your authored self-modification subagent source is mounted at ${sourcePath}. For changes to this subagent itself, inspect that directory directly instead of searching /source. Its agent.ts owns agent options such as model; config.ts owns policy shared by the self-modification agent, sandbox, and extension.`;+ return "This self-modification subagent is implemented by the eve package, not an authored directory under /source. Configure its model, reasoning, and policy in /source/extensions/self-modification/extension.ts; do not search for or edit a child implementation directory.";}function readTrace(@@ -120,7 +117,7 @@ export default defineDynamic({markdown: renderInstructions([role,sourceWorkspace,- readSubagentSourceGuidance(event),+ packagedSubagentGuidance(event),sourceEditing,toolAuthoring,registryWorkflow,diff --git a/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.tsnew file mode 100644index 000000000..f3bb40a80--- /dev/null+++ b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts@@ -0,0 +1,119 @@+import { shellQuote } from "#shared/shell-quote.js";+import { SANDBOX_BACKEND_PROBES, type DefaultSandboxProbes } from "#sandbox/backends/probes.js";+import {+ defaultBackend,+ defineSandbox,+ type SandboxBackend,+ type SandboxDefinition,+} from "eve/sandbox";+import { justbash } from "eve/sandbox/just-bash";+import { microsandbox } from "eve/sandbox/microsandbox";+import { vercel } from "eve/sandbox/vercel";++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";+import selfModification from "../../extension.js";++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 ?? selfModification.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/extension/tools/edit_file.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/edit_file.tssimilarity index 100%rename from packages/eve/src/self-modification/extension/tools/edit_file.tsrename to packages/eve/src/self-modification/extension/subagents/agent/tools/edit_file.tsdiff --git a/packages/eve/src/self-modification/extension/tools/publish.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.tssimilarity index 87%rename from packages/eve/src/self-modification/extension/tools/publish.tsrename to packages/eve/src/self-modification/extension/subagents/agent/tools/publish.tsindex c0900f189..58e59e464 100644--- a/packages/eve/src/self-modification/extension/tools/publish.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/publish.ts@@ -1,12 +1,12 @@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";+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",diff --git a/packages/eve/src/self-modification/extension/tools/registry_add.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.tssimilarity index 96%rename from packages/eve/src/self-modification/extension/tools/registry_add.tsrename to packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.tsindex a072fa543..8d27132b6 100644--- a/packages/eve/src/self-modification/extension/tools/registry_add.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts@@ -6,17 +6,17 @@ 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";+} 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 {assertOfficialRegistryAddress,installProductionRegistryItem,-} from "../production-registry-add.js";+} from "../../../production-registry-add.js";import {loadRegistryIndex,officialRegistryIndexUrl,@@ -233,7 +233,7 @@ export async function addLocalRegistryItem(}// Shares the catalog fetch and its five-minute cache with- // `selfmod__search_registry`, rather than reading the registry index twice.+ // `search_registry`, rather than reading the registry index twice.const entries = await loadRegistryIndex({nowMs: Date.now(),signal: options.signal,diff --git a/packages/eve/src/self-modification/extension/tools/search_models.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/search_models.tssimilarity index 100%rename from packages/eve/src/self-modification/extension/tools/search_models.tsrename to packages/eve/src/self-modification/extension/subagents/agent/tools/search_models.tsdiff --git a/packages/eve/src/self-modification/extension/tools/search_registry.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/search_registry.tssimilarity index 99%rename from packages/eve/src/self-modification/extension/tools/search_registry.tsrename to packages/eve/src/self-modification/extension/subagents/agent/tools/search_registry.tsindex d61e31c17..37a9b1493 100644--- a/packages/eve/src/self-modification/extension/tools/search_registry.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/search_registry.ts@@ -455,7 +455,7 @@ async function annotateInstalled(input: {export default defineTool({description:- "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, memory providers, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",+ "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, memory providers, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to registry_add.",inputSchema,outputSchema,async execute(input, ctx) {diff --git a/packages/eve/src/self-modification/git-workspace.ts b/packages/eve/src/self-modification/git-workspace.tsindex 58111871f..bbcd68803 100644--- a/packages/eve/src/self-modification/git-workspace.ts+++ b/packages/eve/src/self-modification/git-workspace.ts@@ -7,7 +7,7 @@ import type { GitHubRepository } from "./config.js";import { gitOutput, runGitCommand, withBrokeredGitHubCredential } from "./git.js";import { assertFullSha, assertGitRef } from "./identifiers.js";-export const SELF_MODIFICATION_CONFIG_PATH = "agent/subagents/self-modification/config.ts";+export const SELF_MODIFICATION_CONFIG_PATH = "agent/extensions/self-modification/extension.ts";export const WORKSPACE_PATH = "/workspace";export const REPOSITORY_PATH = `${WORKSPACE_PATH}/repository`;export const BASE_REF = "refs/eve-self-modification/base";diff --git a/packages/eve/src/self-modification/migration.integration.test.ts b/packages/eve/src/self-modification/migration.integration.test.tsnew file mode 100644index 000000000..91c5a0549--- /dev/null+++ b/packages/eve/src/self-modification/migration.integration.test.ts@@ -0,0 +1,146 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { join, relative } from "node:path";+import { tmpdir } from "node:os";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import type { SelfModificationSetupOperations } from "#self-modification/setup.js";+import { headlessAsker, interactiveAsker, withAnswers } from "#setup/ask.js";+import { integrationSetupEnvironment } from "#setup/integrations/shared/environment.js";+import { createSetupContexts } from "#setup/integrations/shared/ui.js";+import {+ applySelfModificationSetup,+ prepareLocalSelfModificationSetup,+} from "#setup/integrations/self-modification/setup.js";++import {+ detectLegacySelfModificationScaffold,+ removeLegacySelfModificationScaffold,+} from "./migration.js";++const roots: string[] = [];+const legacy = {+ "agent.ts":+ 'import { defineSelfModificationAgent } from "eve/self-modification/agent";\n\nimport config from "./config";\n\nexport default defineSelfModificationAgent({\n config,\n\n // To use a specific model instead of eve\'s default, add:\n // model: "provider/model",\n});\n',+ "config.ts":+ 'import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({});\n',+ "sandbox.ts":+ 'import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";\n\nimport config from "./config";\n\nexport default defineSelfModificationSandbox({ config });\n',+ "extensions/selfmod.ts":+ 'import selfModification from "eve/self-modification";\nimport config from "../config";\n\nexport default selfModification(config);\n',+};++async function scaffold(custom = false): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "eve-self-modification-migration-"));+ roots.push(root);+ for (const [path, source] of Object.entries(legacy)) {+ await mkdir(join(root, "agent/subagents/self-modification", path, ".."), { recursive: true });+ await writeFile(+ join(root, "agent/subagents/self-modification", path),+ custom && path === "config.ts" ? `${source}// custom\n` : source,+ "utf8",+ );+ }+ return root;+}++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++function setupOperations(): SelfModificationSetupOperations {+ return {+ attachConnector: vi.fn(),+ detectChannelNames: vi.fn(async () => []),+ detectGitRepository: vi.fn(async () => ({ remoteKind: "missing" as const })),+ findOrCreateConnector: vi.fn(async () => "github/example"),+ readConfig: vi.fn(async () => undefined),+ writeConfig: vi.fn(),+ };+}++describe("self-modification scaffold migration", () => {+ it("recognizes the default scaffold without evaluating consumer code", async () => {+ const root = await scaffold();+ await expect(detectLegacySelfModificationScaffold(root)).resolves.toMatchObject({+ customized: false,+ });+ });++ it("marks changed configuration and extra files as customized", async () => {+ const root = await scaffold(true);+ await writeFile(join(root, "agent/subagents/self-modification/notes.md"), "custom", "utf8");+ await expect(detectLegacySelfModificationScaffold(root)).resolves.toMatchObject({+ customized: true,+ });+ });++ it("rechecks and removes the scaffold without writing the extension", async () => {+ const root = await scaffold();+ const detected = await detectLegacySelfModificationScaffold(root);+ if (detected === undefined) throw new Error("Expected legacy scaffold");+ await removeLegacySelfModificationScaffold(root, detected);+ await expect(+ readFile(join(root, "agent/extensions/self-modification/extension.ts"), "utf8"),+ ).rejects.toMatchObject({ code: "ENOENT" });+ await expect(detectLegacySelfModificationScaffold(root)).resolves.toBeUndefined();+ });++ it("defaults to removing a legacy scaffold without reporting customizations", async () => {+ const root = await scaffold(true);+ const fake = createFakePrompter({+ single: (options) => {+ expect(options).toMatchObject({+ message: `A legacy self-modification scaffold was found at ${relative(root, join(root, "agent/subagents/self-modification"))}. This scaffold format is no longer supported. Do you want to remove it?`,+ initialValue: "yes",+ options: [+ { value: "yes", label: "Yes" },+ { value: "no", label: "No" },+ ],+ });+ return "yes";+ },+ });+ const contexts = createSetupContexts({+ appRoot: root,+ asker: interactiveAsker(fake.prompter),+ environment: integrationSetupEnvironment("unavailable", { kind: "unresolved" }),+ prompter: fake.prompter,+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),+ });++ const plan = await prepareLocalSelfModificationSetup(contexts.prepare, setupOperations());+ await applySelfModificationSetup(plan, contexts.apply, setupOperations());++ await expect(detectLegacySelfModificationScaffold(root)).resolves.toBeUndefined();+ expect(fake.prompter.log.success).toHaveBeenCalledWith(+ "Removed the retired self-modification scaffold.",+ );+ });++ it("keeps a declined legacy scaffold while continuing setup", async () => {+ const root = await scaffold();+ const contexts = createSetupContexts({+ appRoot: root,+ asker: withAnswers({ "self-modification-cleanup": false })(headlessAsker()),+ environment: integrationSetupEnvironment("unavailable", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),+ });++ const plan = await prepareLocalSelfModificationSetup(contexts.prepare, setupOperations());+ await applySelfModificationSetup(plan, contexts.apply, setupOperations());++ await expect(detectLegacySelfModificationScaffold(root)).resolves.toBeDefined();+ });++ it("rejects concurrent changes", async () => {+ const root = await scaffold();+ const detected = await detectLegacySelfModificationScaffold(root);+ if (detected === undefined) throw new Error("Expected legacy scaffold");+ await writeFile(join(root, "agent/subagents/self-modification/config.ts"), "changed", "utf8");+ await expect(removeLegacySelfModificationScaffold(root, detected)).rejects.toThrow(+ /changed while setup/,+ );+ });+});diff --git a/packages/eve/src/self-modification/migration.ts b/packages/eve/src/self-modification/migration.tsnew file mode 100644index 000000000..9a999a321--- /dev/null+++ b/packages/eve/src/self-modification/migration.ts@@ -0,0 +1,103 @@+import { readdir, readFile, rm } from "node:fs/promises";+import { join, relative } from "node:path";++export const LEGACY_SELF_MODIFICATION_ROOT = "agent/subagents/self-modification";+const LEGACY_FILES = ["agent.ts", "config.ts", "sandbox.ts", "extensions/selfmod.ts"] as const;+const LEGACY_DEFAULTS: Readonly<Record<string, readonly string[]>> = {+ "agent.ts": [+ 'import { defineSelfModificationAgent } from "eve/self-modification/agent";\n\nimport config from "./config";\n\nexport default defineSelfModificationAgent({\n config,\n\n // To use a specific model instead of eve\'s default, add:\n // model: "provider/model",\n});\n',+ ],+ "sandbox.ts": [+ 'import { defineSelfModificationSandbox } from "eve/self-modification/sandbox";\n\nimport config from "./config";\n\nexport default defineSelfModificationSandbox({ config });\n',+ ],+ "config.ts": [+ 'import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({});\n',+ 'import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({\n local: { enabled: true },\n});\n',+ ],+ "extensions/selfmod.ts": [+ 'import selfModification from "eve/self-modification";\nimport config from "../config";\n\nexport default selfModification(config);\n',+ ],+};++export interface LegacySelfModificationScaffold {+ readonly root: string;+ readonly paths: readonly string[];+ readonly customized: boolean;+ readonly signature: string;+}++/** Reads only the bounded legacy scaffold; consumer modules are never imported or executed. */+export async function detectLegacySelfModificationScaffold(+ appRoot: string,+): Promise<LegacySelfModificationScaffold | undefined> {+ const root = join(appRoot, LEGACY_SELF_MODIFICATION_ROOT);+ const paths = await listFiles(root);+ if (!paths.includes("agent.ts")) return undefined;+ const agent = await readText(join(root, "agent.ts"));+ if (agent === undefined || !agent.includes("defineSelfModificationAgent")) return undefined;++ const expected = new Set(LEGACY_FILES);+ const signature = JSON.stringify(+ await Promise.all(paths.map(async (path) => [path, await readText(join(root, path))] as const)),+ );+ const customized =+ paths.some((path) => !expected.has(path as (typeof LEGACY_FILES)[number])) ||+ (+ await Promise.all(+ Object.entries(LEGACY_DEFAULTS).map(async ([path, contents]) => {+ const actual = await readText(join(root, path));+ return actual === undefined || !contents.includes(actual);+ }),+ )+ ).some(Boolean) ||+ !agent.includes('from "eve/self-modification/agent"') ||+ (await readText(join(root, "sandbox.ts")))?.includes('from "eve/self-modification/sandbox"') !==+ true;++ return {+ root,+ paths: paths.map((path) => join(LEGACY_SELF_MODIFICATION_ROOT, path)),+ customized,+ signature,+ };+}++export async function removeLegacySelfModificationScaffold(+ appRoot: string,+ scaffold: LegacySelfModificationScaffold,+): Promise<void> {+ const current = await detectLegacySelfModificationScaffold(appRoot);+ if (+ current === undefined ||+ current.root !== scaffold.root ||+ current.customized !== scaffold.customized ||+ current.signature !== scaffold.signature+ ) {+ throw new Error(+ "The self-modification scaffold changed while setup was waiting for cleanup approval.",+ );+ }+ await rm(scaffold.root, { recursive: true, force: true });+}++async function listFiles(root: string): Promise<string[]> {+ try {+ const entries = await readdir(root, { recursive: true, withFileTypes: true });+ return entries+ .filter((entry) => entry.isFile())+ .map((entry) => relative(root, join(entry.parentPath, entry.name)).replaceAll("\\", "/"))+ .sort();+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }+}++async function readText(path: string): Promise<string | undefined> {+ try {+ return await readFile(path, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ }+}diff --git a/packages/eve/src/self-modification/package-consumption.scenario.test.ts b/packages/eve/src/self-modification/package-consumption.scenario.test.tsindex 8cdcb1b34..cff220d9e 100644--- a/packages/eve/src/self-modification/package-consumption.scenario.test.ts+++ b/packages/eve/src/self-modification/package-consumption.scenario.test.ts@@ -81,6 +81,9 @@ describe("packed package consumption", () => {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"));+ await access(+ join(packageRoot, "dist/src/self-modification/extension/subagents/agent/tools/edit_file.js"),+ );const root = await mkdtemp(join(tmpdir(), "eve-self-modification-package-"));temporaryRoots.push(root);@@ -103,6 +106,7 @@ describe("packed package consumption", () => {"@vercel/connect": "2.2.0",eve: `file:${eveTarball}`,"just-bash": "3.1.0",+ microsandbox: "0.5.5",},},null,@@ -122,7 +126,7 @@ describe("packed package consumption", () => {await writeAppFile(appRoot, "agent/instructions.md", "You are a test agent.\n");await writeAppFile(appRoot,- "agent/subagents/self-modification/config.ts",+ "agent/extensions/self-modification/extension.ts",renderSelfModificationConfig({branch: "main",channelNames: [],@@ -132,21 +136,6 @@ describe("packed package consumption", () => {vercelBackend: true,}),);- await writeAppFile(- appRoot,- "agent/subagents/self-modification/agent.ts",- '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",- '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",- 'import selfModification from "eve/self-modification";\nimport config from "../config";\n\nexport default selfModification(config);\n',- );await run("pnpm",diff --git a/packages/eve/src/self-modification/proposal.test.ts b/packages/eve/src/self-modification/proposal.test.tsindex dc9aed3d9..1af4119bc 100644--- a/packages/eve/src/self-modification/proposal.test.ts+++ b/packages/eve/src/self-modification/proposal.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { publishGitHubDraftPullRequest, selfModificationBranchName } from "./github-publisher.js";-import { assertAllowedChange, parseRawDiff } from "./proposal.js";+import { assertAllowedChange, captureSelfModificationProposal, parseRawDiff } from "./proposal.js";describe("self-modification proposal capture", () => {it("parses only complete, safe raw Git diff records", () => {@@ -31,14 +31,37 @@ describe("self-modification proposal capture", () => {".turbo/cache/state.json","node_modules/eve/index.js","agent/subagents/self-modification/agent.ts",+ "agent/extensions/self-modification/extension.ts",+ "agent/extensions/self-modification.ts","agent/extensions/selfmod.ts",]) {expect(() => assertAllowedChange({ mode: "100644", objectId: blob, path }, ".")).toThrow("protected path",);}+ expect(() =>+ assertAllowedChange(+ { mode: "100644", objectId: blob, path: "agent/extensions/editor/policy.ts" },+ ".",+ ["agent/extensions/editor"],+ ),+ ).toThrow("protected path");});+ it.each([+ ["flat", "deletion", "agent/extensions/editor.ts", "D"],+ ["directory", "deletion", "agent/extensions/editor/extension.ts", "D"],+ ["flat", "import replacement", "agent/extensions/editor.ts", "M"],+ ["directory", "import replacement", "agent/extensions/editor/extension.ts", "M"],+ ] as const)(+ "protects a non-canonical %s self-modification mount from %s",+ async (_mount, _change, path, status) => {+ await expect(captureWithBaseSelfModificationMount(path, status)).rejects.toThrow(+ `Self-modification proposal changes a protected path: ${JSON.stringify(path)}.`,+ );+ },+ );+it("derives a stable namespaced branch from trusted base and operation identifiers", () => {const branch = selfModificationBranchName("a".repeat(40), "parent-session:child-session");expect(branch).toMatch(/^eve-self-modification\/aaaaaaaaaaaa\/[a-f0-9]{24}$/u);@@ -82,6 +105,37 @@ const baseTree = "b".repeat(40);const proposedTree = "c".repeat(40);const blob = "c1b0730e0133447badcfd47fd144e254807b06e1";+function captureWithBaseSelfModificationMount(path: string, status: "D" | "M") {+ const newMode = status === "D" ? "000000" : "100644";+ const newObjectId = status === "D" ? "0".repeat(40) : blob;+ return captureSelfModificationProposal({+ sandbox: {+ run: async ({ command }) => {+ if (command.includes(" add -A")) return result("");+ if (command.includes("write-tree")) return result(proposedTree);+ if (command.includes("^{tree}")) return result(baseTree);+ if (command.includes("diff-tree")) {+ return result(`:100644 ${newMode} ${base} ${newObjectId} ${status}\0${path}\0`);+ }+ if (command.includes(" grep -l ")) {+ if (command.includes(`'${base}'`)) return result(`${base}:${path}\0`);+ if (command.includes(`'${proposedTree}'`)) {+ return { exitCode: 1, stderr: "", stdout: "" };+ }+ }+ throw new Error(`Unexpected Git command: ${command}`);+ },+ },+ workspace: {+ baseSha: base,+ directory: ".",+ repository: { owner: "acme", repo: "agent" },+ repositoryPath: "/workspace/repository",+ targetBranch: "main",+ },+ });+}+function publish(fetch: typeof globalThis.fetch) {return publishGitHubDraftPullRequest({credentialProvider: { resolve: async () => "token" },@@ -95,6 +149,7 @@ function publish(fetch: typeof globalThis.fetch) {if (command.includes("^{tree}")) return result(baseTree);if (command.includes("diff-tree"))return result(`:100644 100644 ${base} ${blob} M\0agent/instructions.md\0`);+ if (command.includes(" grep -l ")) return { exitCode: 1, stderr: "", stdout: "" };if (command.includes("cat-file -s")) return result("1");if (command.includes("cat-file blob")) return result("eA==");throw new Error(`Unexpected Git command: ${command}`);diff --git a/packages/eve/src/self-modification/proposal.ts b/packages/eve/src/self-modification/proposal.tsindex 9c2be222a..7806fab40 100644--- a/packages/eve/src/self-modification/proposal.ts+++ b/packages/eve/src/self-modification/proposal.ts@@ -57,12 +57,29 @@ export async function captureSelfModificationProposal(input: {);}+ const baseProtectedMounts = await selfModificationMountPaths({+ directory: input.workspace.directory,+ repositoryPath: input.workspace.repositoryPath,+ sandbox: input.sandbox,+ tree: input.workspace.baseSha,+ });+ const proposedProtectedMounts = await selfModificationMountPaths({+ directory: input.workspace.directory,+ repositoryPath: input.workspace.repositoryPath,+ sandbox: input.sandbox,+ tree: proposedTreeSha,+ });+ const protectedMounts = [...new Set([...baseProtectedMounts, ...proposedProtectedMounts])];const changes: ProposalChange[] = [];let changedBytes = 0;for (const record of records) {const mode = record.status === "D" ? null : proposalMode(record.newMode, record.path);const objectId = record.status === "D" ? null : record.newObjectId;- assertAllowedChange({ mode, objectId, path: record.path }, input.workspace.directory);+ assertAllowedChange(+ { mode, objectId, path: record.path },+ input.workspace.directory,+ protectedMounts,+ );const bytes =objectId === null? 0@@ -143,6 +160,7 @@ export function parseRawDiff(raw: string): readonly RawChange[] {export function assertAllowedChange(change: Pick<ProposalChange, "mode" | "objectId" | "path">,directory: string,+ protectedMounts: readonly string[] = [],): void {const path = change.path;const appRoot = directory === "." ? "" : `${directory}/`;@@ -170,6 +188,9 @@ export function assertAllowedChange() ||path.startsWith(".github/workflows/") ||path.startsWith(`${agentRoot}subagents/self-modification/`) ||+ path.startsWith(`${agentRoot}extensions/self-modification/`) ||+ path === `${appRoot}agent/extensions/self-modification.ts` ||+ protectedMounts.some((mount) => path === mount || path.startsWith(`${mount}/`)) ||path === `${appRoot}agent/extensions/selfmod.ts` ||path === `${appRoot}agent/self-modification.config.ts`) {@@ -179,6 +200,41 @@ export function assertAllowedChange(}}+async function selfModificationMountPaths(input: {+ readonly directory: string;+ readonly repositoryPath: string;+ readonly sandbox: ProposalSandbox;+ readonly tree: string;+}): Promise<readonly string[]> {+ const appRoot = input.directory === "." ? "" : `${input.directory}/`;+ const extensionsRoot = `${appRoot}agent/extensions`;+ const matches = await gitOutput(+ input.sandbox,+ `git -C ${quote(input.repositoryPath)} grep -l -z -F -- "eve/self-modification" ${quote(input.tree)} -- ${quote(extensionsRoot)}`,+ false,+ ).catch((error: unknown) => {+ if (error instanceof Error && error.message.includes("failed with exit 1:")) return "";+ throw error;+ });+ return [+ ...new Set(+ matches+ .split("\0")+ .filter(Boolean)+ .flatMap((match) => {+ const path = match.slice(match.indexOf(":") + 1);+ if (!path.startsWith(`${extensionsRoot}/`)) return [];+ const relativePath = path.slice(extensionsRoot.length + 1);+ if (relativePath.endsWith("/extension.ts")) {+ return [`${extensionsRoot}/${relativePath.slice(0, -"/extension.ts".length)}`];+ }+ if (!relativePath.includes("/")) return [path];+ return [`${extensionsRoot}/${relativePath.split("/")[0]}`];+ }),+ ),+ ];+}+function isSafePath(path: string): boolean {return (path.length > 0 &&diff --git a/packages/eve/src/self-modification/publish-tool.test.ts b/packages/eve/src/self-modification/publish-tool.test.tsindex 0416987e6..14f700304 100644--- a/packages/eve/src/self-modification/publish-tool.test.ts+++ b/packages/eve/src/self-modification/publish-tool.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { publicationOperationId } from "./extension/tools/publish.js";+import { publicationOperationId } from "./extension/subagents/agent/tools/publish.js";describe("production publish tool", () => {it("derives operation identity from trusted parent lineage", () => {diff --git a/packages/eve/src/self-modification/registry-add.test.ts b/packages/eve/src/self-modification/registry-add.test.tsindex d0c79ef8f..ca4ab6b94 100644--- a/packages/eve/src/self-modification/registry-add.test.ts+++ b/packages/eve/src/self-modification/registry-add.test.ts@@ -22,8 +22,8 @@ import {handoffMessage,resolveRegistryAddTool,unsetEnvVars,-} from "./extension/tools/registry_add.js";-import { clearRegistryIndexCache } from "./extension/tools/search_registry.js";+} from "./extension/subagents/agent/tools/registry_add.js";+import { clearRegistryIndexCache } from "./extension/subagents/agent/tools/search_registry.js";const APP_ROOT = "/workspace/agent";const originalEveDev = process.env.EVE_DEV;diff --git a/packages/eve/src/self-modification/sandbox.test.ts b/packages/eve/src/self-modification/sandbox.test.tsindex 3c446de9f..fe0364468 100644--- a/packages/eve/src/self-modification/sandbox.test.ts+++ b/packages/eve/src/self-modification/sandbox.test.ts@@ -1,108 +1,28 @@-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 { describe, expect, it, vi } from "vitest";-import type { SelfModificationConfig } from "./config.js";import { defineSelfModificationSandbox, selectDeployedSelfModificationBackend } from "./sandbox.js";-const providerConfig: SelfModificationConfig = {- deployed: {- credentials: { resolve: async () => "github-token" },- source: { git: { directory: ".", repository: "github.com/acme/agent" } },- target: { branch: "main" },- authorize: () => true,- },-};--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");+describe("retired self-modification sandbox scaffold", () => {+ it("returns an inert sandbox definition", () => {+ const definition = defineSelfModificationSandbox({+ config: { deployed: { authorize: vi.fn() } },+ });+ expect(definition.backend).toBeUndefined();+ expect(definition.onSession).toBeUndefined();});- 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("does not select or provision a backend", () => {+ expect(() => selectDeployedSelfModificationBackend(undefined, {})).toThrow(+ "Deployed self-modification is disabled in the retired scaffold.",);});- it("reports the same backend guidance when automatic selection cannot find one", () => {+ it("preserves explicitly typed options for compatibility", () => {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: providerConfig });- 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");- const definition = defineSelfModificationSandbox({ config: providerConfig });- 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,+ defineSelfModificationSandbox({+ backend: { name: "just-bash" } as never,+ config: {},}),- ).rejects.toBe(failure);- expect(setNetworkPolicy).toHaveBeenCalledWith("allow-all");+ ).not.toThrow();});});diff --git a/packages/eve/src/self-modification/sandbox.ts b/packages/eve/src/self-modification/sandbox.tsindex ad7614ab2..0f257c3c7 100644--- a/packages/eve/src/self-modification/sandbox.ts+++ b/packages/eve/src/self-modification/sandbox.ts@@ -1,118 +1,30 @@-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";+/** Options retained for source compatibility with the retired scaffold. */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;+ readonly config?: unknown;}-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.- */+/** @deprecated The scaffolded sandbox is inert; use the packaged extension. */export function selectDeployedSelfModificationBackend(configured: SandboxBackend | undefined,- probes: SelfModificationSandboxProbes,+ _probes: unknown,): 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();+ if (configured !== undefined) return configured;+ throw new Error("Deployed self-modification is disabled in the retired scaffold.");}-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 function defineSelfModificationSandbox(+ _options: SelfModificationSandboxOptions = {},+): SandboxDefinition {+ return defineSandbox({});}+/** @deprecated The scaffolded sandbox is inert; use the packaged extension. */export default defineSelfModificationSandbox();diff --git a/packages/eve/src/self-modification/search-models.test.ts b/packages/eve/src/self-modification/search-models.test.tsindex 4dd281a95..952e0c65f 100644--- a/packages/eve/src/self-modification/search-models.test.ts+++ b/packages/eve/src/self-modification/search-models.test.ts@@ -2,7 +2,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { parseGatewayModelCatalog } from "#shared/gateway-model-catalog.js";-import searchModels, { searchGatewayModels } from "./extension/tools/search_models.js";+import searchModels, {+ searchGatewayModels,+} from "./extension/subagents/agent/tools/search_models.js";const CATALOG = {data: [diff --git a/packages/eve/src/self-modification/search-registry.test.ts b/packages/eve/src/self-modification/search-registry.test.tsindex a8c2d8872..4a44ed4ad 100644--- a/packages/eve/src/self-modification/search-registry.test.ts+++ b/packages/eve/src/self-modification/search-registry.test.ts@@ -7,7 +7,7 @@ import searchRegistry, {selectIntegrationPage,selectIntegrations,type CatalogEntry,-} from "./extension/tools/search_registry.js";+} from "./extension/subagents/agent/tools/search_registry.js";const INDEX = {items: [diff --git a/packages/eve/src/self-modification/setup.test.ts b/packages/eve/src/self-modification/setup.test.tsindex 85e4af21d..0263dad92 100644--- a/packages/eve/src/self-modification/setup.test.ts+++ b/packages/eve/src/self-modification/setup.test.ts@@ -22,7 +22,9 @@ function evaluateGeneratedConfig(source: string, getToken = vi.fn()) {source.replace('import { getToken } from "@vercel/connect";', "").replace('import { defineSelfModificationConfig } from "eve/self-modification/config";', "")- .replace("export default ", ""),+ .replace('import selfModification from "eve/self-modification";', "")+ .replace("export default ", "")+ .replace("selfModification(", "defineSelfModificationConfig("),{defineSelfModificationConfig,getToken,@@ -33,7 +35,10 @@ function evaluateGeneratedConfig(source: string, getToken = vi.fn()) {describe("self-modification setup", () => {it("recognizes default local configurations", () => {- expect(renderSelfModificationConfig()).toContain("local: { enabled: true }");+ expect(renderSelfModificationConfig()).toContain(+ 'import selfModification from "eve/self-modification";',+ );+ expect(renderSelfModificationConfig()).toContain('// model: "provider/model"');expect(classifySelfModificationConfig(renderSelfModificationConfig())).toBe("local");expect(classifySelfModificationConfig(@@ -55,6 +60,7 @@ describe("self-modification setup", () => {expect(source).toContain('directory: "apps/support"');expect(source).toContain('target: { branch: "release/production" }');expect(source).toContain('import { getToken } from "@vercel/connect"');+ expect(source).toContain('import selfModification from "eve/self-modification"');expect(source).toContain('return await getToken("github/selfmod-acme-agents"');expect(source).toContain("async resolve({ capability, repository })");expect(source).toContain('case "http"');diff --git a/packages/eve/src/self-modification/setup.ts b/packages/eve/src/self-modification/setup.tsindex cf2b0e78f..ac24663c6 100644--- a/packages/eve/src/self-modification/setup.ts+++ b/packages/eve/src/self-modification/setup.ts@@ -1,6 +1,6 @@import { execFile } from "node:child_process";import { createHash } from "node:crypto";-import { readFile, writeFile } from "node:fs/promises";+import { mkdir, readFile, writeFile } from "node:fs/promises";import { join, relative } from "node:path";import { promisify } from "node:util";@@ -19,6 +19,7 @@ const runFile = promisify(execFile);const GENERATED_MARKER = "// eve-self-modification: generated-v1";const LEGACY_LOCAL_CONFIG ='import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({});\n';+const DEFAULT_EXTENSION = `import selfModification from "eve/self-modification";\n\nexport default selfModification({\n // model: "provider/model",\n // reasoning: "high",\n});\n`;export interface SelfModificationSetupValues {readonly branch: string;@@ -59,9 +60,8 @@ export function connectorName(owner: string, repo: string): string {}export function renderSelfModificationConfig(values?: SelfModificationSetupValues): string {- if (values === undefined) {- return `import { defineSelfModificationConfig } from "eve/self-modification/config";\n\nexport default defineSelfModificationConfig({\n local: { enabled: true },\n});\n`;- }+ if (values === undefined) return DEFAULT_EXTENSION;+const channelNames = [...new Set(values.channelNames)].filter((name) => name !== "eve").sort();const channelCases = (values.vercelBackend ? channelNames : []).map(@@ -87,9 +87,9 @@ export function renderSelfModificationConfig(values?: SelfModificationSetupValueconst switchCases = `${httpCase}${channelCases}`;const credentialErrorMessage = `Self-modification could not obtain a GitHub credential from Vercel Connect for ${values.connector}. Install and attach the configured GitHub connector to this Vercel project, install the managed GitHub App for the configured repository, then retry.`;const body = `import { getToken } from "@vercel/connect";-import { defineSelfModificationConfig } from "eve/self-modification/config";+import selfModification from "eve/self-modification";-export default defineSelfModificationConfig({+export default selfModification({deployed: {source: {git: {@@ -200,7 +200,10 @@ export function defaultSelfModificationSetupOperations(throw error;}},- writeConfig: (source) => writeFile(configPath, source, "utf8"),+ async writeConfig(source) {+ await mkdir(join(configPath, ".."), { recursive: true });+ await writeFile(configPath, source, "utf8");+ },async findOrCreateConnector(name, project) {const connectors = await listGitHubConnectors(projectRoot, project, deps.captureVercel);const expected = `github/${name}`;diff --git a/packages/eve/src/setup/integrations/self-modification/setup.test.ts b/packages/eve/src/setup/integrations/self-modification/setup.test.tsindex 391187ab0..7573047dd 100644--- a/packages/eve/src/setup/integrations/self-modification/setup.test.ts+++ b/packages/eve/src/setup/integrations/self-modification/setup.test.ts@@ -38,13 +38,13 @@ function operations(config?: string): SelfModificationSetupOperations & {}function applyDependencies(): SelfModificationApplyDependencies & {- ensureConnectionDependencies: ReturnType<typeof vi.fn>;+ ensurePackageDependencies: ReturnType<typeof vi.fn>;installScaffoldDependencies: ReturnType<typeof vi.fn>;} {return {- ensureConnectionDependencies: vi.fn(async () => [+ ensurePackageDependencies: vi.fn(async () => [{- dependencies: ["@vercel/connect"],+ dependencies: ["@vercel/connect", "microsandbox"],devDependencies: [],path: "/project/package.json",scripts: [],@@ -76,14 +76,17 @@ function contexts(describe("self-modification integration setup", () => {it("keeps the default setup local without mutation", async () => {const effects = operations();+ const deps = applyDependencies();const ctx = contexts({});const plan = await prepareLocalSelfModificationSetup(ctx.prepare, effects);- await expect(applySelfModificationSetup(plan, ctx.apply, effects)).resolves.toEqual({+ await expect(applySelfModificationSetup(plan, ctx.apply, effects, deps)).resolves.toEqual({facts: [],});expect(effects.findOrCreateConnector).not.toHaveBeenCalled();expect(effects.writeConfig).not.toHaveBeenCalled();+ expect(deps.ensurePackageDependencies).not.toHaveBeenCalled();+ expect(deps.installScaffoldDependencies).not.toHaveBeenCalled();});it("offers deployed and local modes before collecting deployed settings", async () => {@@ -146,7 +149,10 @@ describe("self-modification integration setup", () => {orgId: "team",projectId: "project",});- expect(deps.ensureConnectionDependencies).toHaveBeenCalledWith({ projectRoot: "/project" });+ expect(deps.ensurePackageDependencies).toHaveBeenCalledWith({+ dependencies: { "@vercel/connect": "2.2.0", microsandbox: "0.5.5" },+ projectRoot: "/project",+ });expect(deps.installScaffoldDependencies).toHaveBeenCalledWith(expect.objectContaining({ changed: true, projectPath: "/project" }),);diff --git a/packages/eve/src/setup/integrations/self-modification/setup.ts b/packages/eve/src/setup/integrations/self-modification/setup.tsindex eff87972c..5770968a0 100644--- a/packages/eve/src/setup/integrations/self-modification/setup.ts+++ b/packages/eve/src/setup/integrations/self-modification/setup.ts@@ -1,3 +1,5 @@+import { relative } from "node:path";+import { confirm, select, text } from "#setup/ask.js";import {classifySelfModificationConfig,@@ -11,8 +13,17 @@ import {type SelfModificationSetupValues,} from "#self-modification/setup.js";import { SELF_MODIFICATION_CONFIG_PATH } from "#self-modification/git-workspace.js";+import {+ detectLegacySelfModificationScaffold,+ removeLegacySelfModificationScaffold,+ type LegacySelfModificationScaffold,+} from "#self-modification/migration.js";import type { VercelProjectReference } from "#setup/project-resolution.js";-import { ensureConnectionDependencies } from "#setup/scaffold/index.js";+import { ensurePackageDependencies } from "#setup/scaffold/index.js";+import {+ DEFAULT_CONNECT_PACKAGE_VERSION,+ DEFAULT_MICROSANDBOX_PACKAGE_VERSION,+} from "#setup/scaffold/version-tokens.js";import { describeIntegrationSetupEnvironment } from "../shared/environment.js";import { installScaffoldDependencies } from "../shared/scaffold.js";@@ -23,16 +34,21 @@ import {} from "../types.js";export interface SelfModificationApplyDependencies {- ensureConnectionDependencies: typeof ensureConnectionDependencies;+ ensurePackageDependencies: typeof ensurePackageDependencies;installScaffoldDependencies: typeof installScaffoldDependencies;}const defaultApplyDependencies: SelfModificationApplyDependencies = {- ensureConnectionDependencies,+ ensurePackageDependencies,installScaffoldDependencies,};-type SelfModificationSetupPlan =+const SELF_MODIFICATION_PRODUCTION_DEPENDENCIES = {+ "@vercel/connect": DEFAULT_CONNECT_PACKAGE_VERSION,+ microsandbox: DEFAULT_MICROSANDBOX_PACKAGE_VERSION,+};++type SelfModificationSetupPlan = (| { readonly kind: "authored" }| { readonly kind: "local" }| {@@ -40,12 +56,37 @@ type SelfModificationSetupPlan =readonly connectorName: string;readonly project: VercelProjectReference;readonly values: SelfModificationSetupValues;- };+ }+) & { readonly legacyScaffold?: LegacySelfModificationScaffold };function validationResult(error: string | undefined): string | null {return error ?? null;}+async function prepareLegacyScaffoldCleanup(+ context: SetupPrepareContext,+): Promise<LegacySelfModificationScaffold | undefined> {+ const scaffold = await detectLegacySelfModificationScaffold(context.appRoot);+ if (scaffold === undefined) return undefined;++ const approved = await context.asker.ask(+ confirm({+ key: "self-modification-cleanup",+ message: `A legacy self-modification scaffold was found at ${relative(context.appRoot, scaffold.root)}. This scaffold format is no longer supported. Do you want to remove it?`,+ recommended: true,+ required: true,+ }),+ );+ return approved ? scaffold : undefined;+}++function withLegacyScaffold(+ plan: SelfModificationSetupPlan,+ legacyScaffold: LegacySelfModificationScaffold | undefined,+): SelfModificationSetupPlan {+ return legacyScaffold === undefined ? plan : { ...plan, legacyScaffold };+}+export async function prepareSelfModificationSetup(context: SetupPrepareContext,operations: SelfModificationSetupOperations = defaultSelfModificationSetupOperations(@@ -54,6 +95,7 @@ export async function prepareSelfModificationSetup(context.projectRoot,),): Promise<SelfModificationSetupPlan> {+ const legacyScaffold = await prepareLegacyScaffoldCleanup(context);const existing = await operations.readConfig();if (classifySelfModificationConfig(existing) === "authored") {context.presenter.note(@@ -61,7 +103,7 @@ export async function prepareSelfModificationSetup("Manual update required",{ tone: "warning" },);- return { kind: "authored" };+ return withLegacyScaffold({ kind: "authored" }, legacyScaffold);}const mode = await context.asker.ask(@@ -86,7 +128,7 @@ export async function prepareSelfModificationSetup(required: true,}),);- if (mode === "local") return { kind: "local" };+ if (mode === "local") return withLegacyScaffold({ kind: "local" }, legacyScaffold);const [project, detected, channelNames] = await Promise.all([context.resolveVercelProject("self-modification"),@@ -154,7 +196,10 @@ export async function prepareSelfModificationSetup(required: true,}),);- return confirmed ? { kind: "deployed", connectorName: name, project, values } : { kind: "local" };+ return withLegacyScaffold(+ confirmed ? { kind: "deployed", connectorName: name, project, values } : { kind: "local" },+ legacyScaffold,+ );}export async function applySelfModificationSetup(@@ -167,6 +212,10 @@ export async function applySelfModificationSetup(),deps: SelfModificationApplyDependencies = defaultApplyDependencies,) {+ if (plan.legacyScaffold !== undefined) {+ await removeLegacySelfModificationScaffold(context.appRoot, plan.legacyScaffold);+ context.presenter.log.success("Removed the retired self-modification scaffold.");+ }if (plan.kind === "authored") {return {facts: [{ label: "Self-modification", value: "manual configuration update required" }],@@ -178,7 +227,8 @@ export async function applySelfModificationSetup(const connector = await operations.findOrCreateConnector(plan.connectorName, plan.project);await operations.attachConnector(connector, plan.project);- const packageJsonUpdated = await deps.ensureConnectionDependencies({+ const packageJsonUpdated = await deps.ensurePackageDependencies({+ dependencies: SELF_MODIFICATION_PRODUCTION_DEPENDENCIES,projectRoot: context.appRoot,});await deps.installScaffoldDependencies({@@ -192,8 +242,8 @@ export async function applySelfModificationSetup(context.presenter.nextSteps(["Install the managed GitHub App for the configured repository, then deploy or redeploy.",plan.values.vercelBackend- ? "After deployment, try self-modification by running `eve dev <deployment-url>` from this linked project. The generated policy admits its Vercel OIDC identity over HTTP; configured channels remain denied until you update `agent/subagents/self-modification/config.ts`."- : "Before deployment, configure `deployed.authorize` in `agent/subagents/self-modification/config.ts` to admit a trusted principal for your deployment's channel. After deployment, use that channel to try self-modification.",+ ? "After deployment, try self-modification by running `eve dev <deployment-url>` from this linked project. The generated policy admits its Vercel OIDC identity over HTTP; configured channels remain denied until you update `agent/extensions/self-modification/extension.ts`."+ : "Before deployment, configure `deployed.authorize` in `agent/extensions/self-modification/extension.ts` to admit a trusted principal for your deployment's channel. After deployment, use that channel to try self-modification.",]);return {deploymentRequired: true as const,@@ -214,6 +264,7 @@ export async function prepareLocalSelfModificationSetup(context.projectRoot,),): Promise<SelfModificationSetupPlan> {+ const legacyScaffold = await prepareLegacyScaffoldCleanup(context);const existing = await operations.readConfig();if (classifySelfModificationConfig(existing) === "authored") {context.presenter.note(@@ -221,9 +272,9 @@ export async function prepareLocalSelfModificationSetup("Manual update required",{ tone: "warning" },);- return { kind: "authored" };+ return withLegacyScaffold({ kind: "authored" }, legacyScaffold);}- return { kind: "local" };+ return withLegacyScaffold({ kind: "local" }, legacyScaffold);}function describeEnvironment(environment: SetupPrepareContext["environment"]): string {diff --git a/packages/eve/src/setup/scaffold/index.ts b/packages/eve/src/setup/scaffold/index.tsindex 1837f7957..de391134b 100644--- a/packages/eve/src/setup/scaffold/index.ts+++ b/packages/eve/src/setup/scaffold/index.ts@@ -61,6 +61,12 @@ export {type OpenApiEndpoint,} from "./connections/catalog.js";+export {+ ensurePackageDependencies,+ type EnsurePackageDependenciesOptions,+ type PackageDependencyMutation,+} from "./update/dependencies.js";+export { WriteFileExistsError } from "./files.js";export { HumanActionRequiredError, type HumanAction } from "../human-action.js";diff --git a/packages/eve/src/setup/scaffold/update/dependencies.integration.test.ts b/packages/eve/src/setup/scaffold/update/dependencies.integration.test.tsnew file mode 100644index 000000000..94b0039f1--- /dev/null+++ b/packages/eve/src/setup/scaffold/update/dependencies.integration.test.ts@@ -0,0 +1,56 @@+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { ensurePackageDependencies } from "./dependencies.js";++const roots: string[] = [];++async function project(packageJson: unknown): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "eve-dependencies-"));+ roots.push(root);+ await writeFile(join(root, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`, "utf8");+ return root;+}++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));+});++describe("ensurePackageDependencies", () => {+ it("adds only missing or outdated runtime dependencies", async () => {+ const root = await project({+ dependencies: { "@vercel/connect": "2.2.0", existing: "1.0.0" },+ });++ await expect(+ ensurePackageDependencies({+ dependencies: { "@vercel/connect": "2.2.0", microsandbox: "0.5.5" },+ projectRoot: root,+ }),+ ).resolves.toEqual([+ {+ dependencies: ["microsandbox"],+ devDependencies: [],+ path: join(root, "package.json"),+ scripts: [],+ },+ ]);+ await expect(readFile(join(root, "package.json"), "utf8")).resolves.toContain(+ '"microsandbox": "0.5.5"',+ );+ });++ it("does not report a mutation when dependencies already match", async () => {+ const root = await project({ dependencies: { microsandbox: "0.5.5" } });++ await expect(+ ensurePackageDependencies({+ dependencies: { microsandbox: "0.5.5" },+ projectRoot: root,+ }),+ ).resolves.toEqual([]);+ });+});diff --git a/packages/eve/src/setup/scaffold/update/dependencies.ts b/packages/eve/src/setup/scaffold/update/dependencies.tsnew file mode 100644index 000000000..f8fe820d7--- /dev/null+++ b/packages/eve/src/setup/scaffold/update/dependencies.ts@@ -0,0 +1,51 @@+import { readFile } from "node:fs/promises";+import { join } from "node:path";++import { patchPackageJson } from "./package-json.js";++export interface EnsurePackageDependenciesOptions {+ readonly dependencies: Readonly<Record<string, string>>;+ readonly projectRoot: string;+}++export interface PackageDependencyMutation {+ readonly dependencies: readonly string[];+ readonly devDependencies: readonly string[];+ readonly path: string;+ readonly scripts: readonly string[];+}++/** Adds missing or outdated runtime dependencies to an existing package.json. */+export async function ensurePackageDependencies(+ options: EnsurePackageDependenciesOptions,+): Promise<readonly PackageDependencyMutation[]> {+ const packageJsonPath = join(options.projectRoot, "package.json");+ let parsed: unknown;+ try {+ parsed = JSON.parse(await readFile(packageJsonPath, "utf8"));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }++ const current = isRecord(parsed) && isRecord(parsed.dependencies) ? parsed.dependencies : {};+ const missing = Object.fromEntries(+ Object.entries(options.dependencies).filter(([name, version]) => current[name] !== version),+ );+ const names = Object.keys(missing);+ if (names.length === 0) return [];++ await patchPackageJson(packageJsonPath, { dependencies: missing });+ return [+ {+ dependencies: names,+ devDependencies: [],+ path: packageJsonPath,+ scripts: [],+ },+ ];+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/packages/eve/src/setup/scaffold/version-tokens.test.ts b/packages/eve/src/setup/scaffold/version-tokens.test.tsindex 3f563bbe7..2f2b981a7 100644--- a/packages/eve/src/setup/scaffold/version-tokens.test.ts+++ b/packages/eve/src/setup/scaffold/version-tokens.test.ts@@ -3,7 +3,11 @@ import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { DEFAULT_CONNECT_PACKAGE_VERSION, resolveVersionToken } from "./version-tokens.js";+import {+ DEFAULT_CONNECT_PACKAGE_VERSION,+ DEFAULT_MICROSANDBOX_PACKAGE_VERSION,+ resolveVersionToken,+} from "./version-tokens.js";// These tests always execute from the dev tree (vitest runs over src), so the// fallback's sources — eve's package.json and the workspace catalog — are the@@ -16,9 +20,11 @@ describe("resolveVersionToken", () => {expect(resolveVersionToken("evePackage.version", "1.0.0-beta.3")).toBe("1.0.0-beta.3");});- it("uses a concrete default Connect version", () => {+ it("uses concrete production integration dependency versions", () => {expect(DEFAULT_CONNECT_PACKAGE_VERSION).toBe("2.2.0");expect(DEFAULT_CONNECT_PACKAGE_VERSION).not.toMatch(/^__/);+ expect(DEFAULT_MICROSANDBOX_PACKAGE_VERSION).toBe("0.5.5");+ expect(DEFAULT_MICROSANDBOX_PACKAGE_VERSION).not.toMatch(/^__/);});it("resolves eve runtime and dependency version tokens from eve's own package.json", () => {diff --git a/packages/eve/src/setup/scaffold/version-tokens.ts b/packages/eve/src/setup/scaffold/version-tokens.tsindex 0c9c4bb2e..f2b9fd703 100644--- a/packages/eve/src/setup/scaffold/version-tokens.ts+++ b/packages/eve/src/setup/scaffold/version-tokens.ts@@ -29,6 +29,7 @@ function bareToken(name: string): string {const NODE_ENGINE_TOKEN = bareToken("NODE_ENGINE");export const DEFAULT_CONNECT_PACKAGE_VERSION = "2.2.0";+export const DEFAULT_MICROSANDBOX_PACKAGE_VERSION = "0.5.5";const TOKEN_SOURCES: Readonly<Record<string, TokenSource>> = {[versionToken("EVE_PACKAGE")]: { kind: "eve-version" },