Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat: add sendStdin/closeStdin to CommandHandle (#1397)
Mish Ushakov08012eeb4a06
diff --git a/.changeset/command-handle-stdin.md b/.changeset/command-handle-stdin.mdnew file mode 100644index 000000000..ecb837bc9--- /dev/null+++ b/.changeset/command-handle-stdin.md@@ -0,0 +1,8 @@+---+"e2b": patch+"@e2b/python-sdk": patch+---++feat: add `sendStdin`/`send_stdin` and `closeStdin`/`close_stdin` to `CommandHandle`++You can now send and close stdin directly on a background command handle instead of going through `sandbox.commands` with the command's PID.diff --git a/packages/js-sdk/src/sandbox/commands/commandHandle.ts b/packages/js-sdk/src/sandbox/commands/commandHandle.tsindex 2f58e41c4..09713bbb8 100644--- a/packages/js-sdk/src/sandbox/commands/commandHandle.ts+++ b/packages/js-sdk/src/sandbox/commands/commandHandle.ts@@ -1,6 +1,7 @@import { handleRpcError } from '../../envd/rpc'import { SandboxError } from '../../errors'import { ConnectResponse, StartResponse } from '../../envd/process/process_pb'+import type { CommandRequestOpts } from '.'declare const __brand: unique symboltype Brand<B> = { [__brand]: B }@@ -104,7 +105,14 @@ export class CommandHandleprivate readonly events: AsyncIterable<ConnectResponse | StartResponse>,private readonly onStdout?: (stdout: string) => void | Promise<void>,private readonly onStderr?: (stderr: string) => void | Promise<void>,- private readonly onPty?: (pty: Uint8Array) => void | Promise<void>+ private readonly onPty?: (pty: Uint8Array) => void | Promise<void>,+ private readonly handleSendStdin?: (+ data: string | Uint8Array,+ opts?: CommandRequestOpts+ ) => Promise<void>,+ private readonly handleCloseStdin?: (+ opts?: CommandRequestOpts+ ) => Promise<void>) {this._wait = this.handleEvents()}@@ -184,6 +192,45 @@ export class CommandHandlereturn await this.handleKill()}+ /**+ * Send data to the command stdin.+ *+ * The command must have been started with `stdin: true`.+ *+ * @param data data to send to the command.+ * @param opts connection options.+ */+ async sendStdin(+ data: string | Uint8Array,+ opts?: CommandRequestOpts+ ): Promise<void> {+ if (!this.handleSendStdin) {+ throw new SandboxError(+ 'Sending stdin is not supported for this command handle.'+ )+ }++ await this.handleSendStdin(data, opts)+ }++ /**+ * Close the command stdin.+ *+ * This signals EOF to the command. The command must have been started with+ * `stdin: true`.+ *+ * @param opts connection options.+ */+ async closeStdin(opts?: CommandRequestOpts): Promise<void> {+ if (!this.handleCloseStdin) {+ throw new SandboxError(+ 'Closing stdin is not supported for this command handle.'+ )+ }++ await this.handleCloseStdin(opts)+ }+private async *iterateEvents(): AsyncGenerator<[Stdout, null, null] | [null, Stderr, null] | [null, null, PtyOutput]> {diff --git a/packages/js-sdk/src/sandbox/commands/index.ts b/packages/js-sdk/src/sandbox/commands/index.tsindex 108a75073..6302ed2d9 100644--- a/packages/js-sdk/src/sandbox/commands/index.ts+++ b/packages/js-sdk/src/sandbox/commands/index.ts@@ -225,8 +225,12 @@ export class Commands {}/**- * @hidden- * @internal+ * Close command stdin.+ *+ * This signals EOF to the command. The command must have been started with `stdin: true`.+ *+ * @param pid process ID of the command. You can get the list of running commands using {@link Commands.list}.+ * @param opts connection options.*/async closeStdin(pid: number, opts?: CommandRequestOpts): Promise<void> {if (!this.supportsStdinClose) {@@ -348,7 +352,9 @@ export class Commands {events,opts?.onStdout,opts?.onStderr,- undefined+ undefined,+ (data, stdinOpts) => this.sendStdin(pid, data, stdinOpts),+ (stdinOpts) => this.closeStdin(pid, stdinOpts))} catch (err) {cleanup()@@ -460,7 +466,9 @@ export class Commands {events,opts?.onStdout,opts?.onStderr,- undefined+ undefined,+ (data, stdinOpts) => this.sendStdin(pid, data, stdinOpts),+ (stdinOpts) => this.closeStdin(pid, stdinOpts))} catch (err) {cleanup()diff --git a/packages/js-sdk/tests/sandbox/commands/sendStdin.test.ts b/packages/js-sdk/tests/sandbox/commands/sendStdin.test.tsindex cd3860852..a08b6ad1b 100644--- a/packages/js-sdk/tests/sandbox/commands/sendStdin.test.ts+++ b/packages/js-sdk/tests/sandbox/commands/sendStdin.test.ts@@ -22,6 +22,44 @@ sandboxTest('send stdin to process', async ({ sandbox }) => {assert.equal(cmd.stdout, text)})+sandboxTest('send stdin via command handle', async ({ sandbox }) => {+ const text = 'Hello, World!'+ const cmd = await sandbox.commands.run('cat', {+ background: true,+ stdin: true,+ })++ await cmd.sendStdin(text)++ for (let i = 0; i < 5; i++) {+ if (cmd.stdout === text) {+ break+ }+ await new Promise((r) => setTimeout(r, 500))+ }++ await cmd.kill()++ assert.equal(cmd.stdout, text)+})++sandboxTest('close stdin via command handle', async ({ sandbox }) => {+ const text = 'Hello, World!'+ const cmd = await sandbox.commands.run('cat', {+ background: true,+ stdin: true,+ })++ await cmd.sendStdin(text)+ await cmd.closeStdin()++ // `cat` exits once stdin is closed (EOF).+ const result = await cmd.wait()++ assert.equal(result.exitCode, 0)+ assert.equal(result.stdout, text)+})+sandboxTest('send empty stdin to process', async ({ sandbox }) => {const text = ''const cmd = await sandbox.commands.run('cat', {diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command.py b/packages/python-sdk/e2b/sandbox_async/commands/command.pyindex 32b75fd26..4476558b2 100644--- a/packages/python-sdk/e2b/sandbox_async/commands/command.py+++ b/packages/python-sdk/e2b/sandbox_async/commands/command.py@@ -11,7 +11,7 @@ from e2b.connection_config import ()from e2b.envd.process import process_connect, process_pb2from e2b.envd.rpc import authentication_header, handle_rpc_exception-from e2b.envd.versions import ENVD_COMMANDS_STDIN+from e2b.envd.versions import ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSEfrom e2b.exceptions import SandboxExceptionfrom e2b.sandbox.commands.main import ProcessInfofrom e2b.sandbox.commands.command_handle import CommandResult@@ -133,6 +133,37 @@ class Commands:except Exception as e:raise handle_rpc_exception(e)+ async def close_stdin(+ self,+ pid: int,+ request_timeout: Optional[float] = None,+ ) -> None:+ """+ Close the command stdin.++ This signals EOF to the command. The command must have been started with `stdin=True`.++ :param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`.+ :param request_timeout: Timeout for the request in **seconds**+ """+ if self._envd_version < ENVD_ENVD_CLOSE:+ raise SandboxException(+ f"Sandbox envd version {self._envd_version} doesn't support closing stdin. "+ f"Please rebuild your template to pick up the latest sandbox version."+ )++ try:+ await self._rpc.aclose_stdin(+ process_pb2.CloseStdinRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )+ except Exception as e:+ raise handle_rpc_exception(e)+@overloadasync def run(self,@@ -274,12 +305,15 @@ class Commands:f"Failed to start process: expected start event, got {start_event}")+ pid = start_event.event.start.pidreturn AsyncCommandHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),+ pid=pid,+ handle_kill=lambda: self.kill(pid),events=events,on_stdout=on_stdout,on_stderr=on_stderr,+ handle_send_stdin=lambda data: self.send_stdin(pid, data),+ handle_close_stdin=lambda: self.close_stdin(pid),)except Exception as e:raise handle_rpc_exception(e)@@ -325,12 +359,15 @@ class Commands:f"Failed to connect to process: expected start event, got {start_event}")+ pid = start_event.event.start.pidreturn AsyncCommandHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),+ pid=pid,+ handle_kill=lambda: self.kill(pid),events=events,on_stdout=on_stdout,on_stderr=on_stderr,+ handle_send_stdin=lambda data: self.send_stdin(pid, data),+ handle_close_stdin=lambda: self.close_stdin(pid),)except Exception as e:raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py b/packages/python-sdk/e2b/sandbox_async/commands/command_handle.pyindex 054ff41bc..3a8c0ae8e 100644--- a/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py+++ b/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py@@ -12,6 +12,7 @@ from typing import (from e2b.envd.rpc import handle_rpc_exceptionfrom e2b.envd.process import process_pb2+from e2b.exceptions import SandboxExceptionfrom e2b.sandbox.commands.command_handle import (CommandExitException,CommandResult,@@ -82,9 +83,13 @@ class AsyncCommandHandle:on_stdout: Optional[OutputHandler[Stdout]] = None,on_stderr: Optional[OutputHandler[Stderr]] = None,on_pty: Optional[OutputHandler[PtyOutput]] = None,+ handle_send_stdin: Optional[Callable[[str], Coroutine[Any, Any, None]]] = None,+ handle_close_stdin: Optional[Callable[[], Coroutine[Any, Any, None]]] = None,):self._pid = pidself._handle_kill = handle_kill+ self._handle_send_stdin = handle_send_stdin+ self._handle_close_stdin = handle_close_stdinself._events = eventsself._stdout: str = ""@@ -197,3 +202,29 @@ class AsyncCommandHandle:"""result = await self._handle_kill()return result++ async def send_stdin(self, data: str) -> None:+ """+ Send data to the command stdin.++ The command must have been started with `stdin=True`.++ :param data: Data to send to the command+ """+ if self._handle_send_stdin is None:+ raise SandboxException(+ "Sending stdin is not supported for this command handle."+ )+ await self._handle_send_stdin(data)++ async def close_stdin(self) -> None:+ """+ Close the command stdin.++ This signals EOF to the command. The command must have been started with `stdin=True`.+ """+ if self._handle_close_stdin is None:+ raise SandboxException(+ "Closing stdin is not supported for this command handle."+ )+ await self._handle_close_stdin()diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command.py b/packages/python-sdk/e2b/sandbox_sync/commands/command.pyindex 512b7d992..e23c1809e 100644--- a/packages/python-sdk/e2b/sandbox_sync/commands/command.py+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command.py@@ -11,7 +11,7 @@ from e2b.connection_config import ()from e2b.envd.process import process_connect, process_pb2from e2b.envd.rpc import authentication_header, handle_rpc_exception-from e2b.envd.versions import ENVD_COMMANDS_STDIN+from e2b.envd.versions import ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSEfrom e2b.exceptions import SandboxExceptionfrom e2b.sandbox.commands.main import ProcessInfofrom e2b.sandbox.commands.command_handle import CommandResult@@ -132,6 +132,37 @@ class Commands:except Exception as e:raise handle_rpc_exception(e)+ def close_stdin(+ self,+ pid: int,+ request_timeout: Optional[float] = None,+ ) -> None:+ """+ Close the command stdin.++ This signals EOF to the command. The command must have been started with `stdin=True`.++ :param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`.+ :param request_timeout: Timeout for the request in **seconds**+ """+ if self._envd_version < ENVD_ENVD_CLOSE:+ raise SandboxException(+ f"Sandbox envd version {self._envd_version} doesn't support closing stdin. "+ f"Please rebuild your template to pick up the latest sandbox version."+ )++ try:+ self._rpc.close_stdin(+ process_pb2.CloseStdinRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )+ except Exception as e:+ raise handle_rpc_exception(e)+@overloaddef run(self,@@ -274,10 +305,13 @@ class Commands:f"Failed to start process: expected start event, got {start_event}")+ pid = start_event.event.start.pidreturn CommandHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),+ pid=pid,+ handle_kill=lambda: self.kill(pid),events=events,+ handle_send_stdin=lambda data: self.send_stdin(pid, data),+ handle_close_stdin=lambda: self.close_stdin(pid),)except Exception as e:raise handle_rpc_exception(e)@@ -319,10 +353,13 @@ class Commands:f"Failed to connect to process: expected start event, got {start_event}")+ pid = start_event.event.start.pidreturn CommandHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),+ pid=pid,+ handle_kill=lambda: self.kill(pid),events=events,+ handle_send_stdin=lambda data: self.send_stdin(pid, data),+ handle_close_stdin=lambda: self.close_stdin(pid),)except Exception as e:raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py b/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.pyindex a58a613e0..7a4599bcc 100644--- a/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py@@ -2,6 +2,7 @@ from typing import Optional, Callable, Any, Generator, Union, Tuplefrom e2b.envd.rpc import handle_rpc_exceptionfrom e2b.envd.process import process_pb2+from e2b.exceptions import SandboxExceptionfrom e2b.sandbox.commands.command_handle import (CommandExitException,CommandResult,@@ -32,9 +33,13 @@ class CommandHandle:events: Generator[Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any, None],+ handle_send_stdin: Optional[Callable[[str], None]] = None,+ handle_close_stdin: Optional[Callable[[], None]] = None,):self._pid = pidself._handle_kill = handle_kill+ self._handle_send_stdin = handle_send_stdin+ self._handle_close_stdin = handle_close_stdinself._events = eventsself._stdout: str = ""@@ -148,3 +153,29 @@ class CommandHandle::return: Whether the command was killed successfully"""return self._handle_kill()++ def send_stdin(self, data: str) -> None:+ """+ Send data to the command stdin.++ The command must have been started with `stdin=True`.++ :param data: Data to send to the command+ """+ if self._handle_send_stdin is None:+ raise SandboxException(+ "Sending stdin is not supported for this command handle."+ )+ self._handle_send_stdin(data)++ def close_stdin(self) -> None:+ """+ Close the command stdin.++ This signals EOF to the command. The command must have been started with `stdin=True`.+ """+ if self._handle_close_stdin is None:+ raise SandboxException(+ "Closing stdin is not supported for this command handle."+ )+ self._handle_close_stdin()diff --git a/packages/python-sdk/tests/async/sandbox_async/commands/test_send_stdin.py b/packages/python-sdk/tests/async/sandbox_async/commands/test_send_stdin.pyindex 4db1022fd..839857e2c 100644--- a/packages/python-sdk/tests/async/sandbox_async/commands/test_send_stdin.py+++ b/packages/python-sdk/tests/async/sandbox_async/commands/test_send_stdin.py@@ -19,6 +19,33 @@ async def test_send_stdin_to_process(async_sandbox: AsyncSandbox):assert cmd.stdout == "Hello, World!"+async def test_send_stdin_via_command_handle(async_sandbox: AsyncSandbox):+ ev = asyncio.Event()++ def handle_event(stdout: str):+ ev.set()++ cmd = await async_sandbox.commands.run(+ "cat", background=True, on_stdout=handle_event, stdin=True+ )+ await cmd.send_stdin("Hello, World!")++ await ev.wait()++ assert cmd.stdout == "Hello, World!"+++async def test_close_stdin_via_command_handle(async_sandbox: AsyncSandbox):+ cmd = await async_sandbox.commands.run("cat", background=True, stdin=True)+ await cmd.send_stdin("Hello, World!")+ await cmd.close_stdin()++ # `cat` exits once stdin is closed (EOF).+ result = await cmd.wait()+ assert result.exit_code == 0+ assert result.stdout == "Hello, World!"++async def test_send_special_characters_to_process(async_sandbox: AsyncSandbox):ev = asyncio.Event()diff --git a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_send_stdin.py b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_send_stdin.pyindex bb6eb93ff..0b04ec787 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_send_stdin.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_send_stdin.py@@ -10,6 +10,26 @@ def test_send_stdin_to_process(sandbox: Sandbox):break+def test_send_stdin_via_command_handle(sandbox: Sandbox):+ cmd = sandbox.commands.run("cat", background=True, stdin=True)+ cmd.send_stdin("Hello, World!")++ for stdout, _, _ in cmd:+ assert stdout == "Hello, World!"+ break+++def test_close_stdin_via_command_handle(sandbox: Sandbox):+ cmd = sandbox.commands.run("cat", background=True, stdin=True)+ cmd.send_stdin("Hello, World!")+ cmd.close_stdin()++ # `cat` exits once stdin is closed (EOF).+ result = cmd.wait()+ assert result.exit_code == 0+ assert result.stdout == "Hello, World!"++def test_send_special_characters_to_process(sandbox: Sandbox):cmd = sandbox.commands.run("cat", background=True, stdin=True)sandbox.commands.send_stdin(cmd.pid, "!@#$%^&*()_+")