Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Set env variables when starting session sdks (#175)

Jakub Novák872e83dbbe80
diff --git a/.changeset/good-files-play.md b/.changeset/good-files-play.md
new file mode 100644
index 000000000..c522eb5e6
--- /dev/null
+++ b/.changeset/good-files-play.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'@e2b/sdk': patch
+---
+
+Add env vars for whole session
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6db5a4397..0cd59b448 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -88,9 +88,6 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- - name: Update lock file
- run: pnpm i --no-link --no-frozen-lockfile
-
- name: Release new versions
uses: changesets/action@v1
with:
@@ -100,6 +97,9 @@ jobs:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+ - name: Update lock file
+ run: pnpm i --no-link --no-frozen-lockfile
+
- name: Commit new versions
run: |
git config user.name "github-actions[bot]"
diff --git a/apps/docs/src/app/playgrounds/process/page.mdx b/apps/docs/src/app/playgrounds/process/page.mdx
index e4dffc335..b07c7f172 100644
--- a/apps/docs/src/app/playgrounds/process/page.mdx
+++ b/apps/docs/src/app/playgrounds/process/page.mdx
@@ -4,22 +4,24 @@ export const metadata = {
}
export const sections = [
- { title: 'Start process', id: 'start-process' },
- { title: 'Stop process', id: 'stop-process' },
- { title: 'Stream stdout', id: 'stream-stdout' },
- { title: 'Stream stderr', id: 'stream-stderr' },
- { title: 'Send stdin', id: 'send-stdin' },
+ {title: 'Start process', id: 'start-process'},
+ {title: 'Stop process', id: 'stop-process'},
+ {title: 'Stream stdout', id: 'stream-stdout'},
+ {title: 'Stream stderr', id: 'stream-stderr'},
+ {title: 'Send stdin', id: 'send-stdin'},
+ {title: 'Set environment variables', id: 'set-environment-variables'},
]
## Process
Here are the basic operations you can do with the process inside a cloud playground:
-- [Start process](/getting-started/basics#start-process)
-- [Stop process](/getting-started/basics#stop-process)
-- [Stdout](/getting-started/basics#stream-stdout)
-- [Stdin](/getting-started/basics#send-stdin)
-- [Stderr](/getting-started/basics#stream-stderr)
+- [Start process](/playgrounds/process#start-process)
+- [Stop process](/playgrounds/process#stop-process)
+- [Stdout](/playgrounds/process#stream-stdout)
+- [Stdin](/playgrounds/process#send-stdin)
+- [Stderr](/playgrounds/process#stream-stderr)
+- [Environment variables](/playgrounds/process#set-environment-variables)
## Start process
@@ -55,3 +57,12 @@ Here are the basic operations you can do with the process inside a cloud playgro
path="basics/process_write_stdin"
isRunnable={true}
/>
+
+## Set environment variables
+
+Environment variables set on process has precedence over the ones set on the session.
+
+<CodeGroupAutoload
+ path="basics/set_env_vars"
+ isRunnable={true}
+/>
diff --git a/apps/docs/src/code/js/basics/set_env_vars.js b/apps/docs/src/code/js/basics/set_env_vars.js
new file mode 100644
index 000000000..9b4398a6c
--- /dev/null
+++ b/apps/docs/src/code/js/basics/set_env_vars.js
@@ -0,0 +1,19 @@
+import { Session } from '@e2b/sdk'
+
+const session = await Session.create({
+ id: 'Nodejs',
+ apiKey: process.env.E2B_API_KEY,
+ envVars: { FOO: 'Hello' }, // $HighlightLine
+})
+
+// This example will print back the string we send to the process using `sendStdin()`
+
+const proc = await session.process.start({
+ cmd: 'echo $FOO $BAR!',
+ envVars: { BAR: 'World' }, // $HighlightLine
+})
+await proc.finished
+console.log(proc.output.stdout)
+// output: Hello World!
+
+await session.close()
diff --git a/apps/docs/src/code/python/basics/set_env_vars.py b/apps/docs/src/code/python/basics/set_env_vars.py
new file mode 100644
index 000000000..9a7b8f2db
--- /dev/null
+++ b/apps/docs/src/code/python/basics/set_env_vars.py
@@ -0,0 +1,25 @@
+import asyncio
+from os import getenv
+from e2b import Session
+
+E2B_API_KEY = getenv("E2B_API_KEY")
+
+async def main():
+ session = await Session.create(
+ id="Nodejs",
+ api_key=E2B_API_KEY,
+ env_vars={"FOO": "Hello"} # $HighlightLine
+ )
+
+ proc = await session.process.start(
+ "echo $FOO $BAR!",
+ env_vars={"BAR": "World"}, # $HighlightLine
+ )
+ await proc
+ print(proc.output.stdout)
+ # output: Hello World!
+
+ await session.close()
+
+
+asyncio.run(main())
\ No newline at end of file
diff --git a/packages/js-sdk/src/session/index.ts b/packages/js-sdk/src/session/index.ts
index 3f20896c0..1aa84f68d 100644
--- a/packages/js-sdk/src/session/index.ts
+++ b/packages/js-sdk/src/session/index.ts
@@ -177,6 +177,9 @@ export class Session extends SessionConnection {
if (!cwd && this.cwd) {
cwd = this.cwd
}
+ envVars = envVars || {}
+ envVars = { ...this.envVars, ...envVars }
+
const { promise: terminalExited, resolve: triggerExit } =
createDeferredPromise()
@@ -263,6 +266,10 @@ export class Session extends SessionConnection {
cwd = this.cwd
}
if (!cmd) throw new Error('cmd is required')
+
+ envVars = envVars || {}
+ envVars = { ...this.envVars, ...envVars }
+
this.logger.debug?.(`Starting process "${processID}", cmd: "${cmd}"`)
const { promise: processExited, resolve: triggerExit } = createDeferredPromise()
diff --git a/packages/js-sdk/src/session/sessionConnection.ts b/packages/js-sdk/src/session/sessionConnection.ts
index 4366eab1a..2fb8c0943 100644
--- a/packages/js-sdk/src/session/sessionConnection.ts
+++ b/packages/js-sdk/src/session/sessionConnection.ts
@@ -15,6 +15,7 @@ import { codeSnippetService } from './codeSnippet'
import { filesystemService } from './filesystem'
import { processService } from './process'
import { terminalService } from './terminal'
+import { EnvVars } from './envVars'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type SubscriptionHandler = (result: any) => void
@@ -42,6 +43,7 @@ export interface SessionConnectionOpts {
id: string
apiKey?: string
cwd?: string
+ envVars?: EnvVars
logger?: Logger
__debug_hostname?: string
__debug_port?: number
@@ -60,6 +62,7 @@ const refreshSession = api
export class SessionConnection {
cwd: string | undefined
+ envVars: EnvVars
protected readonly logger: Logger
protected session?: components['schemas']['Session']
@@ -84,6 +87,7 @@ export class SessionConnection {
this.cwd = this.cwd.replace('~', '/home/user')
}
+ this.envVars = opts.envVars || {}
this.logger = opts.logger ?? {
// by default, we log to the console
// we don't log debug messages by default
diff --git a/packages/js-sdk/test/envVars.test.mjs b/packages/js-sdk/test/envVars.test.mjs
new file mode 100644
index 000000000..7767e070d
--- /dev/null
+++ b/packages/js-sdk/test/envVars.test.mjs
@@ -0,0 +1,53 @@
+import {Session} from '../src'
+import {expect, test} from 'vitest'
+
+test('test_env_vars', async () => {
+ const session = await Session.create({id: 'Bash'})
+
+ const process = await session.process.start({
+ cmd: 'echo $FOO',
+ envVars: {FOO: 'BAR'},
+ })
+ await process.finished
+ const output = process.output.stdout
+ expect(output).toEqual('BAR')
+
+ await session.close()
+})
+
+test('test_profile_env_vars', async () => {
+ const session = await Session.create({id: 'Bash'})
+
+ await session.filesystem.write('/home/user/.profile', 'export FOO=BAR')
+ const process = await session.process.start({cmd: 'echo $FOO'})
+ await process.finished
+ const output = process.output.stdout
+ expect(output).toEqual('BAR')
+
+ await session.close()
+})
+
+test('test_default_env_vars', async () => {
+ const session = await Session.create({id: 'Bash', envVars: {FOO: 'BAR'}})
+
+ const process = await session.process.start({cmd: 'echo $FOO'})
+ await process.finished
+ const output = process.output.stdout
+ expect(output).toEqual('BAR')
+
+ await session.close()
+})
+
+test('test_overriding_env_vars', async () => {
+ const session = await Session.create({id: 'Bash', envVars: {FOO: 'BAR'}})
+
+ const process = await session.process.start({
+ cmd: 'echo $FOO',
+ envVars: {FOO: 'QUX'},
+ })
+ await process.finished
+ const output = process.output.stdout
+ expect(output).toEqual('QUX')
+
+ await session.close()
+})
diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.py
index ab764df41..429dd5bf6 100644
--- a/packages/python-sdk/e2b/session/main.py
+++ b/packages/python-sdk/e2b/session/main.py
@@ -5,6 +5,7 @@ from async_timeout import timeout as async_timeout
from e2b.constants import TIMEOUT
from e2b.session.code_snippet import CodeSnippetManager, OpenPort
+from e2b.session.env_vars import EnvVars
from e2b.session.filesystem import FilesystemManager
from e2b.session.process import ProcessManager
from e2b.session.session_connection import SessionConnection
@@ -64,6 +65,7 @@ class Session(SessionConnection):
id: Union[Environment, str],
api_key: Optional[str],
cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
@@ -97,6 +99,7 @@ class Session(SessionConnection):
id=id,
api_key=api_key,
cwd=cwd,
+ env_vars=env_vars,
_debug_hostname=_debug_hostname,
_debug_port=_debug_port,
_debug_dev_env=_debug_dev_env,
@@ -145,6 +148,7 @@ class Session(SessionConnection):
id: Union[Environment, str],
api_key: Optional[str] = None,
cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
timeout: Optional[float] = TIMEOUT,
_debug_hostname: Optional[str] = None,
@@ -175,6 +179,7 @@ class Session(SessionConnection):
id=id,
api_key=api_key,
cwd=cwd,
+ env_vars=env_vars,
on_scan_ports=on_scan_ports,
_debug_hostname=_debug_hostname,
_debug_port=_debug_port,
diff --git a/packages/python-sdk/e2b/session/process.py b/packages/python-sdk/e2b/session/process.py
index 90b00fbb2..039ed6ff5 100644
--- a/packages/python-sdk/e2b/session/process.py
+++ b/packages/python-sdk/e2b/session/process.py
@@ -221,8 +221,8 @@ class ProcessManager:
"""
logger.info(f"Starting process (id: {process_id}): {cmd}")
async with async_timeout.timeout(timeout):
- if not env_vars:
- env_vars = {}
+ env_vars = env_vars or {}
+ env_vars = {**self._session.env_vars, **env_vars}
future_exit = DeferredFuture(self._process_cleanup)
process_id = process_id or create_id(12)
diff --git a/packages/python-sdk/e2b/session/session_connection.py b/packages/python-sdk/e2b/session/session_connection.py
index ecc8498db..a0a4b44fd 100644
--- a/packages/python-sdk/e2b/session/session_connection.py
+++ b/packages/python-sdk/e2b/session/session_connection.py
@@ -19,6 +19,7 @@ from e2b.constants import (
WS_PORT,
WS_ROUTE,
)
+from e2b.session.env_vars import EnvVars
from e2b.session.exception import (
AuthenticationException,
MultipleExceptions,
@@ -64,6 +65,7 @@ class SessionConnection:
id: str,
api_key: Optional[str],
cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
_debug_dev_env: Optional[Literal["remote", "local"]] = None,
@@ -77,6 +79,7 @@ class SessionConnection:
)
self.cwd = cwd
+ self.env_vars = env_vars or {}
self._id = id
self._api_key = api_key
self._debug_hostname = _debug_hostname
diff --git a/packages/python-sdk/e2b/session/terminal.py b/packages/python-sdk/e2b/session/terminal.py
index 866a3ac7e..7de811c51 100644
--- a/packages/python-sdk/e2b/session/terminal.py
+++ b/packages/python-sdk/e2b/session/terminal.py
@@ -3,13 +3,14 @@ import logging
from typing import Any, Awaitable, Callable, Coroutine, List, Optional
import async_timeout
+from pydantic import BaseModel
+
from e2b.constants import TIMEOUT
from e2b.session.env_vars import EnvVars
from e2b.session.exception import MultipleExceptions, RpcException, TerminalException
from e2b.session.session_connection import SessionConnection
from e2b.utils.future import DeferredFuture
from e2b.utils.id import create_id
-from pydantic import BaseModel
logger = logging.getLogger(__file__)
@@ -172,6 +173,8 @@ class TerminalManager:
:return: Terminal session
"""
async with async_timeout.timeout(timeout):
+ env_vars = self._session.env_vars.update(env_vars or {})
+
future_exit = DeferredFuture(self._process_cleanup)
terminal_id = terminal_id or create_id(12)
diff --git a/packages/python-sdk/tests/test_env_vars.py b/packages/python-sdk/tests/test_env_vars.py
index f34cc552a..e974c6db2 100644
--- a/packages/python-sdk/tests/test_env_vars.py
+++ b/packages/python-sdk/tests/test_env_vars.py
@@ -7,10 +7,10 @@ async def test_env_vars():
process = await session.process.start("echo $FOO", env_vars={"FOO": "BAR"})
await process
output = process.stdout
- await session.close()
-
assert output == "BAR"
+ await session.close()
+
async def test_profile_env_vars():
session = await Session.create("Bash")
@@ -19,6 +19,27 @@ async def test_profile_env_vars():
process = await session.process.start("echo $FOO")
await process
output = process.stdout
+ assert output == "BAR"
+
await session.close()
+
+async def test_default_env_vars():
+ session = await Session.create("Bash", env_vars={"FOO": "BAR"})
+ process = await session.process.start("echo $FOO")
+ await process
+ output = process.stdout
assert output == "BAR"
+
+ await session.close()
+
+
+async def test_overriding_env_vars():
+ session = await Session.create("Bash", env_vars={"FOO": "BAR"})
+
+ process = await session.process.start("echo $FOO", env_vars={"FOO": "QUX"})
+ await process
+ output = process.stdout
+ assert output == "QUX"
+
+ await session