Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add persistent process handling

Tomas Valentad296693cf9ab
diff --git a/api-service/playground/src/sessions/process.ts b/api-service/playground/src/sessions/process.ts
new file mode 100644
index 000000000..b790e7561
--- /dev/null
+++ b/api-service/playground/src/sessions/process.ts
@@ -0,0 +1,38 @@
+import {
+ OutStderrResponse,
+ OutStdoutResponse,
+ ProcessManager,
+ createSessionProcess,
+ Process,
+} from '@devbookhq/sdk'
+
+export interface RunProcessParams extends Pick<Parameters<ProcessManager['start']>[0], 'cmd' | 'envVars' | 'rootdir'> { }
+
+export class CachedProcess {
+ readonly stdout: OutStdoutResponse[] = []
+ readonly stderr: OutStderrResponse[] = []
+
+ private started = false
+ process?: Process
+ exited?: Promise<void>
+
+ constructor(private readonly manager: ProcessManager) { }
+
+ async start(params: RunProcessParams) {
+ if (this.started) throw new Error('Process already started')
+ this.started = true
+
+ const stderr: OutStderrResponse[] = []
+ const stdout: OutStdoutResponse[] = []
+
+ const process = await createSessionProcess({
+ manager: this.manager,
+ ...params,
+ onStderr: stderr.push,
+ onStdout: stdout.push,
+ })
+
+ this.process = process
+ return process
+ }
+}
diff --git a/api-service/playground/src/sessions/session.ts b/api-service/playground/src/sessions/session.ts
new file mode 100644
index 000000000..66b87422c
--- /dev/null
+++ b/api-service/playground/src/sessions/session.ts
@@ -0,0 +1,84 @@
+import { Session } from '@devbookhq/sdk'
+import NodeCache from 'node-cache'
+import { CachedProcess, RunProcessParams } from './process'
+
+export const sessionCache = new NodeCache({
+ stdTTL: 60000,
+ checkperiod: 5000,
+ useClones: false,
+ deleteOnExpire: true,
+})
+
+sessionCache.on('expired', async function (_, cached: CachedSession) {
+ try {
+ await cached.delete()
+ } catch (err) {
+ console.error(err)
+ }
+})
+
+export class CachedSession {
+ private readonly cachedProcesses: CachedProcess[] = []
+
+ private id?: string
+ session: Session
+
+ /**
+ * You must call `.init()` to start the session.
+ *
+ * @param envID
+ */
+ constructor(envID: string) {
+ this.session = new Session({ id: envID })
+ }
+
+ async init() {
+ await this.session.open()
+
+ const url = this.session.getHostname()
+ if (!url) throw new Error('Cannot start session')
+
+ const [id,] = url.split('.')
+ this.id = id
+ sessionCache.set(id, this)
+
+ return id
+ }
+
+ async delete() {
+ if (!this.id) return
+
+ await this.session.close()
+ sessionCache.del(this.id)
+
+ this.id = undefined
+ }
+
+ async stopProcess(processID: string) {
+ await this.findProcess(processID)?.process?.kill()
+ const idx = this.cachedProcesses.findIndex(p => p.process?.processID === processID)
+ if (idx !== -1) {
+ this.cachedProcesses.splice(idx, 1)
+ }
+ }
+
+ findProcess(processID: string) {
+ return this.cachedProcesses.find(p => p.process?.processID === processID)
+ }
+
+ async startProcess(params: RunProcessParams) {
+ if (!this.session.process) throw new Error('Session is not open')
+
+ const cachedProcess = new CachedProcess(this.session.process)
+ await cachedProcess.start(params)
+ this.cachedProcesses.push(cachedProcess)
+
+ return cachedProcess
+ }
+
+ static findSession(id: string) {
+ const cachedSession = sessionCache.get(id) as CachedSession
+ if (!cachedSession) throw new Error('Session does not exist')
+ return cachedSession
+ }
+}
diff --git a/api-service/playground/src/sessions/sessions.ts b/api-service/playground/src/sessions/sessions.ts
deleted file mode 100644
index e0495b0e1..000000000
--- a/api-service/playground/src/sessions/sessions.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { OutStderrResponse, OutStdoutResponse, Process, Session } from '@devbookhq/sdk'
-import NodeCache from 'node-cache'
-
-export const sessionCache = new NodeCache({
- stdTTL: 60000,
- checkperiod: 5000,
- useClones: false,
- deleteOnExpire: true,
-})
-
-interface CachedProcess {
- process: Process
- stdout: OutStdoutResponse[]
- stderr: OutStderrResponse[]
-}
-
-interface CacheEntry {
- session: Session
- processes?: CachedProcess[]
-}
-
-sessionCache.on('del', async function (_, entry: CacheEntry) {
- try {
- await entry.session.close()
- } catch (err) {
- console.error(err)
- }
-})
-
-export async function initSession(envID: string) {
- const session = new Session({
- id: envID,
- })
- await session.open()
- const url = session.getHostname()
- if (!url) throw new Error('Cannot start session')
-
- const [id,] = url.split('.')
-
- const entry: CacheEntry = {
- session,
- }
-
- sessionCache.set(id, entry)
- return id
-}
-
-export function retrieveEntry(id: string) {
- const entry = sessionCache.get(id) as CacheEntry | undefined
- if (!entry) throw new Error('Session does not exist')
-
- return entry
-}
-
-export async function closeSession(id: string) {
- const entry = retrieveEntry(id)
- if (entry) {
- await entry.session.close()
- sessionCache.del(id)
- }
-}