Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): rewrite dynamic skill files into a recreated sandbox (#5225)

Andrew Barba1fe0d915be18
diff --git a/.changeset/rewrite-dynamic-skills-recreated-sandbox.md b/.changeset/rewrite-dynamic-skills-recreated-sandbox.md
new file mode 100644
index 000000000..178b38b36
--- /dev/null
+++ b/.changeset/rewrite-dynamic-skills-recreated-sandbox.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Dynamic skills with supporting files are written into a sandbox that eve recreates after the old one was gone, at the start of the next turn. Before, the recreated sandbox got the same identity as the old one, so its skills were missing their files until the skill changed.
diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.md
index 07dcfbb93..ace024e74 100644
--- a/docs/guides/dynamic-capabilities.md
+++ b/docs/guides/dynamic-capabilities.md
@@ -448,7 +448,7 @@ Skills follow the same naming rule as tools: a single `defineSkill(...)` is name
A dynamic skill with `deferred: true` is left out of the dynamic skill announcement and isn't named in context. The model finds it with `eve__search` and loads it with `eve__skill({ name })`, like a static deferred skill. When it overrides a static skill that isn't deferred, the system prompt still lists the static skill's description, and loading returns the dynamic body.
-A dynamic skill that returns only `markdown` never starts a sandbox: eve keeps its instructions in session state and returns them when the model loads the skill. When the skill also returns `files`, eve writes the package to the sandbox skill root when the resolver first returns it, and again only when its contents change or the session gets a new sandbox. A changed package replaces the previous directory, so files omitted from the new result are removed, and a skill the resolver stops returning has its files removed. A skill that keeps its name but stops returning `files` keeps the files already written, since the sandbox may provide them another way, such as from its snapshot. Keep content meant for only some callers in `markdown`, or stop returning the skill for the others.
+A dynamic skill that returns only `markdown` never starts a sandbox: eve keeps its instructions in session state and returns them when the model loads the skill. When the skill also returns `files`, eve writes the package to the sandbox skill root when the resolver first returns it, and again only when its contents change or the session gets a new sandbox. Resolvers run when the turn starts, before the sandbox opens, so when eve replaces a sandbox that was removed outside eve, it writes the files into the new sandbox at the start of the next turn. A replacement made by a subagent or workflow step that shares the session's sandbox is not detected: the session treats the files as written until their contents change. A changed package replaces the previous directory, so files omitted from the new result are removed, and a skill the resolver stops returning has its files removed. A skill that keeps its name but stops returning `files` keeps the files already written, since the sandbox may provide them another way, such as from its snapshot. Keep content meant for only some callers in `markdown`, or stop returning the skill for the others.
## Dynamic instructions
diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.ts
index bc418ff8c..40ddc0358 100644
--- a/packages/eve/src/context/build-callback-context.ts
+++ b/packages/eve/src/context/build-callback-context.ts
@@ -3,7 +3,7 @@ import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js"
import type { RuntimeSandboxSession, SandboxSession } from "#shared/sandbox-session.js";
import { readSessionSchedule } from "#context/session-schedule.js";
import { loadContext } from "#context/container.js";
-import { DynamicSkillSandboxKey, SandboxKey, SessionKey } from "#context/keys.js";
+import { SandboxKey, SessionKey } from "#context/keys.js";
/**
* Builds a {@link SessionContext} from the active ALS scope.
@@ -47,8 +47,6 @@ export function buildCallbackContext(): SessionContext {
throw new Error("The active sandbox runtime does not support deletion.");
}
await access.delete(options);
- // A recreated sandbox can reuse the same persisted identity.
- ctx.delete(DynamicSkillSandboxKey);
},
async () => await access.stop(),
);
diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
index a0c9e6bed..939afab35 100644
--- a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts
@@ -21,9 +21,23 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { defineSkill } from "#public/definitions/skill.js";
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { ResolvedDynamicSkillResolver } from "#runtime/types.js";
-import type { SandboxSessionState } from "#sandbox/state.js";
+import type { SandboxAccess, SandboxSessionState, SandboxState } from "#sandbox/state.js";
+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import {
+ defineSandboxProvider,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
+import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
import type { SkillPackageDefinition } from "#shared/skill-definition.js";
+// Sandbox start loads the prepared artifact; these tests prepare none.
+vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
+ loadSandboxPreparedArtifact: vi.fn(async () => null),
+}));
+
const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;
const SKILL_ROOT = "/home/agent/.agents/skills";
@@ -49,6 +63,59 @@ function persistedSandbox(id: string): SandboxSessionState {
return { providerName: "mock", state: { id }, stateProtocolVersion: 1 };
}
+/**
+ * A provider that, like the built-in ones, names a session's sandbox the same
+ * way on every start, and whose sandbox can be removed outside eve.
+ */
+function recreatableSandbox() {
+ const sandboxes: ReturnType<typeof mockSandbox>[] = [];
+ let gone = false;
+ const handle = (sandbox: ReturnType<typeof mockSandbox>) => ({
+ sandbox: sandbox.session,
+ onRuntimeShutdown: async () => {},
+ onSandboxDelete: async () => {},
+ onSandboxStop: async () => {},
+ });
+ const environment = defineSandboxProvider({
+ name: "recreatable",
+ environment: () => ({
+ onSessionEnd: async () => {},
+ prepare: async () => null,
+ async resume() {
+ if (gone) {
+ gone = false;
+ throw new SandboxSessionGoneError("The sandbox was removed.");
+ }
+ return handle(sandboxes.at(-1)!);
+ },
+ async start(context: SandboxProviderSessionContext) {
+ const sandbox = mockSandbox({
+ commands: {
+ [HOME_PROBE_COMMAND]: { exitCode: 0, stderr: "", stdout: "/home/agent\n" },
+ },
+ });
+ sandboxes.push(sandbox);
+ return { handle: handle(sandbox), state: { name: `sandbox-${context.session.id}` } };
+ },
+ }),
+ }).environment();
+ const registry: RuntimeSandboxRegistry = {
+ sandbox: {
+ definition: {
+ environment,
+ kind: "independent",
+ logicalPath: "sandbox.ts",
+ revisionHash: "hash",
+ selector: defineSandbox(() => environment.open()),
+ sourceId: "sandbox",
+ sourceKind: "module",
+ },
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+ return { registry, removeOutsideEve: () => void (gone = true), sandboxes };
+}
+
/** Mirrors ensureSandboxAccess: the persisted state appears once the sandbox starts. */
function createCtx(authoredSkillNames: readonly string[] = []) {
const ctx = new ContextContainer();
@@ -354,7 +421,7 @@ describe("dynamic skill supporting files", () => {
expect(sandbox.files.has(`${SKILL_ROOT}/policy/b.md`)).toBe(false);
});
- it("rewrites unchanged packages for a different sandbox or after the sandbox is deleted", async () => {
+ it("rewrites unchanged packages for a different sandbox", async () => {
const { ctx, sandbox, state } = createCtx();
const resolver = createResolver("policy", () =>
makeSkill("Policy", "# Policy", { "rules.md": "Rules" }),
@@ -364,10 +431,59 @@ describe("dynamic skill supporting files", () => {
state.session = persistedSandbox("sandbox-2");
await dispatch(ctx, resolver);
expect(sandbox.writes).toHaveLength(4);
+ });
- ctx.delete(DynamicSkillSandboxKey);
- await dispatch(ctx, resolver);
- expect(sandbox.writes).toHaveLength(6);
+ it("writes files into a sandbox recreated after it was gone, at the next turn", async () => {
+ const { registry, removeOutsideEve, sandboxes } = recreatableSandbox();
+ const ctx = new ContextContainer();
+ ctx.set(StaticModelReferenceKey, { id: "openai/gpt-5.5" });
+ ctx.set(SessionIdKey, "session-1");
+ ctx.set(BundleKey, createMockBundle());
+ const handler = () => makeSkill("Policy", "# Policy", { "rules.md": "Rules" });
+ const resolver: ResolvedDynamicSkillResolver = {
+ ...createResolver("policy", handler),
+ eventNames: ["turn.started"],
+ events: { "turn.started": handler },
+ };
+ // Each turn resumes from the state the previous turn checkpointed.
+ let state: SandboxState | null = null;
+ const turn = async (work?: (access: SandboxAccess) => Promise<unknown>) => {
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry,
+ sessionId: "session-1",
+ state,
+ });
+ ctx.setVirtualContext(SandboxKey, access);
+ await dispatchDynamicSkillEvent({
+ ctx,
+ event: { data: {}, type: "turn.started" } as UnstampedMessageStreamEvent,
+ messages: [],
+ resolvers: [resolver],
+ });
+ await work?.(access);
+ state = await access.captureState();
+ };
+ const rules = (index: number) => sandboxes[index]?.files.get(`${SKILL_ROOT}/policy/rules.md`);
+
+ await turn();
+ expect(rules(0)).toBe("Rules");
+
+ // The turn starts with the files counted as written; a tool then finds the
+ // sandbox gone, and eve starts a fresh one under the same provider state.
+ removeOutsideEve();
+ await turn(async (access) => await access.get());
+ expect(sandboxes).toHaveLength(2);
+ expect(rules(1)).toBeUndefined();
+
+ await turn();
+ expect(rules(1)).toBe("Rules");
+
+ // Resuming keeps the identity, so nothing is written again.
+ const writes = sandboxes[1]!.writes.length;
+ await turn();
+ expect(sandboxes[1]!.writes).toHaveLength(writes);
});
it("removes files when a package is withdrawn", async () => {
diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.ts b/packages/eve/src/context/dynamic-skill-lifecycle.ts
index e3f1a1cff..5c01d3c30 100644
--- a/packages/eve/src/context/dynamic-skill-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-skill-lifecycle.ts
@@ -86,6 +86,8 @@ function toDurableSkill(skill: MaterializableSkillPackage): DurableDynamicSkillM
};
}
+// The whole persisted record, including the generation `start()` sets: provider
+// state alone repeats when a gone sandbox is recreated under the same name.
function sandboxIdentity(state: SandboxState): string | null {
return state.session === null ? null : JSON.stringify(state.session);
}
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 018bed830..4c10cac67 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -214,7 +214,12 @@ describe("ensureSandboxAccess", () => {
expect(setup).toHaveBeenCalledOnce();
expect(value.start).toHaveBeenCalledOnce();
await expect(access.captureState()).resolves.toEqual({
- session: { providerName: "test", state: { key: "session-1" }, stateProtocolVersion: 1 },
+ session: {
+ generation: expect.any(String),
+ providerName: "test",
+ state: { key: "session-1" },
+ stateProtocolVersion: 1,
+ },
});
});
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index 5a291b08d..40976d8be 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from "node:crypto";
+
import { ensureDevelopmentSandboxesPrepared } from "#execution/sandbox/development-lazy-prewarm.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger } from "#internal/logging.js";
@@ -189,6 +191,7 @@ export async function ensureSandboxAccess(
);
}
persisted = {
+ generation: randomUUID(),
providerName: provider.providerName,
state: result.state,
stateProtocolVersion: provider.stateProtocolVersion,
diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.ts
index e10d7d8ba..1226fd853 100644
--- a/packages/eve/src/sandbox/state.ts
+++ b/packages/eve/src/sandbox/state.ts
@@ -5,6 +5,15 @@ import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sand
export type SandboxSessionEndReason = "completed" | "expired" | "failed";
export interface SandboxSessionState {
+ /**
+ * Set anew each time this session's access calls `start()`, which is an upsert,
+ * and kept on resume. Providers name a session's sandbox deterministically, so
+ * without it a sandbox recreated after it was gone would look like the old one
+ * to dynamic skills, which then write their files into it at the next turn. A
+ * sandbox that a sharing subagent or a borrowed workflow step starts keeps this
+ * session's generation. Absent in state saved by earlier releases.
+ */
+ readonly generation?: string;
readonly providerName: string;
readonly state: SandboxPreparedArtifact;
readonly stateProtocolVersion: number;