Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add helper method for running code in JS SDK

Vasek Mlejnsky7ee828c076d2
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 3a5f9e63d..ff89c78af 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -20,3 +20,6 @@ export type {
export { Process, ProcessMessage, ProcessOutput } from './session/process'
export type { ProcessManager } from './session/process'
export type { EnvVars } from './session/envVars'
+export { runCode } from './runCode'
+export type { CodeRuntime } from './runCode'
+// export { runCmd } from './runCmd'
diff --git a/packages/js-sdk/src/runCmd.ts b/packages/js-sdk/src/runCmd.ts
new file mode 100644
index 000000000..a77644c3d
--- /dev/null
+++ b/packages/js-sdk/src/runCmd.ts
@@ -0,0 +1,20 @@
+import { Session } from './session'
+
+export async function runCmd(command: string, opts?: { apiKey?: string }) {
+ const session = await Session.create({
+ id: 'Bash',
+ apiKey: opts?.apiKey || process.env.E2B_API_KEY || '', // Session.create will throw an error if the API key is not provided so no need to check here
+ })
+
+ const proc = await session.process.start({
+ cmd: command,
+ })
+ const out = await proc.finished
+
+ await session.close()
+
+ return {
+ stdout: out.stdout,
+ stderr: out.stderr,
+ }
+}
diff --git a/packages/js-sdk/src/runCode.ts b/packages/js-sdk/src/runCode.ts
new file mode 100644
index 000000000..6eb31553c
--- /dev/null
+++ b/packages/js-sdk/src/runCode.ts
@@ -0,0 +1,74 @@
+import { Session } from './session'
+
+export enum CodeRuntime {
+ Node16 = 'Node16',
+ Python3 = 'Python3',
+}
+
+// Fucntions that sleeps for a given amount of time
+function sleep(ms: number) {
+ return new Promise(resolve => setTimeout(resolve, ms))
+}
+
+/**
+ * Run code in a sandboxed cloud environment.
+ * `runCode` wraps the `Session` class and provides a simple interface for running code in a sandboxed environment
+ * without any need to manage lifecycle of the session.
+ * `runCode` automatically loads the E2B API key from the `E2B_API_KEY` environment variable.
+ *
+ * @param runtime The runtime to use when running the code. Can be one of the following:
+ * - "Node16"
+ * - "Python3"
+ *
+ * **Let us know if you need support for other runtimes.**
+ * @param code The code to run
+ * @param opts Optional parameters to pass
+ * @returns
+ */
+export async function runCode(
+ runtime: CodeRuntime,
+ code: string,
+ opts?: { apiKey?: string },
+) {
+ let binary = ''
+ let filepath = ''
+ let envID = ''
+ switch (runtime) {
+ case CodeRuntime.Node16:
+ envID = 'Nodejs'
+ binary = 'node'
+ filepath = '/index.js'
+ break
+ case CodeRuntime.Python3:
+ envID = 'Python3'
+ binary = 'python3'
+ filepath = '/main.py'
+ break
+ default:
+ throw new Error(
+ `The "${runtime}" runtime isn't supported. Please let us know if you need support for this runtime.`,
+ )
+ }
+
+ const session = await Session.create({
+ id: envID,
+ apiKey: opts?.apiKey || process.env.E2B_API_KEY || '', // Session.create will throw an error if the API key is not provided so no need to check here
+ })
+
+ await session.filesystem.write(filepath, code)
+
+ const codeProc = await session.process.start({
+ cmd: `${binary} ${filepath}`,
+ onStdout: data => console.log('stdout: ', data.line),
+ onStderr: data => console.error('stderr: ', data.line),
+ })
+ await sleep(3000)
+ const out = await codeProc.finished
+
+ await session.close()
+
+ return {
+ stdout: out.stdout,
+ stderr: out.stderr,
+ }
+}
diff --git a/packages/js-sdk/test/_smoke.test.mjs b/packages/js-sdk/test/_smoke.test.mjs
index 3b3125b43..55d0f6ad7 100644
--- a/packages/js-sdk/test/_smoke.test.mjs
+++ b/packages/js-sdk/test/_smoke.test.mjs
@@ -7,7 +7,7 @@ const E2B_API_KEY = process.env.E2B_API_KEY
test('Smoke test', async () => {
const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
await session.filesystem.makeDir('/test/new')
-
+
const ls = await session.filesystem.list('/test')
expect(ls.map(x => x.name)).toEqual(['new'])
diff --git a/packages/js-sdk/test/filesystem.test.mjs b/packages/js-sdk/test/filesystem.test.mjs
index 099c54255..ca5a8e50b 100644
--- a/packages/js-sdk/test/filesystem.test.mjs
+++ b/packages/js-sdk/test/filesystem.test.mjs
@@ -1,7 +1,7 @@
import { Session } from '../src'
import { expect, test } from 'vitest'
-import * as fs from "node:fs"
-import * as path from 'node:path';
+import * as fs from 'node:fs'
+import * as path from 'node:path'
const E2B_API_KEY = process.env.E2B_API_KEY
@@ -28,12 +28,12 @@ test('create file', async () => {
test('read and write', async () => {
const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
-
+
// String
await session.filesystem.write('/tmp/test.txt', 'Hello World!')
const content = await session.filesystem.read('/tmp/test.txt')
expect(content).toEqual('Hello World!')
-
+
// Binary file
const binaryFile = fs.readFileSync(path.join(__dirname, '/assets/video.webm'))
await session.filesystem.writeBytes('/tmp/video.webm', binaryFile)
diff --git a/packages/js-sdk/test/logging.test.mjs b/packages/js-sdk/test/logging.test.mjs
index 50ba87db8..6e8b28f1e 100644
--- a/packages/js-sdk/test/logging.test.mjs
+++ b/packages/js-sdk/test/logging.test.mjs
@@ -3,34 +3,34 @@ import { expect, test, vi } from 'vitest'
test('no logs in console during very basic scenario', async () => {
const consoleSpy = {
- debug: vi.spyOn(console, "debug"),
- info: vi.spyOn(console, "info"),
- warn: vi.spyOn(console, "warn"),
- error: vi.spyOn(console, "error"),
+ debug: vi.spyOn(console, 'debug'),
+ info: vi.spyOn(console, 'info'),
+ warn: vi.spyOn(console, 'warn'),
+ error: vi.spyOn(console, 'error'),
}
- const session = await Session.create({ id: "Nodejs", apiKey: process.env.E2B_API_KEY });
- await session.filesystem.write("test.txt", "Hello World");
+ const session = await Session.create({ id: 'Nodejs', apiKey: process.env.E2B_API_KEY })
+ await session.filesystem.write('test.txt', 'Hello World')
await session.close()
- expect(consoleSpy.debug).toHaveBeenCalledTimes(0);
- expect(consoleSpy.info).toHaveBeenCalledTimes(2);
- expect(consoleSpy.error).toHaveBeenCalledTimes(0);
+ expect(consoleSpy.debug).toHaveBeenCalledTimes(0)
+ expect(consoleSpy.info).toHaveBeenCalledTimes(2)
+ expect(consoleSpy.error).toHaveBeenCalledTimes(0)
})
// TODO: Re-enable https://e2b-team.slack.com/archives/C05AGT4UFMJ/p1694697558738799?thread_ts=1694697479.308769&cid=C05AGT4UFMJ
test.skip('warn logs in console during convoluted scenario', async () => {
const consoleSpy = {
- debug: vi.spyOn(console, "debug"),
- info: vi.spyOn(console, "info"),
- warn: vi.spyOn(console, "warn"),
- error: vi.spyOn(console, "error"),
+ debug: vi.spyOn(console, 'debug'),
+ info: vi.spyOn(console, 'info'),
+ warn: vi.spyOn(console, 'warn'),
+ error: vi.spyOn(console, 'error'),
}
- const session = await Session.create({ id: "Nodejs", apiKey: process.env.E2B_API_KEY });
+ const session = await Session.create({ id: 'Nodejs', apiKey: process.env.E2B_API_KEY })
await session.close() // Note that we are intentionally closing and then trying to write
const warnsAmount = consoleSpy.warn.mock.calls.length
-
+
// void to explicitly not awaiting, we wanna check if logging is happening correctly during retries
void session.filesystem.read('/etc/hosts') // this should trigger retries
setTimeout(() => {
@@ -40,23 +40,25 @@ test.skip('warn logs in console during convoluted scenario', async () => {
test('verbose & info logs in console when opted-in', async () => {
const consoleSpy = {
- info: vi.spyOn(console, "info"),
- warn: vi.spyOn(console, "warn"),
- error: vi.spyOn(console, "error"),
+ info: vi.spyOn(console, 'info'),
+ warn: vi.spyOn(console, 'warn'),
+ error: vi.spyOn(console, 'error'),
}
-
+
const logger = {
info: console.info,
warn: console.warn,
error: console.error,
}
- const session = await Session.create({ id: "Nodejs", apiKey: process.env.E2B_API_KEY, logger });
- await session.filesystem.write("test.txt", "Hello World");
+ const session = await Session.create({
+ id: 'Nodejs',
+ apiKey: process.env.E2B_API_KEY,
+ logger,
+ })
+ await session.filesystem.write('test.txt', 'Hello World')
await session.close()
- expect(consoleSpy.info).toHaveBeenCalled();
- expect(consoleSpy.error).toHaveBeenCalledTimes(0);
+ expect(consoleSpy.info).toHaveBeenCalled()
+ expect(consoleSpy.error).toHaveBeenCalledTimes(0)
})
-
-
diff --git a/packages/js-sdk/test/process.test.mjs b/packages/js-sdk/test/process.test.mjs
index 05c6126ef..5fdb84fa7 100644
--- a/packages/js-sdk/test/process.test.mjs
+++ b/packages/js-sdk/test/process.test.mjs
@@ -4,36 +4,44 @@ import { expect, test, vi } from 'vitest'
const E2B_API_KEY = process.env.E2B_API_KEY
test('process on stdout/stderr', async () => {
- const session = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
const stdout = []
const stderr = []
const process = await session.process.start({
- cmd: "pwd",
+ cmd: 'pwd',
onStdout: data => stdout.push(data),
onStderr: data => stderr.push(data),
- rootdir: "/tmp"
+ rootdir: '/tmp',
})
-
+
const output = await process.finished
expect(output.error).toEqual(false)
- expect(output.stdout).toEqual("/tmp")
- expect(output.stderr).toEqual("")
- expect(stdout.map(message => message.line)).toEqual(["/tmp"])
+ expect(output.stdout).toEqual('/tmp')
+ expect(output.stderr).toEqual('')
+ expect(stdout.map(message => message.line)).toEqual(['/tmp'])
expect(stderr).toEqual([])
await session.close()
})
+test('process expected stdout', async () => {
+ // TODO
+})
+
+test('process expected stderr', async () => {
+ // TODO
+})
+
test('process on exit', async () => {
- const session = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
const onExit = vi.fn(() => {})
const process = await session.process.start({
- cmd: "pwd",
- onExit
+ cmd: 'pwd',
+ onExit,
})
await process.finished
@@ -43,18 +51,18 @@ test('process on exit', async () => {
})
test('process send stdin', async () => {
- const session = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
const process = await session.process.start({
cmd: 'read -r line; echo "$line"',
- rootdir: "/code"
+ rootdir: '/code',
})
- await process.sendStdin("ping\n")
+ await process.sendStdin('ping\n')
await process.finished
- expect(process.output.stdout).toEqual("ping")
+ expect(process.output.stdout).toEqual('ping')
// TODO: Parity with Python SDK
- // expect(process.output.messages.length).toEqual(1)
+ // expect(process.output.messages.length).toEqual(1)
// const message = process.output_messages[0]
// assert.equal(message.line, "ping")
// assert.equal(message.error, false)
diff --git a/packages/js-sdk/test/run.mjs b/packages/js-sdk/test/run.mjs
index 601adb553..0c2972fe0 100644
--- a/packages/js-sdk/test/run.mjs
+++ b/packages/js-sdk/test/run.mjs
@@ -1,12 +1,22 @@
-import { Session } from '../dist/cjs/index.js'
+import { runCode } from '../dist/cjs/index.js'
async function main() {
- const session = await Session.create({
- id: 'Nodejs',
- apiKey: process.env.E2B_API_KEY,
- })
+ // const session = await Session.create({
+ // id: 'Nodejs',
+ // apiKey: process.env.E2B_API_KEY,
+ // })
try {
+ // const code = 'console.log("Hello World"); console.error("Bum")'
+ const code = `
+print("hello")
+raise Exception("err")
+`
+ const out = await runCode('Python3', code)
+ console.log(out)
+ // console.log('stdout', stdout)
+ // console.log('stderr', stderr)
+
// await session.filesystem.write('/code/file', 'test')
// const content = await session.filesystem.read('/code/file')
// console.log('content', content)
@@ -16,15 +26,6 @@ async function main() {
// // onExit: () => console.log('exit'),
// // onStdout: data => console.log(data.line),
// })
- const process = await session.process.start('npm init -y')
-
- const output = await process.finished
-
- console.log('output:', output)
- console.log('stdout:', output.stdout)
- console.log('stderr:', output.stderr)
-
- await session.close()
// const cmd = 'npm i'
// await session.process.start({
diff --git a/packages/js-sdk/test/runCode.test.mjs b/packages/js-sdk/test/runCode.test.mjs
new file mode 100644
index 000000000..fca6e8dbf
--- /dev/null
+++ b/packages/js-sdk/test/runCode.test.mjs
@@ -0,0 +1,21 @@
+import { runCode } from '../src'
+import { expect, test } from 'vitest'
+
+// test('run code', async () => {
+// const code = `
+// print("hello")
+// raise Exception("err")
+// `
+// const { stdout, stderr } = await runCode('Python3', code)
+// console.log('stdout', stdout)
+// console.log('stderr', stderr)
+
+// expect(stdout).toEqual('hello')
+// // expect(stderr).toContain('Exception: err')
+// })
+
+test('run code using unsupported runtime', async () => {
+ await expect(await runCode('Unsupported', 'print("hello")')).rejects.toThrow(
+ "runtime isn't supported",
+ )
+})
diff --git a/packages/js-sdk/test/session.test.mjs b/packages/js-sdk/test/session.test.mjs
index da06f060a..aa626384c 100644
--- a/packages/js-sdk/test/session.test.mjs
+++ b/packages/js-sdk/test/session.test.mjs
@@ -1,16 +1,16 @@
import { Session } from '../src'
-import { expect, test, vi } from 'vitest'
+import { test } from 'vitest'
const E2B_API_KEY = process.env.E2B_API_KEY
test('create session', async () => {
- const session = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
await session.close()
})
test('create multiple sessions', async () => {
- const session = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
- const session2 = await Session.create({ id: "Nodejs", apiKey: E2B_API_KEY })
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session2 = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
await session.close()
await session2.close()
}, 10000)
diff --git a/packages/js-sdk/test/timeout.test.mjs b/packages/js-sdk/test/timeout.test.mjs
index f7fd5ff90..41be4ab0d 100644
--- a/packages/js-sdk/test/timeout.test.mjs
+++ b/packages/js-sdk/test/timeout.test.mjs
@@ -58,16 +58,21 @@ test.skip('timeout process', async () => {
})
// TODO: Waiting for https://github.com/vitest-dev/vitest/issues/3119
-test.skip('timeout longer than cmd should not leak', () => new Promise(async (resolve) => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
- const start = Date.now();
- const proc = await session.process.start({
- cmd: "node -e 'setTimeout(() => {}, 1000)'", // should take around 1 second
- onExit: () => {
- // TODO: Verify that process finished after successful cmd, and not after timeout
- resolve()
- },
- timeout: 10_000 // but we give it 10 seconds
- })
- await proc.finished
-}), {timeout: 12_000})
+test.skip(
+ 'timeout longer than cmd should not leak',
+ () =>
+ new Promise(async resolve => {
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const start = Date.now()
+ const proc = await session.process.start({
+ cmd: "node -e 'setTimeout(() => {}, 1000)'", // should take around 1 second
+ onExit: () => {
+ // TODO: Verify that process finished after successful cmd, and not after timeout
+ resolve()
+ },
+ timeout: 10_000, // but we give it 10 seconds
+ })
+ await proc.finished
+ }),
+ { timeout: 12_000 },
+)