Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add sandbox lifecycle create option (#1404)

Matt Brockmanf90f35dbc418
diff --git a/.changeset/loud-sandboxes-pause.md b/.changeset/loud-sandboxes-pause.md
new file mode 100644
index 000000000..c0ad886da
--- /dev/null
+++ b/.changeset/loud-sandboxes-pause.md
@@ -0,0 +1,5 @@
+---
+"@e2b/cli": patch
+---
+
+Add `--lifecycle.ontimeout`, `--lifecycle.autoresume`, and `--timeout` support to `e2b sandbox create`.
diff --git a/packages/cli/src/commands/sandbox/create.ts b/packages/cli/src/commands/sandbox/create.ts
index 3205f8220..6cf856e55 100644
--- a/packages/cli/src/commands/sandbox/create.ts
+++ b/packages/cli/src/commands/sandbox/create.ts
@@ -11,6 +11,13 @@ import fs from 'fs'
import { configOption, pathOption } from '../../options'
import { printDashboardSandboxInspectUrl } from 'src/utils/urls'
+type SandboxLifecycle = {
+ onTimeout: 'pause' | 'kill'
+ autoResume?: boolean
+}
+
+const MIN_TIMEOUT_MS = 30_000
+
export function createCommand(
name: string,
alias: string,
@@ -25,6 +32,16 @@ export function createCommand(
.addOption(pathOption)
.addOption(configOption)
.option('-d, --detach', 'create sandbox without connecting terminal to it')
+ .option(
+ '--lifecycle.ontimeout <action>',
+ 'action when sandbox timeout is reached: pause or kill',
+ parseOnTimeout
+ )
+ .option(
+ '--lifecycle.autoresume',
+ 'enable sandbox auto-resume, requires --lifecycle.ontimeout pause'
+ )
+ .option('--timeout <seconds>', 'sandbox timeout in seconds', parseTimeout)
.alias(alias)
.action(
async (
@@ -34,6 +51,9 @@ export function createCommand(
path?: string
config?: string
detach?: boolean
+ 'lifecycle.ontimeout'?: SandboxLifecycle['onTimeout']
+ 'lifecycle.autoresume'?: boolean
+ timeout?: number
}
) => {
if (deprecated) {
@@ -72,11 +92,24 @@ export function createCommand(
templateID = 'base'
}
- const sandbox = await e2b.Sandbox.create(templateID, { apiKey })
+ const lifecycle = buildLifecycle(
+ opts['lifecycle.ontimeout'],
+ opts['lifecycle.autoresume']
+ )
+ const sandboxOpts = {
+ apiKey,
+ ...(lifecycle ? { lifecycle } : {}),
+ ...(opts.timeout !== undefined ? { timeoutMs: opts.timeout } : {}),
+ }
+ const sandbox = await e2b.Sandbox.create(templateID, sandboxOpts)
printDashboardSandboxInspectUrl(sandbox.sandboxId)
if (!opts.detach) {
- await connectSandbox({ sandbox, template: { templateID } })
+ await connectSandbox({
+ sandbox,
+ template: { templateID },
+ timeoutMs: opts.timeout,
+ })
} else {
console.log(
`Sandbox created with ID ${sandbox.sandboxId} using template ${templateID}`
@@ -91,17 +124,69 @@ export function createCommand(
)
}
+function parseTimeout(timeoutRaw: string): number {
+ const timeoutSeconds = Number(timeoutRaw)
+ const timeoutMs = Math.floor(timeoutSeconds * 1000)
+ if (
+ !Number.isFinite(timeoutSeconds) ||
+ timeoutSeconds <= 0 ||
+ timeoutMs < MIN_TIMEOUT_MS
+ ) {
+ throw new commander.InvalidArgumentError(
+ '--timeout must be at least 30 seconds'
+ )
+ }
+
+ return timeoutMs
+}
+
+function parseOnTimeout(onTimeout: string): SandboxLifecycle['onTimeout'] {
+ if (onTimeout !== 'pause' && onTimeout !== 'kill') {
+ throw new commander.InvalidArgumentError(
+ '--lifecycle.ontimeout must be "pause" or "kill"'
+ )
+ }
+
+ return onTimeout
+}
+
+function buildLifecycle(
+ onTimeout: SandboxLifecycle['onTimeout'] | undefined,
+ autoResume: boolean | undefined
+): SandboxLifecycle | undefined {
+ if (!onTimeout && !autoResume) {
+ return undefined
+ }
+
+ if (autoResume && onTimeout !== 'pause') {
+ throw new commander.InvalidArgumentError(
+ '--lifecycle.autoresume requires --lifecycle.ontimeout pause'
+ )
+ }
+
+ if (!onTimeout) {
+ throw new commander.InvalidArgumentError(
+ '--lifecycle.ontimeout is required when using --lifecycle.autoresume'
+ )
+ }
+
+ return { onTimeout, ...(autoResume ? { autoResume: true } : {}) }
+}
+
export async function connectSandbox({
sandbox,
template,
+ timeoutMs,
}: {
sandbox: e2b.Sandbox
template: Pick<e2b.components['schemas']['Template'], 'templateID'>
+ timeoutMs?: number
}) {
// keep-alive loop — track the in-flight promise so we can await it on shutdown
let pendingKeepAlive: Promise<void> = Promise.resolve()
+ const keepAliveTimeoutMs = timeoutMs ?? 30_000
const intervalId = setInterval(() => {
- pendingKeepAlive = sandbox.setTimeout(30_000)
+ pendingKeepAlive = sandbox.setTimeout(keepAliveTimeoutMs)
}, 5_000)
console.log(
@@ -114,7 +199,7 @@ export async function connectSandbox({
} finally {
clearInterval(intervalId)
await pendingKeepAlive.catch(() => {})
- await sandbox.setTimeout(1_000)
+ await sandbox.setTimeout(timeoutMs ?? 1_000)
console.log(
`Closing terminal connection to template ${asFormattedSandboxTemplate(
template
diff --git a/packages/cli/tests/commands/sandbox/create_lifecycle.test.ts b/packages/cli/tests/commands/sandbox/create_lifecycle.test.ts
new file mode 100644
index 000000000..d4200f0cb
--- /dev/null
+++ b/packages/cli/tests/commands/sandbox/create_lifecycle.test.ts
@@ -0,0 +1,264 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => {
+ const create = vi.fn()
+ const ensureAPIKey = vi.fn(() => 'test-api-key')
+ const spawnConnectedTerminal = vi.fn()
+
+ return {
+ create,
+ ensureAPIKey,
+ spawnConnectedTerminal,
+ }
+})
+
+vi.mock('e2b', () => ({
+ Sandbox: {
+ create: mocks.create,
+ },
+}))
+
+vi.mock('../../../src/api', () => ({
+ ensureAPIKey: mocks.ensureAPIKey,
+}))
+
+vi.mock('src/utils/urls', () => ({
+ printDashboardSandboxInspectUrl: vi.fn(),
+}))
+
+vi.mock('src/terminal', () => ({
+ spawnConnectedTerminal: mocks.spawnConnectedTerminal,
+}))
+
+describe('sandbox create lifecycle options', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+
+ mocks.create.mockResolvedValue({
+ sandboxId: 'sandbox-id',
+ setTimeout: vi.fn().mockResolvedValue(undefined),
+ })
+ mocks.spawnConnectedTerminal.mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ test('passes ontimeout and autoresume to Sandbox.create', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ [
+ 'base',
+ '--detach',
+ '--lifecycle.ontimeout',
+ 'pause',
+ '--lifecycle.autoresume',
+ ],
+ { from: 'user' }
+ )
+
+ expect(mocks.create).toHaveBeenCalledWith('base', {
+ apiKey: 'test-api-key',
+ lifecycle: {
+ onTimeout: 'pause',
+ autoResume: true,
+ },
+ })
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+
+ test('passes ontimeout without autoresume to Sandbox.create', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ ['base', '--detach', '--lifecycle.ontimeout', 'kill'],
+ { from: 'user' }
+ )
+
+ expect(mocks.create).toHaveBeenCalledWith('base', {
+ apiKey: 'test-api-key',
+ lifecycle: {
+ onTimeout: 'kill',
+ },
+ })
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+
+ test('passes timeout seconds to Sandbox.create as milliseconds', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ ['base', '--detach', '--timeout', '120'],
+ { from: 'user' }
+ )
+
+ expect(mocks.create).toHaveBeenCalledWith('base', {
+ apiKey: 'test-api-key',
+ timeoutMs: 120_000,
+ })
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+
+ test('preserves explicit timeout after attached terminal closes', async () => {
+ vi.useFakeTimers()
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+ const sandbox = {
+ sandboxId: 'sandbox-id',
+ setTimeout: vi.fn().mockResolvedValue(undefined),
+ }
+ mocks.create.mockResolvedValue(sandbox)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ ['base', '--timeout', '120'],
+ { from: 'user' }
+ )
+
+ expect(mocks.spawnConnectedTerminal).toHaveBeenCalledWith(sandbox)
+ expect(sandbox.setTimeout).toHaveBeenCalledWith(120_000)
+ expect(sandbox.setTimeout).not.toHaveBeenCalledWith(1_000)
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ vi.useRealTimers()
+ })
+
+ test('rejects autoresume without pause on timeout', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ [
+ 'base',
+ '--detach',
+ '--lifecycle.ontimeout',
+ 'kill',
+ '--lifecycle.autoresume',
+ ],
+ { from: 'user' }
+ )
+
+ expect(mocks.create).not.toHaveBeenCalled()
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: '--lifecycle.autoresume requires --lifecycle.ontimeout pause',
+ })
+ )
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test('rejects invalid ontimeout option', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await expect(
+ createCommand('create', 'cr', false).parseAsync(
+ ['base', '--detach', '--lifecycle.ontimeout', 'hibernate'],
+ { from: 'user' }
+ )
+ ).rejects.toThrow('--lifecycle.ontimeout must be "pause" or "kill"')
+
+ expect(mocks.create).not.toHaveBeenCalled()
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test('rejects zero timeout before creating sandbox', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await expect(
+ createCommand('create', 'cr', false).parseAsync(
+ ['base', '--detach', '--timeout', '0'],
+ { from: 'user' }
+ )
+ ).rejects.toThrow('--timeout must be at least 30 seconds')
+
+ expect(mocks.create).not.toHaveBeenCalled()
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test('rejects timeout values shorter than the keep-alive interval', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await expect(
+ createCommand('create', 'cr', false).parseAsync(
+ ['base', '--detach', '--timeout', '29.999'],
+ { from: 'user' }
+ )
+ ).rejects.toThrow('--timeout must be at least 30 seconds')
+
+ expect(mocks.create).not.toHaveBeenCalled()
+ expect(exitSpy).toHaveBeenCalledWith(1)
+ })
+
+ test('passes lifecycle and timeout together to Sandbox.create', async () => {
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation((() => undefined) as never)
+
+ const { createCommand } = await import(
+ '../../../src/commands/sandbox/create'
+ )
+ await createCommand('create', 'cr', false).parseAsync(
+ [
+ 'base',
+ '--detach',
+ '--timeout',
+ '120',
+ '--lifecycle.ontimeout',
+ 'pause',
+ '--lifecycle.autoresume',
+ ],
+ { from: 'user' }
+ )
+
+ expect(mocks.create).toHaveBeenCalledWith('base', {
+ apiKey: 'test-api-key',
+ lifecycle: {
+ onTimeout: 'pause',
+ autoResume: true,
+ },
+ timeoutMs: 120_000,
+ })
+ expect(exitSpy).toHaveBeenCalledWith(0)
+ })
+})