Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(cli): add `e2b sandbox fork` command (#1879)

devin-ai-integration[bot]6a608ef87702
diff --git a/.changeset/cli-sandbox-fork.md b/.changeset/cli-sandbox-fork.md
new file mode 100644
index 000000000..69f865d01
--- /dev/null
+++ b/.changeset/cli-sandbox-fork.md
@@ -0,0 +1,5 @@
+---
+'@e2b/cli': minor
+---
+
+Add `e2b sandbox fork` command to fork a running sandbox into one or more new sandboxes
diff --git a/packages/cli/src/commands/sandbox/create.ts b/packages/cli/src/commands/sandbox/create.ts
index a106a3ff0..5b2356e0f 100644
--- a/packages/cli/src/commands/sandbox/create.ts
+++ b/packages/cli/src/commands/sandbox/create.ts
@@ -115,7 +115,7 @@ export function createCommand(
)
}
-function parseTimeout(timeoutRaw: string): number {
+export function parseTimeout(timeoutRaw: string): number {
const timeoutSeconds = Number(timeoutRaw)
const timeoutMs = Math.floor(timeoutSeconds * 1000)
if (
diff --git a/packages/cli/src/commands/sandbox/fork.ts b/packages/cli/src/commands/sandbox/fork.ts
new file mode 100644
index 000000000..d6880bde4
--- /dev/null
+++ b/packages/cli/src/commands/sandbox/fork.ts
@@ -0,0 +1,76 @@
+import * as commander from 'commander'
+import * as e2b from 'e2b'
+import { NotFoundError } from 'e2b'
+
+import { ensureAPIKey } from 'src/api'
+import { asBold } from 'src/utils/format'
+import { parseTimeout } from './create'
+
+const MAX_COUNT = 100
+
+function parseCount(countRaw: string): number {
+ const count = Number(countRaw)
+ if (!Number.isInteger(count) || count < 1 || count > MAX_COUNT) {
+ throw new commander.InvalidArgumentError(
+ `--count must be an integer between 1 and ${MAX_COUNT}`
+ )
+ }
+
+ return count
+}
+
+export const forkCommand = new commander.Command('fork')
+ .description(
+ 'fork running sandbox into new sandboxes and print their IDs, one per line'
+ )
+ .argument(
+ '<sandboxID>',
+ `fork the sandbox specified by ${asBold('<sandboxID>')}`
+ )
+ .alias('fk')
+ .option(
+ '-n, --count <count>',
+ `number of forks to create, at most ${MAX_COUNT} (default: 1)`,
+ parseCount
+ )
+ .option(
+ '--timeout <seconds>',
+ 'timeout of the forked sandboxes in seconds',
+ parseTimeout
+ )
+ .action(
+ async (sandboxID: string, opts: { count?: number; timeout?: number }) => {
+ try {
+ const apiKey = ensureAPIKey()
+
+ const forks = await e2b.Sandbox.fork(sandboxID, {
+ apiKey,
+ ...(opts.count !== undefined ? { count: opts.count } : {}),
+ ...(opts.timeout !== undefined ? { timeoutMs: opts.timeout } : {}),
+ })
+
+ let failed = 0
+ forks.forEach((fork, index) => {
+ if (fork instanceof Error) {
+ failed += 1
+ console.error(
+ `Fork ${asBold(String(index + 1))} of ${asBold(
+ sandboxID
+ )} failed: ${fork.message}`
+ )
+ } else {
+ console.log(fork.sandboxId)
+ }
+ })
+
+ process.exit(failed > 0 ? 1 : 0)
+ } catch (err: unknown) {
+ if (err instanceof NotFoundError) {
+ console.error(`Sandbox ${asBold(sandboxID)} wasn't found`)
+ } else {
+ console.error(err)
+ }
+ process.exit(1)
+ }
+ }
+ )
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index 82f11edcf..e79b98b01 100644
--- a/packages/cli/src/commands/sandbox/index.ts
+++ b/packages/cli/src/commands/sandbox/index.ts
@@ -11,6 +11,7 @@ import { logsCommand } from './logs'
import { metricsCommand } from './metrics'
import { execCommand } from './exec'
import { snapshotCommand } from './snapshot'
+import { forkCommand } from './fork'
export const sandboxCommand = new commander.Command('sandbox')
.description('work with sandboxes')
@@ -28,3 +29,4 @@ export const sandboxCommand = new commander.Command('sandbox')
.addCommand(metricsCommand)
.addCommand(execCommand)
.addCommand(snapshotCommand)
+ .addCommand(forkCommand)
diff --git a/packages/cli/tests/commands/sandbox/fork.test.ts b/packages/cli/tests/commands/sandbox/fork.test.ts
new file mode 100644
index 000000000..4d6b22412
--- /dev/null
+++ b/packages/cli/tests/commands/sandbox/fork.test.ts
@@ -0,0 +1,126 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => {
+ class NotFoundError extends Error {}
+
+ return {
+ fork: vi.fn(),
+ ensureAPIKey: vi.fn(() => 'test-api-key'),
+ NotFoundError,
+ }
+})
+
+vi.mock('e2b', () => ({
+ Sandbox: {
+ fork: mocks.fork,
+ },
+ NotFoundError: mocks.NotFoundError,
+}))
+
+vi.mock('../../../src/api', () => ({
+ ensureAPIKey: mocks.ensureAPIKey,
+}))
+
+async function runFork(args: string[]) {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined)
+ const errorSpy = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined)
+
+ const { forkCommand } = await import('../../../src/commands/sandbox/fork')
+ await forkCommand.exitOverride().parseAsync(args, { from: 'user' })
+
+ return { exitSpy, logSpy, errorSpy }
+}
+
+describe('sandbox fork', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ test('forks once by default and prints the new sandbox ID', async () => {
+ mocks.fork.mockResolvedValue([{ sandboxId: 'fork-1' }])
+
+ const { exitSpy, logSpy } = await runFork(['source-id'])
+
+ expect(mocks.fork).toHaveBeenCalledWith('source-id', {
+ apiKey: 'test-api-key',
+ })
+ expect(logSpy).toHaveBeenCalledTimes(1)
+ expect(logSpy).toHaveBeenCalledWith('fork-1')
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+
+ test('passes count and timeout seconds as milliseconds', async () => {
+ mocks.fork.mockResolvedValue([
+ { sandboxId: 'fork-1' },
+ { sandboxId: 'fork-2' },
+ ])
+
+ const { exitSpy, logSpy } = await runFork([
+ 'source-id',
+ '--count',
+ '2',
+ '--timeout',
+ '120',
+ ])
+
+ expect(mocks.fork).toHaveBeenCalledWith('source-id', {
+ apiKey: 'test-api-key',
+ count: 2,
+ timeoutMs: 120_000,
+ })
+ expect(logSpy.mock.calls.map(([line]: unknown[]) => line)).toEqual([
+ 'fork-1',
+ 'fork-2',
+ ])
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+
+ test('prints successful forks and exits 1 when any fork fails', async () => {
+ const failure = new Error('rate limited')
+ mocks.fork.mockResolvedValue([{ sandboxId: 'fork-1' }, failure])
+
+ const { exitSpy, logSpy, errorSpy } = await runFork([
+ 'source-id',
+ '-n',
+ '2',
+ ])
+
+ expect(logSpy).toHaveBeenCalledWith('fork-1')
+ expect(errorSpy).toHaveBeenCalledTimes(1)
+ const [message] = errorSpy.mock.calls[0] as [string]
+ expect(message).toContain('2')
+ expect(message).toContain('source-id')
+ expect(message).toContain('failed: rate limited')
+ expect(message).not.toContain('at ')
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test('reports a missing source sandbox', async () => {
+ mocks.fork.mockRejectedValue(new mocks.NotFoundError('not found'))
+
+ const { exitSpy, errorSpy } = await runFork(['missing-id'])
+
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('missing-id'))
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test.each(['0', '101', '1.5', 'abc'])(
+ 'rejects count %s',
+ async (count: string) => {
+ await expect(runFork(['source-id', '--count', count])).rejects.toThrow(
+ '--count must be an integer between 1 and 100'
+ )
+ expect(mocks.fork).not.toHaveBeenCalled()
+ }
+ )
+})