feat(subprocess): add SubprocessError and make Win32Error a HarnessError

The subprocess Service Definition exports SubprocessError with a closed
SUBPROCESS_* code list, rebases SubprocessExecutableNotFoundError on it
with the same name, and adds subprocessSpawnFailure() so consumers that
report a spawn rejection classify ENOENT and other platform errors with
the original as cause. subprocess-local codes empty argv, Windows Job
runner failures, runner IPC failures, and an unloadable node-pty, and
names its pre-aborted spawn error AbortError so the tool registry
classifies it as cancellation.

Win32Error now extends HarnessError with code WIN32_ERROR, keeping its
name, api, and win32Code fields.

Refs #7869
This commit is contained in:
sjw1231 committed 2026-11-06 16:29:31 +08:00
1 parent 7e00f186e2
commit 4ef46e21b1
25 files changed
+292 -54

No files matched your search

@@ -36,8 +36,8 @@
en: cd0b8a5dc61335a5
zh: ac5077a9ac277141
/deepseek-ai-dsh-subprocess-local/use-this-package/what-can-go-wrong:
en: 1e1ce532b004c92b
zh: ca7274b7a9207a5d
en: 8320b322423ed5a4
zh: a32e769d2a351694
/deepseek-ai-dsh-subprocess-local/understand-the-implementation:
en: 531a48766c666ea0
zh: b40df533a2fd7244
@@ -69,7 +69,7 @@ Linux ordinary and terminal cancellation preserves the observed termination sign
### What can go wrong
An executable that cannot be resolved fails loud with a stable error. `done` rejects when spawn or provider failure prevents a direct outcome, and that rejection does not prove whether target execution began. `waitForExit()` rejects if the selected owner can no longer prove its range empty, and cleanup still attempts termination. A read past the retained tail is `lossy` and points at the spill file when one exists. A fallback process group or observed terminal session can miss a descendant that escapes before observation — see the limitations below.
An executable that cannot be resolved fails loud with a stable error. `done` rejects when spawn or provider failure prevents a direct outcome, and that rejection does not prove whether target execution began: a platform spawn error stays the original Node error, while a Windows Job runner that fails after it started or breaks its IPC channel rejects with `SubprocessError` `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`. A terminal request on a host where node-pty cannot load throws `SUBPROCESS_PTY_UNAVAILABLE`. `waitForExit()` rejects if the selected owner can no longer prove its range empty, and cleanup still attempts termination. A read past the retained tail is `lossy` and points at the spill file when one exists. A fallback process group or observed terminal session can miss a descendant that escapes before observation — see the limitations below.
-----
@@ -69,7 +69,7 @@ Linux 普通进程和终端进程即使在 bootstrap 消费启动请求前被取
### 可能出错的地方
无法解析的可执行文件会明确报出稳定错误。当 spawn 或提供方故障使 direct outcome 无法产生时,`done` 会 reject;该 rejection 不能证明 target 是否已经开始执行。若所选 owner 无法再证明其范围为空,`waitForExit()` 会 reject,清理仍会尝试终止。越过保留尾部的读取是 `lossy` 的,并在 spill 文件存在时指向它。fallback 进程组或已观察终端 session 可能遗漏在观察前逃逸的后代——见下文限制。
无法解析的可执行文件会明确报出稳定错误。当 spawn 或提供方故障使 direct outcome 无法产生时,`done` 会 reject;该 rejection 不能证明 target 是否已经开始执行:平台 spawn 错误保持为原始 Node 错误,而 Windows Job runner 启动后失败或其 IPC 通道损坏时以 `SubprocessError` 的 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED` reject。在无法加载 node-pty 的主机上请求终端会抛出 `SUBPROCESS_PTY_UNAVAILABLE`。若所选 owner 无法再证明其范围为空,`waitForExit()` 会 reject,清理仍会尝试终止。越过保留尾部的读取是 `lossy` 的,并在 spill 文件存在时指向它。fallback 进程组或已观察终端 session 可能遗漏在观察前逃逸的后代——见下文限制。
-----
@@ -17,7 +17,7 @@ import { Context } from '@deepseek-ai/cordis'
import type * as NodePty from 'node-pty'
import type { IPtyForkOptions, IWindowsPtyForkOptions } from 'node-pty'
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
import { SubprocessRuntime, SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess'
import { SubprocessRuntime, SubprocessError, SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess'
import type {
SubprocessHandle,
SubprocessSpawnSpec,
@@ -54,6 +54,19 @@ import { prepareShellActivity } from './shell-activity.ts'
const requireNodePty = createLazyRequire<typeof NodePty>('node-pty', import.meta.url)
/** Load node-pty, reporting a missing or unloadable native module as `SUBPROCESS_PTY_UNAVAILABLE`. */
function loadNodePty(): typeof NodePty {
try {
return requireNodePty()
} catch (error) {
throw new SubprocessError(
`subprocess-local: terminals are unavailable because node-pty cannot be loaded: ${String(error)}`,
'SUBPROCESS_PTY_UNAVAILABLE',
{ cause: error },
)
}
}
/**
* Local subprocess service: platform-selected managed ranges, Node-shaped stdio
* dispositions (raw pipes, inherit, bounded tail-keep collection with spill
@@ -290,7 +303,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
async spawnTerminal(spec: SubprocessTerminalSpawnSpec): Promise<SubprocessTerminalHandle> {
const file = spec.argv[0]
if (file === undefined || file.length === 0) {
throw new Error('subprocess-local: terminal argv must contain a program')
throw new SubprocessError('subprocess-local: terminal argv must contain a program', 'SUBPROCESS_INVALID_ARGV')
}
spec.signal?.throwIfAborted()
const inspector = this.terminalInspector ?? createProcessInspector()
@@ -319,7 +332,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
? undefined
: prepareLinuxTerminalScope(launch, { ...activity?.env ?? env, PWD: spec.cwd, TERM: spec.terminalType }, linuxScope.literalArgv)
if (scope !== undefined) { options.cwd = scope.cwd; options.env = scope.env }
terminal = requireNodePty().spawn(
terminal = loadNodePty().spawn(
scope?.command ?? file,
scope?.args ?? [...launch.argv.slice(1)],
options,
@@ -11,7 +11,7 @@
import { type ChildProcess, type SpawnOptions, spawn, spawnSync } from 'node:child_process'
import type { Readable } from 'node:stream'
import { setTimeout as sleepMs } from 'node:timers/promises'
import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
import { scrubbedParentEnv, SubprocessError } from '@deepseek-ai/dsh-subprocess'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import type {
SubprocessCollect,
@@ -172,11 +172,14 @@ export function validateSubprocessSpec(spec: SubprocessSpawnSpec): void {
} catch {
// Arbitrary caller-owned reasons cannot escape the stable Error boundary.
}
throw new Error(`aborted before spawn: ${reason}`)
// Named as a cancellation so the tool registry classifies it as the caller's abort.
const error = new Error(`aborted before spawn: ${reason}`)
error.name = 'AbortError'
throw error
}
const [program] = spec.argv
if (program === undefined || program.length === 0) {
throw new Error('invalid argv: expected a non-empty program name at argv[0]')
throw new SubprocessError('invalid argv: expected a non-empty program name at argv[0]', 'SUBPROCESS_INVALID_ARGV')
}
}
@@ -5,6 +5,7 @@ import { spawn } from 'node:child_process'
import { closeSync, openSync } from 'node:fs'
import { devNull } from 'node:os'
import type { Readable, Writable } from 'node:stream'
import { SubprocessError } from '@deepseek-ai/dsh-subprocess'
import type { SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
import {
loadWin32ProcessBindings,
@@ -26,6 +27,16 @@ import {
} from './runner-launch.ts'
import type { RunnerInvocation } from './runner-launch.ts'
/** Classify a failure on the private runner channel, keeping an already coded failure. */
function runnerIpcFailure(error: unknown): SubprocessError {
if (error instanceof SubprocessError) return error
return new SubprocessError(
`subprocess-local: Windows runner IPC failed: ${String(error)}`,
'SUBPROCESS_RUNNER_IPC_FAILED',
{ cause: error },
)
}
/** Test seams for runner launch and dynamic capability checks. */
export interface WindowsJobInternals {
spawn?: typeof spawn
@@ -171,8 +182,9 @@ export function launchWindowsJob(
const status = signal !== null
? `signal ${signal}`
: exitCode === null ? 'without an exit status' : `exit code ${String(exitCode)}`
failInfrastructure(new Error(
failInfrastructure(new SubprocessError(
`subprocess-local: Windows Job runner exited with ${status} before proving its managed range empty`,
'SUBPROCESS_RUNNER_FAILED',
))
}
@@ -184,7 +196,7 @@ export function launchWindowsJob(
)
child.on('message', (value: unknown) => {
if (directResultType !== undefined) {
const error = new Error('subprocess-local: Windows runner emitted more than one direct result')
const error = new SubprocessError('subprocess-local: Windows runner emitted more than one direct result', 'SUBPROCESS_RUNNER_IPC_FAILED')
failInfrastructure(error)
owner.terminateForHostExit()
return
@@ -193,7 +205,11 @@ export function launchWindowsJob(
try {
result = parseWindowsRunnerResult(value)
} catch (error) {
failInfrastructure(error)
failInfrastructure(new SubprocessError(
`subprocess-local: Windows runner emitted a malformed result: ${String(error)}`,
'SUBPROCESS_RUNNER_IPC_FAILED',
{ cause: error },
))
owner.terminateForHostExit()
return
}
@@ -208,14 +224,16 @@ export function launchWindowsJob(
child.once('spawn', () => {
runnerSpawned = true
try {
if (child.send === undefined) throw new Error('subprocess-local: Windows runner has no IPC channel')
if (child.send === undefined) {
throw new SubprocessError('subprocess-local: Windows runner has no IPC channel', 'SUBPROCESS_RUNNER_IPC_FAILED')
}
child.send({ type: 'start', cwd: spec.cwd, env: targetEnv, ...spec.stdio.control === undefined ? {} : { control: spec.stdio.control } }, (error) => {
if (error === null) return
failInfrastructure(error)
failInfrastructure(runnerIpcFailure(error))
owner.terminateForHostExit()
})
} catch (error) {
failInfrastructure(error)
failInfrastructure(runnerIpcFailure(error))
owner.terminateForHostExit()
}
})
@@ -225,7 +243,11 @@ export function launchWindowsJob(
rangeExit.resolve()
return
}
failInfrastructure(error)
failInfrastructure(new SubprocessError(
`subprocess-local: Windows Job runner failed after it started: ${String(error)}`,
'SUBPROCESS_RUNNER_FAILED',
{ cause: error },
))
})
child.once('exit', (exitCode, signal) => {
runnerExit = { exitCode, signal }
@@ -490,6 +490,36 @@ describe('LocalSubprocessRuntime', () => {
}
})
it('reports an unloadable node-pty as SUBPROCESS_PTY_UNAVAILABLE', async () => {
const loadFailure = new Error('Cannot find module node-pty')
vi.resetModules()
mockWin32ForIsolatedRuntime()
vi.doMock('@deepseek-ai/dsh-lazy-require', () => ({
createLazyRequire: () => () => { throw loadFailure },
}))
vi.doMock('../src/linux-scope.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/linux-scope.ts')>(),
probeLinuxNative: () => undefined,
}))
try {
const { default: IsolatedLocalSubprocessRuntime } = await import('../src/index.ts')
const ctx = new Context()
const fiber = await ctx.plugin(IsolatedLocalSubprocessRuntime)
await expect(ctx.subprocess.spawnTerminal({
argv: ['shell'], cwd: process.cwd(), rows: 24, cols: 80, terminalType: 'dumb', graceMs: 1,
})).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_PTY_UNAVAILABLE', cause: loadFailure })
await expect(ctx.subprocess.spawnTerminal({
argv: [''], cwd: process.cwd(), rows: 24, cols: 80, terminalType: 'dumb', graceMs: 1,
})).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_INVALID_ARGV' })
await fiber.dispose()
} finally {
unmockLazyRequireForIsolatedRuntime()
vi.doUnmock('../src/linux-scope.ts')
unmockWin32ForIsolatedRuntime()
vi.resetModules()
}
})
it('allocates Windows terminals through the console host node-pty ships', async () => {
const exitListeners: ((event: { exitCode: number; signal?: number }) => void)[] = []
const terminal = {
@@ -352,7 +352,7 @@ describe('spawnSubprocess', () => {
expect(result.signal).toBe(process.platform === 'win32' ? null : 'SIGTERM')
})
it('throws a stable Error when already aborted before spawn', () => {
it('throws a stable AbortError when already aborted before spawn', () => {
for (const [reason, message] of [
['too late', 'aborted before spawn: too late'],
[null, 'aborted before spawn: aborted'],
@@ -360,7 +360,7 @@ describe('spawnSubprocess', () => {
const controller = new AbortController()
controller.abort(reason)
expect(() => { validateSubprocessSpec(spec('echo hi', { signal: controller.signal })) })
.toThrow(new Error(message))
.toThrow(expect.objectContaining({ name: 'AbortError', message }))
}
const controller = new AbortController()
@@ -370,7 +370,7 @@ describe('spawnSubprocess', () => {
},
})
expect(() => { validateSubprocessSpec(spec('echo hi', { signal: controller.signal })) })
.toThrow(new Error('aborted before spawn: aborted'))
.toThrow(expect.objectContaining({ name: 'AbortError', message: 'aborted before spawn: aborted' }))
})
it('rejects with a spawn error for a nonexistent cwd', async () => {
@@ -1446,7 +1446,8 @@ describe('coverage seams 2', () => {
describe('argv validation', () => {
it('rejects an empty argv before spawning', () => {
expect(() => { validateSubprocessSpec({ ...spec('true'), argv: [] }) }).toThrow(/non-empty program name/)
expect(() => { validateSubprocessSpec({ ...spec('true'), argv: [] }) })
.toThrow(expect.objectContaining({ name: 'SubprocessError', code: 'SUBPROCESS_INVALID_ARGV' }))
})
it('rejects an empty program name before spawning', () => {
@@ -1468,7 +1469,7 @@ describe('abort edge cases', () => {
removeEventListener() {},
} as unknown as AbortSignal
expect(() => { validateSubprocessSpec(spec('echo hi', { signal: bare })) })
.toThrow(new Error('aborted before spawn: aborted'))
.toThrow(expect.objectContaining({ name: 'AbortError', message: 'aborted before spawn: aborted' }))
})
it.skipIf(process.platform === 'win32')('reports the terminating signal of an externally self-killed command', async () => {
@@ -350,6 +350,7 @@ describe('Windows parent runner contract', () => {
statusless.child.connected = false
statusless.child.exit( null, null)
await expect(statusless.result.direct).rejects.toThrow('without an exit status')
await expect(statusless.result.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED' })
})
it('fails closed on malformed/duplicate result, runner spawn error, and start-send error', async () => {
@@ -357,6 +358,7 @@ describe('Windows parent runner contract', () => {
malformed.child.emit('message', { type: 'target-exit', exitCode: -1 })
expect(malformed.child.killed).toEqual(['SIGKILL'])
await expect(malformed.result.direct).rejects.toThrow('invalid target-exit')
await expect(malformed.result.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' })
await expect(malformed.result.owner.waitForExit()).rejects.toThrow('invalid target-exit')
const duplicate = launch()
@@ -364,6 +366,7 @@ describe('Windows parent runner contract', () => {
duplicate.child.emit('message', { type: 'target-exit', exitCode: 0 })
await expect(duplicate.result.direct).resolves.toEqual({ exitCode: 0, signal: null })
await expect(duplicate.result.owner.waitForExit()).rejects.toThrow('more than one direct result')
await expect(duplicate.result.owner.waitForExit()).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' })
const errored = launch(new FakeChild(), spec, false)
const spawnError = new Error('runner executable missing')
@@ -375,8 +378,9 @@ describe('Windows parent runner contract', () => {
const postSpawnError = launch()
const infrastructureError = new Error('runner failed after spawn')
postSpawnError.child.emit('error', infrastructureError)
await expect(postSpawnError.result.direct).rejects.toBe(infrastructureError)
await expect(postSpawnError.result.owner.waitForExit()).rejects.toBe(infrastructureError)
const runnerFailure = { name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED', cause: infrastructureError }
await expect(postSpawnError.result.direct).rejects.toMatchObject(runnerFailure)
await expect(postSpawnError.result.owner.waitForExit()).rejects.toMatchObject(runnerFailure)
const sendFailedChild = new FakeChild()
sendFailedChild.sendError = new Error('IPC send failed')
@@ -389,14 +393,16 @@ describe('Windows parent runner contract', () => {
Object.defineProperty(noIpc, 'send', { value: undefined })
const noIpcResult = launch(noIpc).result
await expect(noIpcResult.direct).rejects.toThrow('has no IPC channel')
await expect(noIpcResult.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' })
await expect(noIpcResult.owner.waitForExit()).rejects.toThrow('has no IPC channel')
const nonError = new FakeChild()
nonError.throwOnSendCall = 1
nonError.sendThrown = 'start send failed'
const nonErrorResult = launch(nonError).result
await expect(nonErrorResult.direct).rejects.toBe('start send failed')
await expect(nonErrorResult.owner.waitForExit()).rejects.toBe('start send failed')
const ipcFailure = { name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED', cause: 'start send failed' }
await expect(nonErrorResult.direct).rejects.toMatchObject(ipcFailure)
await expect(nonErrorResult.owner.waitForExit()).rejects.toMatchObject(ipcFailure)
})
it('fails infrastructure and kills the runner when termination delivery fails', async () => {
@@ -39,8 +39,8 @@
en: 4d4cbb311575d071
zh: 7be2d265adb661bc
/deepseek-ai-dsh-subprocess/use-this-package/what-can-go-wrong:
en: 51f2f43087a1ed18
zh: 6d2ebb099b707df3
en: 718494d6530da700
zh: a41b7d48a9d12178
/deepseek-ai-dsh-subprocess/understand-the-implementation:
en: 25cd344c959cfd9e
zh: 045880776ab82d1e
@@ -48,8 +48,8 @@
en: 07201ec2256c25f6
zh: 046109cfa92194f3
/deepseek-ai-dsh-subprocess/understand-the-implementation/source-map:
en: 85e3d2109f49356d
zh: 071ccfef37e8e33f
en: e56d6825d1b990a5
zh: c70cabda3bfcd2ab
/deepseek-ai-dsh-subprocess/understand-the-implementation/data-model-and-flow:
en: 9998dc0a990fbcf1
zh: ba179617f60cb9bc
+2 -1
View File
@@ -81,7 +81,7 @@ Children never inherit the harness's ambient secrets: credential-shaped names an
### What can go wrong
An executable that cannot be resolved fails loudly with a stable error. A spawn that never starts rejects `done`; there is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced.
Coded failures are `SubprocessError` instances whose `code` is one of `SUBPROCESS_ERROR_CODES`: an empty argv is `SUBPROCESS_INVALID_ARGV`, an executable lookup miss is `SubprocessExecutableNotFoundError` (`SUBPROCESS_EXECUTABLE_NOT_FOUND`), a provider's private runner that fails or breaks its channel is `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`, and an unloadable terminal implementation is `SUBPROCESS_PTY_UNAVAILABLE`. A spawn requested on an already aborted signal throws an error named `AbortError`. A spawn that never starts rejects `done` with the platform's original error, so consumers can inspect its errno fields; a consumer that reports the rejection as its own failure converts it with `subprocessSpawnFailure()`, which yields `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` otherwise. There is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced.
-----
@@ -103,6 +103,7 @@ The seam is built on one separation: the service owns process coordinates and li
|---|---|
| [`src/index.ts`](src/index.ts) | Plugin entry: abstract `SubprocessRuntime`, `ctx.subprocess` registration, the shared `scrubbedParentEnv` scrub |
| [`src/types.ts`](src/types.ts) | Vocabulary: spawn spec, stdio modes, handles, readers, outcomes, `DSH_*` namespace |
| [`src/error.ts`](src/error.ts) | `SubprocessError`, its closed code list, and spawn-rejection classification |
### Data model and flow
+2 -1
View File
@@ -81,7 +81,7 @@ const output = handle.collected.stdout?.readFrom(0)
### 可能出错的地方
无法解析可执行文件时,服务会明确报出稳定的错误。从未启动成功的 spawn 会让 `done` reject;从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。
带 code 的失败都是 `SubprocessError`,其 `code` 属于 `SUBPROCESS_ERROR_CODES`:argv 为空是 `SUBPROCESS_INVALID_ARGV`,可执行文件查找未命中是 `SubprocessExecutableNotFoundError`(`SUBPROCESS_EXECUTABLE_NOT_FOUND`),提供方私有 runner 失败或通道损坏是 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED`,终端实现无法加载是 `SUBPROCESS_PTY_UNAVAILABLE`。在已 abort 的 signal 上请求 spawn 会抛出名为 `AbortError` 的错误。从未启动成功的 spawn 会让 `done` 以平台原始错误 reject,便于消费者检查 errno 字段;把该 reject 报告为自身失败的消费者用 `subprocessSpawnFailure()` 转换,`ENOENT` 得到 `SUBPROCESS_SPAWN_NOT_FOUND`,其余得到 `SUBPROCESS_SPAWN_FAILED`。从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。
-----
@@ -103,6 +103,7 @@ const output = handle.collected.stdout?.readFrom(0)
|---|---|
| [`src/index.ts`](src/index.ts) | 插件入口:抽象 `SubprocessRuntime`、`ctx.subprocess` 注册、共享的 `scrubbedParentEnv` 清除 |
| [`src/types.ts`](src/types.ts) | 词汇:spawn spec、stdio 模式、句柄、读取器、结果、`DSH_*` 命名空间 |
| [`src/error.ts`](src/error.ts) | `SubprocessError`、其封闭 code 列表与 spawn reject 分类 |
### 数据模型与流程
+4 -2
View File
@@ -36,11 +36,13 @@
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-http-proxy": "workspace:*"
"@deepseek-ai/dsh-http-proxy": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-http-proxy": "workspace:*",
"@deepseek-ai/dsh-launch-environment": "workspace:*"
"@deepseek-ai/dsh-launch-environment": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*"
}
}
@@ -0,0 +1,87 @@
/** Machine-routable subprocess failures shared by every `ctx.subprocess` provider and its consumers. @module */
import { HarnessError } from '@deepseek-ai/dsh-llm'
/**
* Every {@link SubprocessError} code:
* - `SUBPROCESS_INVALID_ARGV` — the request names no program; the caller fixes its argv.
* - `SUBPROCESS_EXECUTABLE_NOT_FOUND` — executable lookup found no executable file.
* - `SUBPROCESS_SPAWN_NOT_FOUND` — the platform reported `ENOENT` for the program or the working directory.
* - `SUBPROCESS_SPAWN_FAILED` — the platform refused the spawn for another reason; `cause` holds the original error.
* - `SUBPROCESS_RUNNER_FAILED` — the provider's private runner exited or reported a result before proving the process range empty.
* - `SUBPROCESS_RUNNER_IPC_FAILED` — the provider's private runner channel was missing or carried a malformed message.
* - `SUBPROCESS_PTY_UNAVAILABLE` — the host cannot load its terminal implementation.
*/
export const SUBPROCESS_ERROR_CODES = [
'SUBPROCESS_INVALID_ARGV',
'SUBPROCESS_EXECUTABLE_NOT_FOUND',
'SUBPROCESS_SPAWN_NOT_FOUND',
'SUBPROCESS_SPAWN_FAILED',
'SUBPROCESS_RUNNER_FAILED',
'SUBPROCESS_RUNNER_IPC_FAILED',
'SUBPROCESS_PTY_UNAVAILABLE',
] as const
/** One code from {@link SUBPROCESS_ERROR_CODES}. */
export type SubprocessErrorCode = typeof SUBPROCESS_ERROR_CODES[number]
/** Subprocess failure carrying a stable {@link SubprocessErrorCode}. */
export class SubprocessError extends HarnessError {
override readonly code: SubprocessErrorCode
/**
* @param message - names the process operation and the safe next step.
* @param code - the failure class consumers route on.
* @param options - standard `cause` chaining; foreign errno and Win32 codes stay there and in `message`.
*/
constructor(message: string, code: SubprocessErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'SubprocessError'
this.code = code
}
}
/** Executable lookup completed without finding an executable file; `code` is `SUBPROCESS_EXECUTABLE_NOT_FOUND`. */
export class SubprocessExecutableNotFoundError extends SubprocessError {
/**
* @param message - provider-specific lookup diagnostic.
* @param options - original provider failure, when available.
*/
constructor(message: string, options?: ErrorOptions) {
super(message, 'SUBPROCESS_EXECUTABLE_NOT_FOUND', options)
this.name = 'SubprocessExecutableNotFoundError'
}
}
/**
* Classify a spawn rejection for a consumer that reports it as its own
* failure. Providers reject with the platform's original error so that
* consumers can inspect errno fields; the consumer that turns the rejection
* into a tool or service failure converts it here and keeps the original as
* `cause`.
* @param error - the provider's rejection value.
* @param program - the program the consumer asked to spawn, named in the message.
* @returns `error` unchanged when it is a `HarnessError` or a cancellation
* (`name === 'AbortError'`); otherwise a {@link SubprocessError} with
* `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` for
* any other value.
*/
export function subprocessSpawnFailure(error: unknown, program: string): unknown {
if (error instanceof HarnessError) return error
if (error instanceof Error && error.name === 'AbortError') return error
const errno = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined
let detail = 'unprintable failure'
try {
detail = error instanceof Error ? error.message : String(error)
} catch {
// A provider-owned rejection whose conversion throws still yields a coded failure.
}
if (errno === 'ENOENT') {
return new SubprocessError(
`cannot start ${JSON.stringify(program)}: the program or the working directory does not exist (${detail})`,
'SUBPROCESS_SPAWN_NOT_FOUND',
{ cause: error },
)
}
return new SubprocessError(`cannot start ${JSON.stringify(program)}: ${detail}`, 'SUBPROCESS_SPAWN_FAILED', { cause: error })
}
+7 -12
View File
@@ -15,6 +15,13 @@ import type { SubprocessHandle, SubprocessSpawnSpec } from './types.ts'
import type { SubprocessTerminalEnvironment, SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from './types.ts'
export { DSH_ENV_PREFIX } from './types.ts'
export {
SUBPROCESS_ERROR_CODES,
SubprocessError,
SubprocessExecutableNotFoundError,
subprocessSpawnFailure,
type SubprocessErrorCode,
} from './error.ts'
export type {
CollectedOutput,
DshEnvironment,
@@ -163,15 +170,3 @@ export abstract class SubprocessRuntime extends Service {
}
export default SubprocessRuntime
/** Executable lookup completed without finding an executable file. */
export class SubprocessExecutableNotFoundError extends Error {
/**
* @param message - provider-specific lookup diagnostic.
* @param options - original provider failure, when available.
*/
constructor(message: string, options?: ErrorOptions) {
super(message, options)
this.name = 'SubprocessExecutableNotFoundError'
}
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { HarnessError } from '@deepseek-ai/dsh-llm'
import {
SUBPROCESS_ERROR_CODES,
SubprocessError,
SubprocessExecutableNotFoundError,
subprocessSpawnFailure,
} from '../src/index.ts'
describe('SubprocessError', () => {
it('carries a literal name and a code from the closed list', () => {
const cause = new Error('low level')
const error = new SubprocessError('runner failed', 'SUBPROCESS_RUNNER_FAILED', { cause })
expect(error).toBeInstanceOf(HarnessError)
expect(error).toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED', cause })
expect(SUBPROCESS_ERROR_CODES).toContain(error.code)
})
it('keeps the executable lookup miss as its own subclass', () => {
const error = new SubprocessExecutableNotFoundError('not on PATH')
expect(error).toBeInstanceOf(SubprocessError)
expect(error).toMatchObject({ name: 'SubprocessExecutableNotFoundError', code: 'SUBPROCESS_EXECUTABLE_NOT_FOUND' })
})
})
describe('subprocessSpawnFailure', () => {
it('classifies ENOENT and other spawn rejections, keeping the original as cause', () => {
const missing = Object.assign(new Error('spawn pwsh ENOENT'), { code: 'ENOENT', syscall: 'spawn pwsh' })
expect(subprocessSpawnFailure(missing, 'pwsh')).toMatchObject({
name: 'SubprocessError',
code: 'SUBPROCESS_SPAWN_NOT_FOUND',
cause: missing,
message: 'cannot start "pwsh": the program or the working directory does not exist (spawn pwsh ENOENT)',
})
const denied = Object.assign(new Error('spawn bash EACCES'), { code: 'EACCES' })
expect(subprocessSpawnFailure(denied, 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', cause: denied })
expect(subprocessSpawnFailure('raw', 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', message: 'cannot start "bash": raw' })
const unprintable = { [Symbol.toPrimitive]() { throw new Error('no') } }
expect(subprocessSpawnFailure(unprintable, 'bash')).toMatchObject({ message: 'cannot start "bash": unprintable failure' })
})
it('returns coded errors and cancellations unchanged', () => {
const coded = new HarnessError('sandbox unavailable', 'SANDBOX_UNAVAILABLE')
expect(subprocessSpawnFailure(coded, 'bash')).toBe(coded)
const abort = new DOMException('aborted', 'AbortError')
expect(subprocessSpawnFailure(abort, 'bash')).toBe(abort)
})
})
@@ -19,6 +19,9 @@
},
{
"path": "../../util/launch-environment"
},
{
"path": "../../llm/llm"
}
]
}
@@ -15,8 +15,8 @@
en: a3450c8cdd5f5802
zh: 15eec66f42e42ce7
/deepseek-ai-dsh-win32-process/behavior:
en: 77806095cd7f781d
zh: 69d09cabc4d49185
en: 9b81bbd4b1a16ddc
zh: b07fc32b41c3cc66
/deepseek-ai-dsh-win32-process/header-verification:
en: 2b60a9001b480546
zh: 12a621e421c7d789
+1 -1
View File
@@ -24,7 +24,7 @@ This low-level Win32 process library is consumed by the Windows ACL sandbox and
<a id="behavior"></a>
## Behavior
- **One reusable ABI owner** — `abi.ts` owns the Win32 constants and x64 layout values consumed by both process paths. `ffi.ts` lazily loads `kernel32.dll` and `advapi32.dll`, verifies `STARTUPINFOW` and `PROCESS_INFORMATION`, exposes typed operations and error formatting, and lets sandbox policy bind its remaining APIs through the same loaded libraries.
- **One reusable ABI owner** — `abi.ts` owns the Win32 constants and x64 layout values consumed by both process paths. `ffi.ts` lazily loads `kernel32.dll` and `advapi32.dll`, verifies `STARTUPINFOW` and `PROCESS_INFORMATION`, exposes typed operations and error formatting, and lets sandbox policy bind its remaining APIs through the same loaded libraries. A failed checked call throws `Win32Error`, a `HarnessError` with code `WIN32_ERROR` whose `api` and `win32Code` fields name the call; callers that own the failing operation wrap it in their own coded error with the `Win32Error` as `cause`.
- **Restricted-token creation** — `RestrictedProcessSpawnOptions` requires the sandbox's primary token and uses `CreateProcessAsUserW`. Piped and inherited-stdio paths share command-line quoting, cwd, the restricted-token null-environment policy, checked return values, and handle cleanup.
- **Piped process primitive** — `spawnPipedProcess()` creates anonymous stdin/stdout/stderr pipes, closes stdin immediately, returns the two read ends, and leaves process waiting and pipe draining to the caller. Every partial failure closes the handles already owned by the operation, and every Koffi out-parameter or struct allocation is freed after its Win32 lifetime.
- **Inherited-stdio Job primitive** — `spawnInheritedJobProcess()` creates one kill-on-close Job, temporarily marks the current stdio handles inheritable, creates the restricted child suspended, assigns it to the Job, and then resumes its initial thread. Target code cannot run before Job assignment; controlled assignment or resume failures terminate the suspended child or close the assigned Job before releasing every owned handle.
@@ -24,7 +24,7 @@ kind: "package-library"
<a id="behavior"></a>
## 行为
- **唯一可复用 ABI owner** — `abi.ts` 拥有两条 process 路径消费的 Win32 常量与 x64 布局值。`ffi.ts` 懒加载 `kernel32.dll` 与 `advapi32.dll`,核验 `STARTUPINFOW` 和 `PROCESS_INFORMATION`,提供带类型的操作与错误格式化,并让沙箱策略通过同一组已加载库绑定剩余 API。
- **唯一可复用 ABI owner** — `abi.ts` 拥有两条 process 路径消费的 Win32 常量与 x64 布局值。`ffi.ts` 懒加载 `kernel32.dll` 与 `advapi32.dll`,核验 `STARTUPINFOW` 和 `PROCESS_INFORMATION`,提供带类型的操作与错误格式化,并让沙箱策略通过同一组已加载库绑定剩余 API。受检调用失败时抛出 `Win32Error`,它是 code 为 `WIN32_ERROR` 的 `HarnessError`,`api` 与 `win32Code` 字段标明失败的调用;拥有该操作的调用方再把它包装为自己的带 code 错误,并以 `Win32Error` 作为 `cause`。
- **restricted-token 创建** — `RestrictedProcessSpawnOptions` 要求沙箱的 primary token,并使用 `CreateProcessAsUserW`。pipe 与 inherited-stdio 路径共用命令行引号处理、cwd、restricted-token null 环境策略、返回值检查与句柄清理。
- **管道进程原语** — `spawnPipedProcess()` 创建匿名 stdin/stdout/stderr 管道,立即关闭 stdin,并返回两个读取端;调用方负责等待进程与排空管道。任一局部失败都会关闭该操作已经拥有的句柄,并在各自 Win32 生命周期结束后释放每个 Koffi 输出槽与结构体分配。
- **继承 stdio 的 Job 原语** — `spawnInheritedJobProcess()` 创建一个 kill-on-close Job,临时把当前 stdio 句柄设为可继承,以 suspended 状态创建 restricted child,把它分配给 Job,再恢复初始线程。目标代码不会在 Job 分配前运行;受控的分配或恢复失败会终止 suspended child,或在释放全部已拥有句柄前关闭已分配的 Job。
@@ -30,13 +30,15 @@
],
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-llm": "workspace:*"
},
"dependencies": {
"@deepseek-ai/dsh-lazy-require": "workspace:*",
"koffi": "3.1.1"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~"
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-llm": "workspace:*"
}
}
@@ -1,12 +1,22 @@
import { HarnessError } from '@deepseek-ai/dsh-llm'
/** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */
export const WIN32_ERROR = 'WIN32_ERROR'
/** Win32 call failure with the exact API name and error code. */
export class Win32Error extends Error {
export class Win32Error extends HarnessError {
/** Win32 function whose checked result failed. */
readonly api: string
/** Exact GetLastError value or direct Win32 API error code. */
readonly win32Code: number
/**
* @param api - Win32 function whose checked result failed.
* @param win32Code - exact GetLastError value or direct API error code.
* @param detail - optional subject, such as the path the call targeted.
*/
constructor(api: string, win32Code: number, detail?: string) {
super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`)
super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`, WIN32_ERROR)
this.name = 'Win32Error'
this.api = api
this.win32Code = win32Code
@@ -1,6 +1,8 @@
import koffi from 'koffi'
import { describe, expect, it, vi } from 'vitest'
import { HarnessError } from '@deepseek-ai/dsh-llm'
import {
WIN32_ERROR,
Win32Error,
allocPtrSlot,
decodePtr,
@@ -35,6 +37,9 @@ describe('shared Win32 process ABI', () => {
expect(errorText(api, 5)).toBe('access denied')
expect(() => throwLastError(api, 'Probe')).toThrow(Win32Error)
expect(new Win32Error('CloseHandle', 6).message).toBe('CloseHandle failed (Win32 6)')
const error = new Win32Error('CloseHandle', 6)
expect(error).toBeInstanceOf(HarnessError)
expect(error).toMatchObject({ name: 'Win32Error', code: WIN32_ERROR, api: 'CloseHandle', win32Code: 6 })
})
it('decodes a pointer stored by Koffi', () => {
@@ -11,6 +11,9 @@
},
{
"path": "../../util/lazy-require"
},
{
"path": "../../llm/llm"
}
]
}
+6
View File
@@ -16984,6 +16984,9 @@ importers:
'@deepseek-ai/dsh-launch-environment':
specifier: workspace:*
version: link:../../util/launch-environment
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
packages/subprocess/subprocess-local:
dependencies:
@@ -17025,6 +17028,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:~
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
packages/team/agent-team:
dependencies: