Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(sandbox): build the just-bash provider on the public provider API (#5275)

Andrew Barba62112b5d7a54
diff --git a/.changeset/just-bash-public-provider-api.md b/.changeset/just-bash-public-provider-api.md
new file mode 100644
index 000000000..18dd70294
--- /dev/null
+++ b/.changeset/just-bash-public-provider-api.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+The just-bash sandbox provider now runs on the public `defineSandboxProvider()` API, and `customCommands` and `filesystem` use eve-owned types from `eve/sandbox/just-bash`, such as `JustBashCommand` and `JustBashFilesystem`, that still accept just-bash's `defineCommand()` results and filesystems. Local just-bash templates rebuild once after upgrading, since their keys no longer include custom commands or the filesystem; reading a directory now rejects instead of returning `null`, and a command ending in a `# comment` runs in any working directory.
diff --git a/docs/sandbox/just-bash.mdx b/docs/sandbox/just-bash.mdx
index e49d1e1e8..a9787f40f 100644
--- a/docs/sandbox/just-bash.mdx
+++ b/docs/sandbox/just-bash.mdx
@@ -21,4 +21,58 @@ When an environment uses just-bash during `eve dev`, eve installs the package in
For pnpm projects, automatic installation adds `@mongodb-js/zstd` and `node-liblzma` to `ignoredOptionalDependencies` in the owning `pnpm-workspace.yaml` when they have no explicit package policy. These optional native codecs are not needed for basic shell and filesystem operations. Commands that require those codecs may be unavailable without them. eve preserves existing package-specific build decisions and does not automatically approve build scripts.
+## Custom commands
+
+`customCommands` registers your own functions as commands in each live just-bash shell, where they work in pipelines and redirections. Write a `JustBashCommand` from `eve/sandbox/just-bash`:
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { JustBashSandbox, type JustBashCommand } from "eve/sandbox/just-bash";
+
+const today: JustBashCommand = {
+ name: "today",
+ async execute() {
+ return { exitCode: 0, stderr: "", stdout: `${new Date().toISOString().slice(0, 10)}\n` };
+ },
+};
+
+export const environment = JustBashSandbox.environment({ customCommands: [today] });
+export default defineSandbox(() => environment.open());
+```
+
+A `JustBashCommand` receives `cwd`, `env`, `fs`, and `signal` in its context. When a command needs standard input or the rest of just-bash's command context, create it with `defineCommand()` from `just-bash`; `customCommands` accepts the result.
+
+Custom commands run as application code in the app runtime process, outside the virtual filesystem. They are not available while eve prepares the template.
+
+## Custom filesystem
+
+`filesystem` composes the filesystem of each live sandbox. eve calls it with `defaultFilesystem`, the session's durable filesystem that holds `/workspace`, and `justBash`, the loaded `just-bash` module. Return a `JustBashFilesystem` that keeps `defaultFilesystem` as its base, such as a just-bash `MountableFs`:
+
+```ts
+import { defineSandbox } from "eve/sandbox";
+import { JustBashSandbox } from "eve/sandbox/just-bash";
+
+export const environment = JustBashSandbox.environment({
+ async filesystem({ defaultFilesystem, justBash, resolveProjectPath }) {
+ await defaultFilesystem.mkdir("/reference", { recursive: true });
+ return new justBash.MountableFs({
+ base: defaultFilesystem,
+ mounts: [
+ {
+ filesystem: new justBash.OverlayFs({
+ mountPoint: "/",
+ readOnly: true,
+ root: resolveProjectPath("reference"),
+ }),
+ mountPoint: "/reference",
+ },
+ ],
+ });
+ },
+});
+export default defineSandbox(() => environment.open());
+```
+
+eve does not call `filesystem` while it prepares the template, so files under a mount are not part of the template.
+
See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-identity.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-identity.integration.test.ts
new file mode 100644
index 000000000..b1da5fdbd
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-identity.integration.test.ts
@@ -0,0 +1,84 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { createSandboxEnvironmentHarness } from "#internal/testing/sandbox-provider-harness.js";
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+import { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+// Recorded from the provider before it moved to the public provider API.
+// Running sessions depend on it, so it must never change.
+const GOLDEN_SESSION_ROOT = "just-bash/sessions/e87bbba07bceb2ae5b77ad77";
+
+class QueryCommand {
+ readonly name = "query";
+ readonly client = new Map([["primary", "db.internal"]]);
+ readonly since = new Date(0);
+ async execute() {
+ return { exitCode: 0, stderr: "", stdout: "" };
+ }
+}
+
+function createProvider(options?: JustBashEnvironmentOptions) {
+ return createSandboxEnvironmentHarness(JustBashSandbox.environment(options));
+}
+
+describe("just-bash persisted identities", () => {
+ it("keeps custom commands and the filesystem out of the template key", async () => {
+ const appRoot = await createScratchDirectory("eve-just-bash-template-keys-");
+
+ const plain = await createProvider().prepare({ appRoot });
+ const customized = await createProvider({
+ customCommands: [new QueryCommand()],
+ filesystem: ({ defaultFilesystem }) => defaultFilesystem,
+ }).prepare({ appRoot });
+
+ expect(customized).toEqual(plain);
+ });
+
+ it("records the same session root and state as earlier releases", async () => {
+ const appRoot = await createScratchDirectory("eve-just-bash-session-state-");
+ const provider = createProvider();
+ await provider.prepare({ appRoot });
+
+ const { state } = await provider.start({ appRoot, sandboxName: "session_golden" });
+
+ expect(state).toEqual({ rootPath: join(appRoot, GOLDEN_SESSION_ROOT), version: 2 });
+ });
+
+ it("opens a template and resumes a session that an earlier release wrote", async () => {
+ const appRoot = await createScratchDirectory("eve-just-bash-earlier-release-");
+ const templateKey = "81d1596e5801b5002c9c98f1";
+ const templateRoot = join(appRoot, "just-bash/templates", templateKey);
+ await mkdir(join(templateRoot, "fs/workspace"), { recursive: true });
+ await writeFile(join(templateRoot, "fs/workspace/notes.txt"), "from the template\n");
+ await writeFile(
+ join(templateRoot, "metadata.json"),
+ `${JSON.stringify({ env: { GREETING: "hello" }, version: 1 }, null, 2)}\n`,
+ );
+ const sessionRoot = join(appRoot, GOLDEN_SESSION_ROOT);
+ await mkdir(join(sessionRoot, "fs/workspace"), { recursive: true });
+ await writeFile(join(sessionRoot, "fs/workspace/kept.txt"), "kept\n");
+ const provider = createProvider();
+
+ const started = await provider.openSession({
+ appRoot,
+ prepared: { templateKey },
+ sandboxName: "session_new",
+ });
+ await expect(
+ started.sandbox.run({ command: 'cat notes.txt && echo "$GREETING"' }),
+ ).resolves.toMatchObject({ exitCode: 0, stdout: "from the template\nhello\n" });
+
+ const resumed = await provider.openSession({
+ appRoot,
+ existing: { rootPath: sessionRoot, version: 2 },
+ prepared: { templateKey },
+ sandboxName: "session_golden",
+ });
+ await expect(resumed.sandbox.readTextFile({ path: "kept.txt" })).resolves.toBe("kept\n");
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts
deleted file mode 100644
index 729be72b5..000000000
--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.integration.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { access, mkdtemp, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-import { describe, expect, it, vi } from "vitest";
-
-import {
- createJustBashHandle,
- type BashSandbox,
-} from "#execution/sandbox/bindings/just-bash-runtime.js";
-
-describe("just-bash sandbox deletion", () => {
- it("disposes the interpreter and removes the session root", async () => {
- const rootPath = await mkdtemp(join(tmpdir(), "eve-just-bash-delete-"));
- await writeFile(join(rootPath, "state.txt"), "persisted");
- const dispose = vi.fn(async () => {});
- const sandbox = {
- captureState: vi.fn(async () => ({ rootPath })),
- dispose,
- readFileBytes: vi.fn(async () => null),
- removePath: vi.fn(async () => {}),
- rootPath,
- sessionKey: "session-key",
- async spawn() {
- throw new Error("spawn is not used by this test");
- },
- writeFiles: vi.fn(async () => {}),
- } satisfies BashSandbox;
- const handle = createJustBashHandle(sandbox);
-
- await handle.onSandboxDelete();
-
- expect(dispose).toHaveBeenCalledTimes(1);
- await expect(access(rootPath)).rejects.toMatchObject({ code: "ENOENT" });
- });
-});
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
index 58b0f63cf..9e4abcbd0 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash-runtime.ts
@@ -1,29 +1,22 @@
-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
-import type { IFileSystem } from "just-bash";
-
-import {
- createFileBackedInternalSandboxSession,
- pathExists,
-} from "#execution/sandbox/bindings/local-provider-utils.js";
+import { pathExists } from "#execution/sandbox/bindings/local-provider-utils.js";
import { adaptMultiplexedCommandToSandboxProcess } from "#execution/sandbox/multiplexed-command.js";
import { shellQuote } from "#execution/sandbox/shell-quote.js";
-import { buildSandboxSession, SANDBOX_AGENT_ENV } from "#execution/sandbox/session.js";
-import type { SandboxProviderHandle, SandboxProviderHost } from "#shared/sandbox-provider.js";
-import type { SandboxSession } from "#shared/sandbox-session.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
+import { importOptionalEnginePackage } from "#internal/application/optional-package-import.js";
+import { loadOptionalEnginePackage } from "#internal/application/optional-package-install.js";
import type {
- SandboxProcess,
- SandboxRemovePathOptions,
- SandboxSpawnOptions,
-} from "#shared/sandbox-session.js";
+ JustBashFilesystem,
+ JustBashSandboxCreateOptions,
+} from "#public/sandbox/just-bash-sandbox.js";
+import { SANDBOX_AGENT_ENV, type SandboxConnection } from "#public/sandbox/provider.js";
+import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
+import { isObject } from "#shared/guards.js";
const LOCAL_SANDBOX_METADATA_VERSION = 1;
const LOCAL_SANDBOX_FILESYSTEM_DIRECTORY_NAME = "fs";
const LOCAL_SANDBOX_METADATA_FILE_NAME = "metadata.json";
-const JUST_BASH_PACKAGE_NAME = "just-bash";
type JustBashModule = typeof import("just-bash");
@@ -32,83 +25,72 @@ interface LocalSandboxMetadata {
readonly version: typeof LOCAL_SANDBOX_METADATA_VERSION;
}
-export interface JustBashSessionMetadata {
- readonly rootPath: string;
+/** One just-bash interpreter over a session or template root. The root's files outlive it. */
+export interface BashSandbox extends SandboxConnection {
+ /** Records the interpreter's environment, so sessions created from this template start with it. */
+ captureState(): Promise<void>;
}
-export interface BashSandbox {
- captureState(): Promise<JustBashSessionMetadata>;
- dispose(): Promise<void>;
- readFileBytes(path: string): Promise<Buffer | null>;
- removePath(options: SandboxRemovePathOptions): Promise<void>;
- readonly rootPath: string;
- readonly sessionKey: string;
- spawn(options: SandboxSpawnOptions): Promise<SandboxProcess>;
- writeFiles(files: ReadonlyArray<{ path: string; content: string | Uint8Array }>): Promise<void>;
-}
-
-let justBashModulePromise: Promise<JustBashModule> | undefined;
+/**
+ * The package is intentionally not bundled with eve — the provider is opt-in —
+ * so it loads from the application's own dependency tree.
+ */
+const JUST_BASH_PACKAGE = {
+ importModule: async () => await import("just-bash"),
+ missingMessage:
+ "The just-bash sandbox provider requires the `just-bash` package, which is not bundled " +
+ "with eve. Install it in your application (for example `pnpm add -D just-bash`), or use " +
+ "DockerSandbox or DefaultSandbox instead.",
+ packageName: "just-bash",
+};
/**
- * Loads `just-bash` from the application's own dependency tree. The
- * package is intentionally not bundled with eve — the provider is
- * opt-in — so when it is missing eve installs it into the project
- * during `eve dev` (unless `autoInstall: false`) and otherwise fails
- * with an actionable install error.
+ * Loads `just-bash` for template preparation, installing it into the project
+ * when it is missing during `eve dev` (unless `autoInstall` is false).
*/
-async function loadJustBashModule(input: {
+export async function installJustBashModule(input: {
+ readonly appRoot: string;
readonly autoInstall: boolean;
- readonly host: SandboxProviderHost;
}): Promise<JustBashModule> {
- justBashModulePromise ??= input.host
- .loadOptionalPackage<JustBashModule>({
- autoInstall: input.autoInstall,
- importModule: async () => await import("just-bash"),
- missingMessage:
- "The just-bash sandbox provider requires the `just-bash` package, which is not bundled " +
- "with eve. Install it in your application (for example `pnpm add -D just-bash`), or use " +
- "DockerSandbox or DefaultSandbox instead.",
- packageName: JUST_BASH_PACKAGE_NAME,
- ignoredOptionalDependencies: ["@mongodb-js/zstd", "node-liblzma"],
- })
- .catch((error: unknown) => {
- justBashModulePromise = undefined;
- throw error;
- });
- return await justBashModulePromise;
+ return await loadOptionalEnginePackage<JustBashModule>({
+ ...JUST_BASH_PACKAGE,
+ appRoot: input.appRoot,
+ autoInstall: input.autoInstall,
+ ignoredOptionalDependencies: ["@mongodb-js/zstd", "node-liblzma"],
+ });
+}
+
+/** Loads `just-bash` for a session without installing it. */
+export async function importJustBashModule(appRoot: string): Promise<JustBashModule> {
+ return await importOptionalEnginePackage<JustBashModule>({ ...JUST_BASH_PACKAGE, appRoot });
}
export async function createBashSandbox(input: {
- readonly autoInstall: boolean;
- readonly host: SandboxProviderHost;
readonly customCommands?: JustBashSandboxCreateOptions["customCommands"];
readonly filesystem?: JustBashSandboxCreateOptions["filesystem"];
+ readonly justBash: JustBashModule;
+ resolveProjectPath(path: string): string;
readonly rootPath: string;
- readonly sessionKey: string;
readonly storagePath: string;
}): Promise<BashSandbox> {
- const justBash = await loadJustBashModule({
- autoInstall: input.autoInstall,
- host: input.host,
- });
- const { ReadWriteFs, Sandbox } = justBash;
+ const { justBash } = input;
const filesystemRootPath = resolveLocalSandboxFilesystemRootPath(input.rootPath);
const metadataPath = resolveLocalSandboxMetadataPath(input.rootPath);
const metadata = await readLocalMetadata(metadataPath);
await mkdir(filesystemRootPath, { recursive: true });
- const defaultFilesystem = new ReadWriteFs({
+ const defaultFilesystem = new justBash.ReadWriteFs({
allowSymlinks: true,
maxFileReadSize: Number.MAX_SAFE_INTEGER,
root: filesystemRootPath,
});
- let filesystem: IFileSystem = defaultFilesystem;
+ let filesystem: JustBashFilesystem = defaultFilesystem;
if (input.filesystem !== undefined) {
try {
filesystem = await input.filesystem({
defaultFilesystem,
- resolveProjectPath: input.host.resolveProjectPath,
+ resolveProjectPath: (path) => input.resolveProjectPath(path),
storagePath: input.storagePath,
justBash,
});
@@ -117,9 +99,9 @@ export async function createBashSandbox(input: {
}
}
- await ensureLocalSandboxDirectories(filesystem);
+ await filesystem.mkdir(WORKSPACE_ROOT, { recursive: true });
- const sandbox = await Sandbox.create({
+ const sandbox = await justBash.Sandbox.create({
cwd: WORKSPACE_ROOT,
customCommands: input.customCommands === undefined ? undefined : [...input.customCommands],
env: metadata === null ? undefined : { ...metadata.env },
@@ -135,36 +117,29 @@ export async function createBashSandbox(input: {
env: { ...sandbox.bashEnvInstance.getEnv() },
version: LOCAL_SANDBOX_METADATA_VERSION,
});
- return { rootPath: input.rootPath };
- },
- async dispose() {
- await sandbox.stop();
},
- async readFileBytes(path: string): Promise<Buffer | null> {
- let bytes: Uint8Array;
+ async readFile({ path }) {
try {
- bytes = await filesystem.readFileBuffer(path);
- } catch {
- return null;
+ return await filesystem.readFileBuffer(path);
+ } catch (error) {
+ if (!(await filesystem.exists(path))) return null;
+ throw error;
}
- return Buffer.from(bytes);
},
- async removePath(options: SandboxRemovePathOptions): Promise<void> {
+ async removePath(options) {
await filesystem.rm(options.path, {
force: options.force,
recursive: options.recursive,
});
},
- rootPath: input.rootPath,
- sessionKey: input.sessionKey,
- async spawn(options: SandboxSpawnOptions): Promise<SandboxProcess> {
+ async spawn(options) {
if (options.abortSignal?.aborted) {
throw new DOMException("The operation was aborted.", "AbortError");
}
- const wrapped =
- options.workingDirectory !== undefined
- ? `( cd ${shellQuote(options.workingDirectory)} && ${options.command} )`
- : options.command;
+ // The command sits on its own lines so a trailing `# comment` cannot
+ // swallow the closing brace. `cd X || exit` would lose cd's error in
+ // just-bash, so the braces keep `&&` applying to the whole command.
+ const wrapped = `( cd ${shellQuote(options.workingDirectory)} && {\n${options.command}\n} )`;
// just-bash has no separate `bash` executable — it IS the bash
// interpreter. The `eval` builtin re-parses its single string
// argument as a shell line, which is the only way to feed an
@@ -174,6 +149,7 @@ export async function createBashSandbox(input: {
args: [wrapped],
cmd: "eval",
detached: true,
+ // just-bash has no sandbox-level environment for `SANDBOX_AGENT_ENV`, so each command gets it.
env: { ...SANDBOX_AGENT_ENV, ...options.env },
signal: options.abortSignal,
});
@@ -182,46 +158,18 @@ export async function createBashSandbox(input: {
getOutput: (log) => log.type,
});
},
- async writeFiles(files) {
+ async stop() {
+ await sandbox.stop();
+ },
+ async writeFiles({ files }) {
for (const file of files) {
- const dir = dirname(file.path);
- await filesystem.mkdir(dir, { recursive: true });
- // Preserve Buffer content byte-for-byte so binary assets (for
- // example images under a skill's `assets/` directory) survive
- // the write. `Buffer` is a `Uint8Array` subclass, which the
- // just-bash filesystem accepts directly alongside strings.
+ await filesystem.mkdir(dirname(file.path), { recursive: true });
await filesystem.writeFile(file.path, file.content);
}
},
};
}
-/**
- * The just-bash engine cannot honor a run-time network policy: just-bash takes
- * its `NetworkConfig` only at sandbox creation (no live update) and runs no
- * `git` or other binaries, so credential brokering has nothing to act on.
- * Throw rather than silently no-op so brokering code surfaces the gap instead
- * of leaking.
- */
-export function createJustBashHandle(sandbox: BashSandbox): SandboxProviderHandle<SandboxSession> {
- const session = buildSandboxSession(createFileBackedInternalSandboxSession({ sandbox }));
- return {
- sandbox: session,
- async onSandboxDelete() {
- await sandbox.dispose();
- await rm(sandbox.rootPath, { force: true, recursive: true });
- },
- async onSandboxStop() {
- await sandbox.dispose();
- },
- // The interpreter lives in this process, so stopping it is all the
- // shutdown a just-bash sandbox needs.
- async onRuntimeShutdown() {
- await sandbox.dispose();
- },
- };
-}
-
function resolveLocalSandboxFilesystemRootPath(rootPath: string): string {
return `${rootPath}/${LOCAL_SANDBOX_FILESYSTEM_DIRECTORY_NAME}`;
}
@@ -230,12 +178,6 @@ function resolveLocalSandboxMetadataPath(rootPath: string): string {
return `${rootPath}/${LOCAL_SANDBOX_METADATA_FILE_NAME}`;
}
-async function ensureLocalSandboxDirectories(filesystem: IFileSystem): Promise<void> {
- await filesystem.mkdir(WORKSPACE_ROOT, {
- recursive: true,
- });
-}
-
async function readLocalMetadata(metadataPath: string): Promise<LocalSandboxMetadata | null> {
if (!(await pathExists(metadataPath))) {
return null;
@@ -244,7 +186,7 @@ async function readLocalMetadata(metadataPath: string): Promise<LocalSandboxMeta
const metadata: unknown = JSON.parse(await readFile(metadataPath, "utf8"));
if (
- !isRecord(metadata) ||
+ !isObject(metadata) ||
metadata.version !== LOCAL_SANDBOX_METADATA_VERSION ||
!isStringRecord(metadata.env)
) {
@@ -265,15 +207,6 @@ async function writeLocalMetadata(
await writeFile(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`);
}
-function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-
function isStringRecord(value: unknown): value is Readonly<Record<string, string>> {
- return (
- value !== null &&
- typeof value === "object" &&
- !Array.isArray(value) &&
- Object.values(value).every((entry) => typeof entry === "string")
- );
+ return isObject(value) && Object.values(value).every((entry) => typeof entry === "string");
}
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
index 0e0a7ec9d..5a3a6c19b 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.integration.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it, vi } from "vitest";
-import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/just-bash.js";
-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
+import { createSandboxEnvironmentHarness } from "#internal/testing/sandbox-provider-harness.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+import { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
vi.mock("just-bash", () => {
throw new Error("Cannot find module 'just-bash'");
@@ -10,10 +10,14 @@ vi.mock("just-bash", () => {
const createScratchDirectory = useTemporaryDirectories();
+function createJustBashProvider(options?: JustBashEnvironmentOptions) {
+ return createSandboxEnvironmentHarness(JustBashSandbox.environment(options));
+}
+
describe("just-bash provider without the optional dependency installed", () => {
it("fails with an actionable install hint outside eve dev", async () => {
const appRoot = await createScratchDirectory("eve-just-bash-missing-");
- const provider = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
+ const provider = createJustBashProvider();
await expect(
provider.openSession({
appRoot,
@@ -26,10 +30,7 @@ describe("just-bash provider without the optional dependency installed", () => {
vi.stubEnv("EVE_DEV", "1");
try {
const appRoot = await createScratchDirectory("eve-just-bash-no-autoinstall-");
- const provider = createSandboxProviderHarness(
- createJustBashSandboxProvider({ autoInstall: false }),
- undefined,
- );
+ const provider = createJustBashProvider({ autoInstall: false });
await expect(
provider.openSession({
appRoot,
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
index 8d155942d..c09336029 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts
@@ -6,9 +6,8 @@ import { decodeBytesToUtf8, defineCommand, MountableFs, ReadWriteFs } from "just
import { describe, expect, it } from "vitest";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
-import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/just-bash.js";
-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
+import { createSandboxEnvironmentHarness } from "#internal/testing/sandbox-provider-harness.js";
+import { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
import { executeBashOnSandbox } from "#execution/sandbox/bash.js";
import { executeGlobOnSandbox } from "#execution/sandbox/glob-tool.js";
import { executeGrepOnSandbox } from "#execution/sandbox/grep-tool.js";
@@ -18,8 +17,8 @@ const createScratchDirectory = useTemporaryDirectories();
// The whole file exercises the opt-in just-bash provider; the workspace
// devDependency provides the `just-bash` install that applications opt
// into explicitly.
-function createJustBashProvider(options: JustBashSandboxCreateOptions = {}) {
- return createSandboxProviderHarness(createJustBashSandboxProvider(options), undefined);
+function createJustBashProvider(options: JustBashEnvironmentOptions = {}) {
+ return createSandboxEnvironmentHarness(JustBashSandbox.environment(options));
}
async function createTemporaryCacheDirectory(label: string): Promise<string> {
@@ -298,9 +297,9 @@ describe("just-bash sandbox file API", () => {
await firstHandle.onSandboxStop();
- expect(state).toMatchObject({ version: 2 });
+ const { rootPath } = state as { readonly rootPath: string };
await expect(
- readFile(join(state.rootPath, "fs", "workspace", "persisted.txt"), "utf8"),
+ readFile(join(rootPath, "fs", "workspace", "persisted.txt"), "utf8"),
).resolves.toBe("survives reconnect");
const reconnectedHandle = await provider.openSession({
@@ -361,6 +360,47 @@ describe("just-bash sandbox file API", () => {
expect(content).toBe("relative write");
});
+ it("runs commands in any working directory, even with a trailing comment", async () => {
+ const cacheDirectory = await createTemporaryCacheDirectory("working-directory");
+ const handle = await createPrewarmedLocalHandle({
+ appRoot: cacheDirectory,
+ sandboxName: "session-working-directory",
+ });
+ await handle.sandbox.writeTextFile({ content: "nested", path: "sub/deeper/note.txt" });
+
+ await expect(handle.sandbox.run({ command: "pwd # workspace" })).resolves.toMatchObject({
+ exitCode: 0,
+ stdout: "/workspace\n",
+ });
+ await expect(
+ handle.sandbox.run({
+ command: "pwd; exit 4 # subdirectory",
+ workingDirectory: "sub/deeper/..",
+ }),
+ ).resolves.toMatchObject({ exitCode: 4, stdout: "/workspace/sub\n" });
+ await expect(
+ handle.sandbox.run({ command: "echo unreachable", workingDirectory: "missing" }),
+ ).resolves.toMatchObject({
+ exitCode: 1,
+ stderr: expect.stringContaining("/workspace/missing"),
+ stdout: "",
+ });
+ await expect(handle.sandbox.readTextFile({ path: "sub/../sub/deeper/note.txt" })).resolves.toBe(
+ "nested",
+ );
+ });
+
+ it("rejects reading a directory instead of reporting it missing", async () => {
+ const cacheDirectory = await createTemporaryCacheDirectory("file-api");
+ const handle = await createPrewarmedLocalHandle({
+ appRoot: cacheDirectory,
+ sandboxName: "session-read-directory",
+ });
+ await handle.sandbox.writeTextFile({ content: "inside", path: "folder/file.txt" });
+
+ await expect(handle.sandbox.readTextFile({ path: "folder" })).rejects.toThrow(/EISDIR/);
+ });
+
it("preserves Buffer bytes written through the public session", async () => {
const cacheDirectory = await createTemporaryCacheDirectory("file-api");
const handle = await createPrewarmedLocalHandle({
diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
index 79adde6e0..c1007e628 100644
--- a/packages/eve/src/execution/sandbox/bindings/just-bash.ts
+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.ts
@@ -5,44 +5,37 @@ import { dirname, join } from "node:path";
import {
copyDirectoryAtomically,
- createFileBackedInternalSandboxSession,
pathExists,
resolveLocalProviderSessionRootPath,
resolveLocalProviderTemplateRootPath,
resolveLocalProviderTemplatesDirectory,
touchDirectory,
- writeSandboxSeedFiles,
} from "#execution/sandbox/bindings/local-provider-utils.js";
import {
createBashSandbox,
- createJustBashHandle,
+ importJustBashModule,
+ installJustBashModule,
} from "#execution/sandbox/bindings/just-bash-runtime.js";
import {
LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,
LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,
selectStaleTemplateEntries,
} from "#execution/sandbox/bindings/local-template-prune.js";
-import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";
-import { buildSandboxSession } from "#execution/sandbox/session.js";
import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";
-import { withToolSessionSandboxes } from "#execution/tool-session/sandbox.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
-import type { SandboxSession } from "#shared/sandbox-session.js";
import {
- isSandboxPreparedArtifactRecord,
- providerResourceTargetFiles,
- sandboxProviderResourceIdentity,
- type SandboxPreparedArtifact,
- type LegacySandboxProviderImplementation,
- type SandboxProviderSessionContext,
-} from "#shared/sandbox-provider.js";
-import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";
+ SandboxSessionGoneError,
+ SandboxTemplateNotProvisionedError,
+ type SandboxJson,
+ type SandboxProviderImplementation,
+ type SandboxSessionContext,
+} from "#public/sandbox/provider.js";
+import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
+import { isObject } from "#shared/guards.js";
import {
invalidPreparedSandboxArtifactError,
invalidSandboxSessionStateError,
} from "#shared/sandbox-recorded-data-error.js";
-import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";
const JUST_BASH_CACHE_DIRECTORY_NAME = "just-bash";
export const JUST_BASH_PROVIDER_NAME = "just-bash";
@@ -52,63 +45,49 @@ type JustBashPreparedArtifact = { readonly templateKey: string };
type JustBashSessionState = { readonly rootPath: string; readonly version: 2 };
export function createJustBashSandboxProvider(
- authoredOptions: JustBashSandboxCreateOptions | undefined = undefined,
-): LegacySandboxProviderImplementation<
- undefined,
- JustBashPreparedArtifact,
- JustBashSessionState,
- SandboxSession
-> {
- const options = authoredOptions ?? {};
+ options: JustBashSandboxCreateOptions = {},
+): SandboxProviderImplementation<undefined, JustBashPreparedArtifact, JustBashSessionState, {}> {
const autoInstall = options.autoInstall ?? true;
- const environmentIdentity = {
- autoInstall,
- customCommands: options.customCommands,
- filesystem: options.filesystem,
- version: 2,
- };
- const implementation: ReturnType<typeof createJustBashSandboxProvider> = {
+ async function connect(context: SandboxSessionContext, rootPath: string) {
+ return await createBashSandbox({
+ customCommands: options.customCommands,
+ filesystem: options.filesystem,
+ justBash: await importJustBashModule(context.resolveProjectPath(".")),
+ resolveProjectPath: (path) => context.resolveProjectPath(path),
+ rootPath,
+ storagePath: context.storagePath,
+ });
+ }
+
+ return {
async onSessionEnd(context, state) {
await rm(state?.rootPath ?? sessionRootPath(context), { force: true, recursive: true });
},
async prepare(context) {
- const templateKey = createSandboxProviderIdentity({
- ...environmentIdentity,
- resources: sandboxProviderResourceIdentity(context.resources),
- sourceRevision: context.sourceRevision,
- }).slice(0, 24);
+ // Custom commands and the filesystem apply only to live sessions, so they stay out of the key.
+ const templateKey = context.templateKey({ version: 2 }).slice(0, 24);
const templateRootPath = resolveTemplateRootPath(context.storagePath, templateKey);
if (await pathExists(templateRootPath)) {
await touchDirectory(templateRootPath);
- context.log?.("reusing cached template filesystem");
+ context.log("reusing cached template filesystem");
return { templateKey };
}
const temporaryTemplateRootPath = `${templateRootPath}.${randomUUID()}.tmp`;
let published = false;
const templateSandbox = await createBashSandbox({
- autoInstall,
- host: context.host,
+ justBash: await installJustBashModule({
+ appRoot: context.resolveProjectPath("."),
+ autoInstall,
+ }),
+ resolveProjectPath: (path) => context.resolveProjectPath(path),
rootPath: temporaryTemplateRootPath,
- sessionKey: `prepare-${templateKey}`,
storagePath: context.storagePath,
});
- const templateSession = buildSandboxSession(
- createFileBackedInternalSandboxSession({ sandbox: templateSandbox }),
- );
try {
- await writeSandboxSeedFiles(
- templateSession,
- providerResourceTargetFiles(context.resources),
- );
- if (options.prepare !== undefined) {
- context.log?.("running sandbox preparation");
- await options.prepare(
- createLoggingSandboxSession({ log: context.log, session: templateSession }),
- );
- }
+ await context.populate(templateSandbox);
await templateSandbox.captureState();
await mkdir(dirname(templateRootPath), { recursive: true });
try {
@@ -119,7 +98,7 @@ export function createJustBashSandboxProvider(
throw error;
}
} finally {
- await templateSandbox.dispose();
+ await templateSandbox.stop();
if (!published) await rm(temporaryTemplateRootPath, { force: true, recursive: true });
}
return { templateKey };
@@ -129,7 +108,7 @@ export function createJustBashSandboxProvider(
if (!(await pathExists(rootPath))) {
throw new SandboxSessionGoneError(`just-bash session root "${rootPath}" no longer exists.`);
}
- return await openHandle(context, rootPath, options);
+ return await connect(context, rootPath);
},
async start(context, _openOptions, artifactValue) {
const artifact = requirePreparedJustBashArtifact(artifactValue);
@@ -138,23 +117,18 @@ export function createJustBashSandboxProvider(
resolveTemplateRootPath(context.storagePath, artifact.templateKey),
rootPath,
);
- return {
- handle: await openHandle(context, rootPath, options),
- state: { rootPath, version: 2 },
- };
+ return { connection: await connect(context, rootPath), state: { rootPath, version: 2 } };
},
+ // eve never ends a keyed sandbox; just-bash keeps it only as files on the local disk.
+ toolSessions: true,
};
- // Each handle runs its own interpreter in this process; stopping it keeps the root's files.
- return withToolSessionSandboxes(implementation, {
- releaseHandle: (handle) => handle.onSandboxStop(),
- });
}
/**
* The session's root, under the app's storage path. The template applies
* only when the root is created, so a session keeps its files across rebuilds.
*/
-function sessionRootPath(context: SandboxProviderSessionContext): string {
+function sessionRootPath(context: SandboxSessionContext): string {
return resolveSessionRootPath(
context.storagePath,
createSandboxProviderIdentity({ sessionId: context.session.id, version: 2 }).slice(0, 24),
@@ -174,23 +148,6 @@ async function ensureSessionRoot(templateRootPath: string, sessionRootPath: stri
await copyDirectoryAtomically(templateRootPath, sessionRootPath);
}
-async function openHandle(
- context: SandboxProviderSessionContext,
- rootPath: string,
- options: JustBashSandboxCreateOptions,
-) {
- const sandbox = await createBashSandbox({
- autoInstall: options.autoInstall ?? true,
- customCommands: options.customCommands,
- filesystem: options.filesystem,
- host: context.host,
- rootPath,
- sessionKey: context.session.id,
- storagePath: context.storagePath,
- });
- return createJustBashHandle(sandbox);
-}
-
export async function pruneJustBashSandboxTemplates(input: {
readonly appRoot: string;
readonly now?: number;
@@ -238,21 +195,15 @@ export async function pruneJustBashSandboxTemplates(input: {
);
}
-function requirePreparedJustBashArtifact(
- artifact: SandboxPreparedArtifact,
-): JustBashPreparedArtifact {
- if (!isSandboxPreparedArtifactRecord(artifact) || typeof artifact.templateKey !== "string") {
+function requirePreparedJustBashArtifact(artifact: SandboxJson): JustBashPreparedArtifact {
+ if (!isObject(artifact) || typeof artifact.templateKey !== "string") {
throw invalidPreparedSandboxArtifactError("just-bash sandbox");
}
return { templateKey: artifact.templateKey };
}
-function requireJustBashSessionState(state: SandboxPreparedArtifact): JustBashSessionState {
- if (
- !isSandboxPreparedArtifactRecord(state) ||
- state.version !== 2 ||
- typeof state.rootPath !== "string"
- ) {
+function requireJustBashSessionState(state: SandboxJson): JustBashSessionState {
+ if (!isObject(state) || state.version !== 2 || typeof state.rootPath !== "string") {
throw invalidSandboxSessionStateError("just-bash sandbox");
}
return { rootPath: state.rootPath, version: 2 };
diff --git a/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
index 0c1597b12..f89e0c85f 100644
--- a/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
+++ b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts
@@ -2,51 +2,14 @@ import { randomUUID } from "node:crypto";
import { access, cp, mkdir, rename, rm, utimes } from "node:fs/promises";
import { dirname, join } from "node:path";
-import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";
import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";
import { resolveSandboxModelPath } from "#shared/skill-paths.js";
+import type { SandboxSession } from "#shared/sandbox-session.js";
+
interface SandboxSeedFile {
readonly content: string | Uint8Array;
readonly path: string;
}
-import type {
- InternalSandboxSession,
- SandboxProcess,
- SandboxRemovePathOptions,
- SandboxSession,
- SandboxSpawnOptions,
-} from "#shared/sandbox-session.js";
-
-interface FileBackedSandbox {
- readFileBytes(path: string): Promise<Buffer | null>;
- removePath(options: SandboxRemovePathOptions): Promise<void>;
- spawn(options: SandboxSpawnOptions): Promise<SandboxProcess>;
- writeFiles(
- files: ReadonlyArray<{ readonly path: string; readonly content: Uint8Array }>,
- ): Promise<void>;
-}
-
-export function createFileBackedInternalSandboxSession(input: {
- readonly sandbox: FileBackedSandbox;
-}): InternalSandboxSession {
- return {
- resolvePath: resolveWorkspacePath,
- async spawn(options: SandboxSpawnOptions) {
- return await input.sandbox.spawn(options);
- },
- async readFile(options) {
- const buf = await input.sandbox.readFileBytes(options.path);
- return buf === null ? null : bufferToStream(buf);
- },
- async removePath(options: SandboxRemovePathOptions) {
- await input.sandbox.removePath(options);
- },
- async writeFile(options) {
- const buf = await streamToBuffer(options.content);
- await input.sandbox.writeFiles([{ content: buf, path: options.path }]);
- },
- };
-}
export function resolveWorkspacePath(path: string): string {
if (path.startsWith("/")) {
diff --git a/packages/eve/src/execution/sandbox/prewarm.ts b/packages/eve/src/execution/sandbox/prewarm.ts
index 4eefbf675..912a0aa9d 100644
--- a/packages/eve/src/execution/sandbox/prewarm.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.ts
@@ -24,7 +24,7 @@ import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";
import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";
-import { createDevelopmentSandboxProviderHost } from "#execution/sandbox/provider-host-development.js";
+import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";
import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
import type { RuntimeRegisteredSandbox } from "#runtime/sandbox/registry.js";
import type { SandboxPreparedArtifactEntry } from "#shared/sandbox-prepared-artifacts.js";
@@ -215,7 +215,7 @@ async function collectPrewarmTargets(input: {
targets.push({
context: {
files: createSandboxProviderFiles(sandboxRoot),
- host: createDevelopmentSandboxProviderHost(input.appRoot),
+ host: createSandboxProviderHost(input.appRoot),
resources,
sourceRevision: definition.revisionHash,
storagePath: resolveSandboxCacheDirectory(input.appRoot),
diff --git a/packages/eve/src/execution/sandbox/provider-host-development.ts b/packages/eve/src/execution/sandbox/provider-host-development.ts
deleted file mode 100644
index 2d56f7e31..000000000
--- a/packages/eve/src/execution/sandbox/provider-host-development.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { resolve } from "node:path";
-
-import { loadOptionalEnginePackage } from "#internal/application/optional-package-install.js";
-import type { SandboxProviderHost } from "#shared/sandbox-provider.js";
-
-export function createDevelopmentSandboxProviderHost(appRoot: string): SandboxProviderHost {
- return {
- async loadOptionalPackage(input) {
- return await loadOptionalEnginePackage({ appRoot, ...input });
- },
- resolveProjectPath(path) {
- return resolve(appRoot, path);
- },
- };
-}
diff --git a/packages/eve/src/execution/sandbox/provider-host.test.ts b/packages/eve/src/execution/sandbox/provider-host.test.ts
deleted file mode 100644
index e7c2090cf..000000000
--- a/packages/eve/src/execution/sandbox/provider-host.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import { importInstalledEnginePackage } from "#internal/application/optional-package-import.js";
-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";
-
-vi.mock("#internal/application/optional-package-import.js", () => ({
- importInstalledEnginePackage: vi.fn(),
-}));
-
-const mockedImportInstalledEnginePackage = vi.mocked(importInstalledEnginePackage);
-
-describe("createSandboxProviderHost", () => {
- it("loads an application-installed package after its bundled import fails", async () => {
- const loadedModule = { ok: true };
- mockedImportInstalledEnginePackage.mockResolvedValueOnce(loadedModule);
- const host = createSandboxProviderHost("/repo/app");
-
- await expect(
- host.loadOptionalPackage({
- autoInstall: true,
- importModule: async () => {
- throw new Error("bundled dependency missing");
- },
- missingMessage: "missing dependency",
- packageName: "dependency",
- }),
- ).resolves.toBe(loadedModule);
-
- expect(mockedImportInstalledEnginePackage).toHaveBeenCalledWith({
- appRoot: "/repo/app",
- packageName: "dependency",
- });
- });
-});
diff --git a/packages/eve/src/execution/sandbox/provider-host.ts b/packages/eve/src/execution/sandbox/provider-host.ts
index 3cc0f72b1..27784bc7f 100644
--- a/packages/eve/src/execution/sandbox/provider-host.ts
+++ b/packages/eve/src/execution/sandbox/provider-host.ts
@@ -1,25 +1,13 @@
import { resolve } from "node:path";
-import { importInstalledEnginePackage } from "#internal/application/optional-package-import.js";
+import { importOptionalEnginePackage } from "#internal/application/optional-package-import.js";
import type { SandboxProviderHost } from "#shared/sandbox-provider.js";
export function createSandboxProviderHost(appRoot: string): SandboxProviderHost {
return {
+ // Unused, but the extension contracts include this type; it goes with the legacy provider shape.
async loadOptionalPackage(input) {
- try {
- return await input.importModule();
- } catch (importError) {
- try {
- return await importInstalledEnginePackage({
- appRoot,
- packageName: input.packageName,
- });
- } catch (installedImportError) {
- throw new Error(input.missingMessage, {
- cause: new AggregateError([importError, installedImportError]),
- });
- }
- }
+ return await importOptionalEnginePackage({ appRoot, ...input });
},
resolveProjectPath(path) {
return resolve(appRoot, path);
diff --git a/packages/eve/src/internal/application/optional-package-import.integration.test.ts b/packages/eve/src/internal/application/optional-package-import.integration.test.ts
new file mode 100644
index 000000000..53510e9a0
--- /dev/null
+++ b/packages/eve/src/internal/application/optional-package-import.integration.test.ts
@@ -0,0 +1,36 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { importOptionalEnginePackage } from "#internal/application/optional-package-import.js";
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+describe("importOptionalEnginePackage", () => {
+ it("falls back to the application's install when eve cannot resolve the package", async () => {
+ const appRoot = await createScratchDirectory("eve-optional-import-");
+ const packageRoot = join(appRoot, "node_modules", "optional-engine");
+ await mkdir(packageRoot, { recursive: true });
+ await writeFile(
+ join(packageRoot, "package.json"),
+ JSON.stringify({ exports: "./index.js", type: "module" }),
+ );
+ await writeFile(join(packageRoot, "index.js"), 'export const engine = "from the app";\n');
+ const load = (root: string) =>
+ importOptionalEnginePackage<{ engine: string }>({
+ appRoot: root,
+ importModule: async () => {
+ throw new Error("Cannot find package 'optional-engine'");
+ },
+ missingMessage: "Install optional-engine.",
+ packageName: "optional-engine",
+ });
+
+ await expect(load(appRoot)).resolves.toMatchObject({ engine: "from the app" });
+ await expect(load(await createScratchDirectory("eve-optional-missing-"))).rejects.toThrow(
+ "Install optional-engine.",
+ );
+ });
+});
diff --git a/packages/eve/src/internal/application/optional-package-import.ts b/packages/eve/src/internal/application/optional-package-import.ts
index 9e03d9e91..f33fbc225 100644
--- a/packages/eve/src/internal/application/optional-package-import.ts
+++ b/packages/eve/src/internal/application/optional-package-import.ts
@@ -12,6 +12,29 @@ export async function importInstalledEnginePackage<T>(input: {
return (await import(entrypointHref)) as T;
}
+/**
+ * Loads an optional engine without installing it: from eve's own resolution
+ * first, then from the application. Fails with `missingMessage`.
+ */
+export async function importOptionalEnginePackage<T>(input: {
+ readonly appRoot: string;
+ readonly importModule: () => Promise<T>;
+ readonly missingMessage: string;
+ readonly packageName: string;
+}): Promise<T> {
+ try {
+ return await input.importModule();
+ } catch (importError) {
+ try {
+ return await importInstalledEnginePackage<T>(input);
+ } catch (installedImportError) {
+ throw new Error(input.missingMessage, {
+ cause: new AggregateError([importError, installedImportError]),
+ });
+ }
+ }
+}
+
export async function resolveInstalledEnginePackageEntrypointHref(input: {
readonly appRoot: string;
readonly packageName: string;
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts
index 1b440d0f6..68c0545be 100644
--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts
+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.ts
@@ -1,11 +1,8 @@
const PRUNED_LOCAL_SANDBOX_MODULE_ID = "\0eve-pruned-local-sandbox-providers";
const PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID = "\0eve-pruned-local-sandbox-provider-constructors";
-const PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID = "\0eve-pruned-optional-engine-install";
const LOCAL_BINDING_SOURCE_RE = /[/\\]bindings[/\\](?:docker|just-bash|local)\.(?:js|ts)$/;
const LOCAL_PROVIDER_SOURCE_RE =
/(?:^|[/\\#])sandbox[/\\]providers[/\\](?:docker|just-bash)\.(?:js|ts)$/;
-const OPTIONAL_ENGINE_INSTALL_SOURCE_RE =
- /[/\\]internal[/\\]application[/\\]optional-package-install\.(?:js|ts)$/;
interface BundlerPluginShape {
readonly enforce?: "pre";
@@ -31,21 +28,6 @@ export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {
name: "eve-hosted-sandbox-provider-prune",
load(id) {
const sourcePath = id.split(/[?#]/u, 1)[0] ?? id;
- if (
- id === PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID ||
- OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(sourcePath)
- ) {
- return [
- "function pruned() {",
- ' throw new Error("Optional local sandbox engines cannot be installed in hosted server runtimes.");',
- "}",
- "export const detectProjectPackageManager = pruned;",
- "export const importInstalledEnginePackage = pruned;",
- "export const installPackageIntoProject = pruned;",
- "export const loadOptionalEnginePackage = pruned;",
- "",
- ].join("\n");
- }
if (
id === PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID ||
LOCAL_PROVIDER_SOURCE_RE.test(sourcePath)
@@ -86,9 +68,6 @@ export function createCompiledSandboxProviderPrunePlugin(): BundlerPluginShape {
if (LOCAL_PROVIDER_SOURCE_RE.test(sourcePath)) {
return PRUNED_LOCAL_SANDBOX_PROVIDER_MODULE_ID;
}
- if (OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(sourcePath)) {
- return PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID;
- }
if (!LOCAL_BINDING_SOURCE_RE.test(sourcePath)) return null;
return PRUNED_LOCAL_SANDBOX_MODULE_ID;
},
diff --git a/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.test.ts b/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.test.ts
index 7d8c5fc34..5765e8c98 100644
--- a/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.test.ts
+++ b/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.test.ts
@@ -17,4 +17,16 @@ describe("createDevelopmentRuntimePrunePlugin", () => {
);
}
});
+
+ it("prunes the optional engine installer from production graphs", () => {
+ const plugin = createDevelopmentRuntimePrunePlugin();
+ for (const path of [
+ "/repo/packages/eve/dist/src/internal/application/optional-package-install.js",
+ "#internal/application/optional-package-install.js",
+ ]) {
+ const id = plugin.resolveId?.(path);
+ if (id === null || id === undefined) throw new Error("Expected a pruned module id.");
+ expect(plugin.load?.(id)).toContain("export const loadOptionalEnginePackage = pruned;");
+ }
+ });
});
diff --git a/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.ts b/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.ts
index 3bcdb3062..c3fc81eb7 100644
--- a/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.ts
+++ b/packages/eve/src/internal/nitro/host/development-runtime-prune-plugin.ts
@@ -1,6 +1,9 @@
const PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID = "\0eve-pruned-development-lazy-prewarm";
const DEVELOPMENT_LAZY_PREWARM_SOURCE_RE =
/(?:^|[/\\#])execution[/\\]sandbox[/\\]development-lazy-prewarm\.(?:js|ts)(?:[?#].*)?$/;
+const PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID = "\0eve-pruned-optional-engine-install";
+const OPTIONAL_ENGINE_INSTALL_SOURCE_RE =
+ /(?:^|[/\\#])internal[/\\]application[/\\]optional-package-install\.(?:js|ts)(?:[?#].*)?$/;
interface BundlerPluginShape {
readonly enforce: "pre";
@@ -9,20 +12,43 @@ interface BundlerPluginShape {
resolveId?(source: string): string | null;
}
-/** Removes development-only lazy sandbox preparation from every hosted runtime bundle. */
+/**
+ * Removes development-only lazy sandbox preparation, and the optional engine
+ * installer only preparation uses, from every production runtime bundle.
+ */
export function createDevelopmentRuntimePrunePlugin(): BundlerPluginShape {
return {
enforce: "pre",
name: "eve-hosted-development-runtime-prune",
load(id) {
- return id === PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID
- ? "export async function ensureDevelopmentSandboxesPrepared() {}\n"
- : null;
+ if (id === PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID) {
+ return "export async function ensureDevelopmentSandboxesPrepared() {}\n";
+ }
+ if (
+ id === PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID ||
+ OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(id)
+ ) {
+ return [
+ "function pruned() {",
+ ' throw new Error("Optional local sandbox engines cannot be installed in production server runtimes.");',
+ "}",
+ "export const detectProjectPackageManager = pruned;",
+ "export const importInstalledEnginePackage = pruned;",
+ "export const installPackageIntoProject = pruned;",
+ "export const loadOptionalEnginePackage = pruned;",
+ "",
+ ].join("\n");
+ }
+ return null;
},
resolveId(source) {
- return DEVELOPMENT_LAZY_PREWARM_SOURCE_RE.test(source)
- ? PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID
- : null;
+ if (DEVELOPMENT_LAZY_PREWARM_SOURCE_RE.test(source)) {
+ return PRUNED_DEVELOPMENT_LAZY_PREWARM_MODULE_ID;
+ }
+ if (OPTIONAL_ENGINE_INSTALL_SOURCE_RE.test(source)) {
+ return PRUNED_OPTIONAL_ENGINE_INSTALL_MODULE_ID;
+ }
+ return null;
},
};
}
diff --git a/packages/eve/src/internal/testing/sandbox-provider-harness.ts b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
index ba2693eea..0c1bd20f7 100644
--- a/packages/eve/src/internal/testing/sandbox-provider-harness.ts
+++ b/packages/eve/src/internal/testing/sandbox-provider-harness.ts
@@ -8,6 +8,18 @@ import {
type SandboxProviderResourceFile,
} from "#shared/sandbox-provider.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
+import {
+ getSandboxEnvironmentRuntime,
+ type SandboxEnvironmentIdentity,
+} from "#shared/sandbox-environment.js";
+
+/** A harness over the provider implementation an environment carries. */
+export function createSandboxEnvironmentHarness(environment: SandboxEnvironmentIdentity) {
+ return createSandboxProviderHarness(
+ getSandboxEnvironmentRuntime(environment).implementation,
+ undefined,
+ );
+}
export function createSandboxProviderHarness<
Options extends object | undefined,
diff --git a/packages/eve/src/public/sandbox/just-bash-sandbox.ts b/packages/eve/src/public/sandbox/just-bash-sandbox.ts
index c1c0eb45c..1b818ef79 100644
--- a/packages/eve/src/public/sandbox/just-bash-sandbox.ts
+++ b/packages/eve/src/public/sandbox/just-bash-sandbox.ts
@@ -1,5 +1,92 @@
-import type { CustomCommand, IFileSystem } from "just-bash";
-import type { SandboxSession } from "#shared/sandbox-session.js";
+/**
+ * The filesystem a just-bash interpreter runs on. just-bash's own filesystems,
+ * such as `ReadWriteFs`, `OverlayFs`, and `MountableFs`, satisfy it.
+ */
+export interface JustBashFilesystem {
+ readFile(
+ path: string,
+ options?: { encoding?: JustBashEncoding | null } | JustBashEncoding,
+ ): Promise<string>;
+ readFileBuffer(path: string): Promise<Uint8Array>;
+ writeFile(
+ path: string,
+ content: string | Uint8Array,
+ options?: { encoding?: JustBashEncoding } | JustBashEncoding,
+ ): Promise<void>;
+ appendFile(
+ path: string,
+ content: string | Uint8Array,
+ options?: { encoding?: JustBashEncoding } | JustBashEncoding,
+ ): Promise<void>;
+ exists(path: string): Promise<boolean>;
+ stat(path: string): Promise<JustBashFileStat>;
+ lstat(path: string): Promise<JustBashFileStat>;
+ mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;
+ readdir(path: string): Promise<string[]>;
+ readdirWithFileTypes?(path: string): Promise<JustBashDirectoryEntry[]>;
+ rm(path: string, options?: { force?: boolean; recursive?: boolean }): Promise<void>;
+ cp(source: string, destination: string, options?: { recursive?: boolean }): Promise<void>;
+ mv(source: string, destination: string): Promise<void>;
+ resolvePath(base: string, path: string): string;
+ getAllPaths(): string[];
+ chmod(path: string, mode: number): Promise<void>;
+ symlink(target: string, linkPath: string): Promise<void>;
+ link(existingPath: string, newPath: string): Promise<void>;
+ readlink(path: string): Promise<string>;
+ realpath(path: string): Promise<string>;
+ utimes(path: string, accessTime: Date, modificationTime: Date): Promise<void>;
+}
+
+type JustBashEncoding = "ascii" | "base64" | "binary" | "hex" | "latin1" | "utf-8" | "utf8";
+
+export interface JustBashFileStat {
+ isDirectory: boolean;
+ isFile: boolean;
+ isSymbolicLink: boolean;
+ mode: number;
+ mtime: Date;
+ size: number;
+}
+
+export interface JustBashDirectoryEntry {
+ isDirectory: boolean;
+ isFile: boolean;
+ isSymbolicLink: boolean;
+ name: string;
+}
+
+/**
+ * A command registered in each live just-bash interpreter. just-bash's
+ * `defineCommand()` returns one; use it when a command needs the rest of
+ * just-bash's command context, such as standard input or `exec`.
+ */
+export interface JustBashCommand {
+ readonly name: string;
+ /** Runs the command with direct access to Node.js globals, as `defineCommand()` does. */
+ readonly trusted?: boolean;
+ execute(args: string[], context: JustBashCommandContext): Promise<JustBashCommandResult>;
+}
+
+/** A command that just-bash loads on its first run. */
+export interface JustBashLazyCommand {
+ readonly name: string;
+ load(): Promise<JustBashCommand>;
+}
+
+export type JustBashCustomCommand = JustBashCommand | JustBashLazyCommand;
+
+export interface JustBashCommandContext {
+ readonly cwd: string;
+ readonly env: ReadonlyMap<string, string>;
+ readonly fs: JustBashFilesystem;
+ readonly signal?: AbortSignal;
+}
+
+export interface JustBashCommandResult {
+ readonly exitCode: number;
+ readonly stderr: string;
+ readonly stdout: string;
+}
/**
* Context passed to a custom just-bash filesystem factory for each live handle.
@@ -10,7 +97,7 @@ export interface JustBashFilesystemContext {
/** Stable provider-private storage directory for this sandbox. */
readonly storagePath: string;
/** eve's durable, session-owned filesystem, including `/workspace`. */
- readonly defaultFilesystem: IFileSystem;
+ readonly defaultFilesystem: JustBashFilesystem;
/** The just-bash engine resolved by eve after its optional installation check. */
readonly justBash: typeof import("just-bash");
}
@@ -41,7 +128,7 @@ export interface JustBashSandboxCreateOptions {
* are responsible for validating their own inputs and cleaning up host
* resources.
*/
- readonly customCommands?: ReadonlyArray<CustomCommand>;
+ readonly customCommands?: ReadonlyArray<JustBashCustomCommand>;
/**
* Composes the filesystem used by each live sandbox handle. The factory is
* called when a handle opens with eve's durable default filesystem; return a
@@ -52,7 +139,7 @@ export interface JustBashSandboxCreateOptions {
* a compatible `just-bash` version. It is not invoked during template
* preparation.
*/
- readonly filesystem?: (context: JustBashFilesystemContext) => IFileSystem | Promise<IFileSystem>;
- /** Idempotent setup captured in the prepared virtual filesystem. */
- readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
+ readonly filesystem?: (
+ context: JustBashFilesystemContext,
+ ) => JustBashFilesystem | Promise<JustBashFilesystem>;
}
diff --git a/packages/eve/src/public/sandbox/just-bash.ts b/packages/eve/src/public/sandbox/just-bash.ts
index 68f10c4af..51d83d4bf 100644
--- a/packages/eve/src/public/sandbox/just-bash.ts
+++ b/packages/eve/src/public/sandbox/just-bash.ts
@@ -1,2 +1,12 @@
export { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
-export type { JustBashFilesystemContext } from "#public/sandbox/just-bash-sandbox.js";
+export type {
+ JustBashCommand,
+ JustBashCommandContext,
+ JustBashCommandResult,
+ JustBashCustomCommand,
+ JustBashDirectoryEntry,
+ JustBashFileStat,
+ JustBashFilesystem,
+ JustBashFilesystemContext,
+ JustBashLazyCommand,
+} from "#public/sandbox/just-bash-sandbox.js";
diff --git a/packages/eve/src/sandbox/providers/default.ts b/packages/eve/src/sandbox/providers/default.ts
index f29c8d184..a220080f7 100644
--- a/packages/eve/src/sandbox/providers/default.ts
+++ b/packages/eve/src/sandbox/providers/default.ts
@@ -7,7 +7,6 @@ import {
} from "#execution/tool-session/sandbox.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import type { DockerSandboxEnvironmentOptions } from "#public/sandbox/docker-sandbox.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
import {
type SandboxSessionEndWithArtifact,
@@ -15,7 +14,7 @@ import {
withSessionEndArtifact,
} from "#sandbox/state.js";
import { DockerSandbox } from "#sandbox/providers/docker.js";
-import { JustBashSandbox } from "#sandbox/providers/just-bash.js";
+import { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";
import { VercelSandbox } from "#sandbox/providers/vercel.js";
import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";
import type {
@@ -35,7 +34,7 @@ import type { SandboxSession } from "#shared/sandbox-session.js";
export interface DefaultSandboxEnvironmentOptions {
readonly docker?: DockerSandboxEnvironmentOptions;
- readonly justBash?: JustBashSandboxCreateOptions;
+ readonly justBash?: JustBashEnvironmentOptions;
readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;
readonly vercel?: VercelSandboxCreateOptions;
}
diff --git a/packages/eve/src/sandbox/providers/just-bash.ts b/packages/eve/src/sandbox/providers/just-bash.ts
index abab78ac0..e017a8914 100644
--- a/packages/eve/src/sandbox/providers/just-bash.ts
+++ b/packages/eve/src/sandbox/providers/just-bash.ts
@@ -1,17 +1,14 @@
import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/local.js";
import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";
+import { defineSandboxProvider, type WithPrepareOption } from "#public/sandbox/provider.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
-export type JustBashEnvironmentOptions = JustBashSandboxCreateOptions;
-
-export const JustBashSandbox = defineLegacySandboxProvider<
- JustBashEnvironmentOptions,
- undefined,
- { readonly templateKey: string },
- { readonly rootPath: string; readonly version: 2 },
+export type JustBashEnvironmentOptions = WithPrepareOption<
+ JustBashSandboxCreateOptions,
SandboxSession
->({
+>;
+
+export const JustBashSandbox = defineSandboxProvider({
name: "just-bash",
- environment: (options) => createJustBashSandboxProvider(options),
+ environment: (options: JustBashSandboxCreateOptions) => createJustBashSandboxProvider(options),
});
diff --git a/packages/eve/src/self-modification/filesystem.ts b/packages/eve/src/self-modification/filesystem.ts
index dafe6c32f..7f1f07fb5 100644
--- a/packages/eve/src/self-modification/filesystem.ts
+++ b/packages/eve/src/self-modification/filesystem.ts
@@ -1,15 +1,16 @@
import { mkdir } from "node:fs/promises";
import { resolve } from "node:path";
-import type { IFileSystem } from "just-bash";
import { getLocalDevCapability } from "eve/local-dev";
+import type { JustBashFilesystem } from "#public/sandbox/just-bash-sandbox.js";
+
export async function createSelfModificationFilesystem(input: {
readonly appRoot?: string;
- readonly defaultFilesystem: IFileSystem;
+ readonly defaultFilesystem: JustBashFilesystem;
resolveProjectPath?(path: string): string;
readonly justBash: typeof import("just-bash");
-}): Promise<IFileSystem> {
+}): Promise<JustBashFilesystem> {
const capability = getLocalDevCapability();
if (capability === undefined) {
throw new Error(
diff --git a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
index 1193a711a..0a4e246eb 100644
--- a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
+++ b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts
@@ -7,11 +7,11 @@ import { discoverAgent } from "../../src/discover/discover-agent.js";
import { resolveDiscoveryProject } from "../../src/discover/project.js";
// The just-bash engine keeps this scenario hermetic (no Docker daemon
// requirement); the workspace devDependency provides the install.
-import { createJustBashSandboxProvider } from "../../src/execution/sandbox/bindings/just-bash.js";
-import { createSandboxProviderHarness } from "../../src/internal/testing/sandbox-provider-harness.js";
+import { createSandboxEnvironmentHarness } from "../../src/internal/testing/sandbox-provider-harness.js";
import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";
import { SANDBOX_WORKSPACES_DESCRIPTOR } from "../../src/internal/testing/scenario-apps/sandbox-workspaces.js";
import { materializeWorkspaceDirectory } from "../../src/runtime/workspace/seed-files.js";
+import { JustBashSandbox } from "../../src/sandbox/providers/just-bash.js";
import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";
const scenarioApp = useScenarioApp();
@@ -37,7 +37,7 @@ describe("sandbox workspace folder convention", () => {
);
const appRoot = await createScratchDirectory("eve-sandbox-workspace-folders-");
- const backend = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
+ const backend = createSandboxEnvironmentHarness(JustBashSandbox.environment());
await backend.prepare({
appRoot,
@@ -69,7 +69,7 @@ describe("sandbox workspace folder convention", () => {
it("opens an empty prewarmed template when the sandbox has no authored workspace files", async () => {
const appRoot = await createScratchDirectory("eve-sandbox-no-workspace-");
- const backend = createSandboxProviderHarness(createJustBashSandboxProvider(), undefined);
+ const backend = createSandboxEnvironmentHarness(JustBashSandbox.environment());
await backend.prepare({
appRoot,