Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat: enable piping on the e2b cli (#1127)
Matt Brockman87ceec29d932
diff --git a/.changeset/strict-paths-kiss.md b/.changeset/strict-paths-kiss.mdnew file mode 100644index 000000000..01c7c72ba--- /dev/null+++ b/.changeset/strict-paths-kiss.md@@ -0,0 +1,5 @@+---+'@e2b/cli': minor+---++Implement closeStdin to allow piping commands into the CLIdiff --git a/packages/cli/src/commands/sandbox/exec.ts b/packages/cli/src/commands/sandbox/exec.tsindex 57a0398da..959ee56ae 100644--- a/packages/cli/src/commands/sandbox/exec.ts+++ b/packages/cli/src/commands/sandbox/exec.ts@@ -1,19 +1,13 @@/*** Execute a command in a running sandbox.- *- * NOTE: Stdin piping (e.g., `echo "data" | e2b exec sandbox cmd`) is not supported.- * The SDK/envd protocol lacks a way to signal EOF to remote commands. Commands that- * read until EOF (cat, grep, wc, etc.) would hang indefinitely. This requires envd- * to add stdin close signaling before it can be implemented.*/-import * as fs from 'fs'--import { Sandbox, CommandExitError } from 'e2b'+import { Sandbox, CommandExitError, NotFoundError } from 'e2b'import * as commander from 'commander'import { ensureAPIKey } from '../../api'import { setupSignalHandlers } from 'src/utils/signal'+import { buildCommand, isPipedStdin, streamStdinChunks } from './exec_helpers'interface ExecOptions {background?: boolean@@ -23,7 +17,6 @@ interface ExecOptions {}const NO_COMMAND_TIMEOUT = 0-export const execCommand = new commander.Command('exec').description('execute a command in a running sandbox').argument('<sandboxID>', 'sandbox ID to execute command in')@@ -46,23 +39,24 @@ export const execCommand = new commander.Command('exec').alias('ex').action(async (sandboxID: string, commandParts: string[], opts: ExecOptions) => {- // Check if stdin is a pipe (data being piped in) - not supported- try {- const stdinStats = fs.fstatSync(0)- if (stdinStats.isFIFO()) {- console.error('e2b: stdin piping is not supported')- process.exit(2)- }- } catch {- // fstatSync may fail in some environments, ignore- }+ const hasPipedStdin = isPipedStdin()- const command = commandParts.join(' ')+ const command = buildCommand(commandParts)try {const apiKey = ensureAPIKey()-const sandbox = await Sandbox.connect(sandboxID, { apiKey })+ if (hasPipedStdin && !sandbox.commands.supportsStdinClose) {+ console.error(+ 'e2b: Warning: Piped stdin is not supported by this sandbox version.\n' ++ 'e2b: Rebuild your template to pick up the latest sandbox version.\n' ++ 'e2b: Ignoring piped stdin.'+ )+ }++ const canPipeStdin =+ hasPipedStdin && sandbox.commands.supportsStdinClose+if (opts.background) {const handle = await sandbox.commands.run(command, {background: true,@@ -70,8 +64,21 @@ export const execCommand = new commander.Command('exec')user: opts.user,envs: opts.env,timeoutMs: NO_COMMAND_TIMEOUT,+ ...(canPipeStdin ? { stdin: true } : {}),})+ const removeSignalHandlers = setupSignalHandlers(async () => {+ await handle.kill()+ })++ try {+ if (canPipeStdin) {+ await sendStdin(sandbox, handle.pid)+ }+ } finally {+ removeSignalHandlers()+ }+console.error(handle.pid)await handle.disconnect()@@ -80,7 +87,7 @@ export const execCommand = new commander.Command('exec')process.exit(0)}- const exitCode = await runCommand(sandbox, command, opts)+ const exitCode = await runCommand(sandbox, command, opts, canPipeStdin)process.exit(exitCode)} catch (err: any) {@@ -93,7 +100,8 @@ export const execCommand = new commander.Command('exec')async function runCommand(sandbox: Sandbox,command: string,- opts: ExecOptions+ opts: ExecOptions,+ openStdin: boolean): Promise<number> {const handle = await sandbox.commands.run(command, {background: true,@@ -117,6 +125,7 @@ async function runCommand(await handle.kill()}},+ ...(openStdin ? { stdin: true } : {}),})const removeSignalHandlers = setupSignalHandlers(async () => {@@ -125,6 +134,10 @@ async function runCommand(})try {+ if (openStdin) {+ await sendStdin(sandbox, handle.pid)+ }+const result = await handle.wait()return result.exitCode@@ -143,3 +156,63 @@ async function runCommand(removeSignalHandlers()}}++async function sendStdin(sandbox: Sandbox, pid: number): Promise<void> {+ const chunkSizeBytes = 64 * 1024+ let processExited = false++ await streamStdinChunks(+ process.stdin,+ async (chunk) => {+ if (processExited) {+ return false+ }++ try {+ await sandbox.commands.sendStdin(pid, chunk)+ } catch (err) {+ if (err instanceof NotFoundError) {+ processExited = true+ console.error(+ 'e2b: Remote command exited before stdin could be delivered.'+ )+ return false+ }+ throw err+ }+ },+ chunkSizeBytes+ )++ if (processExited) {+ return+ }++ // Signal EOF so commands like cat/wc/grep terminate.+ try {+ await sandbox.commands.closeStdin(pid)+ } catch (err) {+ if (err instanceof NotFoundError) {+ // Process already exited — EOF is moot.+ return+ }++ // Fail fast instead of leaving a command blocked on stdin forever.+ await killProcessBestEffort(sandbox, pid)+ throw err+ }+}++async function killProcessBestEffort(+ sandbox: Sandbox,+ pid: number+): Promise<void> {+ try {+ await sandbox.commands.kill(pid)+ } catch (killErr) {+ console.error(+ 'e2b: Failed to kill remote process after stdin EOF signaling failed.'+ )+ console.error(killErr)+ }+}diff --git a/packages/cli/src/commands/sandbox/exec_helpers.ts b/packages/cli/src/commands/sandbox/exec_helpers.tsnew file mode 100644index 000000000..7dc7cb701--- /dev/null+++ b/packages/cli/src/commands/sandbox/exec_helpers.ts@@ -0,0 +1,121 @@+import * as fs from 'fs'++const SHELL_SAFE_RE = /^[A-Za-z0-9_@%+=:,./-]+$/++export const shellQuote = (arg: string): string => {+ if (arg === '') {+ return "''"+ }+ if (SHELL_SAFE_RE.test(arg)) {+ return arg+ }+ const q = "'\"'\"'"+ return `'${arg.replace(/'/g, q)}'`+}++export const buildCommand = (commandParts: string[]): string => {+ if (commandParts.length === 1) {+ return commandParts[0]+ }++ return commandParts.map(shellQuote).join(' ')+}++type StatLike = {+ isFIFO?: () => boolean+ isFile?: () => boolean+ isSocket?: () => boolean+ isCharacterDevice?: () => boolean+}+type FsLike = { fstatSync: (fd: number) => StatLike }++export const isPipedStdin = (fd = 0, fsModule: FsLike = fs as FsLike) => {+ try {+ const stdinStats = fsModule.fstatSync(fd)+ // Treat any non-interactive stdin as "piped": FIFO pipes and file redirection (`< file`).+ // Keep this conservative so normal terminal stdin doesn't get eagerly drained.+ if (stdinStats.isCharacterDevice?.()) {+ return false+ }+ return Boolean(+ stdinStats.isFIFO?.() || stdinStats.isFile?.() || stdinStats.isSocket?.()+ )+ } catch {+ return false+ }+}++type ReadStdinOptions = {+ fd?: number+ fsModule?: FsLike+ stream?: NodeJS.ReadableStream+}++type StdinChunk = Uint8Array | Buffer | string++export const readStdinIfPiped = async (+ options: ReadStdinOptions = {}+): Promise<Buffer | undefined> => {+ const fd = options.fd ?? 0+ const fsModule = options.fsModule ?? (fs as FsLike)+ if (!isPipedStdin(fd, fsModule)) {+ return undefined+ }+ const stream = options.stream ?? process.stdin+ return await readStdinFrom(stream)+}++export const chunkBytesBySize = (+ data: Uint8Array,+ maxBytes: number+): Uint8Array[] => {+ if (maxBytes <= 0) {+ throw new Error('maxBytes must be greater than 0')+ }++ const chunks: Uint8Array[] = []+ for (let offset = 0; offset < data.length; offset += maxBytes) {+ chunks.push(data.subarray(offset, offset + maxBytes))+ }+ return chunks+}++export async function streamStdinChunks(+ stream: NodeJS.ReadableStream,+ onChunk: (chunk: Uint8Array) => Promise<void | boolean> | void | boolean,+ maxBytes: number+): Promise<void> {+ if (maxBytes <= 0) {+ throw new Error('maxBytes must be greater than 0')+ }++ for await (const rawChunk of stream as AsyncIterable<StdinChunk>) {+ const chunk =+ typeof rawChunk === 'string'+ ? Buffer.from(rawChunk)+ : Buffer.from(rawChunk)++ if (chunk.byteLength === 0) {+ continue+ }++ const pieces = chunkBytesBySize(chunk, maxBytes)+ for (const piece of pieces) {+ const shouldContinue = await onChunk(piece)+ if (shouldContinue === false) {+ return+ }+ }+ }+}++export async function readStdinFrom(+ stream: NodeJS.ReadableStream+): Promise<Buffer> {+ return await new Promise((resolve, reject) => {+ const chunks: Buffer[] = []+ stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)))+ stream.on('end', () => resolve(Buffer.concat(chunks)))+ stream.on('error', reject)+ })+}diff --git a/packages/cli/tests/commands/sandbox/backend_integration.test.ts b/packages/cli/tests/commands/sandbox/backend_integration.test.tsnew file mode 100644index 000000000..32d2b3390--- /dev/null+++ b/packages/cli/tests/commands/sandbox/backend_integration.test.ts@@ -0,0 +1,275 @@+import { spawn, spawnSync } from 'node:child_process'+import path from 'node:path'+import { afterAll, beforeAll, describe, expect, test } from 'vitest'+import { Sandbox } from 'e2b'+import { getUserConfig } from 'src/user'++type UserConfigWithDomain = NonNullable<ReturnType<typeof getUserConfig>> & {+ domain?: string+ E2B_DOMAIN?: string+}++const userConfig = safeGetUserConfig() as UserConfigWithDomain | null+const domain =+ process.env.E2B_DOMAIN ||+ userConfig?.E2B_DOMAIN ||+ userConfig?.domain ||+ 'e2b.app'+const apiKey = process.env.E2B_API_KEY || userConfig?.teamApiKey+const templateId =+ process.env.E2B_CLI_BACKEND_TEMPLATE_ID ||+ process.env.E2B_TEMPLATE_ID ||+ 'base'+const isDebug = process.env.E2B_DEBUG !== undefined+const hasCreds = Boolean(apiKey)+const shouldSkip = !hasCreds || isDebug+const testIf = test.skipIf(shouldSkip)+const cliPath = path.join(process.cwd(), 'dist', 'index.js')+const sandboxTimeoutMs = parseEnvInt(+ 'E2B_CLI_BACKEND_SANDBOX_TIMEOUT_MS',+ 20_000+)+const perTestTimeoutMs = parseEnvInt('E2B_CLI_BACKEND_TEST_TIMEOUT_MS', 30_000)+const spawnTimeoutMs = perTestTimeoutMs++describe('sandbox cli backend integration', () => {+ let sandbox: Sandbox++ beforeAll(async () => {+ if (shouldSkip) return++ sandbox = await Sandbox.create(templateId, {+ apiKey,+ domain,+ timeoutMs: sandboxTimeoutMs,+ })+ }, 30_000)++ afterAll(async () => {+ if (!sandbox) return++ try {+ await sandbox.kill()+ } catch (err) {+ console.warn(+ `Failed to kill sandbox ${sandbox.sandboxId} in cleanup: ${String(err)}`+ )+ }+ }, 15_000)++ testIf('list shows the sandbox', { timeout: perTestTimeoutMs }, async () => {+ const listResult = runCli(['sandbox', 'list', '--format', 'json'])+ expect(listResult.status).toBe(0)+ expect(sandboxExistsInList(listResult.stdout, sandbox.sandboxId)).toBe(true)+ })++ testIf(+ 'exec runs a command without piped stdin',+ { timeout: perTestTimeoutMs },+ async () => {+ const execResult = runCli([+ 'sandbox',+ 'exec',+ sandbox.sandboxId,+ '--',+ 'sh',+ '-lc',+ 'echo backend-non-pipe',+ ])+ expect(execResult.status).toBe(0)+ expect(bufferToText(execResult.stdout)).toContain('backend-non-pipe')+ }+ )++ testIf(+ 'exec runs a command with piped stdin',+ { timeout: perTestTimeoutMs },+ async () => {+ const pipedExecResult = await runCliWithPipedStdin(+ ['sandbox', 'exec', sandbox.sandboxId, '--', 'sh', '-lc', 'wc -c'],+ Buffer.from('hello\n', 'utf8')+ )+ expect(pipedExecResult.status).toBe(0)+ const pipedStdout = bufferToText(pipedExecResult.stdout).trim()+ if (pipedStdout !== '6') {+ expect(pipedStdout).toBe('0')+ }+ }+ )++ testIf(+ 'logs returns successfully',+ { timeout: perTestTimeoutMs },+ async () => {+ const logsResult = runCli([+ 'sandbox',+ 'logs',+ sandbox.sandboxId,+ '--format',+ 'json',+ ])+ expect(logsResult.status).toBe(0)+ }+ )++ testIf(+ 'metrics returns successfully',+ { timeout: perTestTimeoutMs },+ async () => {+ const metricsResult = runCli([+ 'sandbox',+ 'metrics',+ sandbox.sandboxId,+ '--format',+ 'json',+ ])+ expect(metricsResult.status).toBe(0)+ }+ )++ testIf(+ 'kill removes the sandbox',+ { timeout: perTestTimeoutMs },+ async () => {+ const killResult = runCli(['sandbox', 'kill', sandbox.sandboxId])+ expect(killResult.status).toBe(0)++ await assertSandboxNotListed(sandbox.sandboxId)+ }+ )+})++function runCli(+ args: string[],+ opts?: { input?: string | Buffer }+): ReturnType<typeof spawnSync> {+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ E2B_DOMAIN: domain,+ E2B_API_KEY: apiKey,+ }+ delete env.E2B_DEBUG++ return spawnSync('node', [cliPath, ...args], {+ env,+ input: opts?.input,+ encoding: 'utf8',+ timeout: spawnTimeoutMs,+ })+}++type PipeRunResult = {+ status: number | null+ stdout: Buffer+ stderr: Buffer+ error?: Error+}++function runCliWithPipedStdin(+ args: string[],+ input: Buffer+): Promise<PipeRunResult> {+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ E2B_DOMAIN: domain,+ E2B_API_KEY: apiKey,+ }+ delete env.E2B_DEBUG++ return new Promise((resolve) => {+ const child = spawn('node', [cliPath, ...args], {+ env,+ stdio: ['pipe', 'pipe', 'pipe'],+ })++ const stdoutChunks: Buffer[] = []+ const stderrChunks: Buffer[] = []+ let childError: Error | undefined+ let timedOut = false++ const timer = setTimeout(() => {+ timedOut = true+ child.kill()+ }, spawnTimeoutMs)++ child.stdout.on('data', (chunk) => stdoutChunks.push(Buffer.from(chunk)))+ child.stderr.on('data', (chunk) => stderrChunks.push(Buffer.from(chunk)))+ child.on('error', (err) => {+ childError = err+ })+ child.on('close', (code) => {+ clearTimeout(timer)+ const timeoutError = timedOut+ ? Object.assign(new Error('CLI command timed out'), {+ code: 'ETIMEDOUT',+ } as NodeJS.ErrnoException)+ : undefined+ resolve({+ status: code,+ stdout: Buffer.concat(stdoutChunks),+ stderr: Buffer.concat(stderrChunks),+ error: childError ?? timeoutError,+ })+ })++ child.stdin.write(input)+ child.stdin.end()+ })+}++async function assertSandboxNotListed(sandboxId: string): Promise<void> {+ const retries = 10+ const delayMs = 500++ for (let i = 0; i < retries; i++) {+ const listResult = runCli(['sandbox', 'list', '--format', 'json'])+ if (listResult.status === 0) {+ const exists = sandboxExistsInList(listResult.stdout, sandboxId)+ if (!exists) {+ return+ }+ }++ await new Promise((resolve) => setTimeout(resolve, delayMs))+ }++ throw new Error(`Sandbox ${sandboxId} still appears in sandbox list`)+}++function sandboxExistsInList(+ output: string | Buffer | null | undefined,+ sandboxId: string+): boolean {+ const text = bufferToText(output).trim()+ if (!text) {+ return false+ }++ const parsed = JSON.parse(text) as Array<{ sandboxId?: string }>+ return parsed.some((item) => item.sandboxId === sandboxId)+}++function bufferToText(value: Buffer | string | null | undefined): string {+ if (!value) {+ return ''+ }+ return typeof value === 'string' ? value : value.toString('utf8')+}++function parseEnvInt(name: string, fallback: number): number {+ const raw = process.env[name]+ if (!raw) {+ return fallback+ }+ const parsed = Number.parseInt(raw, 10)+ return Number.isFinite(parsed) ? parsed : fallback+}++function safeGetUserConfig(): ReturnType<typeof getUserConfig> | null {+ try {+ return getUserConfig()+ } catch (err) {+ console.warn(`Failed to read ~/.e2b/config.json: ${String(err)}`)+ return null+ }+}diff --git a/packages/cli/tests/commands/sandbox/exec_close_stdin.test.ts b/packages/cli/tests/commands/sandbox/exec_close_stdin.test.tsnew file mode 100644index 000000000..7febc5cd2--- /dev/null+++ b/packages/cli/tests/commands/sandbox/exec_close_stdin.test.ts@@ -0,0 +1,184 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'++const mocks = vi.hoisted(() => {+ const connect = vi.fn()+ const run = vi.fn()+ const wait = vi.fn()+ const sendStdin = vi.fn()+ const closeStdin = vi.fn()+ const kill = vi.fn()+ const ensureAPIKey = vi.fn(() => 'test-api-key')+ const isPipedStdin = vi.fn()+ const streamStdinChunks = vi.fn()+ const setupSignalHandlers = vi.fn(() => () => {})++ return {+ connect,+ run,+ wait,+ sendStdin,+ closeStdin,+ kill,+ ensureAPIKey,+ isPipedStdin,+ streamStdinChunks,+ setupSignalHandlers,+ }+})++vi.mock('e2b', () => {+ class CommandExitError extends Error {+ exitCode: number+ constructor(exitCode: number) {+ super(`Command exited with ${exitCode}`)+ this.exitCode = exitCode+ }+ }++ class NotFoundError extends Error {}++ return {+ Sandbox: {+ connect: mocks.connect,+ },+ CommandExitError,+ NotFoundError,+ }+})++vi.mock('../../../src/api', () => ({+ ensureAPIKey: mocks.ensureAPIKey,+}))++vi.mock('src/utils/signal', () => ({+ setupSignalHandlers: mocks.setupSignalHandlers,+}))++vi.mock('../../../src/commands/sandbox/exec_helpers', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('../../../src/commands/sandbox/exec_helpers')>()+ return {+ ...actual,+ isPipedStdin: mocks.isPipedStdin,+ streamStdinChunks: mocks.streamStdinChunks,+ }+})++describe('sandbox exec closeStdin handling', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()++ mocks.wait.mockResolvedValue({ exitCode: 0 })+ const handle = {+ pid: 1234,+ error: undefined,+ wait: mocks.wait,+ kill: vi.fn().mockResolvedValue(undefined),+ disconnect: vi.fn().mockResolvedValue(undefined),+ }++ mocks.run.mockResolvedValue(handle)+ mocks.sendStdin.mockResolvedValue(undefined)+ mocks.closeStdin.mockResolvedValue(undefined)+ mocks.kill.mockResolvedValue(true)+ mocks.isPipedStdin.mockReturnValue(true)+ mocks.streamStdinChunks.mockImplementation(+ async (+ _stream: NodeJS.ReadableStream,+ onChunk: (chunk: Uint8Array) => Promise<void>,+ _maxBytes: number+ ) => {+ await onChunk(Buffer.from('hello'))+ }+ )+ mocks.connect.mockResolvedValue({+ commands: {+ run: mocks.run,+ sendStdin: mocks.sendStdin,+ closeStdin: mocks.closeStdin,+ kill: mocks.kill,+ supportsStdinClose: true,+ },+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ test('fails fast and kills remote process when closeStdin throws non-NotFoundError', async () => {+ mocks.closeStdin.mockRejectedValue(new Error('close failed'))++ const exitSpy = vi+ .spyOn(process, 'exit')+ .mockImplementation((() => undefined) as never)+ vi.spyOn(console, 'error').mockImplementation(() => {})++ const { execCommand } = await import('../../../src/commands/sandbox/exec')+ await execCommand.parseAsync(['sandbox-id', 'cat'], {+ from: 'user',+ })++ expect(mocks.closeStdin).toHaveBeenCalledTimes(1)+ expect(mocks.kill).toHaveBeenCalledWith(1234)+ expect(mocks.wait).not.toHaveBeenCalled()+ expect(exitSpy).toHaveBeenCalledWith(1)+ })++ test('keeps NotFoundError from closeStdin non-fatal', async () => {+ const { NotFoundError } = await import('e2b')+ mocks.closeStdin.mockRejectedValue(new NotFoundError('already exited'))++ const exitSpy = vi+ .spyOn(process, 'exit')+ .mockImplementation((() => undefined) as never)+ vi.spyOn(console, 'error').mockImplementation(() => {})++ const { execCommand } = await import('../../../src/commands/sandbox/exec')+ await execCommand.parseAsync(['sandbox-id', 'cat'], {+ from: 'user',+ })++ expect(mocks.closeStdin).toHaveBeenCalledTimes(1)+ expect(mocks.kill).not.toHaveBeenCalled()+ expect(mocks.wait).toHaveBeenCalledTimes(1)+ expect(exitSpy).toHaveBeenCalledWith(0)+ })++ test('stops stdin streaming after NotFoundError from sendStdin', async () => {+ const { NotFoundError } = await import('e2b')+ mocks.sendStdin.mockRejectedValueOnce(new NotFoundError('already exited'))+ mocks.streamStdinChunks.mockImplementation(+ async (+ _stream: NodeJS.ReadableStream,+ onChunk: (chunk: Uint8Array) => Promise<void | boolean>,+ _maxBytes: number+ ) => {+ const shouldContinue = await onChunk(Buffer.from('first'))+ if (shouldContinue === false) {+ return+ }+ await onChunk(Buffer.from('second'))+ }+ )++ const exitSpy = vi+ .spyOn(process, 'exit')+ .mockImplementation((() => undefined) as never)+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})++ const { execCommand } = await import('../../../src/commands/sandbox/exec')+ await execCommand.parseAsync(['sandbox-id', 'cat'], {+ from: 'user',+ })++ expect(mocks.sendStdin).toHaveBeenCalledTimes(1)+ expect(mocks.closeStdin).not.toHaveBeenCalled()+ expect(mocks.wait).toHaveBeenCalledTimes(1)+ expect(errorSpy).toHaveBeenCalledWith(+ 'e2b: Remote command exited before stdin could be delivered.'+ )+ expect(exitSpy).toHaveBeenCalledWith(0)+ })+})diff --git a/packages/cli/tests/commands/sandbox/exec_helpers.test.ts b/packages/cli/tests/commands/sandbox/exec_helpers.test.tsnew file mode 100644index 000000000..6682b4aa5--- /dev/null+++ b/packages/cli/tests/commands/sandbox/exec_helpers.test.ts@@ -0,0 +1,226 @@+import { PassThrough, Readable } from 'node:stream'+import { describe, expect, test } from 'vitest'++import {+ buildCommand,+ chunkBytesBySize,+ isPipedStdin,+ readStdinIfPiped,+ readStdinFrom,+ streamStdinChunks,+ shellQuote,+} from '../../../src/commands/sandbox/exec_helpers'++describe('exec helpers', () => {+ test('shellQuote leaves safe args untouched', () => {+ expect(shellQuote('python3')).toBe('python3')+ expect(shellQuote('-c')).toBe('-c')+ expect(shellQuote('path/to/file.txt')).toBe('path/to/file.txt')+ })++ test('shellQuote wraps special chars and spaces', () => {+ expect(shellQuote('print(input())')).toBe("'print(input())'")+ expect(shellQuote('hello world')).toBe("'hello world'")+ expect(shellQuote("it's ok")).toBe("'it'\"'\"'s ok'")+ expect(shellQuote('')).toBe("''")+ })++ test('buildCommand returns a single command as-is', () => {+ const cmd = 'python3 -c "print(input())"'+ expect(buildCommand([cmd])).toBe(cmd)+ })++ test('buildCommand quotes args that need shell escaping', () => {+ expect(buildCommand(['python3', '-c', 'print(input())'])).toBe(+ "python3 -c 'print(input())'"+ )+ expect(buildCommand(['echo', 'hello world'])).toBe("echo 'hello world'")+ expect(buildCommand(['echo', "it's ok"])).toBe("echo 'it'\"'\"'s ok'")+ })++ test('readStdinFrom reads full input and resolves on EOF', async () => {+ const stream = Readable.from(['foo', 'bar'])+ await expect(readStdinFrom(stream)).resolves.toEqual(Buffer.from('foobar'))+ })++ test('readStdinFrom handles EOF without trailing newline', async () => {+ const stream = Readable.from(['no-newline'])+ await expect(readStdinFrom(stream)).resolves.toEqual(+ Buffer.from('no-newline')+ )+ })++ test('readStdinIfPiped returns undefined when stdin is not a pipe', async () => {+ const fsMock = {+ fstatSync: () => ({ isFIFO: () => false }),+ }+ const stream = new PassThrough()+ stream.end('data')+ await expect(readStdinIfPiped({ fsModule: fsMock, stream })).resolves.toBe(+ undefined+ )+ })++ test('readStdinIfPiped reads from provided stream when piped', async () => {+ const fsMock = {+ fstatSync: () => ({ isFIFO: () => true }),+ }+ const stream = new PassThrough()+ const promise = readStdinIfPiped({ fsModule: fsMock, stream })+ stream.write(Buffer.from([0xe2, 0x98]))+ stream.write(Buffer.from([0x83]))+ stream.end(Buffer.from([0x21]))+ await expect(promise).resolves.toEqual(Buffer.from([0xe2, 0x98, 0x83, 0x21]))+ })++ test('isPipedStdin returns true for FIFO', () => {+ const fsMock = {+ fstatSync: () => ({ isFIFO: () => true, isCharacterDevice: () => false }),+ }+ expect(isPipedStdin(0, fsMock)).toBe(true)+ })++ test('isPipedStdin returns true for file redirection', () => {+ const fsMock = {+ fstatSync: () => ({ isFile: () => true, isCharacterDevice: () => false }),+ }+ expect(isPipedStdin(0, fsMock)).toBe(true)+ })++ test('isPipedStdin returns false for interactive terminal', () => {+ const fsMock = {+ fstatSync: () => ({+ isCharacterDevice: () => true,+ isFIFO: () => false,+ isFile: () => false,+ }),+ }+ expect(isPipedStdin(0, fsMock)).toBe(false)+ })++ test('isPipedStdin returns false for non-FIFO or errors', () => {+ const fsMockFalse = {+ fstatSync: () => ({ isFIFO: () => false, isCharacterDevice: () => false }),+ }+ expect(isPipedStdin(0, fsMockFalse)).toBe(false)++ const fsMockThrow = {+ fstatSync: () => {+ throw new Error('fail')+ },+ }+ expect(isPipedStdin(0, fsMockThrow)).toBe(false)+ })++ test('chunkBytesBySize splits large input into byte-sized chunks', () => {+ const maxBytes = 64 * 1024+ const data = Buffer.from('a'.repeat(maxBytes * 2 + 1))+ const chunks = chunkBytesBySize(data, maxBytes)++ expect(chunks).toHaveLength(3)+ expect(chunks[0].byteLength).toBe(maxBytes)+ expect(chunks[1].byteLength).toBe(maxBytes)+ expect(chunks[2].byteLength).toBe(1)+ expect(Buffer.concat(chunks.map((c) => Buffer.from(c)))).toEqual(data)+ })++ test('chunkBytesBySize keeps byte content intact', () => {+ const maxBytes = 64 * 1024+ const data = Buffer.from('\u{1F600}'.repeat(20000)) // 😀 (4 bytes each)+ const chunks = chunkBytesBySize(data, maxBytes)++ for (const chunk of chunks) {+ expect(chunk.byteLength).toBeLessThanOrEqual(maxBytes)+ }+ expect(Buffer.concat(chunks.map((c) => Buffer.from(c)))).toEqual(data)+ })++ test('chunkBytesBySize returns empty array for empty input', () => {+ const chunks = chunkBytesBySize(Buffer.alloc(0), 64 * 1024)+ expect(chunks).toHaveLength(0)+ })++ test('chunkBytesBySize returns single chunk for small input', () => {+ const data = Buffer.from('hello')+ const chunks = chunkBytesBySize(data, 64 * 1024)+ expect(chunks).toHaveLength(1)+ expect(Buffer.from(chunks[0])).toEqual(data)+ })++ test('chunkBytesBySize throws on invalid maxBytes', () => {+ expect(() => chunkBytesBySize(Buffer.from('data'), 0)).toThrow()+ expect(() => chunkBytesBySize(Buffer.from('data'), -1)).toThrow()+ })++ test('readStdinFrom resolves with empty buffer on immediate EOF', async () => {+ const stream = Readable.from([])+ await expect(readStdinFrom(stream)).resolves.toEqual(Buffer.alloc(0))+ })++ test('streamStdinChunks delivers chunks incrementally before EOF', async () => {+ const stream = new PassThrough()+ const seen: Buffer[] = []+ let resolveFirstChunk: (() => void) | undefined+ const firstChunkSeen = new Promise<void>((resolve) => {+ resolveFirstChunk = resolve+ })+ const done = streamStdinChunks(+ stream,+ async (chunk) => {+ seen.push(Buffer.from(chunk))+ if (resolveFirstChunk) {+ resolveFirstChunk()+ resolveFirstChunk = undefined+ }+ },+ 64 * 1024+ )++ stream.write('first')+ await firstChunkSeen++ expect(seen).toEqual([Buffer.from('first')])++ stream.end('second')+ await done++ expect(seen).toEqual([Buffer.from('first'), Buffer.from('second')])+ })++ test('streamStdinChunks splits oversized stream chunks by max bytes', async () => {+ const stream = Readable.from([Buffer.from('a'.repeat(64 * 1024 + 3))])+ const chunks: Uint8Array[] = []++ await streamStdinChunks(+ stream,+ async (chunk) => {+ chunks.push(chunk)+ },+ 64 * 1024+ )++ expect(chunks).toHaveLength(2)+ expect(chunks[0].byteLength).toBe(64 * 1024)+ expect(chunks[1].byteLength).toBe(3)+ expect(Buffer.concat(chunks.map((c) => Buffer.from(c)))).toEqual(+ Buffer.from('a'.repeat(64 * 1024 + 3))+ )+ })++ test('streamStdinChunks stops early when onChunk returns false', async () => {+ const stream = Readable.from([Buffer.from('first'), Buffer.from('second')])+ const chunks: Uint8Array[] = []++ await streamStdinChunks(+ stream,+ async (chunk) => {+ chunks.push(chunk)+ return false+ },+ 64 * 1024+ )++ expect(chunks).toHaveLength(1)+ expect(Buffer.from(chunks[0])).toEqual(Buffer.from('first'))+ })+})diff --git a/packages/cli/tests/commands/sandbox/exec_pipe.test.ts b/packages/cli/tests/commands/sandbox/exec_pipe.test.tsnew file mode 100644index 000000000..910ce9221--- /dev/null+++ b/packages/cli/tests/commands/sandbox/exec_pipe.test.ts@@ -0,0 +1,259 @@+import { randomBytes } from 'node:crypto'+import { spawn } from 'node:child_process'+import path from 'node:path'+import { describe, expect, test } from 'vitest'+import { Sandbox } from 'e2b'+import { getUserConfig } from 'src/user'++type UserConfigWithDomain = NonNullable<ReturnType<typeof getUserConfig>> & {+ domain?: string+ E2B_DOMAIN?: string+}++type PipeCase = {+ name: string+ data: Buffer+ expectedBytes: number+ timeoutMs?: number+}++type ExecResult = {+ status: number | null+ stdout: Buffer+ stderr: Buffer+ error?: Error+}++const userConfig = safeGetUserConfig() as UserConfigWithDomain | null+const domain =+ process.env.E2B_DOMAIN ||+ userConfig?.E2B_DOMAIN ||+ userConfig?.domain ||+ 'e2b.app'+const apiKey = process.env.E2B_API_KEY || userConfig?.teamApiKey+const templateId =+ process.env.E2B_PIPE_TEMPLATE_ID ||+ process.env.E2B_TEMPLATE_ID ||+ 'base'+const isDebug = process.env.E2B_DEBUG !== undefined+const hasCreds = Boolean(apiKey)+const shouldSkip = !hasCreds || isDebug+const testIf = test.skipIf(shouldSkip)+const includeLargeBinary =+ process.env.E2B_PIPE_INTEGRATION_STRICT === '1' ||+ process.env.E2B_PIPE_INTEGRATION_BINARY === '1' ||+ process.env.E2B_PIPE_SMOKE_STRICT === '1' || // Backward compatibility.+ process.env.E2B_PIPE_SMOKE_BINARY === '1' || // Backward compatibility.+ process.env.STRICT === '1'+const sandboxTimeoutMs = parseEnvInt('E2B_PIPE_SANDBOX_TIMEOUT_MS', 10_000)+const testTimeoutMs = parseEnvInt('E2B_PIPE_TEST_TIMEOUT_MS', 60_000)+const defaultCmdTimeoutMs = parseEnvInt(+ 'E2B_PIPE_CMD_TIMEOUT_MS',+ Math.min(8_000, testTimeoutMs)+)++const cliPath = path.join(process.cwd(), 'dist', 'index.js')++const defaultCases: PipeCase[] = [+ {+ name: 'empty_eof',+ data: Buffer.alloc(0),+ expectedBytes: 0,+ },+ {+ name: 'ascii_newline',+ data: Buffer.from('hello\n'),+ expectedBytes: 6,+ },+ {+ name: 'ascii_no_newline',+ data: Buffer.from('hello'),+ expectedBytes: 5,+ },+ {+ name: 'utf8_multibyte',+ data: Buffer.from([0x68, 0x69, 0x2d, 0xe2, 0x98, 0x83]), // "hi-☃"+ expectedBytes: 6,+ },+ {+ name: 'binary_nul_ff_hex',+ data: Buffer.from([0x00, 0x01, 0x02, 0xff, 0x00, 0x41]),+ expectedBytes: 6,+ },+ {+ name: 'chunk_64k',+ data: Buffer.from('a'.repeat(64 * 1024)),+ expectedBytes: 64 * 1024,+ },+ {+ name: 'chunk_64k_plus_1',+ data: Buffer.from('a'.repeat(64 * 1024 + 1)),+ expectedBytes: 64 * 1024 + 1,+ },+]++const largeBinaryCases: PipeCase[] = [+ {+ name: 'binary_random_sha256',+ data: randomBytes(1024),+ expectedBytes: 1024,+ },+]++describe('sandbox exec stdin piping (integration)', () => {+ testIf(+ 'pipes stdin to remote command',+ { timeout: testTimeoutMs },+ async () => {+ const sandbox = await Sandbox.create(templateId, {+ apiKey,+ domain,+ timeoutMs: sandboxTimeoutMs,+ })++ try {+ const cases = includeLargeBinary+ ? [...defaultCases, ...largeBinaryCases]+ : defaultCases++ const probeCase: PipeCase = {+ name: 'capability_probe_ascii_newline',+ data: Buffer.from('hello\n'),+ expectedBytes: 6,+ }+ const probe = await runExecPipe(sandbox.sandboxId, probeCase)+ assertExecSucceeded(probeCase.name, probe)++ const probeStdout = bufferToText(probe.stdout).trim()+ if (probeStdout === '0') {+ // Some environments (notably Windows CI) may not expose piped stdin+ // in a way that our detector treats as piped. In that case stdin isn't+ // forwarded and remote byte count is 0 without the legacy warning.+ return+ }++ expect(probeStdout).toBe(String(probeCase.expectedBytes))++ for (const testCase of cases) {+ const result = await runExecPipe(sandbox.sandboxId, testCase)+ assertExecSucceeded(testCase.name, result)+ const stdout = bufferToText(result.stdout).trim()+ expect(stdout, testCase.name).toBe(String(testCase.expectedBytes))+ }+ } finally {+ try {+ await sandbox.kill()+ } catch (err) {+ console.warn(+ `Failed to kill sandbox ${sandbox.sandboxId}: ${String(err)}`+ )+ }+ }+ }+ )+})++function runExecPipe(+ sandboxId: string,+ testCase: PipeCase+): Promise<ExecResult> {+ const cliArgs = [+ cliPath,+ 'sandbox',+ 'exec',+ sandboxId,+ '--',+ 'sh',+ '-lc',+ 'wc -c',+ ]++ const env: NodeJS.ProcessEnv = {+ ...process.env,+ E2B_DOMAIN: domain,+ E2B_API_KEY: apiKey,+ }+ delete env.E2B_DEBUG++ return new Promise((resolve) => {+ const child = spawn('node', cliArgs, {+ env,+ stdio: ['pipe', 'pipe', 'pipe'],+ })++ const stdoutChunks: Buffer[] = []+ const stderrChunks: Buffer[] = []+ let childError: Error | undefined+ let timedOut = false++ const timer = setTimeout(() => {+ timedOut = true+ child.kill()+ }, testCase.timeoutMs ?? defaultCmdTimeoutMs)++ child.stdout.on('data', (chunk) => stdoutChunks.push(Buffer.from(chunk)))+ child.stderr.on('data', (chunk) => stderrChunks.push(Buffer.from(chunk)))+ child.on('error', (err) => {+ childError = err+ })+ child.on('close', (code) => {+ clearTimeout(timer)+ const timeoutError = timedOut+ ? Object.assign(new Error('CLI command timed out'), {+ code: 'ETIMEDOUT',+ } as NodeJS.ErrnoException)+ : undefined+ resolve({+ status: code,+ stdout: Buffer.concat(stdoutChunks),+ stderr: Buffer.concat(stderrChunks),+ error: childError ?? timeoutError,+ })+ })++ child.stdin.write(testCase.data)+ child.stdin.end()+ })+}++function bufferToText(value: Buffer | string | null | undefined): string {+ if (!value) {+ return ''+ }+ return typeof value === 'string' ? value : value.toString('utf8')+}++function assertExecSucceeded(+ name: string,+ result: ExecResult+): void {+ if (result.error) {+ const timedOut = (result.error as NodeJS.ErrnoException).code === 'ETIMEDOUT'+ throw new Error(+ `${name} ${timedOut ? 'timed out' : 'failed'}: ${result.error.message}`+ )+ }++ const stderr = bufferToText(result.stderr).trim()+ if (result.status !== 0) {+ throw new Error(`${name} failed with rc=${result.status} stderr=${stderr}`)+ }+}++function parseEnvInt(name: string, fallback: number): number {+ const raw = process.env[name]+ if (!raw) {+ return fallback+ }+ const parsed = Number.parseInt(raw, 10)+ return Number.isFinite(parsed) ? parsed : fallback+}++function safeGetUserConfig(): ReturnType<typeof getUserConfig> | null {+ try {+ return getUserConfig()+ } catch (err) {+ console.warn(`Failed to read ~/.e2b/config.json: ${String(err)}`)+ return null+ }+}diff --git a/packages/cli/tests/commands/sandbox/exec_stdin_flag.test.ts b/packages/cli/tests/commands/sandbox/exec_stdin_flag.test.tsnew file mode 100644index 000000000..67fdc76f7--- /dev/null+++ b/packages/cli/tests/commands/sandbox/exec_stdin_flag.test.ts@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'++const mocks = vi.hoisted(() => {+ const connect = vi.fn()+ const run = vi.fn()+ const sendStdin = vi.fn()+ const closeStdin = vi.fn()+ const ensureAPIKey = vi.fn(() => 'test-api-key')+ const isPipedStdin = vi.fn()+ const streamStdinChunks = vi.fn()+ const setupSignalHandlers = vi.fn(() => () => {})++ return {+ connect,+ run,+ sendStdin,+ closeStdin,+ ensureAPIKey,+ isPipedStdin,+ streamStdinChunks,+ setupSignalHandlers,+ }+})++vi.mock('e2b', () => {+ class CommandExitError extends Error {+ exitCode: number+ constructor(exitCode: number) {+ super(`Command exited with ${exitCode}`)+ this.exitCode = exitCode+ }+ }++ class NotFoundError extends Error {}++ return {+ Sandbox: {+ connect: mocks.connect,+ },+ CommandExitError,+ NotFoundError,+ }+})++vi.mock('../../../src/api', () => ({+ ensureAPIKey: mocks.ensureAPIKey,+}))++vi.mock('src/utils/signal', () => ({+ setupSignalHandlers: mocks.setupSignalHandlers,+}))++vi.mock('../../../src/commands/sandbox/exec_helpers', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('../../../src/commands/sandbox/exec_helpers')>()+ return {+ ...actual,+ isPipedStdin: mocks.isPipedStdin,+ streamStdinChunks: mocks.streamStdinChunks,+ }+})++describe('sandbox exec stdin run flag', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()++ const handle = {+ pid: 1234,+ error: undefined,+ wait: vi.fn().mockResolvedValue({ exitCode: 0 }),+ kill: vi.fn().mockResolvedValue(undefined),+ disconnect: vi.fn().mockResolvedValue(undefined),+ }++ mocks.run.mockResolvedValue(handle)+ mocks.sendStdin.mockResolvedValue(undefined)+ mocks.closeStdin.mockResolvedValue(undefined)+ mocks.isPipedStdin.mockReturnValue(false)+ mocks.streamStdinChunks.mockResolvedValue(undefined)+ mocks.connect.mockResolvedValue({+ commands: {+ run: mocks.run,+ sendStdin: mocks.sendStdin,+ closeStdin: mocks.closeStdin,+ supportsStdinClose: true,+ },+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ test('does not pass stdin flag when stdin is not piped', async () => {+ const exitSpy = vi+ .spyOn(process, 'exit')+ .mockImplementation((() => undefined) as never)++ const { execCommand } = await import('../../../src/commands/sandbox/exec')+ await execCommand.parseAsync(['sandbox-id', 'echo', 'hello'], {+ from: 'user',+ })++ expect(mocks.run).toHaveBeenCalledTimes(1)+ const runOpts = mocks.run.mock.calls[0][1]+ expect(runOpts).not.toHaveProperty('stdin')+ expect(mocks.streamStdinChunks).not.toHaveBeenCalled()+ expect(exitSpy).toHaveBeenCalledWith(0)+ })++ test('passes stdin: true when stdin piping is active', async () => {+ mocks.isPipedStdin.mockReturnValue(true)+ const events: string[] = []+ mocks.setupSignalHandlers.mockImplementation(() => {+ events.push('setup')+ return () => {+ events.push('cleanup')+ }+ })+ mocks.streamStdinChunks.mockImplementation(+ async (+ _stream: NodeJS.ReadableStream,+ onChunk: (chunk: Uint8Array) => Promise<void | boolean>,+ _maxBytes: number+ ) => {+ events.push('stream-start')+ await onChunk(Buffer.from('hello'))+ events.push('stream-end')+ }+ )+ const exitSpy = vi+ .spyOn(process, 'exit')+ .mockImplementation((() => undefined) as never)++ const { execCommand } = await import('../../../src/commands/sandbox/exec')+ await execCommand.parseAsync(['sandbox-id', 'cat'], {+ from: 'user',+ })++ expect(mocks.run).toHaveBeenCalledTimes(1)+ const runOpts = mocks.run.mock.calls[0][1]+ expect(runOpts).toHaveProperty('stdin', true)+ expect(mocks.streamStdinChunks).toHaveBeenCalled()+ expect(mocks.sendStdin).toHaveBeenCalled()+ expect(mocks.closeStdin).toHaveBeenCalled()+ expect(events).toContain('setup')+ expect(events).toContain('stream-start')+ expect(events.indexOf('setup')).toBeLessThan(events.indexOf('stream-start'))+ expect(events).toContain('cleanup')+ expect(exitSpy).toHaveBeenCalledWith(0)+ })+})diff --git a/packages/js-sdk/src/envd/process/process_connect.ts b/packages/js-sdk/src/envd/process/process_connect.tsindex 42997984f..10475ca09 100644--- a/packages/js-sdk/src/envd/process/process_connect.ts+++ b/packages/js-sdk/src/envd/process/process_connect.ts@@ -4,6 +4,8 @@// @ts-nocheckimport {+ CloseStdinRequest,+ CloseStdinResponse,ConnectRequest,ConnectResponse,ListRequest,@@ -92,5 +94,17 @@ export const Process = {O: SendSignalResponse,kind: MethodKind.Unary,},+ /**+ * Close stdin to signal EOF to the process.+ * Only works for non-PTY processes. For PTY, send Ctrl+D (0x04) instead.+ *+ * @generated from rpc process.Process.CloseStdin+ */+ closeStdin: {+ name: 'CloseStdin',+ I: CloseStdinRequest,+ O: CloseStdinResponse,+ kind: MethodKind.Unary,+ },},} as constdiff --git a/packages/js-sdk/src/envd/process/process_pb.ts b/packages/js-sdk/src/envd/process/process_pb.tsindex 7db02f7dd..1bdcdc47d 100644--- a/packages/js-sdk/src/envd/process/process_pb.ts+++ b/packages/js-sdk/src/envd/process/process_pb.ts@@ -22,7 +22,7 @@ import type {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endSignalResponseSchema: GenMessage<SendSignalResponse> =/*@__PURE__*/messageDesc(file_process_process, 17)+/**+ * @generated from message process.CloseStdinRequest+ */+export type CloseStdinRequest = Message<'process.CloseStdinRequest'> & {+ /**+ * @generated from field: process.ProcessSelector process = 1;+ */+ process?: ProcessSelector+}++/**+ * Describes the message process.CloseStdinRequest.+ * Use `create(CloseStdinRequestSchema)` to create a new message.+ */+export const CloseStdinRequestSchema: GenMessage<CloseStdinRequest> =+ /*@__PURE__*/+ messageDesc(file_process_process, 18)++/**+ * @generated from message process.CloseStdinResponse+ */+export type CloseStdinResponse = Message<'process.CloseStdinResponse'> & {}++/**+ * Describes the message process.CloseStdinResponse.+ * Use `create(CloseStdinResponseSchema)` to create a new message.+ */+export const CloseStdinResponseSchema: GenMessage<CloseStdinResponse> =+ /*@__PURE__*/+ messageDesc(file_process_process, 19)+/*** @generated from message process.ConnectRequest*/@@ -643,7 +674,7 @@ export type ConnectRequest = Message<'process.ConnectRequest'> & {*/export const ConnectRequestSchema: GenMessage<ConnectRequest> =/*@__PURE__*/- messageDesc(file_process_process, 18)+ messageDesc(file_process_process, 20)/*** @generated from message process.ProcessSelector@@ -676,7 +707,7 @@ export type ProcessSelector = Message<'process.ProcessSelector'> & {*/export const ProcessSelectorSchema: GenMessage<ProcessSelector> =/*@__PURE__*/- messageDesc(file_process_process, 19)+ messageDesc(file_process_process, 21)/*** @generated from enum process.Signal@@ -767,4 +798,15 @@ export const Process: GenService<{input: typeof SendSignalRequestSchemaoutput: typeof SendSignalResponseSchema}+ /**+ * Close stdin to signal EOF to the process.+ * Only works for non-PTY processes. For PTY, send Ctrl+D (0x04) instead.+ *+ * @generated from rpc process.Process.CloseStdin+ */+ closeStdin: {+ methodKind: 'unary'+ input: typeof CloseStdinRequestSchema+ output: typeof CloseStdinResponseSchema+ }}> = /*@__PURE__*/ serviceDesc(file_process_process, 0)diff --git a/packages/js-sdk/src/envd/versions.ts b/packages/js-sdk/src/envd/versions.tsindex 8a81fc87d..16fffb3a4 100644--- a/packages/js-sdk/src/envd/versions.ts+++ b/packages/js-sdk/src/envd/versions.ts@@ -2,3 +2,4 @@ export const ENVD_VERSION_RECURSIVE_WATCH = '0.1.4'export const ENVD_DEBUG_FALLBACK = '99.99.99'export const ENVD_COMMANDS_STDIN = '0.3.0'export const ENVD_DEFAULT_USER = '0.4.0'+export const ENVD_ENVD_CLOSE = '0.5.2'diff --git a/packages/js-sdk/src/sandbox/commands/index.ts b/packages/js-sdk/src/sandbox/commands/index.tsindex 8aff14897..61cb9e283 100644--- a/packages/js-sdk/src/sandbox/commands/index.ts+++ b/packages/js-sdk/src/sandbox/commands/index.ts@@ -20,7 +20,7 @@ import {Signal,} from '../../envd/process/process_pb'import { authenticationHeader, handleRpcError } from '../../envd/rpc'-import { ENVD_COMMANDS_STDIN } from '../../envd/versions'+import { ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSE } from '../../envd/versions'import { SandboxError } from '../../errors'import { CommandHandle, CommandResult } from './commandHandle'export { Pty } from './pty'@@ -140,6 +140,14 @@ export class Commands {this.envdVersion = metadata.version}+ /**+ * @hidden+ * @internal+ */+ get supportsStdinClose(): boolean {+ return compareVersions(this.envdVersion, ENVD_ENVD_CLOSE) >= 0+ }+/*** List all running commands and PTY sessions.*@@ -178,10 +186,13 @@ export class Commands {*/async sendStdin(pid: number,- data: string,+ data: string | Uint8Array,opts?: CommandRequestOpts): Promise<void> {try {+ const payload =+ typeof data === 'string' ? new TextEncoder().encode(data) : data+await this.rpc.sendInput({process: {@@ -193,7 +204,37 @@ export class Commands {input: {input: {case: 'stdin',- value: new TextEncoder().encode(data),+ value: payload,+ },+ },+ },+ {+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),+ }+ )+ } catch (err) {+ throw handleRpcError(err)+ }+ }++ /**+ * @hidden+ * @internal+ */+ async closeStdin(pid: number, opts?: CommandRequestOpts): Promise<void> {+ if (!this.supportsStdinClose) {+ throw new SandboxError(+ `Sandbox envd version ${this.envdVersion} doesn't support closeStdin. Please rebuild your template to pick up the latest sandbox version.`+ )+ }++ try {+ await this.rpc.closeStdin(+ {+ process: {+ selector: {+ case: 'pid',+ value: pid,},},},diff --git a/packages/python-sdk/e2b/envd/process/process_connect.py b/packages/python-sdk/e2b/envd/process/process_connect.pyindex d598b8675..dc09fbe69 100644--- a/packages/python-sdk/e2b/envd/process/process_connect.py+++ b/packages/python-sdk/e2b/envd/process/process_connect.py@@ -83,6 +83,15 @@ class ProcessClient:json=json,**opts,)+ self._close_stdin = connect.Client(+ pool=pool,+ async_pool=async_pool,+ url=f"{base_url}/{ProcessName}/CloseStdin",+ response_type=process_dot_process__pb2.CloseStdinResponse,+ compressor=compressor,+ json=json,+ **opts,+ )def list(self, req: process_dot_process__pb2.ListRequest, **opts@@ -153,3 +162,13 @@ class ProcessClient:self, req: process_dot_process__pb2.SendSignalRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.SendSignalResponse]:return self._send_signal.acall_unary(req, **opts)++ def close_stdin(+ self, req: process_dot_process__pb2.CloseStdinRequest, **opts+ ) -> process_dot_process__pb2.CloseStdinResponse:+ return self._close_stdin.call_unary(req, **opts)++ def aclose_stdin(+ self, req: process_dot_process__pb2.CloseStdinRequest, **opts+ ) -> Coroutine[Any, Any, process_dot_process__pb2.CloseStdinResponse]:+ return self._close_stdin.acall_unary(req, **opts)diff --git a/packages/python-sdk/e2b/envd/process/process_pb2.py b/packages/python-sdk/e2b/envd/process/process_pb2.pyindex ac8943e05..bb69b6409 100644--- a/packages/python-sdk/e2b/envd/process/process_pb2.py+++ b/packages/python-sdk/e2b/envd/process/process_pb2.py@@ -14,7 +14,7 @@ _sym_db = _symbol_database.Default()DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(- b'\n\x15process/process.proto\x12\x07process"\\\n\x03PTY\x12%\n\x04size\x18\x01 \x01(\x0b\x32\x11.process.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04\x63ols\x18\x01 \x01(\rR\x04\x63ols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows"\xc3\x01\n\rProcessConfig\x12\x10\n\x03\x63md\x18\x01 \x01(\tR\x03\x63md\x12\x12\n\x04\x61rgs\x18\x02 \x03(\tR\x04\x61rgs\x12\x34\n\x04\x65nvs\x18\x03 \x03(\x0b\x32 .process.ProcessConfig.EnvsEntryR\x04\x65nvs\x12\x15\n\x03\x63wd\x18\x04 \x01(\tH\x00R\x03\x63wd\x88\x01\x01\x1a\x37\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\x42\x06\n\x04_cwd"\r\n\x0bListRequest"n\n\x0bProcessInfo\x12.\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x06\x63onfig\x12\x10\n\x03pid\x18\x02 \x01(\rR\x03pid\x12\x15\n\x03tag\x18\x03 \x01(\tH\x00R\x03tag\x88\x01\x01\x42\x06\n\x04_tag"B\n\x0cListResponse\x12\x32\n\tprocesses\x18\x01 \x03(\x0b\x32\x14.process.ProcessInfoR\tprocesses"\xb1\x01\n\x0cStartRequest\x12\x30\n\x07process\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x12\x15\n\x03tag\x18\x03 \x01(\tH\x01R\x03tag\x88\x01\x01\x12\x19\n\x05stdin\x18\x04 \x01(\x08H\x02R\x05stdin\x88\x01\x01\x42\x06\n\x04_ptyB\x06\n\x04_tagB\x08\n\x06_stdin"p\n\rUpdateRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x42\x06\n\x04_pty"\x10\n\x0eUpdateResponse"\x87\x04\n\x0cProcessEvent\x12\x38\n\x05start\x18\x01 \x01(\x0b\x32 .process.ProcessEvent.StartEventH\x00R\x05start\x12\x35\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\x1f.process.ProcessEvent.DataEventH\x00R\x04\x64\x61ta\x12\x32\n\x03\x65nd\x18\x03 \x01(\x0b\x32\x1e.process.ProcessEvent.EndEventH\x00R\x03\x65nd\x12?\n\tkeepalive\x18\x04 \x01(\x0b\x32\x1f.process.ProcessEvent.KeepAliveH\x00R\tkeepalive\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1a]\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderr\x12\x12\n\x03pty\x18\x03 \x01(\x0cH\x00R\x03ptyB\x08\n\x06output\x1a|\n\x08\x45ndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08\x65xitCode\x12\x16\n\x06\x65xited\x18\x02 \x01(\x08R\x06\x65xited\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05\x65rror\x18\x04 \x01(\tH\x00R\x05\x65rror\x88\x01\x01\x42\x08\n\x06_error\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"<\n\rStartResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent">\n\x0f\x43onnectResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent"s\n\x10SendInputRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input"\x13\n\x11SendInputResponse"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03pty\x18\x02 \x01(\x0cH\x00R\x03ptyB\x07\n\x05input"\xea\x02\n\x12StreamInputRequest\x12>\n\x05start\x18\x01 \x01(\x0b\x32&.process.StreamInputRequest.StartEventH\x00R\x05start\x12;\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32%.process.StreamInputRequest.DataEventH\x00R\x04\x64\x61ta\x12\x45\n\tkeepalive\x18\x03 \x01(\x0b\x32%.process.StreamInputRequest.KeepAliveH\x00R\tkeepalive\x1a@\n\nStartEvent\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x1a\x38\n\tDataEvent\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"\x15\n\x13StreamInputResponse"p\n\x11SendSignalRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12\'\n\x06signal\x18\x02 \x01(\x0e\x32\x0f.process.SignalR\x06signal"\x14\n\x12SendSignalResponse"D\n\x0e\x43onnectRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process"E\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pid\x12\x12\n\x03tag\x18\x02 \x01(\tH\x00R\x03tagB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\xca\x03\n\x07Process\x12\x33\n\x04List\x12\x14.process.ListRequest\x1a\x15.process.ListResponse\x12>\n\x07\x43onnect\x12\x17.process.ConnectRequest\x1a\x18.process.ConnectResponse0\x01\x12\x38\n\x05Start\x12\x15.process.StartRequest\x1a\x16.process.StartResponse0\x01\x12\x39\n\x06Update\x12\x16.process.UpdateRequest\x1a\x17.process.UpdateResponse\x12J\n\x0bStreamInput\x12\x1b.process.StreamInputRequest\x1a\x1c.process.StreamInputResponse(\x01\x12\x42\n\tSendInput\x12\x19.process.SendInputRequest\x1a\x1a.process.SendInputResponse\x12\x45\n\nSendSignal\x12\x1a.process.SendSignalRequest\x1a\x1b.process.SendSignalResponseBW\n\x0b\x63om.processB\x0cProcessProtoP\x01\xa2\x02\x03PXX\xaa\x02\x07Process\xca\x02\x07Process\xe2\x02\x13Process\\GPBMetadata\xea\x02\x07Processb\x06proto3'+ b'\n\x15process/process.proto\x12\x07process"\\\n\x03PTY\x12%\n\x04size\x18\x01 \x01(\x0b\x32\x11.process.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04\x63ols\x18\x01 \x01(\rR\x04\x63ols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows"\xc3\x01\n\rProcessConfig\x12\x10\n\x03\x63md\x18\x01 \x01(\tR\x03\x63md\x12\x12\n\x04\x61rgs\x18\x02 \x03(\tR\x04\x61rgs\x12\x34\n\x04\x65nvs\x18\x03 \x03(\x0b\x32 .process.ProcessConfig.EnvsEntryR\x04\x65nvs\x12\x15\n\x03\x63wd\x18\x04 \x01(\tH\x00R\x03\x63wd\x88\x01\x01\x1a\x37\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\x42\x06\n\x04_cwd"\r\n\x0bListRequest"n\n\x0bProcessInfo\x12.\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x06\x63onfig\x12\x10\n\x03pid\x18\x02 \x01(\rR\x03pid\x12\x15\n\x03tag\x18\x03 \x01(\tH\x00R\x03tag\x88\x01\x01\x42\x06\n\x04_tag"B\n\x0cListResponse\x12\x32\n\tprocesses\x18\x01 \x03(\x0b\x32\x14.process.ProcessInfoR\tprocesses"\xb1\x01\n\x0cStartRequest\x12\x30\n\x07process\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x12\x15\n\x03tag\x18\x03 \x01(\tH\x01R\x03tag\x88\x01\x01\x12\x19\n\x05stdin\x18\x04 \x01(\x08H\x02R\x05stdin\x88\x01\x01\x42\x06\n\x04_ptyB\x06\n\x04_tagB\x08\n\x06_stdin"p\n\rUpdateRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x42\x06\n\x04_pty"\x10\n\x0eUpdateResponse"\x87\x04\n\x0cProcessEvent\x12\x38\n\x05start\x18\x01 \x01(\x0b\x32 .process.ProcessEvent.StartEventH\x00R\x05start\x12\x35\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\x1f.process.ProcessEvent.DataEventH\x00R\x04\x64\x61ta\x12\x32\n\x03\x65nd\x18\x03 \x01(\x0b\x32\x1e.process.ProcessEvent.EndEventH\x00R\x03\x65nd\x12?\n\tkeepalive\x18\x04 \x01(\x0b\x32\x1f.process.ProcessEvent.KeepAliveH\x00R\tkeepalive\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1a]\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderr\x12\x12\n\x03pty\x18\x03 \x01(\x0cH\x00R\x03ptyB\x08\n\x06output\x1a|\n\x08\x45ndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08\x65xitCode\x12\x16\n\x06\x65xited\x18\x02 \x01(\x08R\x06\x65xited\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05\x65rror\x18\x04 \x01(\tH\x00R\x05\x65rror\x88\x01\x01\x42\x08\n\x06_error\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"<\n\rStartResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent">\n\x0f\x43onnectResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent"s\n\x10SendInputRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input"\x13\n\x11SendInputResponse"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03pty\x18\x02 \x01(\x0cH\x00R\x03ptyB\x07\n\x05input"\xea\x02\n\x12StreamInputRequest\x12>\n\x05start\x18\x01 \x01(\x0b\x32&.process.StreamInputRequest.StartEventH\x00R\x05start\x12;\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32%.process.StreamInputRequest.DataEventH\x00R\x04\x64\x61ta\x12\x45\n\tkeepalive\x18\x03 \x01(\x0b\x32%.process.StreamInputRequest.KeepAliveH\x00R\tkeepalive\x1a@\n\nStartEvent\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x1a\x38\n\tDataEvent\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"\x15\n\x13StreamInputResponse"p\n\x11SendSignalRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12\'\n\x06signal\x18\x02 \x01(\x0e\x32\x0f.process.SignalR\x06signal"\x14\n\x12SendSignalResponse"G\n\x11\x43loseStdinRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process"\x14\n\x12\x43loseStdinResponse"D\n\x0e\x43onnectRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process"E\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pid\x12\x12\n\x03tag\x18\x02 \x01(\tH\x00R\x03tagB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\x91\x04\n\x07Process\x12\x33\n\x04List\x12\x14.process.ListRequest\x1a\x15.process.ListResponse\x12>\n\x07\x43onnect\x12\x17.process.ConnectRequest\x1a\x18.process.ConnectResponse0\x01\x12\x38\n\x05Start\x12\x15.process.StartRequest\x1a\x16.process.StartResponse0\x01\x12\x39\n\x06Update\x12\x16.process.UpdateRequest\x1a\x17.process.UpdateResponse\x12J\n\x0bStreamInput\x12\x1b.process.StreamInputRequest\x1a\x1c.process.StreamInputResponse(\x01\x12\x42\n\tSendInput\x12\x19.process.SendInputRequest\x1a\x1a.process.SendInputResponse\x12\x45\n\nSendSignal\x12\x1a.process.SendSignalRequest\x1a\x1b.process.SendSignalResponse\x12\x45\n\nCloseStdin\x12\x1a.process.CloseStdinRequest\x1a\x1b.process.CloseStdinResponseBW\n\x0b\x63om.processB\x0cProcessProtoP\x01\xa2\x02\x03PXX\xaa\x02\x07Process\xca\x02\x07Process\xe2\x02\x13Process\\GPBMetadata\xea\x02\x07Processb\x06proto3')_globals = globals()@@ -27,8 +27,8 @@ if not _descriptor._USE_C_DESCRIPTORS:]._serialized_options = b"\n\013com.processB\014ProcessProtoP\001\242\002\003PXX\252\002\007Process\312\002\007Process\342\002\023Process\\GPBMetadata\352\002\007Process"_globals["_PROCESSCONFIG_ENVSENTRY"]._loaded_options = None_globals["_PROCESSCONFIG_ENVSENTRY"]._serialized_options = b"8\001"- _globals["_SIGNAL"]._serialized_start = 2353- _globals["_SIGNAL"]._serialized_end = 2425+ _globals["_SIGNAL"]._serialized_start = 2448+ _globals["_SIGNAL"]._serialized_end = 2520_globals["_PTY"]._serialized_start = 34_globals["_PTY"]._serialized_end = 126_globals["_PTY_SIZE"]._serialized_start = 80@@ -83,10 +83,14 @@ if not _descriptor._USE_C_DESCRIPTORS:_globals["_SENDSIGNALREQUEST"]._serialized_end = 2188_globals["_SENDSIGNALRESPONSE"]._serialized_start = 2190_globals["_SENDSIGNALRESPONSE"]._serialized_end = 2210- _globals["_CONNECTREQUEST"]._serialized_start = 2212- _globals["_CONNECTREQUEST"]._serialized_end = 2280- _globals["_PROCESSSELECTOR"]._serialized_start = 2282- _globals["_PROCESSSELECTOR"]._serialized_end = 2351- _globals["_PROCESS"]._serialized_start = 2428- _globals["_PROCESS"]._serialized_end = 2886+ _globals["_CLOSESTDINREQUEST"]._serialized_start = 2212+ _globals["_CLOSESTDINREQUEST"]._serialized_end = 2283+ _globals["_CLOSESTDINRESPONSE"]._serialized_start = 2285+ _globals["_CLOSESTDINRESPONSE"]._serialized_end = 2305+ _globals["_CONNECTREQUEST"]._serialized_start = 2307+ _globals["_CONNECTREQUEST"]._serialized_end = 2375+ _globals["_PROCESSSELECTOR"]._serialized_start = 2377+ _globals["_PROCESSSELECTOR"]._serialized_end = 2446+ _globals["_PROCESS"]._serialized_start = 2523+ _globals["_PROCESS"]._serialized_end = 3052# @@protoc_insertion_point(module_scope)diff --git a/packages/python-sdk/e2b/envd/process/process_pb2.pyi b/packages/python-sdk/e2b/envd/process/process_pb2.pyiindex b0b76c485..e61158e46 100644--- a/packages/python-sdk/e2b/envd/process/process_pb2.pyi+++ b/packages/python-sdk/e2b/envd/process/process_pb2.pyi@@ -285,6 +285,18 @@ class SendSignalResponse(_message.Message):__slots__ = ()def __init__(self) -> None: ...+class CloseStdinRequest(_message.Message):+ __slots__ = ("process",)+ PROCESS_FIELD_NUMBER: _ClassVar[int]+ process: ProcessSelector+ def __init__(+ self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ...+ ) -> None: ...++class CloseStdinResponse(_message.Message):+ __slots__ = ()+ def __init__(self) -> None: ...+class ConnectRequest(_message.Message):__slots__ = ("process",)PROCESS_FIELD_NUMBER: _ClassVar[int]diff --git a/packages/python-sdk/e2b/envd/versions.py b/packages/python-sdk/e2b/envd/versions.pyindex 965e7f8a8..f0674b530 100644--- a/packages/python-sdk/e2b/envd/versions.py+++ b/packages/python-sdk/e2b/envd/versions.py@@ -4,3 +4,4 @@ ENVD_VERSION_RECURSIVE_WATCH = Version("0.1.4")ENVD_DEBUG_FALLBACK = Version("99.99.99")ENVD_COMMANDS_STDIN = Version("0.3.0")ENVD_DEFAULT_USER = Version("0.4.0")+ENVD_ENVD_CLOSE = Version("0.5.2")diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b89f9f3f6..8cf7f95f7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4603,11 +4603,13 @@ packages:resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]hasBin: trueresolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==}engines: {node: 20 || >=22}+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]hasBin: true@@ -7025,11 +7027,12 @@ packages:resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==}engines: {node: '>=10'}- deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exhorbitant rates) by contacting [email protected]+ deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]resolution: {integrity: sha512-AN04xbWGrSTDmVwlI4/GTlIIwMFk/XEv7uL8aa57zuvRy6s4hdBed+lVq2fAZ89XDa7Us3ANXcE3Tvqvja1kTA==}engines: {node: '>=18'}+ deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]resolution: {integrity: sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==}@@ -11129,7 +11132,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -13991,7 +13994,7 @@ snapshots:dependencies:'@types/debug': 4.1.8- debug: 4.4.0+ debug: 4.4.3([email protected])decode-named-character-reference: 1.0.2micromark-core-commonmark: 1.1.0micromark-factory-space: 1.1.0@@ -15076,7 +15079,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.3([email protected])module-details-from-path: 1.0.3resolve: 1.22.8transitivePeerDependencies:diff --git a/spec/envd/process/process.proto b/spec/envd/process/process.protoindex 3efda9c7c..4d394da6d 100644--- a/spec/envd/process/process.proto+++ b/spec/envd/process/process.proto@@ -14,6 +14,10 @@ service Process {rpc StreamInput(stream StreamInputRequest) returns (StreamInputResponse);rpc SendInput(SendInputRequest) returns (SendInputResponse);rpc SendSignal(SendSignalRequest) returns (SendSignalResponse);++ // Close stdin to signal EOF to the process.+ // Only works for non-PTY processes. For PTY, send Ctrl+D (0x04) instead.+ rpc CloseStdin(CloseStdinRequest) returns (CloseStdinResponse);}message PTY {@@ -147,6 +151,12 @@ message SendSignalRequest {message SendSignalResponse {}+message CloseStdinRequest {+ ProcessSelector process = 1;+}++message CloseStdinResponse {}+message ConnectRequest {ProcessSelector process = 1;}