The Open Framework for Building Agents
fix(eve): scope local self-modification to dev host facilities (#3590)
prhaaceb298cc31a
diff --git a/.changeset/guard-local-self-modification.md b/.changeset/guard-local-self-modification.mdnew file mode 100644index 000000000..e3b0b7c27--- /dev/null+++ b/.changeset/guard-local-self-modification.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Local self-modification now depends on `eve dev` host facilities instead of request provenance.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 2dfd4273e..9c35ee0da 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -309,7 +309,7 @@ The info route belongs to the selected `channels/eve.ts` source and uses its rescurl http://127.0.0.1:2000/eve/v1/info```-With the default auth chain (`[vercelOidc(), localDev(), placeholderAuth()]`), a Vercel OIDC bearer takes precedence, an `eve dev` or `vercel dev` server authenticates local requests, and everything else is rejected. A deployed Vercel target requires a valid OIDC bearer, with a same-project bypass for in-deployment callers. See [auth & route protection](../guides/auth-and-route-protection).+With the default auth chain (`[vercelOidc(), localDev(), placeholderAuth()]`), a Vercel OIDC bearer takes precedence, `localDev()` accepts requests to an `eve dev` or `vercel dev` server, and everything else is rejected. A deployed Vercel target requires a valid OIDC bearer, with a same-project bypass for in-deployment callers. See [auth & route protection](../guides/auth-and-route-protection).## Dispatch orderdiff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex efb30cbe4..bfc5b8d66 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -154,29 +154,6 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to toExported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). The `exports` field in `packages/eve/package.json` lists every public entrypoint.-## Local development capability--Use `getLocalDevCapability()` when an authored tool needs to modify the local application's source tree during an interactive development turn:--```ts-import { getLocalDevCapability } from "eve/local-dev";--const localDev = getLocalDevCapability();-if (localDev === undefined) {- throw new Error("This tool is available only from a local eve dev client.");-}--await localDev.withSuspendedSource(async () => {- // Write under localDev.appRoot here.-});-```--The function returns `LocalDevCapability | undefined`. It returns a capability only while authored code handles a request from a client on the same machine as the `eve dev` server. Deployed runtimes and clients attached over the network receive `undefined`, even when the target is another development server. A local TUI that attaches to an existing headless server receives the capability because availability follows each request rather than the process that started the server.--`appRoot` is the authored application directory containing `package.json` and `agent/`, not the temporary runtime snapshot. `interactiveClient` is `true` when the requesting local client is the dev TUI; check it before starting a flow that requires terminal interaction.--Run source mutations inside `withSuspendedSource()`. It acquires a unique watcher lease, waits for your asynchronous callback to settle, and then releases the lease. Concurrent or nested calls cannot resume each other early, and releasing the final lease rebuilds the runtime artifacts. The callback's return value is returned, and its error is rethrown after release. If suspension cannot be acquired, the callback does not run. If the host cannot confirm release after a retry, the method throws an actionable error; restart `eve dev` before making more source changes.-## Direct provider models`openai(model?)` from `eve/models/openai` and `anthropic(model?)` from `eve/models/anthropic` return eve-owned model instances using the vendored providers. They accept only an optional model ID. Defaults are `gpt-5.6-luna-fast` and `claude-sonnet-5`, respectively.diff --git a/packages/eve/src/context/container.ts b/packages/eve/src/context/container.tsindex b2d509636..bf956b202 100644--- a/packages/eve/src/context/container.ts+++ b/packages/eve/src/context/container.ts@@ -16,7 +16,7 @@ const EVE_CONTEXT_STORAGE_KEY = Symbol.for("eve.context-storage");* the serialization layer.*/export interface AlsContext extends ContextAccessor {- /** Verified local development provenance, inherited across durable execution contexts. */+ /** Verified originating-client metadata, inherited only for the dev-TUI hint. */readonly localDevRequest?: LocalDevRequestProvenance;/** Removes a durable or step-local value from the context. */delete<T>(key: ContextKey<T>): boolean;@@ -37,7 +37,10 @@ export class ContextContainer implements AlsContext {private readonly _virtualValues = new Map<string, unknown>();constructor(input?: { readonly localDevRequest?: LocalDevRequestProvenance }) {- const localDevRequest = input?.localDevRequest ?? contextStorage.getStore()?.localDevRequest;+ const localDevRequest =+ input !== undefined && Object.hasOwn(input, "localDevRequest")+ ? input.localDevRequest+ : contextStorage.getStore()?.localDevRequest;if (localDevRequest !== undefined) {this._durableValues.set(LocalDevRequestKey.name, localDevRequest);}diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex ee753d2f4..17da3de7a 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -86,7 +86,10 @@ export const ContinuationHookTokensKey = new ContextKey<readonly string[]>("eve.continuationHookTokens",);export const ChannelRequestIdKey = new ContextKey<string>("eve.channelRequestId");-/** Parent-verified local client provenance, valid only for the current dev host secret. */+/**+ * Dev-host-verified originating-client metadata, valid only for the current+ * host secret. It carries the inherited dev-TUI hint, not editing authority.+ */export interface LocalDevRequestProvenance {readonly address: string;readonly interactiveClient: boolean;diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.tsindex e28c8b4a5..e9881ae70 100644--- a/packages/eve/src/execution/coordination-dispatch-shared.ts+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts@@ -86,6 +86,7 @@ export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {/** Number of local children sharing the parent's remaining token quota. */readonly fanoutSize: number;readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];+ /** Inherited originating-client metadata for the dev-TUI hint. */readonly localDevRequest?: LocalDevRequestProvenance;/** Lineage of the session running this dispatch, when it is itself a delegated child. */readonly parentSession: SessionParent | undefined;diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.tsindex 0930d7447..c8a2df430 100644--- a/packages/eve/src/execution/tools/subagent/start.ts+++ b/packages/eve/src/execution/tools/subagent/start.ts@@ -43,6 +43,7 @@ export async function startSubagent(input: {readonly currentSession: RuntimeSession;readonly fanoutSize: number;readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];+ /** Inherited originating-client metadata for the dev-TUI hint. */readonly localDevRequest?: LocalDevRequestProvenance;readonly parentContinuationToken: string | undefined;readonly activityObserver?: ActivityObserverConfig & {diff --git a/packages/eve/src/public/local-dev.ts b/packages/eve/src/public/local-dev.tsindex 9d17a7c62..bf2e897bc 100644--- a/packages/eve/src/public/local-dev.ts+++ b/packages/eve/src/public/local-dev.ts@@ -1,9 +1,8 @@/**- * Runtime capabilities available to authored code handling a same-machine- * request to `eve dev`.+ * Host facilities available to authored code running on an `eve dev` server.*- * A deployed runtime and a client attached to a development server over the- * network receive `undefined`. A local TUI attached to an existing headless- * server receives the capability because authorization follows its requests.+ * The capability is present when the executing host owns the authored root and+ * watcher control origin. It is unavailable in deployed runtimes and does not+ * vary by request or peer address.*/export { getLocalDevCapability, type LocalDevCapability } from "#runtime/local-dev-capability.js";diff --git a/packages/eve/src/runtime/local-dev-capability.test.ts b/packages/eve/src/runtime/local-dev-capability.test.tsindex e4e93be66..4d452548f 100644--- a/packages/eve/src/runtime/local-dev-capability.test.ts+++ b/packages/eve/src/runtime/local-dev-capability.test.ts@@ -70,34 +70,78 @@ describe("installLocalDevCapabilityEnvironment", () => {});describe("getLocalDevCapability", () => {- it("is absent without both the dev environment and a local request", async () => {- expect(getLocalDevCapability(environment())).toBeUndefined();- await withClient("127.0.0.1", () => {- expect(getLocalDevCapability({})).toBeUndefined();- expect(getLocalDevCapability({ EVE_DEV_APP_ROOT: APP_ROOT })).toBeUndefined();- expect(getLocalDevCapability({ EVE_DEV_CONTROL_URL: SERVER_URL })).toBeUndefined();+ it("is absent without both host facilities", () => {+ expect(getLocalDevCapability({})).toBeUndefined();+ expect(getLocalDevCapability({ EVE_DEV_APP_ROOT: APP_ROOT })).toBeUndefined();+ expect(getLocalDevCapability({ EVE_DEV_CONTROL_URL: SERVER_URL })).toBeUndefined();+ expect(+ getLocalDevCapability({ EVE_DEV_APP_ROOT: "", EVE_DEV_CONTROL_URL: SERVER_URL }),+ ).toBeUndefined();+ expect(+ getLocalDevCapability({ EVE_DEV_APP_ROOT: APP_ROOT, EVE_DEV_CONTROL_URL: "" }),+ ).toBeUndefined();+ });++ it("is available on a host with both facilities without a request scope", () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,});});- it("is scoped to a parent-verified loopback client", async () => {+ it("does not make source access depend on the peer address or provenance", async () => {await withClient("127.0.0.1", () => {- expect(getLocalDevCapability(environment())?.appRoot).toBe(APP_ROOT);+ expect(getLocalDevCapability(environment())?.interactiveClient).toBe(false);});await withClient("203.0.113.7", () => {- expect(getLocalDevCapability(environment())).toBeUndefined();+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,+ });});- });- it("follows the request into nested authored execution contexts", async () => {- await withClient("127.0.0.1", async () => {- const nestedContext = new ContextContainer();- await contextStorage.run(nestedContext, () => {- expect(getLocalDevCapability(environment())?.appRoot).toBe(APP_ROOT);+ await withLocalDevRequestScope(new Request(SERVER_URL), async () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,});});});- it("survives durable workflow context serialization", async () => {+ it("inherits a verified dev-TUI hint into nested authored execution contexts", async () => {+ await withClient(+ "127.0.0.1",+ async () => {+ const nestedContext = new ContextContainer();+ await contextStorage.run(nestedContext, () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: true,+ });+ });+ },+ true,+ );+ });++ it("keeps source access while a direct remote request clears the dev-TUI hint", async () => {+ await withClient(+ "127.0.0.1",+ async () => {+ expect(getLocalDevCapability(environment())?.interactiveClient).toBe(true);+ await withClient("203.0.113.7", () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,+ });+ });+ expect(getLocalDevCapability(environment())?.interactiveClient).toBe(true);+ },+ true,+ );+ });++ it("preserves a verified dev-TUI hint through durable context serialization", async () => {await withClient("127.0.0.1",async () => {@@ -116,38 +160,41 @@ describe("getLocalDevCapability", () => {);});- it("invalidates durable provenance when the dev host secret rotates", async () => {- await withClient("127.0.0.1", async () => {- const active = contextStorage.getStore();- expect(active).toBeDefined();- const restored = await deserializeContext(serializeContext(active!));- process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = "replacement-secret";+ it("invalidates a rotated or tampered dev-TUI hint without revoking source access", async () => {+ await withClient(+ "127.0.0.1",+ async () => {+ const active = contextStorage.getStore();+ expect(active).toBeDefined();+ const serialized = serializeContext(active!);+ const restored = await deserializeContext(serialized);+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = "replacement-secret";- await contextStorage.run(restored, () => {- expect(getLocalDevCapability(environment())).toBeUndefined();- });- });- });+ await contextStorage.run(restored, () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,+ });+ });- it("rejects tampered durable local provenance", async () => {- await withClient("127.0.0.1", async () => {- const active = contextStorage.getStore();- expect(active).toBeDefined();- const serialized = serializeContext(active!);- serialized["eve.internal.localDevRequest"] = {- address: "127.0.0.1",- interactiveClient: true,- signature: "forged",- };- const restored = await deserializeContext(serialized);-- await contextStorage.run(restored, () => {- expect(getLocalDevCapability(environment())).toBeUndefined();- });- });+ serialized["eve.internal.localDevRequest"] = {+ address: "127.0.0.1",+ interactiveClient: true,+ signature: "forged",+ };+ const tampered = await deserializeContext(serialized);+ await contextStorage.run(tampered, () => {+ expect(getLocalDevCapability(environment())).toMatchObject({+ appRoot: APP_ROOT,+ interactiveClient: false,+ });+ });+ },+ true,+ );});- it("reports whether the requesting local client is interactive", async () => {+ it("reports whether a verified originating local client is interactive", async () => {await withClient("::1", () => {expect(getLocalDevCapability(environment())?.interactiveClient).toBe(false);});@@ -177,17 +224,13 @@ describe("withSuspendedSource", () => {return fetchMock.mock.calls.map((call) => new URL(String(call[0])).pathname);}- it("suspends the watcher around the task and resumes it afterwards", async () => {+ it("suspends the watcher around host-side work and resumes it afterwards", async () => {fetchMock.mockResolvedValue(new Response(JSON.stringify({ revision: "r2" }), { status: 200 }));const order: string[] = [];- const result = await withClient(- "127.0.0.1",- async () =>- await getLocalDevCapability(environment())?.withSuspendedSource(async () => {- order.push(...requestedPaths());- return "installed";- }),- );+ const result = await getLocalDevCapability(environment())!.withSuspendedSource(async () => {+ order.push(...requestedPaths());+ return "installed";+ });expect(result).toBe("installed");expect(order).toEqual(["/eve/v1/dev/runtime-artifacts/suspend"]);@@ -200,13 +243,9 @@ describe("withSuspendedSource", () => {it("resumes even when the task throws", async () => {fetchMock.mockResolvedValue(new Response(JSON.stringify({ revision: "r2" }), { status: 200 }));await expect(- withClient(- "127.0.0.1",- async () =>- await getLocalDevCapability(environment())?.withSuspendedSource(async () => {- throw new Error("install failed");- }),- ),+ getLocalDevCapability(environment())!.withSuspendedSource(async () => {+ throw new Error("install failed");+ }),).rejects.toThrow("install failed");expect(requestedPaths()).toEqual([@@ -219,12 +258,9 @@ describe("withSuspendedSource", () => {fetchMock.mockResolvedValue(new Response(null, { status: 503 }));const task = vi.fn();- await expect(- withClient(- "127.0.0.1",- async () => await getLocalDevCapability(environment())?.withSuspendedSource(task),- ),- ).rejects.toThrow(/Could not pause the eve development server/u);+ await expect(getLocalDevCapability(environment())!.withSuspendedSource(task)).rejects.toThrow(+ /Could not pause the eve development server/u,+ );expect(task).not.toHaveBeenCalled();});@@ -238,11 +274,7 @@ describe("withSuspendedSource", () => {return Promise.resolve(new Response(JSON.stringify({ revision: "r2" }), { status: 200 }));});- await withClient(- "127.0.0.1",- async () =>- await getLocalDevCapability(environment())?.withSuspendedSource(async () => undefined),- );+ await getLocalDevCapability(environment())!.withSuspendedSource(async () => undefined);expect(requestedPaths()).toEqual(["/eve/v1/dev/runtime-artifacts/suspend",diff --git a/packages/eve/src/runtime/local-dev-capability.ts b/packages/eve/src/runtime/local-dev-capability.tsindex 9d96e84a2..deb824e2d 100644--- a/packages/eve/src/runtime/local-dev-capability.ts+++ b/packages/eve/src/runtime/local-dev-capability.ts@@ -28,13 +28,12 @@ const LOCAL_DEV_CONTROL_URL_ENV = "EVE_DEV_CONTROL_URL";export const LOCAL_DEV_INTERACTIVE_CLIENT_HEADER = "x-eve-dev-interactive-client";/**- * Capabilities available to authored code in an execution initiated by a- * same-machine request to `eve dev`.+ * Host facilities available to authored code running on an `eve dev` server.*- * Absence is the signal, not a disabled flag: a deployed runtime has no- * authored tree to mutate or watcher to pause, and a request from a remote- * client is not authorized to mutate the server's authored tree.- * {@link getLocalDevCapability} returns `undefined` in both cases.+ * Absence means this host has no authored tree to mutate or watcher to pause.+ * When present, the capability is available to every execution on that host;+ * callers admitted to the development server are trusted with enabled local+ * editing tools.*/export interface LocalDevCapability {/**@@ -43,8 +42,9 @@ export interface LocalDevCapability {*/readonly appRoot: string;/**- * Whether the requesting client is the dev TUI and can therefore run a flow- * that asks questions in its terminal.+ * Whether the originating client is the dev TUI and can run a flow that asks+ * questions in its terminal. This inherited hint is not proof that the+ * current sender has a live terminal.*/readonly interactiveClient: boolean;/**@@ -78,8 +78,8 @@ export function installLocalDevCapabilityEnvironment(input: {}/**- * Seeds durable local-dev provenance only when the parent host signed a- * loopback peer address. Public address headers cannot grant access.+ * Seeds the inherited dev-TUI hint only when the dev host signed a loopback+ * peer address. Client-supplied address headers cannot create that hint.*/export async function withLocalDevRequestScope<T>(request: Request,@@ -89,7 +89,7 @@ export async function withLocalDevRequestScope<T>(const address = readTrustedDevelopmentClientAddress(request.headers, secret);const signature = request.headers.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);if (address === undefined || signature === null || !isLoopbackHostname(address)) {- return await callback();+ return await contextStorage.run(new ContextContainer({ localDevRequest: undefined }), callback);}return await contextStorage.run(@@ -105,8 +105,10 @@ export async function withLocalDevRequestScope<T>(}/**- * Resolves the local dev capability, or `undefined` outside an execution- * initiated by an authorized local request to `eve dev`.+ * Resolves local development host facilities, or `undefined` when this host+ * lacks the authored root or watcher control origin installed by `eve dev`.+ * Request provenance affects only the optional dev-TUI hint, never access to+ * the authored tree.** This is deliberately not a {@link import("#public/definitions/tool.js").ToolContext}* field: both values are meaningless in a deployed runtime, and a capability@@ -118,29 +120,28 @@ export function getLocalDevCapability(): LocalDevCapability | undefined {const appRoot = environment[LOCAL_DEV_APP_ROOT_ENV];const controlUrl = environment[LOCAL_DEV_CONTROL_URL_ENV];+ if (appRoot === undefined || appRoot === "" || controlUrl === undefined || controlUrl === "") {+ return undefined;+ }+const requestScope = contextStorage.getStore()?.localDevRequest;- if (- requestScope === undefined ||- typeof requestScope.address !== "string" ||- typeof requestScope.signature !== "string" ||- typeof requestScope.interactiveClient !== "boolean" ||- !isLoopbackHostname(requestScope.address) ||- !isTrustedDevelopmentClientAddress(+ const interactiveClient =+ requestScope !== undefined &&+ typeof requestScope.address === "string" &&+ typeof requestScope.signature === "string" &&+ typeof requestScope.interactiveClient === "boolean" &&+ isLoopbackHostname(requestScope.address) &&+ isTrustedDevelopmentClientAddress(requestScope.address,requestScope.signature,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV],- ) ||- appRoot === undefined ||- appRoot === "" ||- controlUrl === undefined ||- controlUrl === ""- ) {- return undefined;- }+ )+ ? requestScope.interactiveClient+ : false;return {appRoot,- interactiveClient: requestScope.interactiveClient,+ interactiveClient,async withSuspendedSource<T>(task: () => Promise<T>): Promise<T> {const leaseId = randomUUID();if (!(await suspendDevelopmentRuntimeArtifacts({ leaseId, serverUrl: controlUrl }))) {diff --git a/packages/eve/src/self-modification/extension/subagents/agent/agent.test.ts b/packages/eve/src/self-modification/extension/subagents/agent/agent.test.tsnew file mode 100644index 000000000..5aa3a208d--- /dev/null+++ b/packages/eve/src/self-modification/extension/subagents/agent/agent.test.ts@@ -0,0 +1,74 @@+import type { DynamicResolveContext } from "#dynamic/definition.js";+import {+ installLocalDevCapabilityEnvironment,+ withLocalDevRequestScope,+} from "#runtime/local-dev-capability.js";+import { stampDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";+import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";+import { afterEach, describe, expect, it } from "vitest";++import { defineSelfModificationAgent } from "./agent.js";++const serverUrl = "http://127.0.0.1:3000";+const context: DynamicResolveContext = {+ channel: {},+ messages: [],+ model: null,+ session: { auth: { current: null, initiator: null }, id: "session" },+};++const savedEnvironment = { ...process.env };++afterEach(() => {+ process.env = { ...savedEnvironment };+});++async function withDevHost<T>(callback: () => Promise<T>): Promise<T> {+ process.env.EVE_DEV = "1";+ const restore = installLocalDevCapabilityEnvironment({ appRoot: "/workspace/app", serverUrl });+ try {+ return await callback();+ } finally {+ restore();+ }+}++describe("self-modification local agent", () => {+ it("is available on an eve dev host without a request scope", async () => {+ await withDevHost(async () => {+ const agent = defineSelfModificationAgent({ config: { local: { enabled: true } } });++ await expect(agent.events["turn.started"]?.({}, context)).resolves.not.toBeNull();+ });+ });++ it("is available to a direct remote request on an eve dev host", async () => {+ await withDevHost(async () => {+ const secret = "test-secret";+ process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV] = secret;+ const headers = new Headers();+ stampDevelopmentClientAddress(headers, "203.0.113.7", secret);++ await withLocalDevRequestScope(new Request(serverUrl, { headers }), async () => {+ const agent = defineSelfModificationAgent({ config: { local: { enabled: true } } });++ await expect(agent.events["turn.started"]?.({}, context)).resolves.not.toBeNull();+ });+ });+ });++ it("does not expose the editor when eve dev facilities are absent", async () => {+ process.env.EVE_DEV = "1";+ const agent = defineSelfModificationAgent({ config: { local: { enabled: true } } });++ await expect(agent.events["turn.started"]?.({}, context)).resolves.toBeNull();+ });++ it("honors local.enabled: false even when eve dev facilities are available", async () => {+ await withDevHost(async () => {+ const agent = defineSelfModificationAgent({ config: { local: { enabled: false } } });++ await expect(agent.events["turn.started"]?.({}, context)).resolves.toBeNull();+ });+ });+});diff --git a/packages/eve/src/self-modification/extension/subagents/agent/agent.ts b/packages/eve/src/self-modification/extension/subagents/agent/agent.tsindex ad1af572a..e7ebae364 100644--- a/packages/eve/src/self-modification/extension/subagents/agent/agent.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/agent.ts@@ -9,6 +9,7 @@ import {} from "eve";import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";+import { getLocalDevCapability } from "eve/local-dev";import selfModification from "../../extension.js";import { resolveSelfModificationConfig, type SelfModificationConfig } from "../../../config.js";@@ -90,7 +91,10 @@ export function defineSelfModificationAgent(repairDelegation,mode === "local" ? localEffectiveEdits : deployedEffectiveEdits,]);- if (mode === "local") return defineAgent({ description, model, reasoning });+ if (mode === "local") {+ if (getLocalDevCapability() === undefined) return null;+ return defineAgent({ description, model, reasoning });+ }if (mode !== "deployed" || config.deployed === undefined) return null;if (config.deployed.credentials.kind === "pat" && !hasGitHubCredential()) return null;try {diff --git a/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.tsindex f3bb40a80..6b2be2cbe 100644--- a/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/sandbox.ts@@ -12,7 +12,7 @@ import { vercel } from "eve/sandbox/vercel";import { resolveSelfModificationConfig, type SelfModificationConfig } from "../../../config.js";import { createGitHubCredentialProvider } from "../../../credentials.js";-import { createSelfModificationFilesystem } from "../../../filesystem.js";+import { createLocalSelfModificationFilesystem } 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";@@ -44,7 +44,7 @@ export function defineSelfModificationSandbox(return defineSandbox({backend: () => {const mode = resolveSelfModificationMode(config);- if (mode === "local") return justbash({ filesystem: createSelfModificationFilesystem });+ if (mode === "local") return justbash({ filesystem: createLocalSelfModificationFilesystem });if (mode === "disabled") return options.backend ?? defaultBackend();return selectDeployedSelfModificationBackend(options.backend, SANDBOX_BACKEND_PROBES);},diff --git a/packages/eve/src/self-modification/filesystem.ts b/packages/eve/src/self-modification/filesystem.tsindex 9e97a49f0..dd8a3f5a9 100644--- a/packages/eve/src/self-modification/filesystem.ts+++ b/packages/eve/src/self-modification/filesystem.ts@@ -3,14 +3,24 @@ import { resolve } from "node:path";import type { IFileSystem } from "just-bash";-export async function createSelfModificationFilesystem(input: {+import { getLocalDevCapability } from "eve/local-dev";++export async function createLocalSelfModificationFilesystem(input: {readonly appRoot: string;readonly defaultFilesystem: IFileSystem;readonly justBash: typeof import("just-bash");}): Promise<IFileSystem> {+ const capability = getLocalDevCapability();+ if (capability === undefined) {+ throw new Error(+ "Self-modification requires eve dev facilities for the authored source tree and watcher.",+ );+ }+const { MountableFs, OverlayFs, ReadWriteFs } = input.justBash;- const traceRoot = resolve(input.appRoot, ".eve/traces/v1");- const logsRoot = resolve(input.appRoot, ".eve/logs");+ const appRoot = capability.appRoot;+ const traceRoot = resolve(appRoot, ".eve/traces/v1");+ const logsRoot = resolve(appRoot, ".eve/logs");await Promise.all([input.defaultFilesystem.mkdir("/source", { recursive: true }),mkdir(traceRoot, { recursive: true }),@@ -23,7 +33,7 @@ export async function createSelfModificationFilesystem(input: {filesystem: new ReadWriteFs({allowSymlinks: false,maxFileReadSize: Number.MAX_SAFE_INTEGER,- root: resolve(input.appRoot, "agent"),+ root: resolve(appRoot, "agent"),}),mountPoint: "/source",},@@ -47,7 +57,7 @@ export async function createSelfModificationFilesystem(input: {filesystem: new OverlayFs({mountPoint: "/",readOnly: true,- root: resolve(input.appRoot, "node_modules/eve/docs"),+ root: resolve(appRoot, "node_modules/eve/docs"),}),mountPoint: "/eve-docs",},diff --git a/packages/eve/src/self-modification/sandbox.integration.test.ts b/packages/eve/src/self-modification/sandbox.integration.test.tsdeleted file mode 100644index cf0e6fa35..000000000--- a/packages/eve/src/self-modification/sandbox.integration.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";--import * as justBash from "just-bash";-import { afterEach, describe, expect, it } from "vitest";--import { createSelfModificationFilesystem } from "./filesystem.js";--const temporaryDirectories: string[] = [];--afterEach(async () => {- await Promise.all(- temporaryDirectories- .splice(0)- .map((directory) => rm(directory, { force: true, recursive: true })),- );-});--async function createAppRoot(options: { traces?: boolean; logs?: boolean } = {}): Promise<string> {- const appRoot = await mkdtemp(join(tmpdir(), "eve-self-modification-sandbox-"));- temporaryDirectories.push(appRoot);- await mkdir(join(appRoot, "agent"), { recursive: true });- await mkdir(join(appRoot, "node_modules/eve/docs"), { recursive: true });- if (options.traces !== false) {- await mkdir(join(appRoot, ".eve/traces/v1/trace-1/segments"), { recursive: true });- await writeFile(join(appRoot, ".eve/traces/v1/trace-1/segments/span.otlp.json"), "trace\n");- }- if (options.logs !== false) {- await mkdir(join(appRoot, ".eve/logs"), { recursive: true });- await writeFile(join(appRoot, ".eve/logs/dev-test.log"), "diagnostic log\n");- }- await writeFile(join(appRoot, "node_modules/eve/docs/README.md"), "installed eve docs\n");- return appRoot;-}--describe("self-modification filesystem", () => {- it("mounts authored source read-write and traces, logs, and eve docs read-only", async () => {- const appRoot = await createAppRoot();- const filesystem = await createSelfModificationFilesystem({- appRoot,- defaultFilesystem: new justBash.InMemoryFs(),- justBash,- });-- expect(await filesystem.readFile("/traces/trace-1/segments/span.otlp.json")).toBe("trace\n");- await expect(- filesystem.writeFile("/traces/trace-1/segments/span.otlp.json", "changed\n"),- ).rejects.toThrow(/read-only file system/u);-- expect(await filesystem.readFile("/logs/dev-test.log")).toBe("diagnostic log\n");- await expect(filesystem.writeFile("/logs/dev-test.log", "changed\n")).rejects.toThrow(- /read-only file system/u,- );-- expect(await filesystem.readFile("/eve-docs/README.md")).toBe("installed eve docs\n");- await expect(filesystem.writeFile("/eve-docs/README.md", "changed\n")).rejects.toThrow(- /read-only file system/u,- );-- await filesystem.writeFile("/source/instructions.md", "authored\n");- expect(await readFile(join(appRoot, "agent/instructions.md"), "utf8")).toBe("authored\n");- });-- it("mounts empty trace and log directories when nothing has been captured", async () => {- const appRoot = await createAppRoot({ traces: false, logs: false });- const filesystem = await createSelfModificationFilesystem({- appRoot,- defaultFilesystem: new justBash.InMemoryFs(),- justBash,- });-- expect(await filesystem.readdir("/traces")).toEqual([]);- expect(await filesystem.readdir("/logs")).toEqual([]);- });-});diff --git a/packages/eve/src/self-modification/sandbox.scenario.test.ts b/packages/eve/src/self-modification/sandbox.scenario.test.tsnew file mode 100644index 000000000..4ce4735e9--- /dev/null+++ b/packages/eve/src/self-modification/sandbox.scenario.test.ts@@ -0,0 +1,126 @@+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import * as justBash from "just-bash";+import { afterEach, describe, expect, it } from "vitest";++import { installLocalDevCapabilityEnvironment } from "#runtime/local-dev-capability.js";++import { createLocalSelfModificationFilesystem } from "./filesystem.js";++const temporaryDirectories: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { force: true, recursive: true })),+ );+});++async function withLocalDevCapability<T>(appRoot: string, callback: () => Promise<T>): Promise<T> {+ const restore = installLocalDevCapabilityEnvironment({+ appRoot,+ serverUrl: "http://127.0.0.1:3000",+ });+ try {+ return await callback();+ } finally {+ restore();+ }+}++async function createAppRoot(options: { traces?: boolean; logs?: boolean } = {}): Promise<string> {+ const appRoot = await mkdtemp(join(tmpdir(), "eve-self-modification-sandbox-"));+ temporaryDirectories.push(appRoot);+ await mkdir(join(appRoot, "agent"), { recursive: true });+ await mkdir(join(appRoot, "node_modules/eve/docs"), { recursive: true });+ if (options.traces !== false) {+ await mkdir(join(appRoot, ".eve/traces/v1/trace-1/segments"), { recursive: true });+ await writeFile(join(appRoot, ".eve/traces/v1/trace-1/segments/span.otlp.json"), "trace\n");+ }+ if (options.logs !== false) {+ await mkdir(join(appRoot, ".eve/logs"), { recursive: true });+ await writeFile(join(appRoot, ".eve/logs/dev-test.log"), "diagnostic log\n");+ }+ await writeFile(join(appRoot, "node_modules/eve/docs/README.md"), "installed eve docs\n");+ return appRoot;+}++describe("self-modification filesystem", () => {+ it("mounts authored source read-write and traces, logs, and eve docs read-only", async () => {+ const appRoot = await createAppRoot();+ await withLocalDevCapability(appRoot, async () => {+ const filesystem = await createLocalSelfModificationFilesystem({+ appRoot,+ defaultFilesystem: new justBash.InMemoryFs(),+ justBash,+ });++ expect(await filesystem.readFile("/traces/trace-1/segments/span.otlp.json")).toBe("trace\n");+ await expect(+ filesystem.writeFile("/traces/trace-1/segments/span.otlp.json", "changed\n"),+ ).rejects.toThrow(/read-only file system/u);++ expect(await filesystem.readFile("/logs/dev-test.log")).toBe("diagnostic log\n");+ await expect(filesystem.writeFile("/logs/dev-test.log", "changed\n")).rejects.toThrow(+ /read-only file system/u,+ );++ expect(await filesystem.readFile("/eve-docs/README.md")).toBe("installed eve docs\n");+ await expect(filesystem.writeFile("/eve-docs/README.md", "changed\n")).rejects.toThrow(+ /read-only file system/u,+ );++ await filesystem.writeFile("/source/instructions.md", "authored\n");+ expect(await readFile(join(appRoot, "agent/instructions.md"), "utf8")).toBe("authored\n");+ });+ });++ it("uses the capability's authored root instead of the runtime snapshot", async () => {+ const authoredRoot = await createAppRoot();+ const runtimeRoot = await createAppRoot();++ await withLocalDevCapability(authoredRoot, async () => {+ const filesystem = await createLocalSelfModificationFilesystem({+ appRoot: runtimeRoot,+ defaultFilesystem: new justBash.InMemoryFs(),+ justBash,+ });++ await filesystem.writeFile("/source/instructions.md", "authored\n");+ });++ expect(await readFile(join(authoredRoot, "agent/instructions.md"), "utf8")).toBe("authored\n");+ await expect(readFile(join(runtimeRoot, "agent/instructions.md"), "utf8")).rejects.toThrow(+ /ENOENT/u,+ );+ });++ it("mounts empty trace and log directories when nothing has been captured", async () => {+ const appRoot = await createAppRoot({ traces: false, logs: false });+ await withLocalDevCapability(appRoot, async () => {+ const filesystem = await createLocalSelfModificationFilesystem({+ appRoot,+ defaultFilesystem: new justBash.InMemoryFs(),+ justBash,+ });++ expect(await filesystem.readdir("/traces")).toEqual([]);+ expect(await filesystem.readdir("/logs")).toEqual([]);+ });+ });++ it("rejects mounting authored files without eve dev facilities", async () => {+ const appRoot = await createAppRoot();++ await expect(+ createLocalSelfModificationFilesystem({+ appRoot,+ defaultFilesystem: new justBash.InMemoryFs(),+ justBash,+ }),+ ).rejects.toThrow("Self-modification requires eve dev facilities");+ });+});