2026-07-28 10:05:30 +08:00
|
|
|
/**
|
2026-08-09 15:34:32 +08:00
|
|
|
* E2B Service provider for the subprocess capability seam. Each handle starts through the
|
2026-07-28 10:05:30 +08:00
|
|
|
* shared sandbox and retains command output/status paths in that remote world.
|
|
|
|
|
* @module @deepseek-ai/dsh-subprocess-e2b
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { randomUUID } from 'node:crypto'
|
|
|
|
|
import { posix } from 'node:path'
|
build(vendor): rescope the vendored Cordis packages into @deepseek-ai
Machine-produced by `pnpm run rescope-vendor --apply` plus the regeneration it
prints: `pnpm install` for the lockfile, `pnpm run gen-third-party-notices`,
`verify-translation-pairing --write` for the touched bilingual pairs,
`gen-doc-graphs`, and one typert snapshot whose ids embed character offsets.
`pnpm run rescope-vendor --check` verifies the result.
Renames nine vendored packages (cordis, cosmokit, schemastery and the six
@cordisjs plugins) and every reference that resolves them: manifest names and
dependency keys, module specifiers including declare-module merges, cordis.yml
plugin names, tsconfig paths, every Markdown fence, and `docs/` prose.
Directory names, upstream versions, and dependency ranges are unchanged, so
vendor/README.md still reads as an upstream snapshot; its manifest table gains
an upstream-name column so THIRD_PARTY_NOTICES keeps MIT attribution pointed
at each fork's origin.
The tutorial tier follows the rename end to end: its yaml fences named plugins
the Loader can no longer resolve, its `ts ignore-check` fences disagreed with
the compiled fences beside them, and its prose quoted both. The contracts that
told readers to keep upstream names — the root convention and the vendoring
cookbook's tree comment and manifest invariant — now say to rescope instead.
Two rules read `@deepseek-ai/` as "another workspace plugin": the client bundle
purity gate now names the vendored libraries a browser bundle inlines, and the
files where a bare `cordis` is an agent-preset id keep that product data.
2026-08-10 22:04:06 +08:00
|
|
|
import { Context } from '@deepseek-ai/cordis'
|
|
|
|
|
import z from '@deepseek-ai/schemastery'
|
2026-07-28 10:05:30 +08:00
|
|
|
import { SubprocessService } from '@deepseek-ai/dsh-subprocess'
|
fix(e2b): address the v7 review round
- restore the parent's AGENTS.md body around this branch's e2b row (the
replay had resurrected the pre-profile-CLI layout, deleting the api/,
bundle/, settings/, and credentials/ groups); the fs/lsp row
condensations stay for the word budget
- aggregate the composite rollback failure, not the original error, when
private state cleanup also fails — a surviving remote group is no
longer hidden by a later cleanup error (triple-failure regression)
- own the state directory before the makeDir RPC, matching the terminal
transaction, so a cancellation racing a committed creation still
enters cleanup
- drop the hidden pollMs parameter defaults; the schemastery default is
the one home, and tests pass the cadence explicitly
- restore spawn/spawnTerminal graceMs validation to the seam's
documented bound (the earlier removal cited subprocess-local as not
validating; it does), with rejection regressions
2026-08-08 22:37:38 +08:00
|
|
|
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
2026-07-29 02:51:44 +08:00
|
|
|
import type {
|
|
|
|
|
SubprocessHandle,
|
|
|
|
|
SubprocessSpawnSpec,
|
|
|
|
|
SubprocessTerminalHandle,
|
|
|
|
|
SubprocessTerminalSpawnSpec,
|
|
|
|
|
} from '@deepseek-ai/dsh-subprocess'
|
2026-07-29 15:30:32 +08:00
|
|
|
import { e2bControlEnvs, quoteE2BShellArg } from '@deepseek-ai/dsh-e2b'
|
2026-07-28 10:05:30 +08:00
|
|
|
import { E2BSubprocessHandle } from './process.ts'
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
import { asError, signalOpts } from './remote.ts'
|
2026-07-29 02:51:44 +08:00
|
|
|
import { spawnE2BTerminal } from './terminal.ts'
|
|
|
|
|
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
/** Configuration for the E2B subprocess adapter. */
|
|
|
|
|
export interface Config {
|
|
|
|
|
/** Remote status/liveness poll cadence in milliseconds; each tick is one control-plane request. */
|
|
|
|
|
pollMs?: number
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface SchemaResolvedConfig extends Config {
|
|
|
|
|
pollMs: number
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface TerminalSetup {
|
|
|
|
|
done: Promise<void>
|
|
|
|
|
controller: AbortController
|
2026-07-29 02:51:44 +08:00
|
|
|
}
|
2026-07-28 10:05:30 +08:00
|
|
|
|
fix(e2b): address the v7 review round
- restore the parent's AGENTS.md body around this branch's e2b row (the
replay had resurrected the pre-profile-CLI layout, deleting the api/,
bundle/, settings/, and credentials/ groups); the fs/lsp row
condensations stay for the word budget
- aggregate the composite rollback failure, not the original error, when
private state cleanup also fails — a surviving remote group is no
longer hidden by a later cleanup error (triple-failure regression)
- own the state directory before the makeDir RPC, matching the terminal
transaction, so a cancellation racing a committed creation still
enters cleanup
- drop the hidden pollMs parameter defaults; the schemastery default is
the one home, and tests pass the cadence explicitly
- restore spawn/spawnTerminal graceMs validation to the seam's
documented bound (the earlier removal cited subprocess-local as not
validating; it does), with rejection regressions
2026-08-08 22:37:38 +08:00
|
|
|
/**
|
|
|
|
|
* Enforce the seam's documented grace bound (positive, finite, one Node timer),
|
|
|
|
|
* matching subprocess-local's spawn-time check; an unbounded grace would make
|
|
|
|
|
* the remote force-escalation deadline unreachable.
|
|
|
|
|
* @param graceMs - The spec's cleanup grace in milliseconds.
|
|
|
|
|
*/
|
|
|
|
|
function requireRepresentableGrace(graceMs: number): void {
|
|
|
|
|
if (!Number.isFinite(graceMs) || graceMs <= 0 || graceMs > MAX_TIMER_DELAY_MS) {
|
|
|
|
|
throw new Error(`subprocess graceMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 10:05:30 +08:00
|
|
|
/** E2B command manager registered as `ctx.subprocess`. */
|
|
|
|
|
export class E2BSubprocessService extends SubprocessService {
|
|
|
|
|
static inject = ['e2b']
|
|
|
|
|
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
static Config: z<Config> = z.object({
|
|
|
|
|
pollMs: z.number().default(20),
|
|
|
|
|
})
|
|
|
|
|
|
2026-07-28 10:05:30 +08:00
|
|
|
private readonly live = new Set<E2BSubprocessHandle>()
|
2026-07-29 02:51:44 +08:00
|
|
|
private readonly terminals = new Set<SubprocessTerminalHandle>()
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
private readonly terminalSetups = new Set<TerminalSetup>()
|
|
|
|
|
private readonly pollMs: number
|
2026-07-29 07:42:25 +08:00
|
|
|
private disposing = false
|
2026-07-29 02:51:44 +08:00
|
|
|
|
2026-07-28 10:05:30 +08:00
|
|
|
/** Create the E2B subprocess service and bind its disposal policy. */
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
constructor(ctx: Context, config: Config) {
|
2026-07-28 10:05:30 +08:00
|
|
|
super(ctx)
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
// Schemastery fills pollMs before construction; the type does not encode that step.
|
|
|
|
|
const { pollMs } = config as SchemaResolvedConfig
|
|
|
|
|
if (!Number.isSafeInteger(pollMs) || pollMs <= 0) {
|
|
|
|
|
throw new Error('subprocess-e2b: pollMs must be a positive safe integer')
|
|
|
|
|
}
|
|
|
|
|
this.pollMs = pollMs
|
2026-07-28 10:05:30 +08:00
|
|
|
ctx.effect(() => async () => {
|
2026-07-29 07:42:25 +08:00
|
|
|
this.disposing = true
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
for (const setup of this.terminalSetups) {
|
|
|
|
|
setup.controller.abort(new Error('subprocess-e2b: service disposed during terminal setup'))
|
2026-07-29 09:19:46 +08:00
|
|
|
}
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
await Promise.all([...this.terminalSetups].map(setup => setup.done))
|
2026-07-28 10:05:30 +08:00
|
|
|
const handles = [...this.live]
|
2026-07-29 02:51:44 +08:00
|
|
|
const terminals = [...this.terminals]
|
|
|
|
|
const pending: Promise<unknown>[] = []
|
|
|
|
|
for (const handle of handles) {
|
|
|
|
|
handle.terminate()
|
2026-07-29 07:42:25 +08:00
|
|
|
pending.push(handle.waitForExit().then(async () => {
|
|
|
|
|
await handle.done.catch(() => undefined)
|
|
|
|
|
this.live.delete(handle)
|
|
|
|
|
}))
|
2026-07-29 02:51:44 +08:00
|
|
|
}
|
|
|
|
|
for (const terminal of terminals) {
|
2026-07-29 19:07:11 +08:00
|
|
|
pending.push(terminal.terminate().then(() => { this.terminals.delete(terminal) }))
|
2026-07-29 02:51:44 +08:00
|
|
|
}
|
2026-07-29 10:14:06 +08:00
|
|
|
const outcomes = await Promise.allSettled(pending)
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
const failures = outcomes.flatMap<unknown>(outcome => outcome.status === 'rejected'
|
|
|
|
|
? [outcome.reason as unknown]
|
|
|
|
|
: [])
|
|
|
|
|
if (failures.length === 1) throw asError(failures[0])
|
|
|
|
|
if (failures.length > 1) throw new AggregateError(failures, 'subprocess-e2b: teardown failed')
|
2026-07-28 10:05:30 +08:00
|
|
|
}, 'e2b subprocess teardown')
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 02:51:44 +08:00
|
|
|
/** @inheritdoc */
|
|
|
|
|
async resolveExecutable(
|
|
|
|
|
command: string,
|
|
|
|
|
env?: Readonly<Record<string, string>>,
|
|
|
|
|
signal?: AbortSignal,
|
|
|
|
|
): Promise<string> {
|
|
|
|
|
if (command.length === 0) throw new Error('subprocess-e2b: executable name must be non-empty')
|
|
|
|
|
signal?.throwIfAborted()
|
|
|
|
|
const sandbox = await this.ctx.e2b.getSandbox()
|
|
|
|
|
if (posix.isAbsolute(command)) {
|
|
|
|
|
await sandbox.commands.run(
|
|
|
|
|
`test -f ${quoteE2BShellArg(command)} -a -x ${quoteE2BShellArg(command)}`,
|
2026-07-29 15:30:32 +08:00
|
|
|
{ envs: e2bControlEnvs(), ...signalOpts(signal) },
|
2026-07-29 02:51:44 +08:00
|
|
|
)
|
|
|
|
|
signal?.throwIfAborted()
|
|
|
|
|
return command
|
|
|
|
|
}
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
if (command.includes('/')) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`subprocess-e2b: command ${JSON.stringify(command)} is a relative path; use an absolute path or a bare PATH name`,
|
|
|
|
|
)
|
|
|
|
|
}
|
2026-07-29 02:51:44 +08:00
|
|
|
const path = env?.PATH
|
|
|
|
|
const prefix = path === undefined ? '' : `PATH=${quoteE2BShellArg(path)} `
|
|
|
|
|
const result = await sandbox.commands.run(
|
|
|
|
|
`${prefix}command -v -- ${quoteE2BShellArg(command)}`,
|
2026-07-30 14:50:47 +08:00
|
|
|
{ cwd: this.ctx.e2b.cwd, envs: e2bControlEnvs(), ...signalOpts(signal) },
|
2026-07-29 02:51:44 +08:00
|
|
|
)
|
|
|
|
|
signal?.throwIfAborted()
|
|
|
|
|
const executable = result.stdout.trim()
|
2026-07-29 03:55:03 +08:00
|
|
|
if (executable.includes('\n') || (!posix.isAbsolute(executable) && !executable.includes('/'))) {
|
2026-07-29 02:51:44 +08:00
|
|
|
throw new Error(`subprocess-e2b: executable ${JSON.stringify(command)} did not resolve to one absolute path`)
|
|
|
|
|
}
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
// A relative result comes from a relative PATH entry; the lookup ran with the shared cwd.
|
2026-07-30 14:50:47 +08:00
|
|
|
return posix.resolve(this.ctx.e2b.cwd, executable)
|
2026-07-29 02:51:44 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 10:05:30 +08:00
|
|
|
/** @inheritdoc */
|
|
|
|
|
spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
|
2026-07-30 04:25:47 +08:00
|
|
|
if (this.disposing) throw new Error('subprocess-e2b: service is disposing')
|
2026-07-28 10:05:30 +08:00
|
|
|
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]')
|
|
|
|
|
}
|
fix(e2b): address the v7 review round
- restore the parent's AGENTS.md body around this branch's e2b row (the
replay had resurrected the pre-profile-CLI layout, deleting the api/,
bundle/, settings/, and credentials/ groups); the fs/lsp row
condensations stay for the word budget
- aggregate the composite rollback failure, not the original error, when
private state cleanup also fails — a surviving remote group is no
longer hidden by a later cleanup error (triple-failure regression)
- own the state directory before the makeDir RPC, matching the terminal
transaction, so a cancellation racing a committed creation still
enters cleanup
- drop the hidden pollMs parameter defaults; the schemastery default is
the one home, and tests pass the cadence explicitly
- restore spawn/spawnTerminal graceMs validation to the seam's
documented bound (the earlier removal cited subprocess-local as not
validating; it does), with rejection regressions
2026-08-08 22:37:38 +08:00
|
|
|
requireRepresentableGrace(spec.graceMs)
|
2026-07-28 10:05:30 +08:00
|
|
|
if (spec.signal?.aborted === true) {
|
2026-07-30 04:25:47 +08:00
|
|
|
throw new Error(`aborted before spawn: ${String(spec.signal.reason)}`)
|
2026-07-28 10:05:30 +08:00
|
|
|
}
|
|
|
|
|
const stateDir = posix.join(this.ctx.e2b.runtimeRoot, 'processes', randomUUID())
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
const handle = new E2BSubprocessHandle(this.ctx.e2b, spec, stateDir, this.pollMs)
|
2026-07-28 10:05:30 +08:00
|
|
|
this.live.add(handle)
|
|
|
|
|
const release = async (): Promise<void> => {
|
|
|
|
|
await handle.waitForExit()
|
|
|
|
|
this.live.delete(handle)
|
|
|
|
|
}
|
2026-07-29 19:07:11 +08:00
|
|
|
void handle.done.then(release, release).catch((_automaticReleaseFailure: unknown) => {
|
|
|
|
|
// Retain the handle so service disposal can retry its cleanup transaction.
|
|
|
|
|
})
|
2026-07-28 10:05:30 +08:00
|
|
|
return handle
|
|
|
|
|
}
|
2026-07-29 02:51:44 +08:00
|
|
|
|
|
|
|
|
/** @inheritdoc */
|
|
|
|
|
async spawnTerminal(spec: SubprocessTerminalSpawnSpec): Promise<SubprocessTerminalHandle> {
|
2026-07-30 04:25:47 +08:00
|
|
|
if (this.disposing) throw new Error('subprocess-e2b: service is disposing')
|
2026-07-29 02:51:44 +08:00
|
|
|
const program = spec.argv[0]
|
|
|
|
|
if (program === undefined || program.length === 0) {
|
|
|
|
|
throw new Error('subprocess-e2b: terminal argv must contain a program')
|
|
|
|
|
}
|
fix(e2b): address the v7 review round
- restore the parent's AGENTS.md body around this branch's e2b row (the
replay had resurrected the pre-profile-CLI layout, deleting the api/,
bundle/, settings/, and credentials/ groups); the fs/lsp row
condensations stay for the word budget
- aggregate the composite rollback failure, not the original error, when
private state cleanup also fails — a surviving remote group is no
longer hidden by a later cleanup error (triple-failure regression)
- own the state directory before the makeDir RPC, matching the terminal
transaction, so a cancellation racing a committed creation still
enters cleanup
- drop the hidden pollMs parameter defaults; the schemastery default is
the one home, and tests pass the cadence explicitly
- restore spawn/spawnTerminal graceMs validation to the seam's
documented bound (the earlier removal cited subprocess-local as not
validating; it does), with rejection regressions
2026-08-08 22:37:38 +08:00
|
|
|
requireRepresentableGrace(spec.graceMs)
|
2026-07-29 02:51:44 +08:00
|
|
|
spec.signal?.throwIfAborted()
|
2026-07-30 14:50:47 +08:00
|
|
|
const stateDir = posix.join(this.ctx.e2b.runtimeRoot, 'terminals', randomUUID())
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
const done = Promise.withResolvers<void>()
|
|
|
|
|
const setup: TerminalSetup = { done: done.promise, controller: new AbortController() }
|
2026-07-29 09:19:46 +08:00
|
|
|
const setupSignal = spec.signal === undefined
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
? setup.controller.signal
|
|
|
|
|
: AbortSignal.any([spec.signal, setup.controller.signal])
|
|
|
|
|
this.terminalSetups.add(setup)
|
2026-07-29 07:42:25 +08:00
|
|
|
try {
|
2026-07-29 09:19:46 +08:00
|
|
|
const terminal = await spawnE2BTerminal(
|
|
|
|
|
this.ctx.e2b,
|
|
|
|
|
{ ...spec, signal: setupSignal },
|
|
|
|
|
stateDir,
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
this.pollMs,
|
2026-07-29 09:19:46 +08:00
|
|
|
)
|
2026-07-29 07:42:25 +08:00
|
|
|
this.terminals.add(terminal)
|
2026-07-30 04:25:47 +08:00
|
|
|
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Remote allocation yields to disposal.
|
|
|
|
|
if (this.disposing) {
|
2026-07-29 19:07:11 +08:00
|
|
|
await terminal.terminate()
|
2026-07-29 07:42:25 +08:00
|
|
|
this.terminals.delete(terminal)
|
|
|
|
|
throw new Error('subprocess-e2b: service disposed during terminal setup')
|
|
|
|
|
}
|
|
|
|
|
const release = async (): Promise<void> => {
|
2026-07-29 19:07:11 +08:00
|
|
|
await terminal.terminate()
|
2026-07-29 07:42:25 +08:00
|
|
|
this.terminals.delete(terminal)
|
|
|
|
|
}
|
2026-07-29 19:07:11 +08:00
|
|
|
void terminal.done.then(release, release).catch((_automaticReleaseFailure: unknown) => {
|
|
|
|
|
// Retain the terminal so service disposal can retry its cleanup transaction.
|
|
|
|
|
})
|
2026-07-29 07:42:25 +08:00
|
|
|
return terminal
|
|
|
|
|
} finally {
|
fix(e2b): address review round on cadence config, disposal, and SDK edge cases
- subprocess-e2b: the 20 ms remote poll cadence becomes a validated pollMs
Config field (each tick is one control-plane request); the README documents
the latency-versus-request-count trade.
- subprocess-e2b: extract src/remote.ts owning asError, signalOpts,
commandOpts, delay, waitTick, and one tolerant signalRemoteGroups shared by
the pgid-keyed process ladder and sid-keyed terminal ladder, so the two
teardown paths keep identical error tolerance.
- subprocess-e2b: service disposal aggregates sibling cleanup failures into
one AggregateError instead of discarding all but the first.
- subprocess-e2b: waitForProcessGroupId refuses published group ids <= 1, so
a same-UID rewrite of the pid file cannot aim termination at kill -- -1;
README documents the same-UID control-state limitation.
- subprocess-e2b: drain-grace expiry now releases an inherited-output E2B
callback blocked on host backpressure before disconnecting, so the SDK
settlement cannot stay pinned behind an unread host stream.
- subprocess-e2b: spawn/spawnTerminal stop validating typed spec fields
(trust-TypeScript rule; pty-local validates its config before specs exist);
resolveExecutable rejects separator-containing relative paths per the seam
contract; terminal setups tracked as a Set of records.
- subprocess-e2b: PTY output push-without-backpressure is a documented
contract (flowing consumer folds bytes; paused consumer buffers).
- fs-e2b: streamText normalizes the pinned SDK's empty-file '' return into an
empty stream instead of throwing on getReader().
- e2b overlays: comment the one-world cwd invariant across e2b.cwd,
workspaceRoot, and bash-local's implicit default workdir.
2026-08-02 15:38:00 +08:00
|
|
|
this.terminalSetups.delete(setup)
|
|
|
|
|
done.resolve()
|
2026-07-29 02:51:44 +08:00
|
|
|
}
|
2026-07-29 07:42:25 +08:00
|
|
|
}
|
2026-07-28 10:05:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default E2BSubprocessService
|