refactor(e2b): keep provider layer substrate-only
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/e2b/subprocess-e2b/README.md
|
||||
README.md: 9b86af428533ebcc2c0da56339e6ea2a28170fd3
|
||||
README.zh.md: e3e8368534266e35ec04dcf5a2d6718829b4a016
|
||||
README.md: 9e044c13b673461a876e016ec560db4897a27c66
|
||||
README.zh.md: b9180c0c0679915fae7a1db22353613708392a8c
|
||||
|
||||
@@ -9,9 +9,9 @@ E2B implementation of the [`@deepseek-ai/dsh-subprocess`](../../subprocess/subpr
|
||||
- **Asynchronous remote start** — the synchronous seam returns a handle immediately while `Sandbox.commands.run(..., { background: true })` starts remotely. `pid` is `-1` until the wrapper publishes and the adapter validates its process-group id; stdin and ordinary observation wait for that publication. An owned startup signal aborts environment and private-state preparation before allocation; once allocation begins, cancellation waits for a provisional SDK handle it can clean.
|
||||
- **Execution-world coordinates** — `cwd` and private `runtimeRoot` come from the shared owner; executable lookup verifies absolute paths or resolves a bare name against the sandbox PATH plus explicit overrides.
|
||||
- **Linux process groups** — a quoted wrapper starts each argv under `exec setsid --wait` and records its actual process-group id plus private status files beneath `ctx.e2b.runtimeRoot/processes`. The handle waits for that file instead of treating the SDK command PID as its published identity. Termination signals the negative recorded id with `SIGTERM`, waits the caller's `graceMs`, then escalates to `SIGKILL` and the SDK kill fallback; TERM delivery or probe failures also force that escalation. Process-table probes treat groups containing only zombie or dead entries as quiescent. Force cleanup succeeds only after a bounded probe finds the group empty; otherwise `waitForExit()` exposes a retryable failure, while proven quiescence makes later termination a no-op. Publication and monitoring failures apply the same cleanup transaction before rejecting. Service disposal rejects new starts, terminates and joins every retained process group, then awaits SDK settlement and private cleanup before the sandbox owner disposes.
|
||||
- **Environment boundary** — the sandbox command environment crosses the SDK callback boundary as base64 ASCII before one strict UTF-8 decode, then the wrapper removes ambient `DSH_*` and credential-shaped (`*KEY*`, `*SECRET*`, `*TOKEN*`) names and restores every valid `spec.env` entry as an explicit caller opt-in; empty names, `=`, and NUL framing violations reject before launch. E2B's fixed command and PTY login shells receive a fresh randomized root-level `HOME` plus empty overrides for every scrubbed ambient name before user profiles can run; the requested argv receives the serialized environment afterward. Host ambient variables never enter the sandbox implicitly. Private environment files are removed after consumption, and failed command or terminal setup removes its private state before rejecting.
|
||||
- **Environment boundary** — one trusted control-shell probe transports the sandbox environment as base64 ASCII for one strict UTF-8 decode; the wrapper then removes ambient `DSH_*` and credential-shaped (`*KEY*`, `*SECRET*`, `*TOKEN*`) names and restores every valid `spec.env` entry as an explicit caller opt-in. Empty names, `=`, and NUL framing violations reject before launch. Subsequent E2B command and PTY login shells receive a fresh randomized root-level `HOME` plus empty overrides for every scrubbed ambient name before user profiles can run; the requested argv receives the serialized environment afterward. Host ambient variables never enter the sandbox implicitly. Private environment files are removed after consumption, and failed command or terminal setup removes its private state before rejecting.
|
||||
- **Stdio projection** — the remote wrapper branches raw bytes into optional bounded spill files, frames each live chunk as newline-delimited base64 ASCII, and the host incrementally restores bytes across arbitrary SDK callback boundaries. Pipe mode writes those bytes to host Node streams; inherit mode writes them to the harness process streams; collect mode retains a bounded host tail with offset reads. The wrapper publishes the direct command status before waiting for inherited writers. For collect or inherit output, the adapter disconnects an incomplete SDK stream after `graceMs`, withholds its partial spill, and returns that status while retaining the remote group for `waitForExit()` and termination. Natural raw-pipe completion instead awaits lossless transport and preserves backpressure; explicit termination destroys the host pipes and releases blocked output before remote cleanup. Batch and streaming stdin use the SDK handle.
|
||||
- **Terminal sessions** — `spawnTerminal()` uses E2B's byte PTY API, installs the exact argv and scrubbed environment through private mode-`0600` files, reports the foreground process group, sends real signals, and tears down every live group in the remote terminal session before settlement; zombie-only groups are already quiescent. A private random output boundary discards the E2B bootstrap shell's prompt and echoed runner command while preserving every requested-process byte, including its first prompt. PTY allocation is awaited through handle publication before cancellation is observed, so owned rollback can clean the published handle. Setup and teardown own the private state transaction, abort pending setup during service disposal, fence publication, and retain an unproven setup cleanup for disposal retry. Prompt detection, scrollback, readiness, and owner policy remain in `dsh-pty-local`.
|
||||
- **Terminal sessions** — `spawnTerminal()` uses E2B's byte PTY API, installs the exact argv and scrubbed environment through private mode-`0600` files, reports the foreground process group, sends real signals, and tears down every live group in the remote terminal session through one retryable awaited `terminate()`; zombie-only groups are already quiescent. A private random output boundary discards the E2B bootstrap shell's prompt and echoed runner command while preserving every requested-process byte, including its first prompt. PTY allocation is awaited through handle publication before cancellation is observed, so owned rollback can clean the published handle. Setup and teardown own the private state transaction, abort pending setup during service disposal, fence publication, and retain an unproven setup cleanup for disposal retry. Prompt detection, scrollback, readiness, and owner policy remain in `dsh-pty-local`.
|
||||
- **Sandbox disappearance** — `SandboxNotFoundError` during process or terminal liveness, termination, rollback, or disconnect proves the remote execution world cannot retain work, so cleanup treats it as quiescent; unrelated failures remain observable.
|
||||
|
||||
The base E2B image supplies the runtime and Bash/GNU utilities this adapter invokes: `node`, `bash`, `setsid`, `ps`, `awk`, `tr`, `env`, `base64`, `chmod`, `tee`, `head`, `rm`, and `kill`. A custom template must retain compatible commands and E2B PTY support.
|
||||
@@ -30,6 +30,8 @@ No direct invalidation; the named consumers own any request-prefix changes.
|
||||
- **Synchronous-PID consumers are unsupported** — `pid` remains `-1` during remote startup; consumers that require a positive PID immediately, including the ACP child backend, cannot use this provider unchanged.
|
||||
- **Reconnect does not reconstruct handles** — remote PID/status/spill files survive a retained sandbox, but a new harness process does not rebuild live `SubprocessHandle` objects or output cursors from them.
|
||||
- **Remote state accumulates when retained** — process directories and valid spill files remain under `.dsh-e2b`; this POC supplies no retention sweep.
|
||||
- **Numeric process identities are not reuse-fenced** — E2B exposes numeric PID/PGID PTY input, signalling, and cleanup operations but no atomic identity-bound alternative. The adapter minimizes host round trips and live coverage exercises the reproducible stale-interrupt overlap; replacement is deferred until E2B adds an identity primitive or a failure demonstrates a narrower protocol.
|
||||
- **The initial environment probe inherits sandbox defaults** — E2B merges command overrides with default environment entries, so the probe cannot blank unknown credential-shaped names before enumerating them. In a reconnected sandbox, a same-UID untrusted process could inspect that short-lived control shell; this POC therefore does not support secrets in sandbox-default environment variables and requires an E2B replacement-environment primitive or a hardened template to close the gap.
|
||||
- **E2B exposes no signal fact** — an adapter-requested `SIGTERM` or `SIGKILL` is reported only when no wrapper-published direct exit code wins; every unrequested SDK exit remains an exit code, including values shaped like `128 + signal`.
|
||||
- **Exact terminal stdin-wait inspection is unavailable** — E2B exposes the foreground process group but not the syscall evidence needed to prove it is waiting on fd 0, so the generic PTY backend falls back to controlled prompt markers and bounded silence.
|
||||
- **Linux utility and E2B transport semantics are assumed** — there is no Windows, arbitrary-template, escaped-session recovery, or network-partition fidelity layer.
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
- **异步远程启动**:同步 seam 会立即返回一个句柄,同时由 `Sandbox.commands.run(..., { background: true })` 在远程启动进程。包装层发布进程组 ID 并由适配器完成验证之前,`pid` 为 `-1`;stdin 和常规观察会等待该发布。自有启动信号会在分配前中止环境和私有状态准备;分配开始后,取消会等待可清理的临时 SDK 句柄。
|
||||
- **执行世界坐标**:`cwd` 和私有 `runtimeRoot` 来自共享所有者;可执行文件查找会验证绝对路径,或根据沙箱 PATH 加显式覆盖来解析裸名称。
|
||||
- **Linux 进程组**:带引号保护的包装层会在 `exec setsid --wait` 下启动每组 argv,并在 `ctx.e2b.runtimeRoot/processes` 下记录实际进程组 ID 和私有状态文件。句柄会等待该文件,而不会把 SDK 命令 PID 当作已发布的身份。终止操作以记录的负数 ID 发送 `SIGTERM`,等待调用方的 `graceMs`,再升级到 `SIGKILL` 和 SDK kill 回退;TERM 信号发送或探测失败也会强制触发该升级。进程表探测会把仅含僵尸或已死亡条目的进程组视为完全停稳。强制清理只有在有界探测发现进程组为空后才算成功;否则 `waitForExit()` 会公开可重试的失败,而已证明的完全停稳会让后续终止操作不再执行任何动作。发布失败与监控失败都会在拒绝前执行同一清理事务。服务 dispose(资源释放)会拒绝新的启动请求、终止并等待每个保留进程组退出,再等待 SDK 结算和私有清理完成,之后沙箱所有者才会释放。
|
||||
- **环境边界**:沙箱命令环境会先以 base64 ASCII 跨越 SDK 回调边界,再进行一次严格 UTF-8 解码;随后包装层移除环境中的 `DSH_*` 和形似凭据的名称(`*KEY*`、`*SECRET*`、`*TOKEN*`),并把每个有效的 `spec.env` 条目恢复为调用方显式选择。空名称、`=` 和违反 NUL 分帧规则的条目会在启动前被拒绝。在用户 profile 脚本运行前,E2B 固定的命令 shell 与 PTY 登录 shell 会获得位于根目录下、全新随机生成的 `HOME`,并为每个被清理的环境变量名设置空值覆盖;之后,请求的 argv 才会接收序列化环境。宿主环境变量绝不会隐式进入沙箱。私有环境文件在使用后会被删除;命令或终端设置失败时,会先删除其私有状态再拒绝。
|
||||
- **环境边界**:一次受信任的控制 shell 探测会以 base64 ASCII 传输沙箱环境,再进行一次严格 UTF-8 解码;随后包装层移除环境中的 `DSH_*` 和形似凭据的名称(`*KEY*`、`*SECRET*`、`*TOKEN*`),并把每个有效的 `spec.env` 条目恢复为调用方显式选择。空名称、`=` 和违反 NUL 分帧规则的条目会在启动前被拒绝。在用户 profile 脚本运行前,此后的 E2B 命令 shell 与 PTY 登录 shell 会获得位于根目录下、全新随机生成的 `HOME`,并为每个被清理的环境变量名设置空值覆盖;之后,请求的 argv 才会接收序列化环境。宿主环境变量绝不会隐式进入沙箱。私有环境文件在使用后会被删除;命令或终端设置失败时,会先删除其私有状态再拒绝。
|
||||
- **stdio 投影**:远程包装层先把原始字节分流到可选的有界 spill 文件,再把每个实时分片编码为换行分隔的 base64 ASCII 帧;宿主会跨任意 SDK 回调边界增量恢复字节。pipe 模式把这些字节写入宿主 Node 流;inherit 模式把字节写入 harness 进程流;collect 模式保留有界的宿主尾部,并支持基于偏移量读取。包装层会在等待继承管道的写入方之前发布直接命令状态。对于 collect 或 inherit 输出,超过 `graceMs` 后,适配器会断开未完成的 SDK 流,不公开其中不完整的 spill,并返回该状态,同时保留远程进程组供 `waitForExit()` 和终止操作使用。原始 pipe 自然完成时,会等待无损传输完成并保留背压;显式终止则会销毁宿主 pipe,并在远程清理前释放受阻的输出写入。批量 stdin 和流式 stdin 都使用 SDK 句柄。
|
||||
- **终端会话**:`spawnTerminal()` 使用 E2B 的字节 PTY API,以 mode 为 `0600` 的私有文件传入原样 argv 与清理后的环境,报告前台进程组,发送真实信号,并在结算前清理远程终端会话中仍存活的每个进程组;仅含僵尸进程的进程组已经完全停稳。私有随机输出边界会丢弃 E2B 引导 shell 的提示符和回显的 runner 命令,同时保留请求进程的每个字节,包括其第一个提示符。PTY 分配会一直等待到句柄发布后才观察取消,以便由承担清理责任的回滚清理已发布句柄。setup 与 teardown 负责私有状态事务,在服务 dispose 期间中止待处理的 setup、阻止发布,并保留未证明已完成的 setup 清理事务,供 dispose 重试。提示符检测、scrollback、就绪状态与所有者策略仍归 `dsh-pty-local` 所有。
|
||||
- **终端会话**:`spawnTerminal()` 使用 E2B 的字节 PTY API,以 mode 为 `0600` 的私有文件传入原样 argv 与清理后的环境,报告前台进程组,发送真实信号,并通过一项可重试且须等待的 `terminate()` 清理远程终端会话中仍存活的每个进程组;仅含僵尸进程的进程组已经完全停稳。私有随机输出边界会丢弃 E2B 引导 shell 的提示符和回显的 runner 命令,同时保留请求进程的每个字节,包括其第一个提示符。PTY 分配会一直等待到句柄发布后才观察取消,以便由承担清理责任的回滚清理已发布句柄。setup 与 teardown 负责私有状态事务,在服务 dispose 期间中止待处理的 setup、阻止发布,并保留未证明已完成的 setup 清理事务,供 dispose 重试。提示符检测、scrollback、就绪状态与所有者策略仍归 `dsh-pty-local` 所有。
|
||||
- **沙箱消失**:在进程或终端的存活探测、终止、回滚或断开连接期间出现 `SandboxNotFoundError`,证明远程执行环境无法保留工作,因此清理会将其视为完全停稳;其他故障仍可观察。
|
||||
|
||||
基础 E2B 镜像提供该适配器调用的运行时和 Bash/GNU 工具:`node`、`bash`、`setsid`、`ps`、`awk`、`tr`、`env`、`base64`、`chmod`、`tee`、`head`、`rm` 和 `kill`。自定义模板必须保留兼容的命令和 E2B PTY 支持。
|
||||
@@ -30,6 +30,8 @@
|
||||
- **不支持需要同步 PID 的消费方**:远程启动期间,`pid` 保持为 `-1`;包括 ACP 子进程后端在内,要求立即获得正 PID 的消费方无法原样使用本提供方。
|
||||
- **重新连接不会重建句柄**:保留沙箱后,远程 PID/状态/spill 文件仍然存在,但新的 harness 进程不会据此重建实时 `SubprocessHandle` 对象或输出游标。
|
||||
- **保留沙箱时会累积远程状态**:进程目录和有效的 spill 文件会留在 `.dsh-e2b` 下;本 POC 不提供保留清理。
|
||||
- **数值进程身份没有复用围栏**:E2B 公开基于数值 PID/PGID 的 PTY 输入、信号发送和清理操作,却没有与身份原子绑定的替代方案。适配器会尽量减少宿主往返,真实环境测试会覆盖可复现的陈旧中断重叠;在 E2B 新增身份原语,或实际故障证明需要更窄的协议之前,替代方案会继续延后。
|
||||
- **初始环境探测会继承沙箱默认值**:E2B 会把命令覆盖与默认环境条目合并,因此探测无法在枚举未知且形似凭据的名称之前将它们置空。在重新连接的沙箱中,一个同 UID 的不可信进程可以检查该短时存在的控制 shell;因此,该 POC 不支持把 secret 放入沙箱默认环境变量,需要 E2B 的替换环境原语或经加固的模板才能弥合该缺口。
|
||||
- **E2B 不公开信号事实**:适配器请求的 `SIGTERM` 或 `SIGKILL` 只有在包装层发布的直接退出码没有胜出时才报告为信号;其他未请求的 SDK 退出始终保留为退出码,包括形似 `128 + signal` 的值。
|
||||
- **无法精确检查终端 stdin 等待状态**:E2B 会公开前台进程组,但不提供证明其正在等待 fd 0 所需的 syscall 证据,因此通用 PTY 后端会回退到受控提示符标记与有界静默机制。
|
||||
- **依赖 Linux 工具与 E2B 传输语义**:没有 Windows、任意模板、逃逸会话恢复或网络分区的保真层。
|
||||
|
||||
@@ -26,6 +26,8 @@ function remoteEnvironmentEntries(raw: string): Array<readonly [string, string]>
|
||||
* @returns the complete NUL-delimited UTF-8 environment.
|
||||
*/
|
||||
export async function readRemoteEnvironment(sandbox: Sandbox, signal?: AbortSignal): Promise<string> {
|
||||
// TODO(e2b-replace-environment): Remove this ambient probe when E2B can start
|
||||
// a command with a replacement environment instead of merged overrides.
|
||||
const result = await sandbox.commands.run(
|
||||
'set -o pipefail; printf \'%s\' "$PWD" | base64 -w 0; printf \'\\n\'; env -0 | base64 -w 0',
|
||||
{ envs: e2bControlEnvs(), ...(signal === undefined ? {} : { signal }) },
|
||||
|
||||
@@ -61,8 +61,7 @@ export class E2BSubprocessService extends SubprocessService {
|
||||
}))
|
||||
}
|
||||
for (const terminal of terminals) {
|
||||
terminal.terminate()
|
||||
pending.push(terminal.waitForExit().then(() => { this.terminals.delete(terminal) }))
|
||||
pending.push(terminal.terminate().then(() => { this.terminals.delete(terminal) }))
|
||||
}
|
||||
for (const cleanup of failedTerminalSetupCleanups) {
|
||||
pending.push(cleanup().then(() => { this.failedTerminalSetupCleanups.delete(cleanup) }))
|
||||
@@ -125,7 +124,9 @@ export class E2BSubprocessService extends SubprocessService {
|
||||
await handle.waitForExit()
|
||||
this.live.delete(handle)
|
||||
}
|
||||
void handle.done.then(release, release).catch(() => {})
|
||||
void handle.done.then(release, release).catch((_automaticReleaseFailure: unknown) => {
|
||||
// Retain the handle so service disposal can retry its cleanup transaction.
|
||||
})
|
||||
return handle
|
||||
}
|
||||
|
||||
@@ -158,16 +159,17 @@ export class E2BSubprocessService extends SubprocessService {
|
||||
)
|
||||
this.terminals.add(terminal)
|
||||
if (this.isDisposing()) {
|
||||
terminal.terminate()
|
||||
await terminal.waitForExit()
|
||||
await terminal.terminate()
|
||||
this.terminals.delete(terminal)
|
||||
throw new Error('subprocess-e2b: service disposed during terminal setup')
|
||||
}
|
||||
const release = async (): Promise<void> => {
|
||||
await terminal.waitForExit()
|
||||
await terminal.terminate()
|
||||
this.terminals.delete(terminal)
|
||||
}
|
||||
void terminal.done.then(release, release).catch(() => {})
|
||||
void terminal.done.then(release, release).catch((_automaticReleaseFailure: unknown) => {
|
||||
// Retain the terminal so service disposal can retry its cleanup transaction.
|
||||
})
|
||||
return terminal
|
||||
} finally {
|
||||
this.terminalSetups.delete(setup.promise)
|
||||
|
||||
@@ -726,7 +726,9 @@ export class E2BSubprocessHandle implements SubprocessHandle {
|
||||
// A spill mode is a collect mode, so construction always created its reader.
|
||||
const size = (reader as E2BOutputReader).size
|
||||
if (this.outputDrainExpired || size <= mode.maxBytes || size > mode.spill.maxBytes) {
|
||||
removals.push(sandbox.files.remove(path).catch(() => {}))
|
||||
removals.push(sandbox.files.remove(path).catch((_adapterPrivateSpillRemovalFailure: unknown) => {
|
||||
// The command outcome is authoritative; a retained sandbox tolerates private residue.
|
||||
}))
|
||||
}
|
||||
}
|
||||
collect(this.spec.stdio.stdout, this.stdoutReader, this.paths.stdout)
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
quoteE2BShellArg,
|
||||
} from '@deepseek-ai/dsh-e2b'
|
||||
import type { CommandHandle, CommandResult, Sandbox } from '@deepseek-ai/dsh-e2b'
|
||||
import { SubprocessTerminalLifecycle } from '@deepseek-ai/dsh-subprocess'
|
||||
import type {
|
||||
SubprocessOutcome,
|
||||
SubprocessTerminalForeground,
|
||||
@@ -345,7 +344,7 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
|
||||
readonly done: Promise<SubprocessOutcome>
|
||||
|
||||
private topLevelExited = false
|
||||
private readonly lifecycle: SubprocessTerminalLifecycle
|
||||
private cleanup: Promise<void> | undefined
|
||||
private terminationSignal: NodeJS.Signals | null = null
|
||||
|
||||
constructor(
|
||||
@@ -357,21 +356,17 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
|
||||
private readonly controlEnvs: Record<string, string>,
|
||||
private readonly stateDir: string,
|
||||
private readonly graceMs: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
this.pid = handle.pid
|
||||
this.done = this.waitForCommand()
|
||||
this.lifecycle = new SubprocessTerminalLifecycle({
|
||||
done: this.done,
|
||||
cleanup: () => this.closeOnce(),
|
||||
signal,
|
||||
})
|
||||
}
|
||||
|
||||
// TODO(e2b-pgid-identity): Replace retained numeric PTY/session ids when E2B
|
||||
// exposes identity-bound input, foreground-signal, and cleanup operations.
|
||||
/** @inheritdoc */
|
||||
async write(data: Uint8Array): Promise<void> {
|
||||
async write(data: string): Promise<void> {
|
||||
if (this.topLevelExited) throw new Error('terminal process has exited')
|
||||
await this.sandbox.pty.sendInput(this.pid, data)
|
||||
await this.sandbox.pty.sendInput(this.pid, Buffer.from(data, 'utf8'))
|
||||
}
|
||||
|
||||
/** @inheritdoc */
|
||||
@@ -413,13 +408,14 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
|
||||
}
|
||||
|
||||
/** @inheritdoc */
|
||||
terminate(): void {
|
||||
this.lifecycle.terminate()
|
||||
}
|
||||
|
||||
/** @inheritdoc */
|
||||
async waitForExit(signal?: AbortSignal): Promise<boolean> {
|
||||
return await this.lifecycle.waitForExit(signal)
|
||||
terminate(): Promise<void> {
|
||||
if (this.cleanup !== undefined) return this.cleanup
|
||||
const cleanup = this.closeOnce()
|
||||
this.cleanup = cleanup
|
||||
void cleanup.catch((_cleanupFailure: unknown) => {
|
||||
this.cleanup = undefined
|
||||
})
|
||||
return cleanup
|
||||
}
|
||||
|
||||
private async waitForCommand(): Promise<SubprocessOutcome> {
|
||||
@@ -474,7 +470,11 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof SandboxNotFoundError)) throw error
|
||||
}
|
||||
await this.sandbox.files.remove(this.stateDir).catch(() => {})
|
||||
try {
|
||||
await this.sandbox.files.remove(this.stateDir)
|
||||
} catch (_adapterPrivateStateRemovalFailure) {
|
||||
// The terminal is quiescent; a retained sandbox tolerates private residue.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,7 +558,6 @@ export async function spawnE2BTerminal(
|
||||
controlEnvs,
|
||||
stateDir,
|
||||
spec.graceMs,
|
||||
spec.signal,
|
||||
)
|
||||
} catch (error: unknown) {
|
||||
output.destroy()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Buffer } from 'node:buffer'
|
||||
import { once } from 'node:events'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
@@ -14,7 +13,7 @@ import {
|
||||
import type E2BSandboxService from '@deepseek-ai/dsh-e2b'
|
||||
import type { SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess'
|
||||
import E2BSubprocessService from '@deepseek-ai/dsh-subprocess-e2b'
|
||||
import { E2BTerminalHandle, spawnE2BTerminal } from '../src/terminal.ts'
|
||||
import { spawnE2BTerminal } from '../src/terminal.ts'
|
||||
|
||||
function commandError(exitCode: number): CommandExitError {
|
||||
return new CommandExitError({ exitCode, stdout: '', stderr: '', error: `exit ${exitCode}` })
|
||||
@@ -298,20 +297,20 @@ describe('E2B terminal allocation', () => {
|
||||
await fake.createOptions?.onData(Buffer.from('late bootstrap callback'))
|
||||
expect(output).toBe('requested-shell$ ')
|
||||
|
||||
await terminal.write(Buffer.from('echo ok\r'))
|
||||
await terminal.write('echo ok\r')
|
||||
expect(fake.inputs.at(-1)?.data.toString()).toBe('echo ok\r')
|
||||
await expect(terminal.inspectForeground()).resolves.toEqual({ processGroupId: 456, inputWaiting: false })
|
||||
await expect(terminal.signalForeground('SIGINT')).resolves.toBe(456)
|
||||
expect(fake.commands).toContain('kill -INT -- -456')
|
||||
|
||||
terminal.terminate()
|
||||
const terminated = terminal.terminate()
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminated
|
||||
expect(fake.handle.disconnects).toBe(1)
|
||||
expect(fake.removed).toContain('/runtime/terminal-one')
|
||||
})
|
||||
|
||||
it('inherits only safe ambient values and binds live abort to terminal cleanup', async () => {
|
||||
it('inherits only safe ambient values and limits the allocation signal to setup', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
const controller = new AbortController()
|
||||
const terminal = await spawnE2BTerminal(
|
||||
@@ -325,9 +324,10 @@ describe('E2B terminal allocation', () => {
|
||||
expect(environment).not.toContain('DSH_STALE')
|
||||
|
||||
controller.abort(new Error('stop'))
|
||||
await terminal.write('still live\r')
|
||||
expect(fake.inputs.at(-1)?.data.toString()).toBe('still live\r')
|
||||
await terminal.terminate()
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
|
||||
await expect(terminal.waitForExit(controller.signal)).resolves.toBe(false)
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('publishes the PTY handle before honoring allocation cancellation', async () => {
|
||||
@@ -553,31 +553,11 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.handle.succeed(7)
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: 7, signal: null })
|
||||
await ended
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await expect(terminal.write(Buffer.from('late'))).rejects.toThrow('exited')
|
||||
await expect(terminal.write('late')).rejects.toThrow('exited')
|
||||
fake.foregroundFailure = commandError(1)
|
||||
await expect(terminal.inspectForeground()).resolves.toBeUndefined()
|
||||
await expect(terminal.signalForeground('SIGINT')).rejects.toThrow('cannot resolve foreground process group')
|
||||
})
|
||||
|
||||
it('starts cleanup when the lifetime signal is already aborted at handle publication', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
const controller = new AbortController()
|
||||
controller.abort(new Error('publication cancelled'))
|
||||
const terminal = new E2BTerminalHandle(
|
||||
fake.sandbox,
|
||||
fake.handle.asHandle(),
|
||||
new PassThrough(),
|
||||
fake.handle.wait(),
|
||||
123,
|
||||
{ TERM: 'dumb' },
|
||||
'/runtime/pre-aborted',
|
||||
1,
|
||||
controller.signal,
|
||||
)
|
||||
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -590,18 +570,7 @@ describe('E2B terminal lifecycle', () => {
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec(), `/runtime/exit-${exitCode}`)
|
||||
fake.handle.fail(exitCode)
|
||||
await expect(terminal.done).resolves.toEqual(expected)
|
||||
await expect(terminal.waitForExit(new AbortController().signal)).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('lets an early quiescence observer follow a transport rejection', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
fake.groups = []
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec(), '/runtime/early-observer')
|
||||
terminal.output.on('error', () => {})
|
||||
const quiescence = terminal.waitForExit()
|
||||
fake.handle.crash(new Error('transport failed'))
|
||||
await expect(terminal.done).rejects.toThrow('transport failed')
|
||||
await expect(quiescence).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it('treats a terminal session containing only zombies as quiescent', async () => {
|
||||
@@ -612,7 +581,7 @@ describe('E2B terminal lifecycle', () => {
|
||||
|
||||
fake.handle.succeed(0)
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: 0, signal: null })
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
expect(fake.commands).toContain(
|
||||
"set -o pipefail; ps -eo sid=,pgid=,stat= | awk '$1 == 123 && $3 !~ /^[ZXx]/ { print $2 }'",
|
||||
)
|
||||
@@ -625,7 +594,7 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.handle.succeed(0)
|
||||
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: 0, signal: null })
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it('treats sandbox disappearance during PTY kill as quiescent', async () => {
|
||||
@@ -635,8 +604,7 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.ptyKillError = new SandboxNotFoundError('sandbox expired')
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/expired-pty-kill')
|
||||
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
expect(fake.ptyKills).toBe(1)
|
||||
})
|
||||
|
||||
@@ -647,8 +615,11 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.ptyKillError = new Error('PTY kill transport failed')
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/failed-pty-kill')
|
||||
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).rejects.toThrow('PTY kill transport failed')
|
||||
await expect(terminal.terminate()).rejects.toThrow('PTY kill transport failed')
|
||||
fake.ptyKillError = undefined
|
||||
fake.handle.succeed(0)
|
||||
await terminal.done
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -661,8 +632,8 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.groups = []
|
||||
fake.handle.succeed(0)
|
||||
|
||||
if (accepted) await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
else await expect(terminal.waitForExit()).rejects.toThrow('disconnect failed')
|
||||
if (accepted) await expect(terminal.terminate()).resolves.toBeUndefined()
|
||||
else await expect(terminal.terminate()).rejects.toThrow('disconnect failed')
|
||||
})
|
||||
|
||||
it('rejects killing the terminal shell and propagates live foreground failures', async () => {
|
||||
@@ -677,23 +648,17 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.foregroundFailure = commandError(2)
|
||||
await expect(terminal.inspectForeground()).rejects.toBeInstanceOf(CommandExitError)
|
||||
fake.clearOnTerm = true
|
||||
terminal.terminate()
|
||||
await terminal.waitForExit()
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it('escalates surviving process groups and bounds an observing wait', async () => {
|
||||
it('escalates surviving process groups', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
fake.groups = [123, 456]
|
||||
fake.clearOnTerm = false
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/escalate')
|
||||
const controller = new AbortController()
|
||||
const observing = terminal.waitForExit(controller.signal)
|
||||
controller.abort()
|
||||
await expect(observing).resolves.toBe(false)
|
||||
|
||||
terminal.terminate()
|
||||
const terminating = terminal.terminate()
|
||||
await expect(terminal.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminating
|
||||
expect(fake.commands).toContain('kill -TERM -- -123 -456')
|
||||
expect(fake.commands).toContain('kill -KILL -- -123 -456')
|
||||
})
|
||||
@@ -702,49 +667,31 @@ describe('E2B terminal lifecycle', () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
fake.groups = [1]
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/retry')
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit(new AbortController().signal)).rejects.toThrow('unsafe process group 1')
|
||||
await expect(terminal.terminate()).rejects.toThrow('unsafe process group 1')
|
||||
|
||||
fake.groups = []
|
||||
fake.handle.succeed(0)
|
||||
await terminal.done
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
})
|
||||
|
||||
it('propagates a process-group signalling transport failure before retry', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
fake.termFailure = new Error('signal transport failed')
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/signal-failure')
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).rejects.toThrow('signal transport failed')
|
||||
await expect(terminal.terminate()).rejects.toThrow('signal transport failed')
|
||||
|
||||
fake.groups = []
|
||||
fake.handle.succeed(0)
|
||||
await terminal.done
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await terminal.terminate()
|
||||
|
||||
const alreadyExited = new FakeTerminalSandbox()
|
||||
alreadyExited.termFailure = commandError(1)
|
||||
const tolerant = await spawnE2BTerminal(runtime(alreadyExited), spec({ graceMs: 1 }), '/runtime/group-exited')
|
||||
tolerant.terminate()
|
||||
const tolerantTermination = tolerant.terminate()
|
||||
await expect(tolerant.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
|
||||
await expect(tolerant.waitForExit()).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('normalizes a non-Error cleanup rejection for an observing wait', async () => {
|
||||
const fake = new FakeTerminalSandbox()
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec(), '/runtime/non-error-cleanup')
|
||||
fake.commandFailure = 'cleanup transport gone'
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit(new AbortController().signal)).rejects.toThrow('cleanup transport gone')
|
||||
|
||||
fake.groups = []
|
||||
fake.handle.succeed(0)
|
||||
await terminal.done
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await tolerantTermination
|
||||
})
|
||||
|
||||
it('keeps command rejection authoritative while cleanup is already waiting', async () => {
|
||||
@@ -753,11 +700,11 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.removeError = new Error('private state already gone')
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec(), '/runtime/reject-during-cleanup')
|
||||
terminal.output.on('error', () => {})
|
||||
terminal.terminate()
|
||||
const cleanup = terminal.terminate()
|
||||
await Promise.resolve()
|
||||
fake.handle.crash(new Error('command transport failed'))
|
||||
await expect(terminal.done).rejects.toThrow('command transport failed')
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await cleanup
|
||||
})
|
||||
|
||||
it('keeps a late command rejection authoritative after PTY kill', async () => {
|
||||
@@ -766,12 +713,12 @@ describe('E2B terminal lifecycle', () => {
|
||||
fake.settleOnPtyKill = false
|
||||
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/reject-after-kill')
|
||||
terminal.output.on('error', () => {})
|
||||
terminal.terminate()
|
||||
const cleanup = terminal.terminate()
|
||||
while (fake.ptyKills === 0) await new Promise(resolve => setTimeout(resolve, 0))
|
||||
await Promise.resolve()
|
||||
fake.handle.crash(new Error('late command transport failed'))
|
||||
await expect(terminal.done).rejects.toThrow('late command transport failed')
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await cleanup
|
||||
})
|
||||
|
||||
it('reports surviving groups, a surviving top-level pid, and transport failure', async () => {
|
||||
@@ -779,15 +726,13 @@ describe('E2B terminal lifecycle', () => {
|
||||
survivor.clearOnTerm = false
|
||||
survivor.clearOnKill = false
|
||||
const terminal = await spawnE2BTerminal(runtime(survivor), spec({ graceMs: 1 }), '/runtime/survivor')
|
||||
terminal.terminate()
|
||||
await expect(terminal.waitForExit()).rejects.toThrow('surviving process groups: 123')
|
||||
await expect(terminal.terminate()).rejects.toThrow('surviving process groups: 123')
|
||||
|
||||
const livePid = new FakeTerminalSandbox()
|
||||
livePid.groups = []
|
||||
livePid.settleOnPtyKill = false
|
||||
const live = await spawnE2BTerminal(runtime(livePid), spec({ graceMs: 1 }), '/runtime/live-pid')
|
||||
live.terminate()
|
||||
await expect(live.waitForExit()).rejects.toThrow('surviving pid: 123')
|
||||
await expect(live.terminate()).rejects.toThrow('surviving pid: 123')
|
||||
livePid.handle.succeed(0)
|
||||
await live.done
|
||||
|
||||
@@ -798,7 +743,7 @@ describe('E2B terminal lifecycle', () => {
|
||||
crashed.handle.crash('transport gone')
|
||||
await expect(failed.done).rejects.toEqual('transport gone')
|
||||
await expect(outputError).resolves.toMatchObject([{ message: 'transport gone' }])
|
||||
await expect(failed.waitForExit()).resolves.toBe(true)
|
||||
await failed.terminate()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -943,7 +888,7 @@ describe('E2B subprocess terminal service', () => {
|
||||
const terminal = await ctx.subprocess.spawnTerminal(spec())
|
||||
fake.handle.succeed(0)
|
||||
await terminal.done
|
||||
await terminal.waitForExit()
|
||||
await terminal.terminate()
|
||||
const signals = fake.commands.filter(command => command.startsWith('kill -')).length
|
||||
await fiber.dispose()
|
||||
expect(fake.commands.filter(command => command.startsWith('kill -'))).toHaveLength(signals)
|
||||
@@ -961,6 +906,6 @@ describe('E2B subprocess terminal service', () => {
|
||||
|
||||
fake.groups = []
|
||||
await fiber.dispose()
|
||||
await expect(terminal.waitForExit()).resolves.toBe(true)
|
||||
await expect(terminal.terminate()).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user