Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Finish basic parity for JS SDK (#88)

Tomas Valenta42ff773013a1
diff --git a/packages/js-sdk/rollup.config.js b/packages/js-sdk/rollup.config.js
index 382611e6b..f26a6257b 100644
--- a/packages/js-sdk/rollup.config.js
+++ b/packages/js-sdk/rollup.config.js
@@ -32,7 +32,9 @@ export default {
external: ['cross-fetch', 'cross-fetch/polyfill'],
plugins: [
autoExternal({ builtins: false }),
- typescript(),
+ typescript({
+ clean: false,
+ }),
nodePolyfills(),
nodeResolve({
preferBuiltins: true,
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index fac5c6808..458a27fc7 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -2,7 +2,8 @@ export { Session } from './session'
export type { Environment } from './session'
export type { SessionOpts } from './session'
export type { OpenPort } from './session/codeSnippet'
-export type { TerminalManager, Terminal as TerminalSession } from './session/terminal'
+export { Terminal, TerminalOutput } from './session/terminal'
+export type { TerminalManager } from './session/terminal'
export type { FilesystemManager, FileInfo } from './session/filesystem'
export {
default as FilesystemWatcher,
diff --git a/packages/js-sdk/src/session/index.ts b/packages/js-sdk/src/session/index.ts
index 71c4bd19a..990fcadf5 100644
--- a/packages/js-sdk/src/session/index.ts
+++ b/packages/js-sdk/src/session/index.ts
@@ -17,7 +17,7 @@ import {
processService,
} from './process'
import { SessionConnection, SessionConnectionOpts } from './sessionConnection'
-import { TerminalManager, terminalService } from './terminal'
+import { Terminal, TerminalManager, TerminalOutput, terminalService } from './terminal'
export type Environment = components['schemas']['Template']
@@ -126,13 +126,20 @@ export class Session extends SessionConnection {
}) => {
const { promise: terminalExited, resolve: triggerExit } = createDeferredPromise()
+ const output = new TerminalOutput()
+
+ function handleData(data: string) {
+ output.addData(data)
+ onData?.(data)
+ }
+
const [onDataSubID, onExitSubID] = await this.handleSubscriptions(
- this.subscribe(terminalService, onData, 'onData', terminalID),
+ this.subscribe(terminalService, handleData, 'onData', terminalID),
this.subscribe(terminalService, triggerExit, 'onExit', terminalID),
)
const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =
- createDeferredPromise()
+ createDeferredPromise<TerminalOutput>()
terminalExited.then(async () => {
const results = await Promise.allSettled([
@@ -146,7 +153,7 @@ export class Session extends SessionConnection {
}
onExit?.()
- handleFinishUnsubscribing()
+ handleFinishUnsubscribing(output)
})
try {
@@ -163,24 +170,7 @@ export class Session extends SessionConnection {
throw err
}
- return {
- finished: unsubscribing,
- kill: async () => {
- try {
- await this.call(terminalService, 'destroy', [terminalID])
- } finally {
- triggerExit()
- await unsubscribing
- }
- },
- resize: async ({ cols, rows }) => {
- await this.call(terminalService, 'resize', [terminalID, cols, rows])
- },
- sendData: async data => {
- await this.call(terminalService, 'data', [terminalID, data])
- },
- terminalID,
- }
+ return new Terminal(terminalID, this, triggerExit, unsubscribing, output)
},
}
@@ -233,8 +223,8 @@ export class Session extends SessionConnection {
this.logger.error(errMsg)
}
- handleFinishUnsubscribing(output)
onExit?.()
+ handleFinishUnsubscribing(output)
})
try {
diff --git a/packages/js-sdk/src/session/process.ts b/packages/js-sdk/src/session/process.ts
index a47c4952b..577caf22f 100644
--- a/packages/js-sdk/src/session/process.ts
+++ b/packages/js-sdk/src/session/process.ts
@@ -74,7 +74,6 @@ export class ProcessOutput {
/**
* A process running in the environment.
- *
*/
export class Process {
constructor(
diff --git a/packages/js-sdk/src/session/sessionConnection.ts b/packages/js-sdk/src/session/sessionConnection.ts
index 5e8e24974..192eb70a1 100644
--- a/packages/js-sdk/src/session/sessionConnection.ts
+++ b/packages/js-sdk/src/session/sessionConnection.ts
@@ -120,79 +120,6 @@ export class SessionConnection {
}
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- async call(service: Service, method: string, params?: any[]) {
- return this.rpc.call(`${service}_${method}`, params)
- }
-
- async handleSubscriptions<
- T extends (ReturnType<SessionConnection['subscribe']> | undefined)[],
- >(
- ...subs: T
- ): Promise<{
- [P in keyof T]: Awaited<T[P]>
- }> {
- const results = await Promise.allSettled(subs)
-
- if (results.every(r => r.status === 'fulfilled')) {
- return results.map(r => (r.status === 'fulfilled' ? r.value : undefined)) as {
- [P in keyof T]: Awaited<T[P]>
- }
- }
-
- await Promise.all(
- results
- .filter(assertFulfilled)
- .map(r => (r.value ? this.unsubscribe(r.value) : undefined)),
- )
-
- throw new Error(formatSettledErrors(results))
- }
-
- async unsubscribe(subID: string) {
- const subscription = this.subscribers.find(s => s.subID === subID)
- if (!subscription) return
-
- await this.call(subscription.service, 'unsubscribe', [subscription.subID])
-
- this.subscribers = this.subscribers.filter(s => s !== subscription)
- this.logger.log(`Unsubscribed '${subID}' from '${subscription.service}'`)
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- async subscribe(
- service: Service,
- handler: SubscriptionHandler,
- method: string,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ...params: any[]
- ) {
- const subID = await this.call(service, 'subscribe', [method, ...params])
-
- if (typeof subID !== 'string') {
- throw new Error(
- // eslint-disable-next-line prettier/prettier
- `Cannot subscribe to ${service}_${method}${params.length > 0 ? ' with params [' + params.join(', ') + ']' : ''
- }. Expected response should have been a subscription ID, instead we got ${JSON.stringify(
- subID,
- )}`,
- )
- }
-
- this.subscribers.push({
- handler,
- service,
- subID,
- })
- this.logger.log(
- // eslint-disable-next-line prettier/prettier
- `Subscribed to "${service}_${method}"${params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''
- } with id "${subID}"`,
- )
-
- return subID
- }
-
/**
* Open a connection to a new session
*
@@ -309,6 +236,79 @@ export class SessionConnection {
return this
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ async call(service: Service, method: string, params?: any[]) {
+ return this.rpc.call(`${service}_${method}`, params)
+ }
+
+ async handleSubscriptions<
+ T extends (ReturnType<SessionConnection['subscribe']> | undefined)[],
+ >(
+ ...subs: T
+ ): Promise<{
+ [P in keyof T]: Awaited<T[P]>
+ }> {
+ const results = await Promise.allSettled(subs)
+
+ if (results.every(r => r.status === 'fulfilled')) {
+ return results.map(r => (r.status === 'fulfilled' ? r.value : undefined)) as {
+ [P in keyof T]: Awaited<T[P]>
+ }
+ }
+
+ await Promise.all(
+ results
+ .filter(assertFulfilled)
+ .map(r => (r.value ? this.unsubscribe(r.value) : undefined)),
+ )
+
+ throw new Error(formatSettledErrors(results))
+ }
+
+ async unsubscribe(subID: string) {
+ const subscription = this.subscribers.find(s => s.subID === subID)
+ if (!subscription) return
+
+ await this.call(subscription.service, 'unsubscribe', [subscription.subID])
+
+ this.subscribers = this.subscribers.filter(s => s !== subscription)
+ this.logger.log(`Unsubscribed '${subID}' from '${subscription.service}'`)
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ async subscribe(
+ service: Service,
+ handler: SubscriptionHandler,
+ method: string,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ...params: any[]
+ ) {
+ const subID = await this.call(service, 'subscribe', [method, ...params])
+
+ if (typeof subID !== 'string') {
+ throw new Error(
+ // eslint-disable-next-line prettier/prettier
+ `Cannot subscribe to ${service}_${method}${params.length > 0 ? ' with params [' + params.join(', ') + ']' : ''
+ }. Expected response should have been a subscription ID, instead we got ${JSON.stringify(
+ subID,
+ )}`,
+ )
+ }
+
+ this.subscribers.push({
+ handler,
+ service,
+ subID,
+ })
+ this.logger.log(
+ // eslint-disable-next-line prettier/prettier
+ `Subscribed to "${service}_${method}"${params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''
+ } with id "${subID}"`,
+ )
+
+ return subID
+ }
+
private handleNotification(data: IRpcNotification) {
this.subscribers
.filter(s => s.subID === data.params?.subscription)
diff --git a/packages/js-sdk/src/session/terminal.ts b/packages/js-sdk/src/session/terminal.ts
index 2f9643a53..252131ae8 100644
--- a/packages/js-sdk/src/session/terminal.ts
+++ b/packages/js-sdk/src/session/terminal.ts
@@ -1,13 +1,67 @@
import { EnvVars } from './envVars'
+import { SessionConnection } from './sessionConnection'
export const terminalService = 'terminal'
-export interface Terminal {
- readonly sendData: (data: string) => Promise<void>
- readonly resize: ({ cols, rows }: { cols: number; rows: number }) => Promise<void>
- readonly kill: () => Promise<void>
- readonly terminalID: string
- readonly finished: Promise<void>
+export class TerminalOutput {
+ private _data = ''
+
+ get data() {
+ return this._data
+ }
+
+ addData(data: string) {
+ this._data += data
+ }
+}
+
+/**
+ * A terminal session running in the environment.
+ */
+export class Terminal {
+ constructor(
+ readonly terminalID: string,
+ private readonly session: SessionConnection,
+ private readonly triggerExit: () => void,
+ readonly finished: Promise<TerminalOutput>,
+ readonly output: TerminalOutput,
+ ) {}
+
+ get data() {
+ return this.output.data
+ }
+
+ /**
+ * Kills the terminal session.
+ */
+ async kill(): Promise<void> {
+ try {
+ // TODO: Change the "destroy" to "kill" in devbookd
+ await this.session.call(terminalService, 'destroy', [this.terminalID])
+ } finally {
+ this.triggerExit()
+ await this.finished
+ }
+ }
+
+ /**
+ * Sends data to the terminal standard input.
+ *
+ * @param data Data to send
+ */
+ async sendData(data: string): Promise<void> {
+ await this.session.call(terminalService, 'data', [this.terminalID, data])
+ }
+
+ /**
+ * Resizes the terminal tty.
+ *
+ * @param cols Number of columns
+ * @param rows Number of rows
+ */
+ async resize({ cols, rows }: { cols: number; rows: number }): Promise<void> {
+ await this.session.call(terminalService, 'resize', [this.terminalID, cols, rows])
+ }
}
export interface TerminalManager {