Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Implement reconnecting in JS
Jakub Novakb33da692c01c
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex 7286ae232..d6e771169 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -49,6 +49,14 @@ export interface paths {401: components["responses"]["401"];404: components["responses"]["404"];};+ requestBody: {+ content: {+ "application/json": {+ /** @description Duration for which the instance should be kept alive in seconds */+ duration: number;+ };+ };+ };};};"/envs": {diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex f7acdbf7b..e4de80c72 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -454,6 +454,42 @@ export class Sandbox extends SandboxConnection {})}+ /**+ * Reconnects to an existing Sandbox.+ * @param sandboxIDorOpts Sandbox ID or Sandbox options+ * @returns Existing Sandbox+ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.reconnect(sandboxID)+ * ```+ */+ static async reconnect(sandboxIDorOpts: string | Omit<SandboxOpts, 'id'> & { sandboxID: string }) {+ let sandboxID+ let opts: SandboxOpts+ if (typeof sandboxIDorOpts === 'string'){+ sandboxID = sandboxIDorOpts+ opts = {}+ } else {+ sandboxID = sandboxIDorOpts.sandboxID+ opts = sandboxIDorOpts+ }++ const instanceIDAndClientID = sandboxID.split("-")+ const instanceID = instanceIDAndClientID[0]+ const clientID = instanceIDAndClientID[1]+ opts.__sandbox = { instanceID, clientID, envID: 'unknown' }+ return new Sandbox(opts)+ ._open({ timeout: opts?.timeout })+ .then(async (sandbox) => {+ if (opts?.cwd) {+ console.log(`Custom cwd for Sandbox set: "${opts.cwd}"`)+ await sandbox.filesystem.makeDir(opts.cwd)+ }+ return sandbox+ })+ }+protected override async _open(opts: CallOpts) {await super._open(opts)diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.tsindex bbd3da155..ec3747b46 100644--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts@@ -39,6 +39,7 @@ export interface SandboxConnectionOpts {cwd?: string;envVars?: EnvVars;logger?: Logger;+ __sandbox?: components['schemas']['Instance'];__debug_hostname?: string;__debug_port?: number;__debug_devEnv?: 'remote' | 'local';@@ -67,8 +68,10 @@ export class SandboxConnection {private readonly rpc = new RpcWebSocketClient()private subscribers: Subscriber[] = []+// let's keep opts readonly, but public - for convenience, mainly when debuggingprotected constructor(readonly opts: SandboxConnectionOpts) {+ this.sandbox = opts.__sandboxconst apiKey = opts.apiKey || process?.env?.E2B_API_KEYif (!apiKey) {throw new AuthenticationError(@@ -93,10 +96,26 @@ export class SandboxConnection {this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}+ get id() {+ return `${this.sandbox?.instanceID}-${this.sandbox?.clientID}`+ }+private get templateID(): string {return this.opts.id || 'base'}++ public async keepAlive(duration: number) {+ if (!this.sandbox) {+ throw new Error('Cannot keep alive - sandbox is not initialized')+ }+ await refreshSandbox(this.apiKey, {+ instanceID: this.sandbox?.instanceID, duration,+ })+ }+++/*** Get the hostname for the sandbox or for the specified sandbox's port.*@@ -257,14 +276,14 @@ export class SandboxConnection {*/protected async _open(opts: CallOpts) {const open = async () => {- if (this.isOpen || !!this.sandbox) {+ if (this.isOpen) {throw new Error('Sandbox connect was already called')} else {this.isOpen = true}this.logger.debug?.('Opening sandbox...')- if (!this.opts.__debug_hostname) {+ if (!this.sandbox) {try {const res = await createSandbox(this.apiKey, {envID: this.templateID,@@ -272,8 +291,6 @@ export class SandboxConnection {this.sandbox = res.datathis.logger.debug?.(`Acquired sandbox "${this.sandbox.instanceID}"`)-- this.refresh(this.sandbox.instanceID)} catch (e) {if (e instanceof createSandbox.Error) {const error = e.getActualType()@@ -296,7 +313,7 @@ export class SandboxConnection {throw e}}-+ this.refresh(this.sandbox.instanceID)const hostname = this.getHostname(this.opts.__debug_port || ENVD_PORT)if (!hostname) {@@ -417,7 +434,7 @@ export class SandboxConnection {this.logger.debug?.(`Refreshed sandbox "${instanceID}"`)await refreshSandbox(this.apiKey, {- instanceID,+ instanceID, duration: 0,})} catch (e) {if (e instanceof refreshSandbox.Error) {diff --git a/packages/js-sdk/testground/basic.cjs b/packages/js-sdk/testground/basic.cjsindex 7ba7915a8..f7e28aa7b 100644--- a/packages/js-sdk/testground/basic.cjs+++ b/packages/js-sdk/testground/basic.cjs@@ -1,4 +1,7 @@const e2b = require('../dist')+function wait(ms) {+ return new Promise(resolve => setTimeout(resolve, ms))+}async function main() {const sandbox = await e2b.Sandbox.create({@@ -7,35 +10,22 @@ async function main() {})await sandbox.filesystem.write(- '/code/package.json',- JSON.stringify({- dependencies: {- 'is-odd': '3.0.1'- }- })+ '/code/hello.txt', "My friend!")+ const sandboxID = sandbox.id- const proc = await sandbox.process.start({- cmd: 'npm i --silent',- envVars: { NPM_CONFIG_UPDATE_NOTIFIER: 'false' },- cwd: '/code',- onStdout: ({ line }) => console.log('STDOUT', line),- onStderr: ({ line }) => console.log('STDERR', line)- })+ await sandbox.keepAlive(60)+ await sandbox.close()+ await wait(20000)- await proc.finished+ const sandbox2 = await e2b.Sandbox.reconnect(sandboxID)- // list node_modules- const files = await sandbox.filesystem.list('/code/node_modules')+ const files = await sandbox2.filesystem.read('/code/hello.txt')console.log(- 'installed node_modules (first 10 of them):',files- .map(f => f.name)- .slice(0, 10)- .join(', '))- await sandbox.close()+ await sandbox2.close()}main().catch(console.error)diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.pyindex 9e0cfd7df..644ef0922 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py@@ -118,6 +118,7 @@ class SandboxConnection:*args,**kwargs,):+ logger.info(f"Reconnecting to sandbox {sandbox_id}")instance_id, client_id = sandbox_id.split("-")return cls(*args,