Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add exec command to CLI (#1090)

Tomas Valenta4ebabfeaa176
diff --git a/.changeset/famous-colts-shout.md b/.changeset/famous-colts-shout.md
new file mode 100644
index 000000000..0205286f0
--- /dev/null
+++ b/.changeset/famous-colts-shout.md
@@ -0,0 +1,5 @@
+---
+'@e2b/cli': minor
+---
+
+Add exec command
diff --git a/packages/cli/src/commands/sandbox/exec.ts b/packages/cli/src/commands/sandbox/exec.ts
new file mode 100644
index 000000000..57a0398da
--- /dev/null
+++ b/packages/cli/src/commands/sandbox/exec.ts
@@ -0,0 +1,145 @@
+/**
+ * Execute a command in a running sandbox.
+ *
+ * NOTE: Stdin piping (e.g., `echo "data" | e2b exec sandbox cmd`) is not supported.
+ * The SDK/envd protocol lacks a way to signal EOF to remote commands. Commands that
+ * read until EOF (cat, grep, wc, etc.) would hang indefinitely. This requires envd
+ * to add stdin close signaling before it can be implemented.
+ */
+
+import * as fs from 'fs'
+
+import { Sandbox, CommandExitError } from 'e2b'
+import * as commander from 'commander'
+
+import { ensureAPIKey } from '../../api'
+import { setupSignalHandlers } from 'src/utils/signal'
+
+interface ExecOptions {
+ background?: boolean
+ cwd?: string
+ user?: string
+ env?: Record<string, string>
+}
+
+const NO_COMMAND_TIMEOUT = 0
+
+export const execCommand = new commander.Command('exec')
+ .description('execute a command in a running sandbox')
+ .argument('<sandboxID>', 'sandbox ID to execute command in')
+ .argument('<command...>', 'command to execute')
+ .option('-b, --background', 'run in background and return immediately')
+ .option('-c, --cwd <dir>', 'working directory')
+ .option('-u, --user <user>', 'run as specified user')
+ .option(
+ '-e, --env <KEY=VALUE>',
+ 'set environment variable (repeatable)',
+ (value: string, previous: Record<string, string>) => {
+ const [key, ...rest] = value.split('=')
+ if (key && rest.length > 0) {
+ previous[key] = rest.join('=')
+ }
+ return previous
+ },
+ {} as Record<string, string>
+ )
+ .alias('ex')
+ .action(
+ async (sandboxID: string, commandParts: string[], opts: ExecOptions) => {
+ // Check if stdin is a pipe (data being piped in) - not supported
+ try {
+ const stdinStats = fs.fstatSync(0)
+ if (stdinStats.isFIFO()) {
+ console.error('e2b: stdin piping is not supported')
+ process.exit(2)
+ }
+ } catch {
+ // fstatSync may fail in some environments, ignore
+ }
+
+ const command = commandParts.join(' ')
+ try {
+ const apiKey = ensureAPIKey()
+
+ const sandbox = await Sandbox.connect(sandboxID, { apiKey })
+
+ if (opts.background) {
+ const handle = await sandbox.commands.run(command, {
+ background: true,
+ cwd: opts.cwd,
+ user: opts.user,
+ envs: opts.env,
+ timeoutMs: NO_COMMAND_TIMEOUT,
+ })
+
+ console.error(handle.pid)
+
+ await handle.disconnect()
+
+ // We always exit with code 0 when running in background.
+ process.exit(0)
+ }
+
+ const exitCode = await runCommand(sandbox, command, opts)
+
+ process.exit(exitCode)
+ } catch (err: any) {
+ console.error(err)
+ process.exit(1)
+ }
+ }
+ )
+
+async function runCommand(
+ sandbox: Sandbox,
+ command: string,
+ opts: ExecOptions
+): Promise<number> {
+ const handle = await sandbox.commands.run(command, {
+ background: true,
+ cwd: opts.cwd,
+ user: opts.user,
+ envs: opts.env,
+ timeoutMs: NO_COMMAND_TIMEOUT,
+ onStdout: async (data) => {
+ try {
+ process.stdout.write(data)
+ } catch (err: any) {
+ console.error(err)
+ await handle.kill()
+ }
+ },
+ onStderr: async (data) => {
+ try {
+ process.stderr.write(data)
+ } catch (err: any) {
+ console.error(err)
+ await handle.kill()
+ }
+ },
+ })
+
+ const removeSignalHandlers = setupSignalHandlers(async () => {
+ // Kill the remote process - main loop handles exit code.
+ await handle.kill()
+ })
+
+ try {
+ const result = await handle.wait()
+
+ return result.exitCode
+ } catch (err) {
+ if (handle.error) {
+ console.error(handle.error)
+ }
+
+ if (err instanceof CommandExitError) {
+ return err.exitCode
+ }
+
+ // If exit code is not from the command we throw the error.
+ throw err
+ } finally {
+ removeSignalHandlers()
+ }
+}
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index 0e29368ad..9605231a7 100644
--- a/packages/cli/src/commands/sandbox/index.ts
+++ b/packages/cli/src/commands/sandbox/index.ts
@@ -6,6 +6,7 @@ import { killCommand } from './kill'
import { createCommand } from './create'
import { logsCommand } from './logs'
import { metricsCommand } from './metrics'
+import { execCommand } from './exec'
export const sandboxCommand = new commander.Command('sandbox')
.description('work with sandboxes')
@@ -17,3 +18,4 @@ export const sandboxCommand = new commander.Command('sandbox')
.addCommand(createCommand('spawn', 'sp', true), { hidden: true })
.addCommand(logsCommand)
.addCommand(metricsCommand)
+ .addCommand(execCommand)
diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.ts
index 1c259494e..08e1f5fac 100644
--- a/packages/cli/src/options.ts
+++ b/packages/cli/src/options.ts
@@ -13,7 +13,7 @@ export const configOption = new commander.Option(
'--config <e2b-toml>',
`specify path to the E2B config toml. By default E2B tries to find ${asBold(
'./e2b.toml'
- )} in root directory.`
+ )} in root directory. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files.`
)
export const selectOption = new commander.Option(
diff --git a/packages/cli/src/utils/signal.ts b/packages/cli/src/utils/signal.ts
new file mode 100644
index 000000000..568399830
--- /dev/null
+++ b/packages/cli/src/utils/signal.ts
@@ -0,0 +1,16 @@
+import * as os from 'os'
+
+// Signals we handle - filtered to those defined by the OS.
+// Note: SIGKILL and SIGSTOP cannot be caught.
+const HANDLED_SIGNALS = (
+ ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT', 'SIGABRT', 'SIGPIPE'] as const
+).filter((sig) => sig in os.constants.signals)
+
+export function setupSignalHandlers(
+ onSignal: NodeJS.SignalsListener
+): () => void {
+ HANDLED_SIGNALS.forEach((sig) => process.on(sig, onSignal))
+
+ return () =>
+ HANDLED_SIGNALS.forEach((sig) => process.removeListener(sig, onSignal))
+}