refactor(e2b): narrow the sandbox POC

This commit is contained in:
Tianyi Cui
2026-07-30 04:25:47 +08:00
parent bb0be75d85
commit de77310c6f
37 changed files with 176 additions and 881 deletions

View File

@@ -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: 9d563c91c149d28718159af1b1f8ddbd6652dc44
README.zh.md: be189f41818c66aeff2bed7b1851b82ca08f08f4
README.md: 4e47566d55cf9400459993185f03482761c92096
README.zh.md: 21ef231af700f72c2c5ec1fc651297ebdd17d49b

View File

@@ -9,12 +9,12 @@ 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** — one trusted control-shell probe resolves the sandbox user's login home from its passwd entry and 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 without changing the template's umask. 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 resolves the sandbox user's login home from its passwd entry and 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 without changing the sandbox user's umask. 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 through one retryable awaited `terminate()`; termination rejects new handle operations, aborts and joins in-flight writes, inspections, and signals, and treats zombie-only groups as 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`, `kill`, `id`, and `getent`. A custom template must retain compatible commands and E2B PTY support.
The default E2B base image supplies the runtime and Bash/GNU utilities this adapter invokes: `node`, `bash`, `setsid`, `ps`, `awk`, `tr`, `env`, `base64`, `chmod`, `tee`, `head`, `rm`, `kill`, `id`, and `getent`.
## Model Experience
@@ -28,10 +28,9 @@ No direct invalidation; the named consumers own any request-prefix changes.
- **The SDK still retains complete command output in host memory** — E2B `CommandHandle.stdout` and `.stderr` accumulate the base64 transport even when this adapter exposes bounded raw-byte tails, so the subprocess seam's normal host-memory bound is not achieved and transport retention is larger than the source stream.
- **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.
- **Private state lives for the sandbox lifetime** — process directories and valid spill files remain under `.dsh-e2b` until the owner deletes the sandbox; this POC supplies no in-sandbox 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.
- **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. A same-UID untrusted process already in the sandbox 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 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.
- **Linux utility and E2B transport semantics are assumed** — there is no Windows, escaped-session recovery, or network-partition fidelity layer.

View File

@@ -9,12 +9,12 @@
- **异步远程启动**:同步 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 结算和私有清理完成,之后沙箱所有者才会释放。
- **环境边界**:一次受信任的控制 shell 探测会从 passwd 条目解析沙箱用户的登录主目录,以 base64 ASCII 传输沙箱环境,再进行一次严格 UTF-8 解码;随后包装层移除环境中的 `DSH_*` 和形似凭据的名称(`*KEY*``*SECRET*``*TOKEN*`),并把每个有效的 `spec.env` 条目恢复为调用方显式选择。空名称、`=` 和违反 NUL 分帧规则的条目会在启动前被拒绝。在用户 profile 脚本运行前,此后的 E2B 命令 shell 与 PTY 登录 shell 会获得位于根目录下、全新随机生成的 `HOME`,并为每个被清理的环境变量名设置空值覆盖;之后,请求的 argv 会在不改变模板 umask 的前提下接收序列化环境。宿主环境变量绝不会隐式进入沙箱。私有环境文件在使用后会被删除;命令或终端设置失败时,会先删除其私有状态再拒绝。
- **环境边界**:一次受信任的控制 shell 探测会从 passwd 条目解析沙箱用户的登录主目录,以 base64 ASCII 传输沙箱环境,再进行一次严格 UTF-8 解码;随后包装层移除环境中的 `DSH_*` 和形似凭据的名称(`*KEY*``*SECRET*``*TOKEN*`),并把每个有效的 `spec.env` 条目恢复为调用方显式选择。空名称、`=` 和违反 NUL 分帧规则的条目会在启动前被拒绝。在用户 profile 脚本运行前,此后的 E2B 命令 shell 与 PTY 登录 shell 会获得位于根目录下、全新随机生成的 `HOME`,并为每个被清理的环境变量名设置空值覆盖;之后,请求的 argv 会在不改变沙箱用户 umask 的前提下接收序列化环境。宿主环境变量绝不会隐式进入沙箱。私有环境文件在使用后会被删除;命令或终端设置失败时,会先删除其私有状态再拒绝。
- **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 与清理后的环境,报告前台进程组,发送真实信号,并通过一项可重试且须等待的 `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``id``getent`自定义模板必须保留兼容的命令和 E2B PTY 支持。
E2B 默认基础镜像提供该适配器调用的运行时和 Bash/GNU 工具:`node``bash``setsid``ps``awk``tr``env``base64``chmod``tee``head``rm``kill``id``getent`
## 模型体验
@@ -28,10 +28,9 @@
- **SDK 仍会在宿主内存中保留完整命令输出**即使本适配器公开的是有界原始字节尾部E2B `CommandHandle.stdout``.stderr` 仍会累积 base64 传输内容,因此无法达到进程管理 seam 通常提供的宿主内存边界,而且传输保留量大于源数据流。
- **不支持需要同步 PID 的消费方**:远程启动期间,`pid` 保持为 `-1`;包括 ACP 子进程后端在内,要求立即获得正 PID 的消费方无法原样使用本提供方。
- **重新连接不会重建句柄**:保留沙箱后,远程 PID状态spill 文件仍然存在,但新的 harness 进程不会据此重建实时 `SubprocessHandle` 对象或输出游标
- **保留沙箱时会累积远程状态**:进程目录和有效的 spill 文件会留在 `.dsh-e2b` 下;本 POC 不提供保留清理。
- **私有状态随沙箱生命周期存在**:进程目录和有效的 spill 文件会留在 `.dsh-e2b` 下,直到所有者删除沙箱;本 POC 不提供沙箱内清理
- **数值进程身份没有复用围栏**E2B 公开基于数值 PID/PGID 的 PTY 输入、信号发送和清理操作,却没有与身份原子绑定的替代方案。适配器会尽量减少宿主往返,真实环境测试会覆盖可复现的陈旧中断重叠;在 E2B 新增身份原语,或实际故障证明需要更窄的协议之前,替代方案会继续延后。
- **初始环境探测会继承沙箱默认值**E2B 会把命令覆盖与默认环境条目合并,因此探测无法在枚举未知且形似凭据的名称之前将它们置空。在重新连接的沙箱中,一个同 UID 不可信进程可以检查该短时存在的控制 shell因此该 POC 不支持把 secret 放入沙箱默认环境变量,需要 E2B 的替换环境原语或经加固的模板才能弥合该缺口。
- **初始环境探测会继承沙箱默认值**E2B 会把命令覆盖与默认环境条目合并,因此探测无法在枚举未知且形似凭据的名称之前将它们置空。一个已在沙箱内运行的同 UID 不可信进程可以检查该短时存在的控制 shell因此该 POC 不支持把 secret 放入沙箱默认环境变量,需要 E2B 的替换环境原语才能弥合该缺口。
- **E2B 不公开信号事实**:适配器请求的 `SIGTERM``SIGKILL` 只有在包装层发布的直接退出码没有胜出时才报告为信号;其他未请求的 SDK 退出始终保留为退出码,包括形似 `128 + signal` 的值。
- **无法精确检查终端 stdin 等待状态**E2B 会公开前台进程组,但不提供证明其正在等待 fd 0 所需的 syscall 证据,因此通用 PTY 后端会回退到受控提示符标记与有界静默机制。
- **依赖 Linux 工具与 E2B 传输语义**:没有 Windows、任意模板、逃逸会话恢复或网络分区的保真层。
- **依赖 Linux 工具与 E2B 传输语义**:没有 Windows、逃逸会话恢复或网络分区的保真层。

View File

@@ -106,7 +106,7 @@ export class E2BSubprocessService extends SubprocessService {
/** @inheritdoc */
spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
if (this.isDisposing()) throw new Error('subprocess-e2b: service is disposing')
if (this.disposing) throw new Error('subprocess-e2b: service is disposing')
const program = spec.argv[0]
if (program === undefined || program.length === 0) {
throw new Error('invalid argv: expected a non-empty program name at argv[0]')
@@ -115,7 +115,7 @@ export class E2BSubprocessService extends SubprocessService {
throw new Error('subprocess-e2b: graceMs must be a positive finite number')
}
if (spec.signal?.aborted === true) {
throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
throw new Error(`aborted before spawn: ${String(spec.signal.reason)}`)
}
const stateDir = posix.join(this.ctx.e2b.runtimeRoot, 'processes', randomUUID())
const handle = new E2BSubprocessHandle(this.ctx.e2b, spec, stateDir)
@@ -132,7 +132,7 @@ export class E2BSubprocessService extends SubprocessService {
/** @inheritdoc */
async spawnTerminal(spec: SubprocessTerminalSpawnSpec): Promise<SubprocessTerminalHandle> {
if (this.isDisposing()) throw new Error('subprocess-e2b: service is disposing')
if (this.disposing) throw new Error('subprocess-e2b: service is disposing')
const program = spec.argv[0]
if (program === undefined || program.length === 0) {
throw new Error('subprocess-e2b: terminal argv must contain a program')
@@ -158,7 +158,8 @@ export class E2BSubprocessService extends SubprocessService {
(cleanup) => { this.failedTerminalSetupCleanups.add(cleanup) },
)
this.terminals.add(terminal)
if (this.isDisposing()) {
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Remote allocation yields to disposal.
if (this.disposing) {
await terminal.terminate()
this.terminals.delete(terminal)
throw new Error('subprocess-e2b: service disposed during terminal setup')
@@ -176,10 +177,6 @@ export class E2BSubprocessService extends SubprocessService {
setup.resolve()
}
}
private isDisposing(): boolean {
return this.disposing
}
}
export default E2BSubprocessService

View File

@@ -115,9 +115,6 @@ export class E2BOutputReader implements SubprocessOutputReader {
/** @inheritdoc */
readFrom(fromByte: number): SubprocessOutputRead {
if (!Number.isSafeInteger(fromByte) || fromByte < 0) {
throw new Error('subprocess output offset must be a non-negative safe integer')
}
const retained = Buffer.concat(this.chunks, this.retainedBytes)
const firstRetained = this.totalBytes - this.retainedBytes
const lossy = fromByte < firstRetained

View File

@@ -149,10 +149,6 @@ function commandOpts(
return { envs: e2bControlEnvs(envs), ...(signal === undefined ? {} : { signal }) }
}
function isAborted(signal: AbortSignal | undefined): boolean {
return signal?.aborted === true
}
function waitTick(signal?: AbortSignal): Promise<boolean> {
if (signal?.aborted === true) return Promise.resolve(false)
return new Promise<boolean>((resolve) => {
@@ -173,7 +169,7 @@ const WAIT_ABORTED = Symbol('wait aborted')
function waitWithSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T | typeof WAIT_ABORTED> {
if (signal === undefined) return promise
if (signal.aborted) return Promise.resolve(WAIT_ABORTED)
return new Promise<T | typeof WAIT_ABORTED>((resolve, reject) => {
return new Promise<T | typeof WAIT_ABORTED>((resolve) => {
const onAbort = (): void => { cleanup(); resolve(WAIT_ABORTED) }
const cleanup = (): void => { signal.removeEventListener('abort', onAbort) }
signal.addEventListener('abort', onAbort, { once: true })
@@ -181,10 +177,7 @@ function waitWithSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined)
onAbort()
return
}
void promise.then(
(value) => { cleanup(); resolve(value) },
(error: unknown) => { cleanup(); reject(asError(error)) },
)
void promise.then((value) => { cleanup(); resolve(value) })
})
}
@@ -206,12 +199,9 @@ export class E2BSubprocessHandle implements SubprocessHandle {
private readonly paths: RemotePaths
private controlEnvs: Record<string, string> = {}
private remotePid = -1
private commandHandle: CommandHandle | undefined
private outputTransportError: Error | undefined
private outputDrainExpired = false
private stateDirectoryCreated = false
private preparing = true
private terminationStarted = false
private quiescenceProven = false
private terminationAttempt: Promise<void> | undefined
private terminationFailure: Error | undefined
@@ -265,7 +255,6 @@ export class E2BSubprocessHandle implements SubprocessHandle {
/** @inheritdoc */
terminate(): void {
if (this.quiescenceProven || this.terminationAttempt !== undefined) return
this.terminationStarted = true
this.terminationController.abort(new Error('subprocess-e2b: command terminated'))
this.stdout?.destroy()
this.stderr?.destroy()
@@ -285,7 +274,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
async waitForExit(signal?: AbortSignal): Promise<boolean> {
if (this.quiescenceProven) return true
let handle: CommandHandle | undefined
if (this.terminationStarted) {
if (this.terminationController.signal.aborted) {
const observed = await waitWithSignal(this.commandState.promise, signal)
if (observed === WAIT_ABORTED) return false
handle = observed
@@ -295,22 +284,23 @@ export class E2BSubprocessHandle implements SubprocessHandle {
}
if (this.remotePid <= 0) {
const attempt = this.terminationAttempt
if (attempt !== undefined && await waitWithSignal(attempt, signal) === WAIT_ABORTED) return false
if (attempt !== undefined && await waitWithSignal(attempt.catch(() => undefined), signal) === WAIT_ABORTED) {
return false
}
this.throwTerminationFailure()
// Successful pre-publication termination records quiescence; its only other outcome is the failure above.
return true
}
} else {
try {
const observed = await waitWithSignal(this.readyState.promise, signal)
if (observed === WAIT_ABORTED) return false
handle = observed
} catch {
handle = this.commandHandle
if (handle === undefined) {
this.markQuiescent()
return true
}
const observed = await waitWithSignal(
this.readyState.promise.catch(() => this.commandState.promise),
signal,
)
if (observed === WAIT_ABORTED) return false
handle = observed
if (handle === undefined) {
this.markQuiescent()
return true
}
}
this.throwTerminationFailure()
@@ -318,7 +308,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
try {
sandbox = await this.runtime.getSandbox()
} catch (error: unknown) {
if (isAborted(signal)) return false
if (signal?.aborted === true) return false
if (error instanceof SandboxNotFoundError) {
this.markQuiescent()
return true
@@ -331,7 +321,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
if (!await waitTick(signal)) return false
}
this.throwTerminationFailure()
if (isAborted(signal)) return false
if (signal?.aborted === true) return false
this.markQuiescent()
return true
}
@@ -345,10 +335,11 @@ export class E2BSubprocessHandle implements SubprocessHandle {
private async run(): Promise<SubprocessOutcome> {
let sandbox: Sandbox | undefined
let preparing = true
try {
sandbox = await this.runtime.getSandbox()
await this.prepareState(sandbox)
this.preparing = false
preparing = false
const handle = await sandbox.commands.run(
commandText(this.spec, this.paths),
{
@@ -361,7 +352,6 @@ export class E2BSubprocessHandle implements SubprocessHandle {
onStderr: async (data) => { await this.dispatchOutput('stderr', data) },
},
)
this.commandHandle = handle
const completion = handle.wait()
void completion.catch(() => {})
if (!isValidProcessId(handle.pid)) {
@@ -369,7 +359,6 @@ export class E2BSubprocessHandle implements SubprocessHandle {
try {
await handle.kill()
this.markQuiescent()
this.commandHandle = undefined
} catch (cleanupError: unknown) {
this.terminationFailure = asError(cleanupError)
this.commandState.resolve(handle)
@@ -404,9 +393,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
await this.finalizeSpills(sandbox)
return outcome
} catch (error: unknown) {
const canceledPreparation = this.preparing
&& this.terminationStarted
&& this.terminationController.signal.aborted
const canceledPreparation = preparing && this.terminationController.signal.aborted
let failure = await this.rollbackPublishedFailure(error)
if (sandbox !== undefined && this.stateDirectoryCreated) {
try {
@@ -423,7 +410,6 @@ export class E2BSubprocessHandle implements SubprocessHandle {
if (canceledPreparation && failure === error) return { exitCode: null, signal: 'SIGTERM' }
throw failure
} finally {
this.preparing = false
this.spec.signal?.removeEventListener('abort', this.onAbort)
this.stdout?.end()
this.stderr?.end()
@@ -583,7 +569,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
}
private async rollbackPublishedFailure(error: unknown): Promise<unknown> {
if (this.remotePid <= 0 || this.commandHandle === undefined || this.quiescenceProven) return error
if (this.remotePid <= 0 || this.quiescenceProven) return error
this.terminate()
try {
await this.waitForExit()
@@ -626,7 +612,6 @@ export class E2BSubprocessHandle implements SubprocessHandle {
if (!isValidProcessId(handle.pid) && this.remotePid <= 0) {
await handle.kill()
this.markQuiescent()
this.commandHandle = undefined
return
}
const sandbox = await this.runtime.getSandbox()
@@ -730,7 +715,7 @@ export class E2BSubprocessHandle implements SubprocessHandle {
const size = (reader as E2BOutputReader).size
if (this.outputDrainExpired || size <= mode.maxBytes || size > mode.spill.maxBytes) {
removals.push(sandbox.files.remove(path).catch((_adapterPrivateSpillRemovalFailure: unknown) => {
// The command outcome is authoritative; a retained sandbox tolerates private residue.
// The command outcome is authoritative; owner teardown bounds private residue.
}))
}
}

View File

@@ -41,7 +41,6 @@ const TERMINAL_RUNNER_SOURCE = [
' exit 125',
'fi',
'printf \'%s\' "$dsh_output_marker"',
"printf 'ready\\n' > \"$dsh_state/ready\"",
'exec env -i -- "${dsh_env[@]}" "${dsh_argv[@]}"',
'',
].join('\n')
@@ -51,7 +50,6 @@ interface TerminalPaths {
environment: string
argv: string
outputMarker: string
ready: string
}
function signalOpts(signal: AbortSignal | undefined): { signal?: AbortSignal } {
@@ -165,26 +163,6 @@ async function terminalSessionId(
return parsePositiveId(result.stdout, `subprocess-e2b: cannot resolve process session for terminal ${pid}`)
}
async function waitUntilReady(
sandbox: Sandbox,
paths: TerminalPaths,
completion: Promise<CommandResult>,
signal?: AbortSignal,
): Promise<void> {
const settled = completion.then(() => true, () => true)
for (;;) {
signal?.throwIfAborted()
try {
if ((await sandbox.files.read(paths.ready, signalOpts(signal))).trim() === 'ready') return
} catch (error: unknown) {
if (!(error instanceof FileNotFoundError)) throw error
}
if (await Promise.race([settled, delay(POLL_MS).then(() => false)])) {
throw new Error('subprocess-e2b: terminal exited before publishing readiness')
}
}
}
async function sessionProcessGroups(
sandbox: Sandbox,
sessionId: number,
@@ -241,8 +219,13 @@ async function awaitSessionEmpty(
const deadline = Date.now() + graceMs
for (;;) {
const groups = await sessionProcessGroups(sandbox, sessionId, envs)
if (groups.length === 0 || Date.now() >= deadline) return groups
if (kill) await signalGroups(sandbox, groups, 'KILL', envs)
if (groups.length === 0) return groups
if (kill) {
await signalGroups(sandbox, groups, 'KILL', envs)
if (Date.now() >= deadline) return await sessionProcessGroups(sandbox, sessionId, envs)
} else if (Date.now() >= deadline) {
return groups
}
await delay(Math.min(POLL_MS, Math.max(1, deadline - Date.now())))
}
}
@@ -277,7 +260,6 @@ async function rollbackUnpublishedTerminal(
groups = await awaitSessionEmpty(sandbox, sessionId, envs, graceMs)
}
if (groups.length > 0) {
await signalGroups(sandbox, groups, 'KILL', envs)
await awaitSessionEmpty(sandbox, sessionId, envs, graceMs, true)
}
} catch (error: unknown) {
@@ -285,25 +267,13 @@ async function rollbackUnpublishedTerminal(
}
}
// Completion can settle while any awaited provider cleanup above is running.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Provider cleanup yields to completion.
if (!topLevelExited) {
if (validPid) {
try {
await sandbox.pty.kill(handle.pid)
} catch (error: unknown) {
if (error instanceof SandboxNotFoundError) return
attemptFailures.push(asError(error))
}
}
// The awaited PTY fallback can settle completion before the SDK fallback.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!topLevelExited) {
try {
await handle.kill()
} catch (error: unknown) {
if (error instanceof SandboxNotFoundError) return
attemptFailures.push(asError(error))
}
try {
await handle.kill()
} catch (error: unknown) {
if (error instanceof SandboxNotFoundError) return
attemptFailures.push(asError(error))
}
await Promise.race([completion.catch(() => undefined), delay(graceMs)])
}
@@ -321,7 +291,7 @@ async function rollbackUnpublishedTerminal(
}
}
// The bounded completion race above updates this callback-owned state.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
// oxlint-disable-next-line typescript/no-unnecessary-condition -- The callback mutates this after a race.
if (!topLevelExited) {
proofFailures.push(new Error(`subprocess-e2b: terminal setup rollback failed; surviving pid: ${handle.pid}`))
}
@@ -347,7 +317,6 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
private cleanup: Promise<void> | undefined
private readonly operationController = new AbortController()
private readonly operations = new Set<Promise<unknown>>()
private terminating = false
private terminationSignal: NodeJS.Signals | null = null
constructor(
@@ -400,7 +369,6 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
/** @inheritdoc */
terminate(): Promise<void> {
if (this.cleanup !== undefined) return this.cleanup
this.terminating = true
this.operationController.abort(new Error('subprocess-e2b: terminal is terminating'))
const cleanup = this.closeAfterOperations()
this.cleanup = cleanup
@@ -434,7 +402,9 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
}
private trackOperation<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (this.terminating) return Promise.reject(new Error('subprocess-e2b: terminal is terminating'))
if (this.operationController.signal.aborted) {
return Promise.reject(new Error('subprocess-e2b: terminal is terminating'))
}
const pending = operation(this.operationController.signal)
this.operations.add(pending)
void pending.then(
@@ -445,7 +415,7 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
}
private async closeAfterOperations(): Promise<void> {
if (this.operations.size > 0) await Promise.allSettled(this.operations)
await Promise.allSettled(this.operations)
await this.closeOnce()
}
@@ -481,7 +451,7 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
this.terminationSignal = 'SIGKILL'
if (!this.topLevelExited) {
try {
await this.sandbox.pty.kill(this.pid)
await this.handle.kill()
} catch (error: unknown) {
if (error instanceof SandboxNotFoundError) return
throw error
@@ -504,7 +474,7 @@ export class E2BTerminalHandle implements SubprocessTerminalHandle {
try {
await this.sandbox.files.remove(this.stateDir)
} catch (_adapterPrivateStateRemovalFailure) {
// The terminal is quiescent; a retained sandbox tolerates private residue.
// The terminal is quiescent; owner teardown bounds private residue.
}
}
}
@@ -531,7 +501,6 @@ export async function spawnE2BTerminal(
environment: posix.join(stateDir, 'environment'),
argv: posix.join(stateDir, 'argv'),
outputMarker: posix.join(stateDir, 'output-marker'),
ready: posix.join(stateDir, 'ready'),
}
const outputMarker = Buffer.from(`dsh-e2b-bootstrap:${randomUUID()}`)
const output = new PassThrough()
@@ -577,7 +546,6 @@ export async function spawnE2BTerminal(
}
const command = `exec /bin/bash ${quoteE2BShellArg(paths.runner)} ${quoteE2BShellArg(stateDir)}\r`
await sandbox.pty.sendInput(handle.pid, Buffer.from(command), signalOpts(spec.signal))
await waitUntilReady(sandbox, paths, completion, spec.signal)
await waitForBootstrapOutput(outputFilter.ready, completion, spec.signal)
const sessionId = await terminalSessionId(sandbox, handle.pid, controlEnvs, spec.signal)
return new E2BTerminalHandle(

View File

@@ -316,7 +316,6 @@ function runtime(fake: FakeSandbox, getSandbox: () => Promise<Sandbox> = async (
return {
cwd: '/workspace',
runtimeRoot: '/workspace/.dsh-e2b',
disposeMode: 'kill',
getSandbox,
} as unknown as E2BSandboxService
}
@@ -372,8 +371,6 @@ describe('E2BOutputReader', () => {
const overCap = new E2BOutputReader(2, 3, '/too-small')
overCap.push(Buffer.from('abcd'))
expect(overCap.readFrom(0)).toEqual({ text: 'cd', nextOffset: 4, lossy: true })
expect(() => overCap.readFrom(-1)).toThrow(/non-negative safe integer/)
expect(() => overCap.readFrom(1.5)).toThrow(/non-negative safe integer/)
})
})
@@ -1673,7 +1670,6 @@ describe('E2BSubprocessService', () => {
expect(() => ctx.subprocess.spawn(spec({ argv: [] }))).toThrow(/non-empty program/)
expect(() => ctx.subprocess.spawn(spec({ graceMs: 0 }))).toThrow(/positive finite/)
expect(() => ctx.subprocess.spawn(spec({ signal: AbortSignal.abort('stop') }))).toThrow(/aborted before spawn/)
expect(() => ctx.subprocess.spawn(spec({ signal: { aborted: true, reason: undefined } as AbortSignal }))).toThrow(/aborted$/)
})
it('registers the package-owned empty invariant installer', async () => {

View File

@@ -90,9 +90,6 @@ class FakeTerminalSandbox {
readonly writes = new Map<string, string>()
createOptions: Parameters<Sandbox['pty']['create']>[0] | undefined
ambient = 'KEEP=visible\0UNICODE=你好\0NPM_TOKEN=secret\0DSH_STALE=old\0BROKEN\0=bad\0'
ready: string | Error = 'ready\n'
readyMisses = 0
readyReads = 0
sessionId = '123\n'
foreground = '456\n'
groups = [123]
@@ -108,12 +105,9 @@ class FakeTerminalSandbox {
sessionGroupsFailure: unknown
foregroundFailure: unknown
termFailure: unknown
ptyKillError: unknown
removeError: unknown
clearOnTerm = true
clearOnKill = true
settleOnPtyKill = true
ptyKills = 0
resolvedExecutable = '/usr/bin/node\n'
requestedOutput = 'requested-shell$ '
emitOutputMarker = true
@@ -144,15 +138,6 @@ class FakeTerminalSandbox {
if (this.writeError !== undefined) throw this.writeError
return files.map(() => ({}))
},
read: async (): Promise<string> => {
this.readyReads += 1
if (this.readyMisses > 0) {
this.readyMisses -= 1
throw new FileNotFoundError('not ready')
}
if (this.ready instanceof Error) throw this.ready
return this.ready
},
remove: async (path: string): Promise<void> => {
this.removed.push(path)
if (this.removeError !== undefined) throw this.removeError
@@ -237,12 +222,6 @@ class FakeTerminalSandbox {
}
}
},
kill: async (pid: number): Promise<boolean> => {
this.ptyKills += 1
if (this.ptyKillError !== undefined) throw this.ptyKillError
if (this.settleOnPtyKill) this.handle.fail(137)
return pid === this.handle.pid
},
},
} as unknown as Sandbox
}
@@ -251,7 +230,6 @@ function runtime(fake: FakeTerminalSandbox): E2BSandboxService {
return {
cwd: '/workspace',
runtimeRoot: '/workspace/.dsh-e2b',
disposeMode: 'kill',
getSandbox: async () => fake.sandbox,
} as unknown as E2BSandboxService
}
@@ -284,7 +262,6 @@ function holdRequestUntilAbort(started: PromiseWithResolvers<AbortSignal>) {
describe('E2B terminal allocation', () => {
it('hides bootstrap-shell bytes and preserves requested-shell bytes across the output boundary', async () => {
const fake = new FakeTerminalSandbox()
fake.readyMisses = 1
const terminal = await spawnE2BTerminal(runtime(fake), spec(), '/runtime/terminal-one')
let output = ''
terminal.output.on('data', (chunk) => { output += String(chunk) })
@@ -417,12 +394,6 @@ describe('E2B terminal allocation', () => {
expect(failedInput.commands).toContain('kill -TERM -- -123')
expect(failedInput.groups).toEqual([])
const exited = new FakeTerminalSandbox()
exited.ready = new FileNotFoundError('not ready')
queueMicrotask(() => { exited.handle.succeed(0) })
await expect(spawnE2BTerminal(runtime(exited), spec(), '/runtime/exited'))
.rejects.toThrow('exited before publishing readiness')
const invalidSession = new FakeTerminalSandbox()
invalidSession.sessionId = 'not-a-session\n'
invalidSession.clearOnTerm = false
@@ -431,7 +402,7 @@ describe('E2B terminal allocation', () => {
expect(invalidSession.commands).toContain('kill -TERM -- -123')
expect(invalidSession.commands).toContain('kill -KILL -- -123')
expect(invalidSession.groups).toEqual([])
expect(invalidSession.ptyKills).toBe(1)
expect(invalidSession.handle.sdkKills).toBe(1)
const lateData = invalidSession.createOptions?.onData
if (lateData === undefined) throw new Error('missing captured terminal callback')
expect(lateData(Buffer.from('late bytes'))).toBeUndefined()
@@ -442,12 +413,12 @@ describe('E2B terminal allocation', () => {
await expect(spawnE2BTerminal(runtime(termFailed), spec(), '/runtime/term-failed'))
.rejects.toThrow('bootstrap failed')
expect(termFailed.commands).toContain('kill -KILL -- -123')
expect(termFailed.ptyKills).toBe(1)
expect(termFailed.handle.sdkKills).toBe(1)
const uninspectable = new FakeTerminalSandbox()
uninspectable.sendError = new Error('bootstrap failed')
uninspectable.sessionGroupsFailure = 'session enumeration failed'
uninspectable.ptyKillError = new Error('PTY kill failed')
uninspectable.handle.sdkKillError = new Error('PTY kill failed')
let uninspectableFailure: unknown
try {
await spawnE2BTerminal(runtime(uninspectable), spec(), '/runtime/uninspectable')
@@ -455,7 +426,6 @@ describe('E2B terminal allocation', () => {
uninspectableFailure = error
}
expect(uninspectableFailure).toBeInstanceOf(AggregateError)
expect(uninspectable.ptyKills).toBe(1)
expect(uninspectable.handle.sdkKills).toBe(1)
const survivingGroups = new FakeTerminalSandbox()
@@ -468,7 +438,6 @@ describe('E2B terminal allocation', () => {
const survivingPid = new FakeTerminalSandbox()
survivingPid.sendError = new Error('bootstrap failed')
survivingPid.groups = []
survivingPid.settleOnPtyKill = false
survivingPid.handle.settleOnSdkKill = false
await expect(spawnE2BTerminal(runtime(survivingPid), spec({ graceMs: 1 }), '/runtime/surviving-pid'))
.rejects.toThrow('bootstrap failed')
@@ -491,12 +460,12 @@ describe('E2B terminal allocation', () => {
const expiredDuringRollback = new FakeTerminalSandbox()
expiredDuringRollback.sendError = new Error('bootstrap failed before timeout')
expiredDuringRollback.groups = []
expiredDuringRollback.settleOnPtyKill = false
expiredDuringRollback.ptyKillError = new SandboxNotFoundError('sandbox expired')
expiredDuringRollback.handle.settleOnSdkKill = false
expiredDuringRollback.handle.sdkKillError = new SandboxNotFoundError('sandbox expired')
expiredDuringRollback.removeError = new SandboxNotFoundError('sandbox expired')
await expect(spawnE2BTerminal(runtime(expiredDuringRollback), spec(), '/runtime/expired-rollback'))
.rejects.toThrow('bootstrap failed before timeout')
expect(expiredDuringRollback.ptyKills).toBe(1)
expect(expiredDuringRollback.handle.sdkKills).toBe(1)
const expiredBeforeSdkRollback = new FakeTerminalSandbox()
expiredBeforeSdkRollback.handle.waitError = new Error('wait failed after timeout')
@@ -505,15 +474,6 @@ describe('E2B terminal allocation', () => {
await expect(spawnE2BTerminal(runtime(expiredBeforeSdkRollback), spec(), '/runtime/expired-sdk-rollback'))
.rejects.toThrow('wait failed after timeout')
const expiredDuringSdkFallback = new FakeTerminalSandbox()
expiredDuringSdkFallback.sendError = new Error('bootstrap failed before SDK fallback')
expiredDuringSdkFallback.groups = []
expiredDuringSdkFallback.settleOnPtyKill = false
expiredDuringSdkFallback.handle.sdkKillError = new SandboxNotFoundError('sandbox expired')
expiredDuringSdkFallback.handle.settleOnSdkKill = false
await expect(spawnE2BTerminal(runtime(expiredDuringSdkFallback), spec(), '/runtime/expired-sdk-fallback'))
.rejects.toThrow('bootstrap failed before SDK fallback')
const missingDuringDisconnect = new FakeTerminalSandbox()
missingDuringDisconnect.sendError = new Error('bootstrap failed before disconnect')
missingDuringDisconnect.handle.disconnectError = new SandboxNotFoundError('sandbox expired')
@@ -537,10 +497,6 @@ describe('E2B terminal allocation', () => {
await expect(spawnE2BTerminal(runtime(createFailed), spec(), '/runtime/create'))
.rejects.toThrow('create failed')
const readFailed = new FakeTerminalSandbox()
readFailed.ready = new Error('ready transport failed')
await expect(spawnE2BTerminal(runtime(readFailed), spec(), '/runtime/read'))
.rejects.toThrow('ready transport failed')
})
it('bounds a missing bootstrap-output boundary by process exit or cancellation', async () => {
@@ -560,7 +516,6 @@ describe('E2B terminal allocation', () => {
'/runtime/cancel-output-boundary',
)
await vi.waitFor(() => { expect(cancelled.inputs).toHaveLength(1) })
await vi.waitFor(() => { expect(cancelled.readyReads).toBeGreaterThan(0) })
await new Promise(resolve => setTimeout(resolve, 0))
controller.abort(new Error('cancel output boundary'))
await expect(cancelling).rejects.toThrow('cancel output boundary')
@@ -661,23 +616,23 @@ describe('E2B terminal lifecycle', () => {
it('treats sandbox disappearance during PTY kill as quiescent', async () => {
const fake = new FakeTerminalSandbox()
fake.groups = []
fake.settleOnPtyKill = false
fake.ptyKillError = new SandboxNotFoundError('sandbox expired')
fake.handle.settleOnSdkKill = false
fake.handle.sdkKillError = new SandboxNotFoundError('sandbox expired')
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/expired-pty-kill')
await terminal.terminate()
expect(fake.ptyKills).toBe(1)
expect(fake.handle.sdkKills).toBe(1)
})
it('propagates a non-missing PTY kill failure', async () => {
const fake = new FakeTerminalSandbox()
fake.groups = []
fake.settleOnPtyKill = false
fake.ptyKillError = new Error('PTY kill transport failed')
fake.handle.settleOnSdkKill = false
fake.handle.sdkKillError = new Error('PTY kill transport failed')
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/failed-pty-kill')
await expect(terminal.terminate()).rejects.toThrow('PTY kill transport failed')
fake.ptyKillError = undefined
fake.handle.sdkKillError = undefined
fake.handle.succeed(0)
await terminal.done
await terminal.terminate()
@@ -712,11 +667,11 @@ describe('E2B terminal lifecycle', () => {
await terminal.terminate()
})
it('escalates surviving process groups', async () => {
it('sends KILL before checking an expired force-cleanup deadline', async () => {
const fake = new FakeTerminalSandbox()
fake.groups = [123, 456]
fake.clearOnTerm = false
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/escalate')
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 0 }), '/runtime/escalate')
const terminating = terminal.terminate()
await expect(terminal.done).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
await terminating
@@ -771,11 +726,11 @@ describe('E2B terminal lifecycle', () => {
it('keeps a late command rejection authoritative after PTY kill', async () => {
const fake = new FakeTerminalSandbox()
fake.groups = []
fake.settleOnPtyKill = false
fake.handle.settleOnSdkKill = false
const terminal = await spawnE2BTerminal(runtime(fake), spec({ graceMs: 1 }), '/runtime/reject-after-kill')
terminal.output.on('error', () => {})
const cleanup = terminal.terminate()
while (fake.ptyKills === 0) await new Promise(resolve => setTimeout(resolve, 0))
while (fake.handle.sdkKills === 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')
@@ -791,7 +746,7 @@ describe('E2B terminal lifecycle', () => {
const livePid = new FakeTerminalSandbox()
livePid.groups = []
livePid.settleOnPtyKill = false
livePid.handle.settleOnSdkKill = false
const live = await spawnE2BTerminal(runtime(livePid), spec({ graceMs: 1 }), '/runtime/live-pid')
await expect(live.terminate()).rejects.toThrow('surviving pid: 123')
livePid.handle.succeed(0)
@@ -879,13 +834,13 @@ describe('E2B subprocess terminal service', () => {
expect(fake.removed.some(path => path.includes('/terminals/'))).toBe(true)
})
it('aborts and rolls back terminal setup that cannot publish readiness during disposal', async () => {
it('aborts and rolls back terminal setup that cannot publish its output boundary during disposal', async () => {
const fake = new FakeTerminalSandbox()
fake.ready = new FileNotFoundError('not ready')
fake.emitOutputMarker = false
const { ctx, fiber } = await service(fake)
const spawning = ctx.subprocess.spawnTerminal(spec())
const rejected = expect(spawning).rejects.toThrow('service disposed during terminal setup')
await vi.waitFor(() => { expect(fake.readyReads).toBeGreaterThan(0) })
await vi.waitFor(() => { expect(fake.inputs).toHaveLength(1) })
await fiber.dispose()
await rejected