Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Ability to set stdout and stderr handlers for the whole (#180)
Jakub Novákfee49ca2c2f4
diff --git a/.changeset/quiet-bulldogs-train.md b/.changeset/quiet-bulldogs-train.mdnew file mode 100644index 000000000..e7c6be5cd--- /dev/null+++ b/.changeset/quiet-bulldogs-train.md@@ -0,0 +1,6 @@+---+'@e2b/python-sdk': patch+'@e2b/sdk': patch+---++Add session default for process onExit, onStdout and onStderrdiff --git a/packages/js-sdk/src/session/index.ts b/packages/js-sdk/src/session/index.tsindex 1aa84f68d..dd8eae46c 100644--- a/packages/js-sdk/src/session/index.ts+++ b/packages/js-sdk/src/session/index.ts@@ -32,7 +32,9 @@ export type Environment = components['schemas']['Template']export interface SessionOpts extends SessionConnectionOpts {onScanPorts?: ScanOpenPortsHandlertimeout?: number- cwd?: string // Current working directory. Used to resolve relative paths.+ onStdout?: (out: ProcessMessage) => void+ onStderr?: (out: ProcessMessage) => void+ onExit?: () => void}export class Session extends SessionConnection {@@ -276,16 +278,26 @@ export class Session extends SessionConnection {const output = new ProcessOutput()- function handleStdout(data: { line: string; timestamp: number }) {+ const handleStdout = (data: { line: string; timestamp: number }) => {const message = new ProcessMessage(data.line, data.timestamp, false)output.addStdout(message)- onStdout?.(message)++ if (onStdout) {+ onStdout(message)+ } else if (this.opts.onStdout) {+ this.opts.onStdout(message)+ }}- function handleStderr(data: { line: string; timestamp: number }) {+ const handleStderr = (data: { line: string; timestamp: number }) => {const message = new ProcessMessage(data.line, data.timestamp, true)output.addStderr(message)- onStderr?.(message)++ if (onStderr) {+ onStderr(message)+ } else if (this.opts.onStderr) {+ this.opts.onStderr(message)+ }}const [onExitSubID, onStdoutSubID, onStderrSubID] =@@ -311,7 +323,12 @@ export class Session extends SessionConnection {this.logger.error?.(errMsg)}- onExit?.()+ if (onExit) {+ onExit()+ } else if (this.opts.onExit) {+ this.opts.onExit()+ }+handleFinishUnsubscribing(output)})diff --git a/packages/js-sdk/test/process.test.mjs b/packages/js-sdk/test/process.test.mjsindex 08f77f298..9e6d33fce 100644--- a/packages/js-sdk/test/process.test.mjs+++ b/packages/js-sdk/test/process.test.mjs@@ -1,9 +1,8 @@-import {Session} from '../src'-import {expect, test, vi} from 'vitest'-+import { Session } from '../src'+import { expect, test, vi } from 'vitest'test('process on stdout/stderr', async () => {- const session = await Session.create({id: 'Nodejs'})+ const session = await Session.create({ id: 'Nodejs' })const stdout = []const stderr = []@@ -34,10 +33,9 @@ test('process expected stderr', async () => {})test('process on exit', async () => {- const session = await Session.create({id: 'Nodejs'})+ const session = await Session.create({ id: 'Nodejs' })- const onExit = vi.fn(() => {- })+ const onExit = vi.fn(() => {})const process = await session.process.start({cmd: 'pwd',@@ -51,7 +49,7 @@ test('process on exit', async () => {})test('process send stdin', async () => {- const session = await Session.create({id: 'Nodejs'})+ const session = await Session.create({ id: 'Nodejs' })const process = await session.process.start({cmd: 'read -r line; echo "$line"',@@ -69,3 +67,51 @@ test('process send stdin', async () => {await session.close()}, 10000)++test('test default on exit', async () => {+ const onExit = vi.fn(() => {})++ const session = await Session.create({ id: 'Nodejs', onExit })+ const processOverride = await session.process.start({+ cmd: 'pwd',+ onExit: console.log,+ })+ await processOverride.finished+ expect(onExit).not.toHaveBeenCalled()++ const process = await session.process.start({+ cmd: 'pwd',+ })++ await process.finished+ expect(onExit).toHaveBeenCalled()++ await session.close()+})++test('test default on stdout/stderr', async () => {+ const onStdout = vi.fn(() => {})+ const onStderr = vi.fn(() => {})++ const session = await Session.create({ id: 'Nodejs', onStdout, onStderr })++ const processOverride = await session.process.start({+ cmd: "node -e \"console.log('Hello'); throw new Error('Ooopsie -_-')\"",+ onStdout: () => {},+ onStderr: () => {},+ })++ await processOverride.finished+ expect(onStdout).not.toHaveBeenCalled()+ expect(onStderr).not.toHaveBeenCalled()++ const process = await session.process.start({+ cmd: "node -e \"console.log('Hello'); throw new Error('Ooopsie -_-')\"",+ })++ await process.finished+ expect(onStdout).toHaveBeenCalledOnce()+ expect(onStderr).toHaveBeenCalled()++ await session.close()+}, 10000)diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.pyindex 429dd5bf6..f718ef65c 100644--- a/packages/python-sdk/e2b/session/main.py+++ b/packages/python-sdk/e2b/session/main.py@@ -67,6 +67,9 @@ class Session(SessionConnection):cwd: Optional[str] = None,env_vars: Optional[EnvVars] = None,on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,+ on_stdout: Optional[Callable[[str], Any]] = None,+ on_stderr: Optional[Callable[[str], Any]] = None,+ on_exit: Optional[Callable[[int], Any]] = None,_debug_hostname: Optional[str] = None,_debug_port: Optional[int] = None,_debug_dev_env: Optional[Literal["remote", "local"]] = None,@@ -89,6 +92,9 @@ class Session(SessionConnection)::param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used:param cwd: The current working directory to use:param on_scan_ports: A callback to handle opened ports+ :param on_stdout: A default callback that is called when stdout with a newline is received from the process+ :param on_stderr: A default callback that is called when stderr with a newline is received from the process+ :param on_exit: A default callback that is called when the process exits"""logger.info(f"Creating session {id if isinstance(id, str) else type(id)}")@@ -111,7 +117,9 @@ class Session(SessionConnection):)self._terminal = TerminalManager(session=self)self._filesystem = FilesystemManager(session=self)- self._process = ProcessManager(session=self)+ self._process = ProcessManager(+ session=self, on_stdout=on_stdout, on_stderr=on_stderr, on_exit=on_exit+ )async def open(self, timeout: Optional[float] = TIMEOUT) -> None:"""@@ -150,6 +158,9 @@ class Session(SessionConnection):cwd: Optional[str] = None,env_vars: Optional[EnvVars] = None,on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,+ on_stdout: Optional[Callable[[str], Any]] = None,+ on_stderr: Optional[Callable[[str], Any]] = None,+ on_exit: Optional[Callable[[int], Any]] = None,timeout: Optional[float] = TIMEOUT,_debug_hostname: Optional[str] = None,_debug_port: Optional[int] = None,@@ -172,7 +183,11 @@ class Session(SessionConnection)::param api_key: The API key to use:param cwd: The current working directory to use+ :param env_vars: Environment variables to set:param on_scan_ports: A callback to handle opened ports+ :param on_stdout: A default callback that is called when stdout with a newline is received from the process+ :param on_stderr: A default callback that is called when stderr with a newline is received from the process+ :param on_exit: A default callback that is called when the process exits:param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""session = cls(@@ -181,6 +196,9 @@ class Session(SessionConnection):cwd=cwd,env_vars=env_vars,on_scan_ports=on_scan_ports,+ on_stdout=on_stdout,+ on_stderr=on_stderr,+ on_exit=on_exit,_debug_hostname=_debug_hostname,_debug_port=_debug_port,_debug_dev_env=_debug_dev_env,diff --git a/packages/python-sdk/e2b/session/process.py b/packages/python-sdk/e2b/session/process.pyindex 039ed6ff5..84871a44f 100644--- a/packages/python-sdk/e2b/session/process.py+++ b/packages/python-sdk/e2b/session/process.py@@ -180,9 +180,18 @@ class ProcessManager:_service_name = "process"- def __init__(self, session: SessionConnection):+ def __init__(+ self,+ session: SessionConnection,+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,+ on_exit: Optional[Callable[[], Any]] = None,+ ):self._session = sessionself._process_cleanup: List[Callable[[], Any]] = []+ self._on_stdout = on_stdout+ self._on_stderr = on_stderr+ self._on_exit = on_exitdef _close(self):for cleanup in self._process_cleanup:@@ -224,6 +233,10 @@ class ProcessManager:env_vars = env_vars or {}env_vars = {**self._session.env_vars, **env_vars}+ on_stdout = on_stdout or self._on_stdout+ on_stderr = on_stderr or self._on_stderr+ on_exit = on_exit or self._on_exit+future_exit = DeferredFuture(self._process_cleanup)process_id = process_id or create_id(12)diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.tomlindex 0adfd3c0f..d49ac3fca 100644--- a/packages/python-sdk/pyproject.toml+++ b/packages/python-sdk/pyproject.toml@@ -39,4 +39,3 @@ build-backend = "poetry.core.masonry.api"[tool.pytest.ini_options]asyncio_mode = "auto"-addopts = "-n auto"diff --git a/packages/python-sdk/tests/test_process.py b/packages/python-sdk/tests/test_process.pyindex fc45e1e71..784fbf37c 100644--- a/packages/python-sdk/tests/test_process.py+++ b/packages/python-sdk/tests/test_process.py@@ -71,3 +71,56 @@ async def test_process_send_stdin():assert not message.errorawait session.close()+++async def test_default_on_exit():+ on_exit = MagicMock()++ session = await Session.create("Nodejs", on_exit=lambda: on_exit())+ proc = await session.process.start(+ "pwd",+ on_exit=lambda: print("EXIT"),+ )+ await proc+ on_exit.assert_not_called()++ proc = await session.process.start(+ "pwd",+ )+ await proc+ on_exit.assert_called_once()++ await session.close()+++async def test_process_default_on_stdout_stderr():+ on_stdout = MagicMock()+ on_stderr = MagicMock()++ session = await Session.create(+ "Nodejs",+ on_stdout=lambda data: on_stdout(),+ on_stderr=lambda data: on_stderr(),+ )+ code = "node -e \"console.log('hello'); throw new Error('error')\""++ stdout = []+ stderr = []++ proc = await session.process.start(+ code,+ on_stdout=lambda data: stdout.append(data),+ on_stderr=lambda data: stderr.append(data),+ )++ await proc+ on_stdout.assert_not_called()+ on_stderr.assert_not_called()++ proc = await session.process.start(code)+ await proc++ on_stdout.assert_called_once()+ on_stderr.assert_called()++ await session.close()