Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(cli): pass options after the command through to the remote command in sandbox exec (#1759)

devin-ai-integration[bot]587c15fffb28
diff --git a/.changeset/cli-exec-passthrough-options.md b/.changeset/cli-exec-passthrough-options.md
new file mode 100644
index 000000000..cb959975b
--- /dev/null
+++ b/.changeset/cli-exec-passthrough-options.md
@@ -0,0 +1,5 @@
+---
+'@e2b/cli': patch
+---
+
+Pass flags following the command in `e2b sandbox exec` to the remote command instead of parsing them as CLI options
diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts
index aeee06baa..26f3221e2 100644
--- a/packages/cli/src/commands/index.ts
+++ b/packages/cli/src/commands/index.ts
@@ -6,6 +6,7 @@ import { sandboxCommand } from './sandbox'
import { authCommand } from './auth'
export const program = new commander.Command()
+ .enablePositionalOptions()
.description(
`Create sandbox templates from Dockerfiles by running ${asPrimary(
'e2b template create'
diff --git a/packages/cli/src/commands/sandbox/exec.ts b/packages/cli/src/commands/sandbox/exec.ts
index f337f5803..105e2f0df 100644
--- a/packages/cli/src/commands/sandbox/exec.ts
+++ b/packages/cli/src/commands/sandbox/exec.ts
@@ -20,8 +20,15 @@ interface ExecOptions {
const NO_COMMAND_TIMEOUT = 0
export const execCommand = new commander.Command('exec')
.description('execute a command in a running sandbox')
+ .addHelpText(
+ 'after',
+ '\nEverything after the sandbox ID is passed through to the remote command,\n' +
+ 'so e2b options must come before the sandbox ID:\n' +
+ ' e2b sandbox exec -u root <sandboxID> codex exec "prompt" --help'
+ )
.argument('<sandboxID>', 'sandbox ID to execute command in')
.argument('<command...>', 'command to execute')
+ .passThroughOptions()
.option('-b, --background', 'run in background and return immediately')
.option('-c, --cwd <dir>', 'working directory')
.option('-u, --user <user>', 'run as specified user')
@@ -36,7 +43,16 @@ export const execCommand = new commander.Command('exec')
async (sandboxID: string, commandParts: string[], opts: ExecOptions) => {
const hasPipedStdin = isPipedStdin()
- const command = buildCommand(commandParts)
+ let command: string
+ try {
+ command = buildCommand(commandParts)
+ } catch (err) {
+ if (err instanceof commander.InvalidArgumentError) {
+ execCommand.error(`error: ${err.message}`)
+ }
+ throw err
+ }
+
try {
const apiKey = ensureAPIKey()
const sandbox = await Sandbox.connect(sandboxID, { apiKey })
diff --git a/packages/cli/src/commands/sandbox/exec_helpers.ts b/packages/cli/src/commands/sandbox/exec_helpers.ts
index 7dc7cb701..cdd4c6b36 100644
--- a/packages/cli/src/commands/sandbox/exec_helpers.ts
+++ b/packages/cli/src/commands/sandbox/exec_helpers.ts
@@ -1,4 +1,5 @@
import * as fs from 'fs'
+import * as commander from 'commander'
const SHELL_SAFE_RE = /^[A-Za-z0-9_@%+=:,./-]+$/
@@ -14,11 +15,18 @@ export const shellQuote = (arg: string): string => {
}
export const buildCommand = (commandParts: string[]): string => {
- if (commandParts.length === 1) {
- return commandParts[0]
+ // `--` only separates e2b options from the command, it is not part of it.
+ const parts = commandParts[0] === '--' ? commandParts.slice(1) : commandParts
+
+ if (parts.length === 0) {
+ throw new commander.InvalidArgumentError('missing command to execute')
+ }
+
+ if (parts.length === 1) {
+ return parts[0]
}
- return commandParts.map(shellQuote).join(' ')
+ return parts.map(shellQuote).join(' ')
}
type StatLike = {
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index 80ecc5a1f..82f11edcf 100644
--- a/packages/cli/src/commands/sandbox/index.ts
+++ b/packages/cli/src/commands/sandbox/index.ts
@@ -15,6 +15,7 @@ import { snapshotCommand } from './snapshot'
export const sandboxCommand = new commander.Command('sandbox')
.description('work with sandboxes')
.alias('sbx')
+ .enablePositionalOptions()
.addCommand(connectCommand)
.addCommand(infoCommand)
.addCommand(listCommand)
diff --git a/packages/cli/tests/commands/sandbox/exec_helpers.test.ts b/packages/cli/tests/commands/sandbox/exec_helpers.test.ts
index 6682b4aa5..e32fe2f83 100644
--- a/packages/cli/tests/commands/sandbox/exec_helpers.test.ts
+++ b/packages/cli/tests/commands/sandbox/exec_helpers.test.ts
@@ -38,6 +38,16 @@ describe('exec helpers', () => {
expect(buildCommand(['echo', "it's ok"])).toBe("echo 'it'\"'\"'s ok'")
})
+ test('buildCommand strips a leading -- separator', () => {
+ expect(buildCommand(['--', 'codex', 'exec', '--help'])).toBe(
+ 'codex exec --help'
+ )
+ })
+
+ test('buildCommand rejects a separator without a command', () => {
+ expect(() => buildCommand(['--'])).toThrow('missing command to execute')
+ })
+
test('readStdinFrom reads full input and resolves on EOF', async () => {
const stream = Readable.from(['foo', 'bar'])
await expect(readStdinFrom(stream)).resolves.toEqual(Buffer.from('foobar'))
diff --git a/packages/cli/tests/commands/sandbox/exec_passthrough.test.ts b/packages/cli/tests/commands/sandbox/exec_passthrough.test.ts
new file mode 100644
index 000000000..2a11f291e
--- /dev/null
+++ b/packages/cli/tests/commands/sandbox/exec_passthrough.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => {
+ const connect = vi.fn()
+ const run = vi.fn()
+ const ensureAPIKey = vi.fn(() => 'test-api-key')
+ const isPipedStdin = vi.fn()
+ const setupSignalHandlers = vi.fn(() => () => {})
+
+ return {
+ connect,
+ run,
+ ensureAPIKey,
+ isPipedStdin,
+ setupSignalHandlers,
+ }
+})
+
+vi.mock('e2b', () => {
+ class CommandExitError extends Error {
+ exitCode: number
+ constructor(exitCode: number) {
+ super(`Command exited with ${exitCode}`)
+ this.exitCode = exitCode
+ }
+ }
+
+ class NotFoundError extends Error {}
+
+ return {
+ Sandbox: {
+ connect: mocks.connect,
+ },
+ CommandExitError,
+ NotFoundError,
+ }
+})
+
+vi.mock('../../../src/api', () => ({
+ ensureAPIKey: mocks.ensureAPIKey,
+}))
+
+vi.mock('src/utils/signal', () => ({
+ setupSignalHandlers: mocks.setupSignalHandlers,
+}))
+
+vi.mock(
+ '../../../src/commands/sandbox/exec_helpers',
+ async (importOriginal: <T>() => Promise<T>) => {
+ const actual =
+ await importOriginal<
+ typeof import('../../../src/commands/sandbox/exec_helpers')
+ >()
+ return {
+ ...actual,
+ isPipedStdin: mocks.isPipedStdin,
+ }
+ }
+)
+
+async function runExec(argv: string[]): Promise<{ command: string; opts: any }> {
+ vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
+
+ const commander = await import('commander')
+ const { sandboxCommand } = await import('../../../src/commands/sandbox')
+ const program = new commander.Command()
+ .enablePositionalOptions()
+ .addCommand(sandboxCommand)
+
+ await program.parseAsync(['sandbox', 'exec', ...argv], { from: 'user' })
+
+ expect(mocks.run).toHaveBeenCalledTimes(1)
+ return {
+ command: mocks.run.mock.calls[0][0],
+ opts: mocks.run.mock.calls[0][1],
+ }
+}
+
+describe('sandbox exec option pass-through', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+
+ mocks.run.mockResolvedValue({
+ pid: 1234,
+ error: undefined,
+ wait: vi.fn().mockResolvedValue({ exitCode: 0 }),
+ kill: vi.fn().mockResolvedValue(undefined),
+ disconnect: vi.fn().mockResolvedValue(undefined),
+ })
+ mocks.isPipedStdin.mockReturnValue(false)
+ mocks.connect.mockResolvedValue({
+ commands: {
+ run: mocks.run,
+ supportsStdinClose: true,
+ },
+ })
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ test('forwards flags that follow the command to the remote command', async () => {
+ const { command } = await runExec([
+ 'sandbox-id',
+ 'codex',
+ 'exec',
+ 'prompt',
+ '--help',
+ ])
+
+ expect(command).toBe('codex exec prompt --help')
+ })
+
+ test('forwards flags that collide with e2b flags', async () => {
+ const { command, opts } = await runExec([
+ 'sandbox-id',
+ 'ls',
+ '--background',
+ '-u',
+ 'root',
+ ])
+
+ expect(command).toBe('ls --background -u root')
+ expect(opts.user).toBeUndefined()
+ })
+
+ test('still parses e2b options placed before the command', async () => {
+ const { command, opts } = await runExec([
+ '--user',
+ 'root',
+ '--cwd',
+ '/tmp',
+ 'sandbox-id',
+ 'ls',
+ '-la',
+ ])
+
+ expect(command).toBe('ls -la')
+ expect(opts.user).toBe('root')
+ expect(opts.cwd).toBe('/tmp')
+ })
+
+ test('supports -- to separate e2b options from the command', async () => {
+ const { command, opts } = await runExec([
+ 'sandbox-id',
+ '--',
+ 'codex',
+ 'exec',
+ '--help',
+ ])
+
+ expect(command).toBe('codex exec --help')
+ expect(opts.user).toBeUndefined()
+ })
+})