Merge remote-tracking branch 'origin/master' into codex/pr-555-ci-fix

# Conflicts:
#	docs/module-graph.i18n.yaml
#	docs/module-graph.md
#	docs/module-graph.zh.md
#	packages/client/ui-conversation/src/client/input/hub.ts
#	packages/client/ui-conversation/tests/input-bar.spec.tsx
#	packages/client/ui-conversation/tests/service-orchestration.spec.ts
This commit is contained in:
creatixchu
2026-08-10 15:19:32 +08:00
259 changed files with 8182 additions and 626 deletions

View File

@@ -162,12 +162,27 @@ export class PwshLocalExecutor extends BashExecutor {
}
}
/** Map one resolved bash spec onto a fully-specified subprocess spawn. */
private spawnSpec(spec: BashExecSpec, stdoutMaxBytes: number, signal: AbortSignal | undefined): SubprocessSpawnSpec {
/**
* The pwsh invocation argv for one resolved spec — the argv-level seam a
* confining subclass wraps through `ctx.sandbox.confine` (the pwsh twin of
* `dsh-bash-local`'s `runArgv`/`startArgv` hooks; see
* `@deepseek-ai/dsh-pwsh-sandbox`).
*/
protected argv(spec: BashExecSpec): string[] {
return [this.pwshPath, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', `${ENCODING_PREAMBLE}${spec.command}`]
}
/** Map one resolved spec plus its argv onto a fully-specified subprocess spawn. */
private spawnSpec(
spec: BashExecSpec,
stdoutMaxBytes: number,
signal: AbortSignal | undefined,
argv: readonly string[],
): SubprocessSpawnSpec {
const collect = (maxBytes: number): SubprocessCollect =>
({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } })
return {
argv: [this.pwshPath, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', `${ENCODING_PREAMBLE}${spec.command}`],
argv: [...argv],
cwd: spec.workdir,
stdio: {
stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore',
@@ -192,9 +207,14 @@ export class PwshLocalExecutor extends BashExecutor {
}
async run(spec: BashExecSpec): Promise<BashRunResult> {
return this.runArgv(spec, this.argv(spec))
}
/** Foreground run of an exact argv (the confining subclass re-wraps it). */
protected async runArgv(spec: BashExecSpec, argv: readonly string[]): Promise<BashRunResult> {
// One deadline combines timeout and upstream cancellation; disposal clears its timer.
using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT')
const handle = this.ctx.subprocess.spawn(this.spawnSpec(spec, spec.stdoutMaxBytes, d.signal))
const handle = this.ctx.subprocess.spawn(this.spawnSpec(spec, spec.stdoutMaxBytes, d.signal, argv))
const outcome = await handle.done
const collected = PwshLocalExecutor.collected(handle)
// Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts.
@@ -211,8 +231,13 @@ export class PwshLocalExecutor extends BashExecutor {
}
start(spec: BashExecSpec): BashProcess {
return this.startArgv(spec, this.argv(spec))
}
/** Background start of an exact argv (the confining subclass re-wraps it). */
protected startArgv(spec: BashExecSpec, argv: readonly string[]): BashProcess {
// Background runs ignore timeoutMs; callers stop them through kill() or spec.signal.
const running = this.ctx.subprocess.spawn(this.spawnSpec(spec, this.config.maxOutputBytes, spec.signal))
const running = this.ctx.subprocess.spawn(this.spawnSpec(spec, this.config.maxOutputBytes, spec.signal, argv))
const collected = PwshLocalExecutor.collected(running)
// A spawn failure produces no process output, so the subprocess service has nothing
@@ -237,12 +262,12 @@ export class PwshLocalExecutor extends BashExecutor {
}
proc.exitCode = outcome.exitCode
proc.signal = outcome.signal
this.onProcessDone(proc, collected.stderr.readFrom(0).text)
this.onProcessDone(proc, collected.stderr.readFrom(0).text, false)
}, (error: unknown) => {
// Background spawn failures settle as killed and surface through the read path.
proc.status = 'killed'
spawnFailureNote = `spawn failed: ${String(error)}`
this.onProcessDone(proc, spawnFailureNote)
this.onProcessDone(proc, spawnFailureNote, true, error)
}),
readOutput: (): BashProcessRead => {
const out = collected.stdout.readFrom(stdoutOffset)
@@ -278,13 +303,14 @@ export class PwshLocalExecutor extends BashExecutor {
/**
* Settlement hook for subclasses that attach execution facts to a process.
* The base implementation is intentionally empty. Mirrored from
* `dsh-bash-local` (whose sandboxing subclass consumes the same hook); it is
* the protected extension point for a future pwsh-confining subclass and has no consumer
* in this package yet.
* `dsh-bash-local` (whose sandboxing subclass consumes the same hook); the
* pwsh-confining consumer is `@deepseek-ai/dsh-pwsh-sandbox`.
* @param _proc - the settled process handle.
* @param _stderr - the process's retained stderr tail used by subclasses for settlement classification.
* @param _spawnFailed - whether the spawn rejected before any process existed.
* @param _spawnError - the spawn rejection, when `_spawnFailed`.
*/
protected onProcessDone(_proc: BashProcess, _stderr: string): void {}
protected onProcessDone(_proc: BashProcess, _stderr: string, _spawnFailed: boolean, _spawnError?: unknown): void {}
}
/* jscpd:ignore-end */

View File

@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/bash/pwsh-sandbox/README.md
README.md: bd506d011fa6167ddf7d6fe0565e475979ad0ec2
README.zh.md: e9aa380302037be3c9dd07331035544299bf3bec

View File

@@ -0,0 +1,34 @@
# @deepseek-ai/dsh-pwsh-sandbox
English | [中文](README.zh.md)
Sandbox-consuming PowerShell implementation of the [`ctx.bash` executor seam](../bash/): every command runs as `pwsh -NoLogo -NoProfile -NonInteractive -Command <command>` **confined through `ctx.sandbox`**, with the selected mode, enforcement, and denial facts stamped on each settled result. The pwsh twin of [`@deepseek-ai/dsh-bash-sandbox`](../bash-sandbox/), a call-for-call mirror per the [pwsh executor and tool decision](../../../.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md) — the confinement substance is platform-neutral: on Windows the sandbox seam resolves to the ACL restricted-token runner chain ([`@deepseek-ai/dsh-sandbox-windows-acl`](../../sandbox/sandbox-windows-acl/)), on Linux/macOS to bwrap/Landlock/Seatbelt.
The executor inherits [`@deepseek-ai/dsh-pwsh-local`](../pwsh-local/)'s process mechanics and consumes its argv-level seam (`argv()` / `runArgv()` / `startArgv()` / `onProcessDone()`) to wrap the exact pwsh invocation through the provider. The sandbox policy (mode + workspace root) is NOT this package's config: it rides each call from `ctx.sandboxPolicy` (tool calls pass the calling session's resolved policy; direct calls fall back to deployment policy).
## Behavior
- `danger-full-access`: commands run through the local executor unchanged; results carry `sandbox: { mode, denied: false }`.
- Confined modes (`read-only`, `workspace-write`): the pwsh argv is wrapped by `ctx.sandbox.confine()`; runner-launch refusal fails closed with `SANDBOX_UNAVAILABLE` (foreground throw, background `runnerFailed` fact), and a denied write classifies against the selected backend's `denialSignatures` into `sandbox.denied`.
## Model Experience
### Confinement works, denial surfaces as command failure
#### What the model sees
The confined command's own stderr (e.g. `Access to the path '...' is denied.` under the Windows ACL runner); the tool layer converts classified denials into the standard permission-denied surface exactly as it does for the bash tool.
#### Token effect
No model-visible text beyond the command's stderr and the tool layer's standard denial surface.
#### KV Cache effect
None directly; the denial surface belongs to the tool layer.
## Known Limitations and Deferred Work
- **Reads are unrestricted** on Windows (the ACL runner restricts writes only); the read boundary is documented in `@deepseek-ai/dsh-sandbox-windows-acl`.
- **The Windows workspace-write temp area is the real temp directory** (`GetTempPathW`). This is a deliberate backend-defined choice, the same decision Landlock makes (`readWrite: ['/tmp', ...]`): the seam's "backend-defined temp area" permits it, and the escape probe in `tests/acl.e2e.ts` lives outside the temp tree for exactly that reason. A per-run private temp (bwrap's `--tmpfs /tmp` semantics) would additionally need an environment-block rewrite in the runner; it is an optional future hardening, not a correctness gap.
- **Windows read-only is strict zero-grant** — not even the NUL device is writable; `> $null` redirection still works (documented in the backend package).

View File

@@ -0,0 +1,34 @@
# @deepseek-ai/dsh-pwsh-sandbox
[English](README.md) | 中文
沙盒消费型的 [`ctx.bash` 执行器 seam](../bash/) 的 PowerShell 实现:每条命令以 `pwsh -NoLogo -NoProfile -NonInteractive -Command <command>` 运行,**经 `ctx.sandbox` 隔离**,选定模式、强制完整性、拒绝事实都盖在每次结算的结果上。它是 [`@deepseek-ai/dsh-bash-sandbox`](../bash-sandbox/) 的 pwsh 孪生,按 [pwsh 执行器与工具决策](../../../.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md) 逐调用镜像——隔离实体本身是平台无关的Windows 上沙盒 seam 解析到 ACL 受限令牌 runner 链([`@deepseek-ai/dsh-sandbox-windows-acl`](../../sandbox/sandbox-windows-acl/)Linux/macOS 上解析到 bwrap/Landlock/Seatbelt。
执行器继承 [`@deepseek-ai/dsh-pwsh-local`](../pwsh-local/) 的进程机制,并消费其 argv 级 seam`argv()` / `runArgv()` / `startArgv()` / `onProcessDone()`)把精确的 pwsh 调用经 provider 包装。沙盒策略(模式 + 工作区根目录)不是本包的配置:每次调用由 `ctx.sandboxPolicy` 随行(工具层传调用会话解析后的策略;直接调用回退到部署策略)。
## 行为
- `danger-full-access`:命令经本地执行器原样运行;结果携带 `sandbox: { mode, denied: false }`
- 受限模式(`read-only``workspace-write`pwsh argv 由 `ctx.sandbox.confine()` 包装runner 启动失败按 fail-closed 抛 `SANDBOX_UNAVAILABLE`(前台抛错、后台记 `runnerFailed` 事实),被拒绝的写按所选后端的 `denialSignatures` 分类为 `sandbox.denied`
## 模型体验
### 隔离生效,拒绝以命令失败呈现
#### 模型看到什么
受限命令自身的 stderrWindows ACL runner 下如 `Access to the path '...' is denied.`);工具层把分类后的拒绝转成标准权限拒绝面,与 bash 工具完全一致。
#### Token 影响
除命令 stderr 与工具层标准拒绝面外,无额外模型可见文本。
#### KV Cache 影响
无直接影响;拒绝呈现面属于工具层。
## 已知限制与后续工作
- **Windows 上读不受限**ACL runner 只限写);读边界文档在 `@deepseek-ai/dsh-sandbox-windows-acl`
- **Windows workspace-write 的临时区域是真实临时目录**`GetTempPathW`)。这是有意为之的后端自定义选择,与 Landlock 的决策(`readWrite: ['/tmp', ...]`同类seam 的 "backend-defined temp area" 词汇表允许它,`tests/acl.e2e.ts` 的逃逸探针也正是因此位于 temp 树之外。按运行创建私有临时目录bwrap `--tmpfs /tmp` 的语义)还需 runner 改写环境块——这是可选的进一步加固,而非正确性缺口。
- **Windows read-only 是严格零授权**——连 NUL 设备都不可写;`> $null` 重定向不受影响(后端包有文档)。

View File

@@ -0,0 +1,45 @@
{
"name": "@deepseek-ai/dsh-pwsh-sandbox",
"description": "Sandbox-consuming implementation of the DeepSeek Harness PowerShell executor seam (confines every command via ctx.sandbox, reports denial/enforcement result facts)",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-bash": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-pwsh-local": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"@deepseek-ai/dsh-sandbox-policy": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-bash": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-sandbox-local": "workspace:^",
"@deepseek-ai/dsh-sandbox-policy": "workspace:^",
"@deepseek-ai/dsh-subprocess-local": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,120 @@
/**
* Internal sandbox-result classification helpers — deliberate call-for-call
* mirror of `@deepseek-ai/dsh-bash-sandbox/src/helpers.ts` (the pwsh twin of
* the bash consumer shares the identical classification dialect).
*
* @module @deepseek-ai/dsh-pwsh-sandbox/helpers
*/
/* jscpd:ignore-start */
import { accessSync, constants, statSync } from 'node:fs'
import type { BashRunResult } from '@deepseek-ai/dsh-bash'
import type { RunnerFailureRule } from '@deepseek-ai/dsh-sandbox'
/** Node-local spawn codes proven to identify executable resolution or permission failure. */
const EXECUTABLE_SPAWN_CODES = new Set(['EACCES', 'ENOENT'])
/** Whether the caller-owned spawn cwd can be entered. */
function isUsableWorkdir(path: string): boolean {
try {
if (!statSync(path).isDirectory()) return false
accessSync(path, constants.X_OK)
return true
} catch {
return false
}
}
/**
* Attribute only Node ENOENT/EACCES failures with positive argv[0] provenance
* after independently ruling out the caller-owned cwd. A supplied error path
* must exactly identify the runner; without one, the syscall must. With a
* usable cwd, these codes describe resolution or execute permission for that
* argv[0] or its shebang interpreter.
* The workdir is checked at classification time, not atomically with spawn;
* concurrent path replacement may change attribution but cannot permit an
* unconfined execution.
* @param error - the original spawn rejection.
* @param runnerProgram - provider argv[0], the executable that establishes confinement.
* @param workdir - the caller-owned spawn cwd, checked independently for usability.
* @returns whether the rejection has executable-specific runner evidence.
*/
export function isRunnerSpawnFailure(
error: unknown,
runnerProgram: string | undefined,
workdir: string,
): boolean {
if (runnerProgram === undefined || !isUsableWorkdir(workdir)) return false
if (typeof error !== 'object' || error === null) return false
const { code, path, syscall } = error as { code?: unknown; path?: unknown; syscall?: unknown }
if (typeof code !== 'string' || !EXECUTABLE_SPAWN_CODES.has(code)) return false
if (typeof syscall !== 'string') return false
const exactSyscall = `spawn ${runnerProgram}`
if (path === undefined) return syscall === exactSyscall
if (typeof path !== 'string' || path.length === 0 || path !== runnerProgram) return false
return syscall === 'spawn' || syscall === exactSyscall
}
/** Fatal runner evidence retained for infrastructure-error detail. */
interface RunnerFailureMatch {
/** The original stderr line that matched a fatal signature. */
detail: string
}
/**
* Classify a failed run against the selected backend's denial dialect.
* @param result - settled foreground run.
* @param signatures - case-insensitive denial substrings from the active wrap.
* @returns whether the failed run matches that denial dialect.
*/
export function classifyDenial(result: BashRunResult, signatures: readonly string[]): boolean {
return matchesSignature(result.exitCode, result.stderr.text, signatures)
}
/**
* Classify one settled process against the selected backend's structured
* runner-failure rules. Each rule requires a nonzero exit, its optional
* exit-code gate, and a fatal signature on one stderr line after exact
* informational lines are excluded.
* @param exitCode - process exit code; null means signal termination.
* @param stderr - collected stderr text, left unchanged.
* @param rules - structured runner-failure rules from the active wrap.
* @returns the first matching fatal line, or undefined when evidence is insufficient.
*/
export function classifyRunnerFailure(
exitCode: number | null,
stderr: string,
rules: readonly RunnerFailureRule[],
): RunnerFailureMatch | undefined {
if (exitCode === null || exitCode === 0) return undefined
const lines = stderr.split(/\r?\n/)
for (const rule of rules) {
if (rule.allowedExitCodes !== undefined && !rule.allowedExitCodes.includes(exitCode)) continue
const informationalLines = new Set((rule.informationalLines ?? []).map(line => line.toLowerCase()))
// An empty or whitespace-only substring is not meaningful runner evidence.
// Ignore it while keeping any valid signatures beside it active.
const fatalSignatures = rule.fatalSignatures
.filter(signature => signature.trim().length > 0)
.map(signature => signature.toLowerCase())
for (const line of lines) {
const lowered = line.toLowerCase()
if (informationalLines.has(lowered)) continue
if (fatalSignatures.some(signature => lowered.includes(signature))) return { detail: line }
}
}
return undefined
}
/**
* Match a non-zero exit against case-insensitive stderr signatures.
* @param exitCode - process exit code; null means signal termination.
* @param stderr - collected stderr text.
* @param signatures - substrings identifying the selected backend's dialect.
* @returns whether this is a non-zero exit whose stderr matches a signature.
*/
export function matchesSignature(exitCode: number | null, stderr: string, signatures: readonly string[]): boolean {
if (exitCode === null || exitCode === 0) return false
const lowered = stderr.toLowerCase()
return signatures.some(signature => lowered.includes(signature.toLowerCase()))
}
/* jscpd:ignore-end */

View File

@@ -0,0 +1,189 @@
/**
* Sandbox-consuming PowerShell executor — the pwsh twin of
* `@deepseek-ai/dsh-bash-sandbox`. It wraps the exact local pwsh argv through
* `ctx.sandbox` (which on Windows resolves to the ACL restricted-token runner
* chain), inherits local process mechanics, and reports the selected mode,
* enforcement, and denial facts. Positive runner-launch evidence means the
* command never ran: foreground calls throw `SANDBOX_UNAVAILABLE`, while
* background processes carry `runnerFailed`; other spawn rejections retain
* local-executor semantics. The tool layer owns the escalation approval flow
* through `ctx.approval`; this executor reports the sandbox facts the tool
* renders.
* @module @deepseek-ai/dsh-pwsh-sandbox
*/
import { Context } from 'cordis'
import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash'
import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type {
ConfinedArgv,
ConfinedSandboxMode,
RunnerFailureRule,
SandboxEnforcement,
SandboxExecutionPolicy,
SandboxMode,
SandboxPolicy,
} from '@deepseek-ai/dsh-sandbox'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local'
import type { Config as LocalConfig } from '@deepseek-ai/dsh-pwsh-local'
import { classifyDenial, classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature } from './helpers.ts'
/**
* Plugin config: the local executor's knobs, verbatim. The sandbox policy —
* the default mode and fallback `workspace-write` root — is NOT here: it lives
* on `ctx.sandboxPolicy` (`@deepseek-ai/dsh-sandbox-policy`), which resolves
* each calling session's mode and cwd for every enforcing capability. The
* runner choice is likewise the `ctx.sandbox` provider's config, not this
* executor's.
*/
export type Config = LocalConfig
/**
* Registers as `ctx.bash` in place of the local pwsh executor and requires a
* `ctx.sandbox` provider plus `ctx.sandboxPolicy`; the tool layer carries the
* sandbox denial rendering and escalation surface (see the
* pwsh-tool-and-executor Agent Note). Tool calls pass the calling session's
* resolved policy; direct calls fall back to deployment policy.
* `result.sandbox` reports the mode, enforcement, and denial facts the tool
* renders.
*/
/* jscpd:ignore-start -- deliberate call-for-call mirror of bash-sandbox's executor (pwsh-tool-and-executor Agent Note) */
export class SandboxPwshExecutor extends PwshLocalExecutor {
static override inject = ['subprocess', 'sandbox', 'sandboxPolicy']
// No own Config: the sandbox default (mode + workspaceRoot) moved to
// ctx.sandboxPolicy, so this executor inherits PwshLocalExecutor's Config
// verbatim (the config catalog walks the inherited static).
private readonly mode: SandboxMode
/**
* Per-process confinement facts retained until settlement. Providers may
* vary enforcement and diagnostic dialect between overlapping calls, so a
* shared latest-wrap value would classify a process against the wrong facts.
* Unconfined processes have no entry.
*/
private readonly processFacts = new Map<BashProcess, {
mode: ConfinedSandboxMode
enforcement: SandboxEnforcement
denialSignatures: readonly string[]
runnerFailureRules: readonly RunnerFailureRule[]
runnerProgram: string | undefined
workdir: string
}>()
constructor(ctx: Context, config: Config) {
super(ctx, config)
// The default mode is the capability fact used for schema advertisement;
// actual tool executions carry their resolved per-call policy.
this.mode = ctx.sandboxPolicy.defaultMode
}
/** The configured default mode — the capability fact the tool layer reads. */
override get sandboxMode(): SandboxMode {
return this.mode
}
/**
* Stamp a complete per-call policy onto the spec. Tool calls supply the
* calling session's resolved mode and root; lower-level callers fall back to
* the deployment policy.
*/
override resolve(request: BashExecRequest): BashExecSpec {
return { ...super.resolve(request), sandboxPolicy: request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve() }
}
override async run(spec: BashExecSpec): Promise<BashRunResult> {
const policy = spec.sandboxPolicy as SandboxExecutionPolicy
const { mode } = policy
if (mode === 'danger-full-access') {
const result = await super.run(spec)
return { ...result, sandbox: { mode, denied: false } }
}
const confined = this.confine(spec, { ...policy, mode })
let result: BashRunResult
try {
result = await this.runArgv(spec, confined.argv)
} catch (error) {
// An upstream abort remains cancellation even when it prevents spawn.
if (spec.signal?.aborted === true) spec.signal.throwIfAborted()
if (isRunnerSpawnFailure(error, confined.argv[0], spec.workdir)) {
throw new SandboxUnavailableError(mode, String(error))
}
throw error
}
// Runner failure outranks denial because the command did not run. Carry
// the matched fatal line, not an informational line that preceded it.
const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, confined.runnerFailureRules)
if (runnerFailure !== undefined) {
throw new SandboxUnavailableError(mode, runnerFailure.detail)
}
return { ...result, sandbox: { mode, denied: classifyDenial(result, confined.denialSignatures), enforcement: confined.enforcement } }
}
override start(spec: BashExecSpec): BashProcess {
const policy = spec.sandboxPolicy as SandboxExecutionPolicy
const { mode } = policy
if (mode === 'danger-full-access') return super.start(spec)
// Once startArgv returns, install facts synchronously; promise settlement
// cannot run before start() returns.
const confined = this.confine(spec, { ...policy, mode })
let proc: BashProcess
try {
proc = this.startArgv(spec, confined.argv)
} catch (error) {
if (isRunnerSpawnFailure(error, confined.argv[0], spec.workdir)) {
throw new SandboxUnavailableError(mode, String(error))
}
throw error
}
const { enforcement, denialSignatures, runnerFailureRules } = confined
this.processFacts.set(proc, {
mode,
enforcement,
denialSignatures,
runnerFailureRules,
runnerProgram: confined.argv[0],
workdir: spec.workdir,
})
return proc
}
/**
* Stamp per-process sandbox facts before `done` settles. Full-access
* processes have no facts; signal deaths are not denials.
*/
protected override onProcessDone(proc: BashProcess, stderr: string, spawnFailed: boolean, spawnError?: unknown): void {
const facts = this.processFacts.get(proc)
if (facts !== undefined) {
this.processFacts.delete(proc)
// A rejected spawn never started the confined launch. Otherwise runner
// failure outranks denial because its diagnostics may contain denial terms.
const runnerFailed = spawnFailed
? isRunnerSpawnFailure(spawnError, facts.runnerProgram, facts.workdir)
: classifyRunnerFailure(proc.exitCode, stderr, facts.runnerFailureRules) !== undefined
proc.sandbox = {
mode: facts.mode,
denied: !runnerFailed && matchesSignature(proc.exitCode, stderr, facts.denialSignatures),
enforcement: facts.enforcement,
...(runnerFailed ? { runnerFailed } : {}),
}
}
super.onProcessDone(proc, stderr, spawnFailed, spawnError)
}
/**
* Wrap one pwsh invocation via the `ctx.sandbox` provider. Provider errors
* propagate unchanged; the returned argv is handed directly to the local
* executor's subprocess path.
* @param spec - resolved execution spec whose pwsh argv is confined.
* @param policy - resolved confined execution policy.
* @returns the provider's exact argv and settlement-classification facts.
*/
private confine(spec: BashExecSpec, policy: SandboxPolicy): ConfinedArgv {
return this.ctx.sandbox.confine(this.argv(spec), policy)
}
}
/* jscpd:ignore-end */
export default SandboxPwshExecutor

View File

@@ -0,0 +1,30 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-pwsh-sandbox`.
* @module @deepseek-ai/dsh-pwsh-sandbox/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-pwsh-sandbox'
/** Cordis companion plugin name. */
export const name = 'pwsh-sandbox-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: this package exposes no independent event sequence or
* mutable data relation beyond contracts enforced at its owning seams.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -0,0 +1,111 @@
/**
* Real-backend end-to-end: LocalSandboxProvider (win32 chain → the
* windows-acl runner), SandboxPolicyService, and SandboxPwshExecutor with
* REAL pwsh spawns confined through the runner — the debug-instance
* verification of both modes: read-only denies every write (not even NUL),
* workspace-write allows the workspace and temp while denying escape writes,
* and denial/classification facts ride the settled result.
*/
import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
import { SandboxPwshExecutor } from '../src/index.ts'
const isWin32 = process.platform === 'win32'
function pwshAvailable(): boolean {
return spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0
}
describe.skipIf(!isWin32 || !pwshAvailable())('pwsh-sandbox real ACL confinement', () => {
let scratchRoot!: string
let writableDir!: string
let isolatedTemp!: string
let secretFile!: string
let escapeFile!: string
let executor!: SandboxPwshExecutor
beforeAll(async () => {
// The escape probe must live OUTSIDE every legitimately granted tree: the
// provider's workspace-write grants the workspace plus the REAL temp dir
// (the 'backend-defined temp area', same as Landlock granting /tmp), so a
// scratch dir under temp would inherit the grant and the probe would be a
// false pass. A mkdtemp under the profile is removed by afterAll.
scratchRoot = mkdtempSync(join(homedir(), 'dsh-pwsh-sandbox-e2e-'))
writableDir = join(scratchRoot, 'writable')
mkdirSync(writableDir)
isolatedTemp = mkdtempSync(join(tmpdir(), 'dsh-pwsh-sandbox-e2e-temp-'))
secretFile = join(scratchRoot, 'secret.txt')
writeFileSync(secretFile, 'top secret - must stay readable to prove the read boundary')
escapeFile = join(scratchRoot, 'escaped.txt')
const ctx = new Context()
await ctx.plugin(LocalSandboxProvider, {})
await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: writableDir })
await ctx.plugin(LocalSubprocessService)
await ctx.plugin(SandboxPwshExecutor, {})
executor = ctx.bash as SandboxPwshExecutor
})
afterAll(() => {
rmSync(scratchRoot, { recursive: true, force: true })
rmSync(isolatedTemp, { recursive: true, force: true })
})
it('read-only: every write denied (workspace, temp, NUL), reads fine, denial facts ride the result', async () => {
const policy: SandboxExecutionPolicy = { mode: 'read-only', workspaceRoot: writableDir }
const probe = [
"$ErrorActionPreference='SilentlyContinue';",
`try{Set-Content -Path '${writableDir}\\ro-write.txt' -Value ok -ErrorAction Stop;'TARGET-WRITE: OK'}catch{'TARGET-WRITE: DENIED'};`,
`try{Set-Content -Path '${isolatedTemp}\\ro-write.txt' -Value ok -ErrorAction Stop;'TEMP-WRITE: OK'}catch{'TEMP-WRITE: DENIED'};`,
`try{Set-Content -Path '${escapeFile}' -Value ok -ErrorAction Stop;'ESCAPE-WRITE: OK'}catch{'ESCAPE-WRITE: DENIED'};`,
`try{Get-Content '${secretFile}' -ErrorAction Stop | Out-Null;'SECRET-READ: OK'}catch{'SECRET-READ: DENIED'}`,
].join('')
const result = await executor.run(executor.resolve({ command: probe, sandboxPolicy: policy }))
expect(result.exitCode, `stderr: ${result.stderr.text}`).toBe(0)
expect(result.stdout.text).toContain('TARGET-WRITE: DENIED')
expect(result.stdout.text).toContain('TEMP-WRITE: DENIED')
expect(result.stdout.text).toContain('ESCAPE-WRITE: DENIED')
expect(result.stdout.text).toContain('SECRET-READ: OK')
expect(existsSync(join(writableDir, 'ro-write.txt'))).toBe(false)
// A self-caught denial keeps the command exit 0: no denial fact.
expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
// A raw failing write must classify as a denial of the ACL dialect.
const denied = await executor.run(executor.resolve({
command: `Set-Content -Path '${escapeFile}' -Value x`,
sandboxPolicy: policy,
}))
expect(denied.exitCode).not.toBe(0)
expect(denied.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
}, 60_000)
it('workspace-write: workspace and temp writable, escape denied, reads fine', async () => {
const policy: SandboxExecutionPolicy = { mode: 'workspace-write', workspaceRoot: writableDir }
const probe = [
"$ErrorActionPreference='SilentlyContinue';",
`try{Set-Content -Path '${writableDir}\\ww-write.txt' -Value ok -ErrorAction Stop;'TARGET-WRITE: OK'}catch{'TARGET-WRITE: DENIED'};`,
`try{Set-Content -Path '${isolatedTemp}\\ww-write.txt' -Value ok -ErrorAction Stop;'TEMP-WRITE: OK'}catch{'TEMP-WRITE: DENIED'};`,
`try{Set-Content -Path '${escapeFile}' -Value ok -ErrorAction Stop;'ESCAPE-WRITE: OK'}catch{'ESCAPE-WRITE: DENIED'};`,
`try{Get-Content '${secretFile}' -ErrorAction Stop | Out-Null;'SECRET-READ: OK'}catch{'SECRET-READ: DENIED'}`,
].join('')
const result = await executor.run(executor.resolve({ command: probe, sandboxPolicy: policy }))
expect(result.exitCode, `stderr: ${result.stderr.text}`).toBe(0)
expect(result.stdout.text).toContain('TARGET-WRITE: OK')
expect(result.stdout.text).toContain('TEMP-WRITE: OK')
expect(result.stdout.text).toContain('ESCAPE-WRITE: DENIED')
expect(result.stdout.text).toContain('SECRET-READ: OK')
expect(existsSync(join(writableDir, 'ww-write.txt'))).toBe(true)
expect(existsSync(escapeFile)).toBe(false)
expect(result.sandbox).toEqual({ mode: 'workspace-write', denied: false, enforcement: 'full' })
}, 60_000)
})

View File

@@ -0,0 +1,326 @@
/**
* Consumer-side `SandboxPwshExecutor` tests. A fake Cordis sandbox service
* makes wrapping, policy hand-off, fail-closed propagation, and fact stamping
* deterministic; real-provider integration lives in `tests/acl.e2e.ts`.
* Requires pwsh for the integration block (skips without it — same gate as
* pwsh-local's suites); the helpers block is pure and always runs.
*/
import { spawnSync } from 'node:child_process'
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
import { Context, Service } from 'cordis'
import { SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv, RunnerFailureRule, SandboxExecutionPolicy, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local'
import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
import { SandboxPwshExecutor } from '../src/index.ts'
import { classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature } from '../src/helpers.ts'
// The same probe pwsh-local's suites and the vitest coverage exemption use:
// spawnSync never throws on a missing binary (it reports status null), and
// `where.exe pwsh` exits 1 when pwsh is absent — only the status is truth.
function pwshAvailable(): boolean {
return spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0
}
const spillDir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-sandbox-spec-'))
/** One recorded provider call: the argv handed over and the policy it rode with. */
interface ConfineCall {
argv: string[]
policy: SandboxPolicy
}
/** A passthrough wrap: the caller's argv unchanged, asserted full — commands run unconfined, deterministically. */
const passthrough = (argv: readonly string[]): ConfinedArgv =>
({ argv: [...argv], enforcement: 'full', denialSignatures: ['access is denied', 'access to the path'], runnerFailureRules: [] })
/** A subprocess service whose spawn() throws SYNCHRONOUSLY — the paths the async service never produces. */
function throwingSubprocessService(error: unknown): new (ctx: Context) => Service {
return class extends Service {
constructor(ctx: Context) {
super(ctx, 'subprocess')
}
spawn(): never {
throw error
}
}
}
async function setup(
behavior: (argv: readonly string[], policy: SandboxPolicy) => ConfinedArgv = passthrough,
subprocess: new (ctx: Context) => Service = LocalSubprocessService,
): Promise<{ executor: SandboxPwshExecutor; calls: ConfineCall[] }> {
const calls: ConfineCall[] = []
class FakeSandboxProvider extends SandboxProvider {
confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv {
calls.push({ argv: [...argv], policy })
return behavior(argv, policy)
}
}
const ctx = new Context()
await ctx.plugin(FakeSandboxProvider)
await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: spillDir })
await ctx.plugin(subprocess)
if (ctx.subprocess instanceof LocalSubprocessService) {
ctx.subprocess.internals = { spillDir }
}
await ctx.plugin(SandboxPwshExecutor, { graceMs: 200 })
return { executor: ctx.bash as SandboxPwshExecutor, calls }
}
describe('helpers (pure)', () => {
const workdir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-sandbox-helpers-'))
afterAll(() => {
rmSync(workdir, { recursive: true, force: true })
})
describe('isRunnerSpawnFailure', () => {
const absolute = process.execPath
const bare = 'node'
const relative = './sandbox-runner'
it('attributes ENOENT/EACCES with argv[0] provenance and a usable workdir', () => {
for (const runnerProgram of [absolute, bare, relative]) {
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: `spawn ${runnerProgram}`, path: runnerProgram }, runnerProgram, workdir)).toBe(true)
expect(isRunnerSpawnFailure({ code: 'EACCES', syscall: `spawn ${runnerProgram}`, path: runnerProgram }, runnerProgram, workdir)).toBe(true)
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn', path: runnerProgram }, runnerProgram, workdir)).toBe(true)
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: `spawn ${runnerProgram}` }, runnerProgram, workdir)).toBe(true)
}
})
it('rejects mismatched provenance, foreign codes, unusable workdirs, and non-object errors', () => {
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn', path: 'other' }, 'node', workdir)).toBe(false)
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn other', path: 'node' }, 'node', workdir)).toBe(false)
expect(isRunnerSpawnFailure({ code: 'EMFILE', syscall: 'spawn', path: 'node' }, 'node', workdir)).toBe(false)
expect(isRunnerSpawnFailure({ code: 'ENOENT', path: 'node' }, 'node', workdir)).toBe(false)
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn' }, 'node', join(workdir, 'missing'))).toBe(false)
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn' }, undefined, workdir)).toBe(false)
expect(isRunnerSpawnFailure('boom', 'node', workdir)).toBe(false)
expect(isRunnerSpawnFailure(null, 'node', workdir)).toBe(false)
// An existing FILE (not a directory) workdir is unusable without throwing.
const fileWorkdir = join(workdir, 'a-file')
writeFileSync(fileWorkdir, 'x')
expect(isRunnerSpawnFailure({ code: 'ENOENT', syscall: 'spawn', path: 'node' }, 'node', fileWorkdir)).toBe(false)
})
})
describe('classifyRunnerFailure', () => {
const rules: readonly RunnerFailureRule[] = [{
allowedExitCodes: [127],
fatalSignatures: ['fake-runner: '],
informationalLines: ['fake-runner: partial enforcement'],
}]
it('matches a fatal signature on a gated exit code, skipping informational lines', () => {
expect(classifyRunnerFailure(127, 'fake-runner: partial enforcement\nfake-runner: profile refused\n', rules))
.toEqual({ detail: 'fake-runner: profile refused' })
})
it('rejects zero/null exits, gate mismatches, and empty signatures', () => {
expect(classifyRunnerFailure(0, 'fake-runner: x', rules)).toBeUndefined()
expect(classifyRunnerFailure(null, 'fake-runner: x', rules)).toBeUndefined()
expect(classifyRunnerFailure(1, 'fake-runner: x', rules)).toBeUndefined()
expect(classifyRunnerFailure(127, 'clean output', rules)).toBeUndefined()
expect(classifyRunnerFailure(127, 'fake-runner: x', [{ fatalSignatures: [' '] }])).toBeUndefined()
})
it('the windows-acl rule is exit-gated on 127: a confined command that merely prints the signature on a non-127 exit is NOT a runner failure', () => {
const windowsAclRules: readonly RunnerFailureRule[] = [{ allowedExitCodes: [127], fatalSignatures: ['windows-acl-run: '] }]
expect(classifyRunnerFailure(3, 'windows-acl-run: something the command printed', windowsAclRules)).toBeUndefined()
expect(classifyRunnerFailure(127, 'windows-acl-run: missing --workspace', windowsAclRules))
.toEqual({ detail: 'windows-acl-run: missing --workspace' })
})
})
describe('matchesSignature', () => {
it('matches non-zero exits case-insensitively, never zero or signal exits', () => {
expect(matchesSignature(1, 'Access to the path is denied.', ['access to the path'])).toBe(true)
expect(matchesSignature(1, 'ACCESS IS DENIED.', ['access is denied'])).toBe(true)
expect(matchesSignature(1, 'clean', ['access is denied'])).toBe(false)
expect(matchesSignature(0, 'access is denied', ['access is denied'])).toBe(false)
expect(matchesSignature(null, 'access is denied', ['access is denied'])).toBe(false)
})
})
})
describe.skipIf(!pwshAvailable())('SandboxPwshExecutor', () => {
// Denial device for the POSIX classification cases: a mode-0555 directory
// INSIDE a temp scratch tree (the same device as bash-sandbox's suites) —
// unit tests never attempt writes outside the system temp directory. On
// win32 there is no POSIX mode denial; the real-sandbox denial coverage
// lives in tests/acl.e2e.ts, where the ACL runner denies scratch paths.
const readOnlyDir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-sandbox-ro-'))
if (process.platform !== 'win32') chmodSync(readOnlyDir, 0o555)
const deniedWriteCommand = `[IO.File]::WriteAllText('${join(readOnlyDir, 'probe.txt')}', 'x')`
afterAll(() => {
if (process.platform !== 'win32') chmodSync(readOnlyDir, 0o755)
rmSync(readOnlyDir, { recursive: true, force: true })
rmSync(spillDir, { recursive: true, force: true })
})
const RO: SandboxExecutionPolicy = { mode: 'read-only', workspaceRoot: '/ws' }
it('wraps the exact pwsh argv through ctx.sandbox with the per-call policy', async () => {
const { executor, calls } = await setup()
const result = await executor.run(executor.resolve({ command: 'echo wrapped', sandboxPolicy: RO }))
expect(result.exitCode).toBe(0)
expect(calls).toHaveLength(1)
const call = calls[0]
expect(call?.policy).toEqual(RO)
// The confined argv is the pwsh invocation, ready for a runner prefix.
expect(call?.argv[0]).toMatch(/pwsh(\.exe)?$/u)
expect(call?.argv).toContain('-NonInteractive')
expect(call?.argv.at(-1)).toContain('echo wrapped')
expect(result.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
}, 30_000)
it('advertises the deployment default mode and stamps the deployment policy when none rides the request', async () => {
const { executor, calls } = await setup()
expect(executor.sandboxMode).toBe('workspace-write')
const result = await executor.run(executor.resolve({ command: 'echo fallback' }))
expect(result.exitCode).toBe(0)
expect(calls[0]?.policy.mode).toBe('workspace-write')
}, 30_000)
it('danger-full-access bypasses confine entirely and stamps full-access facts', async () => {
const { executor, calls } = await setup()
const result = await executor.run(executor.resolve({ command: 'echo full', sandboxPolicy: { mode: 'danger-full-access', workspaceRoot: '/ws' } }))
expect(result.exitCode).toBe(0)
expect(calls).toHaveLength(0)
expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false })
}, 30_000)
it('an aborted caller signal outranks runner-spawn attribution', async () => {
const controller = new AbortController()
controller.abort('caller-cancel')
const { executor } = await setup(() => ({
argv: ['definitely-not-a-real-runner', '--', 'pwsh'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [],
}))
await expect(executor.run(executor.resolve({ command: 'echo never', sandboxPolicy: RO, signal: controller.signal })))
.rejects.toThrow('caller-cancel')
}, 30_000)
// POSIX-only: the denial device is a mode-0555 scratch dir. On win32 the
// real-sandbox denial classification is covered by tests/acl.e2e.ts
// (the ACL runner denies scratch paths — unit tests never leave temp).
it.skipIf(process.platform === 'win32')('classifies a failed write against the backend denial dialect', async () => {
const { executor } = await setup()
const result = await executor.run(executor.resolve({
command: deniedWriteCommand,
sandboxPolicy: RO,
}))
expect(result.exitCode).not.toBe(0)
expect(result.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
}, 30_000)
it('a runner launch refusal fails closed with SANDBOX_UNAVAILABLE, never unconfined', async () => {
const { executor } = await setup(() => ({
argv: ['definitely-not-a-real-runner', '--', 'pwsh'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [{ fatalSignatures: ['fake-runner: '] }],
}))
await expect(executor.run(executor.resolve({ command: 'echo never-runs', sandboxPolicy: RO })))
.rejects.toThrow(SandboxUnavailableError)
}, 30_000)
it('a SYNCHRONOUS attributable spawn rejection in run() fails closed, an unattributable one rethrows', async () => {
const attributable = Object.assign(new Error('sync-enoent'), { code: 'ENOENT', syscall: 'spawn node', path: 'node' })
const { executor: closed } = await setup(() => ({
argv: ['node', '--', 'pwsh'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [{ fatalSignatures: ['fake-runner: '] }],
}), throwingSubprocessService(attributable))
await expect(closed.run(closed.resolve({ command: 'echo never', sandboxPolicy: RO })))
.rejects.toThrow(SandboxUnavailableError)
const foreign = Object.assign(new Error('sync-emfile'), { code: 'EMFILE', syscall: 'spawn', path: 'node' })
const { executor: passthroughError } = await setup(undefined, throwingSubprocessService(foreign))
await expect(passthroughError.run(passthroughError.resolve({ command: 'echo never', sandboxPolicy: RO })))
.rejects.toThrow('sync-emfile')
}, 30_000)
it('a SYNCHRONOUS spawn rejection in start() follows the same attribution split', async () => {
const attributable = Object.assign(new Error('sync-enoent-start'), { code: 'ENOENT', syscall: 'spawn node', path: 'node' })
const { executor: closed } = await setup(() => ({
argv: ['node', '--', 'pwsh'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [{ fatalSignatures: ['fake-runner: '] }],
}), throwingSubprocessService(attributable))
expect(() => closed.start(closed.resolve({ command: 'echo never', sandboxPolicy: RO })))
.toThrow(SandboxUnavailableError)
const foreign = Object.assign(new Error('sync-emfile-start'), { code: 'EMFILE', syscall: 'spawn', path: 'node' })
const { executor: passthroughError } = await setup(undefined, throwingSubprocessService(foreign))
expect(() => passthroughError.start(passthroughError.resolve({ command: 'echo never', sandboxPolicy: RO })))
.toThrow('sync-emfile-start')
}, 30_000)
it('a runner that REFUSES at runtime (fatal signature, nonzero exit) fails closed too', async () => {
const { executor } = await setup(() => ({
argv: [process.execPath, '-e', 'console.error(\'fake-runner: profile refused\'); process.exit(127)', '--'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [{ fatalSignatures: ['fake-runner: '] }],
}))
await expect(executor.run(executor.resolve({ command: 'echo never-runs', sandboxPolicy: RO })))
.rejects.toThrow(SandboxUnavailableError)
}, 30_000)
it('background confined runs stamp clean facts at settlement', async () => {
const { executor } = await setup()
const clean = executor.start(executor.resolve({ command: 'echo background-ok', sandboxPolicy: RO }))
await clean.done
expect(clean.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
}, 30_000)
// POSIX-only denial device (mode-0555 scratch); win32 real-sandbox denial
// coverage lives in tests/acl.e2e.ts.
it.skipIf(process.platform === 'win32')('background denied writes stamp denied facts at settlement', async () => {
const { executor } = await setup()
const denied = executor.start(executor.resolve({
command: deniedWriteCommand,
sandboxPolicy: RO,
}))
await denied.done
expect(denied.sandbox).toEqual({ mode: 'read-only', denied: true, enforcement: 'full' })
}, 30_000)
it('background spawn rejections settle as runnerFailed facts', async () => {
const { executor } = await setup(() => ({
argv: ['definitely-not-a-real-runner', '--', 'pwsh'],
enforcement: 'full',
denialSignatures: [],
runnerFailureRules: [{ fatalSignatures: ['fake-runner: '] }],
}))
const proc = executor.start(executor.resolve({ command: 'echo never', sandboxPolicy: RO }))
await proc.done
expect(proc.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
// The failure note surfaces through the read path.
const read = proc.readOutput()
expect(read.delta).toContain('spawn failed')
}, 30_000)
it('danger-full-access background runs bypass confine and carry no facts', async () => {
const { executor, calls } = await setup()
const proc = executor.start(executor.resolve({
command: 'echo full-bg',
sandboxPolicy: { mode: 'danger-full-access', workspaceRoot: '/ws' },
}))
await proc.done
expect(calls).toHaveLength(0)
expect(proc.sandbox).toBeUndefined()
}, 30_000)
})

View File

@@ -0,0 +1,39 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../util/brand"
},
{
"path": "../../llm/llm"
},
{
"path": "../../sandbox/sandbox"
},
{
"path": "../../sandbox/sandbox-policy"
},
{
"path": "../../bash/bash"
},
{
"path": "../../bash/pwsh-local"
},
{
"path": "../../support/invariants"
}
]
}

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/bash/tool-pwsh/README.md
README.md: 7d8ee5fb69b71d8e8707d3e4ed07ebdda99f799f
README.zh.md: 40984bbc36be4b5809e6ee4db21e52d842f50cdb
README.md: 3fd5a53946e2b101d6ef4457e312e52f4db5f3a8
README.zh.md: c06b4354b6973a6ff196cda7c49966c7c40e0a90

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface — foreground and `run_in_background` execution through the generic task runtime, the managed `DSH_*` environment through the shared `bash-env` registry, and the bash marker/truncation rendering story (a clean exit produces no marker).
The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Behavior mirrors `dsh-tool-bash` call-for-call — foreground and `run_in_background` execution through the generic task runtime, the managed `DSH_*` environment through the shared `bash-env` registry, the sandbox denial rendering with the same-turn `sandbox_permissions` escalation surface, and the bash marker/truncation rendering story (a clean exit produces no marker).
Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`).
@@ -21,6 +21,8 @@ The plugin also contributes the `tool:pwsh` prompt section (order 105): non-zero
| `timeoutMs` | number | Timeout override in milliseconds. The executor applies its configured default and cap. |
| `workdir` | string | Working directory for this call. Defaults to the calling agent's session cwd (`session.header.cwd`) so each session runs in its own workspace; a relative `workdir` is resolved against that same identity. |
| `run_in_background` | boolean | Return a task id immediately; no timeout applies. |
| `sandbox_permissions` | string enum | Advertised only when a sandboxing executor is mounted (`ctx.bash.sandboxMode` defined). The wider sandbox mode for a one-shot retry of a command the sandbox just denied — the narrowest wider mode that suffices, requiring `justification` and user approval through `ctx.approval` BEFORE execution. A non-widening or unapprovable request fails closed without running anything. |
| `justification` | string | Required with `sandbox_permissions`: one sentence for the user explaining why this exact command needs the wider access. |
`command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution. The workdir default is applied in the tool layer from the calling agent's `session.header.cwd` BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`.
@@ -28,9 +30,9 @@ The plugin also contributes the `tool:pwsh` prompt section (order 105): non-zero
Every foreground and background model pwsh call receives a freshly collected trusted `DSH_*` environment through the shared [`dsh-bash-env`](../bash-env/) registry: `DSH_HOME` (the absolute Harness home), `DSH_SHELL=1`, the agent's `DSH_SESSION_ID`, and `DSH_SESSION_JSONL` when the active persistence backend locates one. Plugins contributing `DSH_*` facts to `ctx.bashEnv` apply to pwsh calls exactly as they do to bash calls. The snapshot passes through the dedicated `BashExecRequest.dshEnv` channel; `process.env` is never modified. The description teaches the generic `$env:DSH_*` convention rather than naming persistence-specific variables.
Result text contains stdout, an optional `[stderr]` section, then applicable truncation, timeout, signal, and exit markers. A clean exit (0, no signal) produces no marker; an empty body renders as `(no output)`. Truncation links a safe complete spill file or reports it unavailable. Timeout is reported independently of final exit status; nonzero exit remains a model-interpreted result rather than `isError`. Windows reports forced termination as exit 1 without a signal, so `[killed by signal: …]` is POSIX-only there. Only infrastructure failures — spawn errors and aborts (`tool call aborted`) — produce `isError`.
Result text contains stdout, an optional `[stderr]` section, then applicable truncation, sandbox-denial (with the same-turn escalation hint when the composition advertises escalation), timeout, signal, and exit markers. A clean exit (0, no signal) produces no marker; an empty body renders as `(no output)`. Truncation links a safe complete spill file or reports it unavailable. Timeout is reported independently of final exit status; nonzero exit remains a model-interpreted result rather than `isError`. Windows reports forced termination as exit 1 without a signal, so `[killed by signal: …]` is POSIX-only there. Only infrastructure failures — spawn errors and aborts (`tool call aborted`) — produce `isError`.
The canonical success is `{ kind: 'foreground', ...BashRunResult }` for a completed foreground process or `{ kind: 'background', taskId }` for a published task. The renderer preserves exactly `started background task <id>` for background acks; programmatic consumers use the typed fields without parsing the rendered text.
The canonical success is `{ kind: 'foreground', ...BashRunResult }` for a completed foreground process (with the executor's `sandbox` facts — `mode`/`denied`, optional `enforcement`/`runnerFailed` — projected when present) or `{ kind: 'background', taskId }` for a published task. The renderer preserves exactly `started background task <id>` for background acks; programmatic consumers use the typed fields without parsing the rendered text.
When `run_in_background` is true, this plugin preflights `ctx.tasks.start()` before spawning, registers the calling agent as owner, and adapts the returned `BashProcess` handle into generic cancel/done/incremental-output hooks. The task runtime owns ids, cross-session isolation, completion notices, waiting, and disposal cleanup; this plugin only maps pwsh exit facts into task output and outcome detail. `enableRunInBackground: false` removes the parameter and rejects a forced background call at execution time.
@@ -78,7 +80,7 @@ Prefix-stable while visibility and the tool definition are unchanged. A restrict
#### What the model sees
The renderer emits the data-dependent stdout tail, then optional `[stderr]` and the stderr tail. Conditional lines are exactly `[output truncated; full output: <path>]`, `[timed out after <timeoutMs>ms]`, `[killed by signal: <signal>]`, and `[exit code: <exitCode>]` (nonzero exits only); an empty body renders as `(no output)`.
The renderer emits the data-dependent stdout tail, then optional `[stderr]` and the stderr tail. Conditional lines are exactly `[output truncated; full output: <path>]`, `[sandbox: file access denied under <mode> mode]` plus the escalation hint `[sandbox: escalation available — …]` (only when the composition advertises escalation), `[timed out after <timeoutMs>ms]`, `[killed by signal: <signal>]`, and `[exit code: <exitCode>]` (nonzero exits only); an empty body renders as `(no output)`.
#### Token effect
@@ -106,7 +108,7 @@ Append-only; newly visible content follows the reusable request prefix and does
#### What the model sees
Validation and infrastructure failures are normalized as `Error: <message>`. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got <value>`, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, and `tool call aborted`.
Validation and infrastructure failures are normalized as `Error: <message>`. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got <value>`, `invalid escalation: sandbox_permissions requires a justification`, `invalid escalation: justification is only valid together with sandbox_permissions`, `invalid justification: expected a non-empty sentence`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the shared escalation failures (not strictly wider / no approval service / no agent to route / no approval channel / user rejected / was cancelled), `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, and `tool call aborted`.
#### Token effect
@@ -118,7 +120,7 @@ Append-only; newly visible content follows the reusable request prefix and does
## Known Limitations and Deferred Work
- **No sandbox escalation** — `sandbox_permissions`/`justification` are absent; escalation waits for a Windows-confining executor (the bash tool's sandbox surface is not mirrored).
- **No persistent shell or PTY** — every call starts a fresh `pwsh -Command`; the PTY backends are Linux/macOS-only.
- **ConstrainedLanguage and named-pipe capture under the Windows sandbox** — when the [Windows ACL sandbox](../../sandbox/sandbox-windows-acl/README.md) confines a call (read-only or workspace-write), the restricted token puts pwsh into ConstrainedLanguage mode: `Add-Type`, non-core .NET statics (`[System.IO.*]::`, `[math]::`), COM objects, and reflection fail with "only core types" errors, and the mode cannot be lifted from inside. The same modes deny named-pipe opens, so a piped-stdio spawn inside a confined command fails with EPERM. The tool description teaches both contracts to the model; the backend README owns the full limitations.
- **No persistent shell or PTY** — every call starts a fresh `pwsh -Command`; the PTY backends are Linux/macOS-only today, and a Windows ConPTY persistent shell is roadmap work.
- **PowerShell-dialect contract** — the model must write PowerShell (native paths, `$env:` variables), not bash; there is no dialect translation.
- **Session-cwd identity is not canonicalized** — the workdir base is the session header cwd as-is, unlike the bash tool's sandbox-root-canonicalized identity; only the sandbox-less case applies here.
- **Session-cwd identity is not canonicalized** — the workdir base is the session header cwd as-is, unlike the bash tool's sandbox-root-canonicalized identity. Under a confining executor the policy's workspace root IS canonicalized (by the shared policy service), so the workdir and the confinement root can diverge when the raw session cwd differs from its canonical form — a parity gap deferred to the shared shell-tool base extraction.

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
注册在 `ctx.bash` 执行器 seam 之上的模型可见 `pwsh` 工具。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具约定是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。行为与 `dsh-tool-bash` 逐调用对齐、减去 sandbox 面——通过通用任务运行时执行前台与 `run_in_background`、通过共享 `bash-env` 注册表管理 `DSH_*` 环境、以及 bash 的 marker/截断渲染故事(干净退出不产生 marker
注册在 `ctx.bash` 执行器 seam 之上的模型可见 `pwsh` 工具。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具约定是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。行为与 `dsh-tool-bash` 逐调用对齐——通过通用任务运行时执行前台与 `run_in_background`、通过共享 `bash-env` 注册表管理 `DSH_*` 环境、sandbox 拒绝渲染与同轮次 `sandbox_permissions` 升级面、以及 bash 的 marker/截断渲染故事(干净退出不产生 marker
需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。
@@ -21,6 +21,8 @@
| `timeoutMs` | number | 超时覆盖值(毫秒)。执行器应用其配置的默认值与上限。 |
| `workdir` | string | 本次调用的工作目录。默认取调用 agent智能体的会话 cwd`session.header.cwd`),使每个会话在自己的工作区运行;相对 `workdir` 基于同一身份解析。 |
| `run_in_background` | boolean | 立即返回 task id不适用超时。 |
| `sandbox_permissions` | string enum | 仅当已挂载 sandbox 执行器时才会公开(`ctx.bash.sandboxMode` 已定义)。用于对刚被 sandbox 拒绝的命令做一次性重试的更宽 sandbox 模式——取刚好足够的最窄更宽模式,要求 `justification` 并在执行**之前**经 `ctx.approval` 获得用户批准。未拓宽或无法获批的请求 fail-closed不运行任何内容。 |
| `justification` | string | 必须与 `sandbox_permissions` 一同提供:用一句话向用户解释为何正是这条命令需要更宽的访问。 |
`command``workdir``timeoutMs` 在执行前经 `ctx.bash.resolve()` 按执行器配置默认值解析。workdir 默认值在工具层于 `resolve()` 之前从调用 agent 的 `session.header.cwd` 取得——每次会话的 cwd 必须来自 `exec.agent`,因为 N 个会话共享一个执行器;仅当没有会话 cwd 时执行器才回退到自己的配置 / `process.cwd()`
@@ -28,9 +30,9 @@
每次前台与后台模型 pwsh 调用都会通过共享的 [`dsh-bash-env`](../bash-env/) 注册表收到一份新收集的受信任 `DSH_*` 环境:`DSH_HOME`Harness 主目录绝对路径)、`DSH_SHELL=1`、agent 的 `DSH_SESSION_ID`,以及活跃持久化后端定位到 JSONL 时的 `DSH_SESSION_JSONL`。向 `ctx.bashEnv` 贡献 `DSH_*` 事实的插件对 pwsh 调用与 bash 调用一视同仁。快照通过专用的 `BashExecRequest.dshEnv` 通道传递;`process.env` 永不被修改。描述只教授通用的 `$env:DSH_*` 约定,而不是点名持久化相关的变量。
结果文本包含 stdout、可选的 `[stderr]`然后是适用的截断、超时、signal 与退出 marker。干净退出0、无 signal不产生 marker空体渲染为 `(no output)`。截断会链接一个安全的完整 spill 文件,或报告其不可用。超时独立于最终退出状态报告;非零退出仍是模型解读的结果而非 `isError`。Windows 上强制终止以无 signal 的 exit 1 结算,因此 `[killed by signal: …]` 在那里仅存在于 POSIX。只有基础设施失败——spawn 错误与中止(`tool call aborted`)——产生 `isError`
结果文本包含 stdout、可选的 `[stderr]` 段,然后是适用的截断、sandbox 拒绝(组合公开升级能力时带同轮次升级提示)、超时、signal 与退出 marker。干净退出0、无 signal不产生 marker空体渲染为 `(no output)`。截断会链接一个安全的完整 spill 文件,或报告其不可用。超时独立于最终退出状态报告;非零退出仍是模型解读的结果而非 `isError`。Windows 上强制终止以无 signal 的 exit 1 结算,因此 `[killed by signal: …]` 在那里仅存在于 POSIX。只有基础设施失败——spawn 错误与中止(`tool call aborted`)——产生 `isError`
规范成功形态是已完成前台进程的 `{ kind: 'foreground', ...BashRunResult }` 或已发布任务的 `{ kind: 'background', taskId }`。渲染器对后台 ack 精确保留 `started background task <id>`;编程消费者使用类型化字段而不解析渲染文本。
规范成功形态是已完成前台进程的 `{ kind: 'foreground', ...BashRunResult }`(存在时投影执行器的 `sandbox` 事实——`mode`/`denied`、可选的 `enforcement`/`runnerFailed`或已发布任务的 `{ kind: 'background', taskId }`。渲染器对后台 ack 精确保留 `started background task <id>`;编程消费者使用类型化字段而不解析渲染文本。
`run_in_background` 为 true 时,本插件在 spawn 前预检 `ctx.tasks.start()`,把调用 agent 注册为 owner并将返回的 `BashProcess` 句柄适配为通用的 cancel/done/增量输出钩子。任务运行时拥有 id、跨会话隔离、完成通知、等待与清理本插件只把 pwsh 退出事实映射进任务输出与结果明细。`enableRunInBackground: false` 会移除参数并在执行时拒绝强制的后台调用。
@@ -78,7 +80,7 @@ Non-zero exits are reported as `[exit code: N]` markers; investigate failures be
#### What the model sees
渲染器输出数据相关的 stdout 尾部,然后是可选的 `[stderr]` 与 stderr 尾部。条件行精确为 `[output truncated; full output: <path>]``[timed out after <timeoutMs>ms]``[killed by signal: <signal>]``[exit code: <exitCode>]`(仅非零退出);空体渲染为 `(no output)`
渲染器输出数据相关的 stdout 尾部,然后是可选的 `[stderr]` 与 stderr 尾部。条件行精确为 `[output truncated; full output: <path>]``[sandbox: file access denied under <mode> mode]` 加升级提示 `[sandbox: escalation available — …]`(仅当组合公开升级能力时)、`[timed out after <timeoutMs>ms]``[killed by signal: <signal>]``[exit code: <exitCode>]`(仅非零退出);空体渲染为 `(no output)`
#### Token effect
@@ -106,7 +108,7 @@ ack 是固定短行;任务输出按读取有界。
#### What the model sees
校验与基础设施失败规范化为 `Error: <message>`。本包的稳定消息包括 `invalid command: expected a non-empty string``invalid description: expected a non-empty string``invalid timeoutMs: expected a positive number, got <value>``run_in_background is disabled for this deployment (enableRunInBackground: false)``background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks``tool call aborted`
校验与基础设施失败规范化为 `Error: <message>`。本包的稳定消息包括 `invalid command: expected a non-empty string``invalid description: expected a non-empty string``invalid timeoutMs: expected a positive number, got <value>``invalid escalation: sandbox_permissions requires a justification``invalid escalation: justification is only valid together with sandbox_permissions``invalid justification: expected a non-empty sentence``sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、共享的升级失败(非严格更宽、无审批服务、无 agent 可路由、无审批通道、用户拒绝、已取消)、`run_in_background is disabled for this deployment (enableRunInBackground: false)``background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks``tool call aborted`
#### Token effect
@@ -118,7 +120,7 @@ ack 是固定短行;任务输出按读取有界。
## Known Limitations and Deferred Work
- ** sandbox 升级** — 没有 `sandbox_permissions`/`justification`;升级等待 Windows-confining 执行器bash 工具的 sandbox 面不被镜像)
- **无持久 shell 或 PTY** — 每次调用都启动全新的 `pwsh -Command`PTY 后端仅限 Linux/macOS。
- **Windows sandbox 下的 ConstrainedLanguage 与 named-pipe 捕获** — 当 [Windows ACL sandbox](../../sandbox/sandbox-windows-acl/README.md) 隔离某次调用read-only 或 workspace-write受限令牌使 pwsh 进入 ConstrainedLanguage 模式:`Add-Type`、非核心 .NET 静态调用(`[System.IO.*]::``[math]::`、COM 对象与反射都会以“only core types”错误失败且该模式无法从内部解除。这两种模式同样会拒绝 named-pipe 打开,因此受限命令内的管道 stdio spawn 以 EPERM 失败。工具描述把这两个约定教给模型;后端 README 负责完整的限制说明
- **无持久 shell 或 PTY** — 每次调用都启动全新的 `pwsh -Command`PTY 后端目前仅限 Linux/macOSWindows ConPTY 持久 shell 属于路线图工作
- **PowerShell 方言约定** — 模型必须写 PowerShell原生路径、`$env:` 变量),而不是 bash没有方言翻译。
- **会话 cwd 身份不做规范化** — workdir 基座直接取会话头 cwd 原值,不同于 bash 工具经 sandbox-root 规范化的身份;此处只涉及无 sandbox 场景
- **会话 cwd 身份不做规范化** — workdir 基座直接取会话头 cwd 原值,不同于 bash 工具经 sandbox-root 规范化的身份。在隔离执行器下,策略的工作区根**会**被规范化(由共享的策略服务完成),因此当原始会话 cwd 与其规范化形态不同时workdir 与隔离根可能不一致——这一 parity 差距留待共享 shell 工具基座提取时解决

View File

@@ -30,9 +30,12 @@
"@deepseek-ai/dsh-bash-env": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-llm": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"@deepseek-ai/dsh-sandbox-policy": "^0.0.1",
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
"@deepseek-ai/dsh-tasks": "^0.0.1",
"@deepseek-ai/dsh-tools": "^0.0.1",
"@deepseek-ai/dsh-user-approval": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"dependencies": {
@@ -46,12 +49,15 @@
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-loader-smoke": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-sandbox-policy": "workspace:^",
"@deepseek-ai/dsh-subprocess-local": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-tasks": "workspace:^",
"@deepseek-ai/dsh-tasks-local": "workspace:^",
"@deepseek-ai/dsh-tool-tasks": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@deepseek-ai/dsh-user-approval": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -4,13 +4,17 @@
* `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is
* PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables.
*
* Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface:
* foreground and `run_in_background` execution (background handles register
* with the generic `ctx.tasks` runtime), the managed `DSH_*` environment
* through the shared `bash-env` registry, and the bash marker/truncation
* rendering story. UI presentation mirrors the bash tool's too: a completed
* foreground call is a terminal card with the parsed exit-status pill, using
* the shared exit-status parse from `@deepseek-ai/dsh-bash`.
* Behavior mirrors `dsh-tool-bash` call-for-call: foreground and
* `run_in_background` execution (background handles register with the
* generic `ctx.tasks` runtime), the managed `DSH_*` environment through the
* shared `bash-env` registry, the per-call sandbox policy resolution (the
* calling session's mode and cwd travel to the confining executor), the
* sandbox-denial rendering with the same-turn escalation surface
* (`sandbox_permissions` + `justification` resolved through
* `ctx.approval`), and the bash marker/truncation rendering story. UI
* presentation mirrors the bash tool's too: a completed foreground call is
* a terminal card with the parsed exit-status pill, using the shared
* exit-status parse from `@deepseek-ai/dsh-bash`.
*
* @module @deepseek-ai/dsh-tool-pwsh
*/
@@ -19,16 +23,21 @@ import { isAbsolute, resolve as resolvePath } from 'node:path'
import type { Context } from 'cordis'
import z from 'schemastery'
import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
import type { GenericCallView, TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
import { HarnessError } from '@deepseek-ai/dsh-llm'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-system-prompt'
import type {} from '@deepseek-ai/dsh-tasks'
import type {} from '@deepseek-ai/dsh-bash-env'
import type {} from '@deepseek-ai/dsh-user-approval'
import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
import { ESCALATION_TARGETS, approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import type { BashRunResult } from '@deepseek-ai/dsh-bash'
import { parseExitStatus } from '@deepseek-ai/dsh-bash'
import { processOutcome } from './background.ts'
import { renderPwshProcessRead, renderPwshResult } from './render.ts'
import type { RenderablePwshResult } from './render.ts'
declare module '@deepseek-ai/dsh-tasks' {
interface TaskKindMap {
@@ -57,6 +66,8 @@ interface PwshToolArgs {
timeoutMs?: number
workdir?: string
run_in_background?: boolean
sandbox_permissions?: string
justification?: string
}
/** The canonical foreground result of one pwsh call (the `output.schema` value shape). */
@@ -69,6 +80,7 @@ interface PwshForegroundResult {
timeoutMs: number
stdout: { text: string; truncated: boolean; spillPath?: string }
stderr: { text: string; truncated: boolean; spillPath?: string }
sandbox?: { mode: string; denied: boolean; enforcement?: string; runnerFailed?: boolean }
}
/* jscpd:ignore-start -- minimal mirror of dsh-tool-bash's validation and execute plumbing (Agent Note). */
@@ -82,21 +94,54 @@ function validatePwshArgs(args: PwshToolArgs): void {
if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
}
// The escalation pairing (sandbox_permissions ⇔ justification, non-empty) is
// the shared rule both enforcing families validate identically.
validateEscalationArgs(args.sandbox_permissions, args.justification)
}
/* jscpd:ignore-end */
function pwshDescription(backgroundEnabled: boolean): string {
function pwshDescription(backgroundEnabled: boolean, escalationModes: readonly SandboxMode[]): string {
const background = backgroundEnabled
? 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.'
: 'Background execution is not available; long-running commands must finish within the timeout.'
return 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. '
const base = 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. '
+ 'Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — '
+ 'pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment '
+ 'variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. '
+ 'Current harness environment facts are exposed through managed `$env:DSH_*` variables; inspect them when needed. '
+ 'Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. '
+ 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
+ 'On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. '
+ background
if (escalationModes.length === 0) return base
// The CLM and named-pipe contracts below are Windows-restricted-token
// behavior, but the gate is 'any confining executor is mounted'
// (escalationModes non-empty). The conflation is safe today because every
// shipped composition pairing tool-pwsh with a confining executor is
// win32-only; a future POSIX pwsh-sandbox composition must gate both
// sentences on the platform instead (tracked in the pwsh-tool-and-executor
// Agent Note).
return base + ' Under the Windows sandbox, pwsh runs in PowerShell ConstrainedLanguage mode (read-only and '
+ 'workspace-write): prefer cmdlets and core types (`[string]`, `[datetime]`, `[regex]`, `[guid]`); '
+ '.NET static calls (`[System.IO.*]::`, `[math]::`), `Add-Type`, COM objects, and reflection fail '
+ 'with "only core types" errors. `-f` formatting, property access, and core cmdlets work. '
+ 'In the same modes, programs cannot open named pipes, so a command that captures another '
+ 'program\'s output through piped stdio (Node.js `child_process.spawn`/`exec` with the default '
+ '`stdio: \'pipe\'`) fails with EPERM, while `stdio: \'inherit\'` and `stdio: \'ignore\'` spawns '
+ 'work and PowerShell\'s own pipelines are unaffected. That EPERM is the documented boundary: '
+ 'do not retry the command another way — escalate the exact command once or restructure it to '
+ 'avoid capturing output. '
+ 'Attempting a command the sandbox may deny is safe and expected: run it and read the '
+ 'marker rather than assuming the denial. When a command is denied and a wider mode would let it '
+ 'succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry '
+ 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
+ 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
+ 'approval prompt raised by that retry is how the user consents. If the session states approval '
+ 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
+ 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
+ 'just hit; escalating up front is fine only when this session already denied the same access. '
+ 'A rejected escalation is final for that command — stop and explain, never work around '
+ 'it — but it does not forbid attempting or escalating other commands later.'
}
/**
@@ -129,6 +174,14 @@ function canonicalPwshResult(result: BashRunResult): PwshForegroundResult {
/* jscpd:ignore-start -- the canonical projection and background-handle shape mirror dsh-tool-bash's by design (Agent Note). */
stdout: output(result.stdout),
stderr: output(result.stderr),
...result.sandbox !== undefined ? {
sandbox: {
mode: result.sandbox.mode,
denied: result.sandbox.denied,
...result.sandbox.enforcement !== undefined ? { enforcement: result.sandbox.enforcement } : {},
...result.sandbox.runnerFailed !== undefined ? { runnerFailed: result.sandbox.runnerFailed } : {},
},
} : {},
}
}
@@ -139,8 +192,55 @@ const BACKGROUND_OUTPUT_PROPERTIES = {
} as const
/* jscpd:ignore-end */
/* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's apply() preamble (pwsh-tool-and-executor Agent Note). */
export function apply(ctx: Context, config: Config = {}): void {
const backgroundEnabled = config.enableRunInBackground ?? true
const defaultMode = ctx.bash.sandboxMode
const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
const sandboxPolicy: SandboxPolicyService | undefined = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
if (defaultMode !== undefined && sandboxPolicy === undefined) {
throw new Error('tool-pwsh: the mounted bash executor confines but ctx.sandboxPolicy is missing')
}
/* jscpd:ignore-end */
/** Resolve the complete standing policy for this call when a confining executor is mounted. */
const resolveSandboxPolicy = (exec: ToolExecution): SandboxExecutionPolicy | undefined =>
sandboxPolicy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
/* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's escalation resolver (pwsh-tool-and-executor Agent Note). */
/**
* Resolve a sandbox-escalation request through `ctx.approval` BEFORE
* anything executes, delegating the shared fail-closed sequence (strict
* widening, channel resolution, outcome mapping) to
* {@link approveEscalation}. This tool contributes only the composition
* guard (the fields are unadvertised without a sandboxing executor, yet
* schema validation checks advertised keys only, so an unadvertised
* `sandbox_permissions` still reaches execute) and the approval
* ingredients. The shared policy resolver is required whenever the
* executor advertises confinement, so a split composition fails at
* tool-plugin load.
*/
const approvePwshEscalation = (
mode: string,
justification: string,
exec: ToolExecution,
standingPolicy: SandboxExecutionPolicy | undefined,
): Promise<SandboxMode> => {
if (escalationModes.length === 0) {
throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)')
}
const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode
return approveEscalation(
{ requestedMode: mode, justification, effectiveMode, subject: 'command' },
{
approver: ctx.get('approval'),
agent: exec.agent,
callId: exec.callId,
toolName: 'pwsh',
signal: exec.signal,
},
)
}
/* jscpd:ignore-end */
ctx.systemPrompt.section({
name: 'tool:pwsh',
@@ -151,7 +251,8 @@ export function apply(ctx: Context, config: Config = {}): void {
ctx.tools.register(defineTool({
name: 'pwsh',
description: pwshDescription(backgroundEnabled),
description: pwshDescription(backgroundEnabled, escalationModes),
/* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's parameter surface (pwsh-tool-and-executor Agent Note). */
parameters: {
command: { type: 'string', required: true, description: 'The PowerShell command to execute.' },
description: {
@@ -166,7 +267,19 @@ export function apply(ctx: Context, config: Config = {}): void {
...backgroundEnabled ? {
run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies.' },
} : {},
...escalationModes.length > 0 ? {
sandbox_permissions: {
type: 'string' as const,
enum: [...escalationModes],
description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.',
},
justification: {
type: 'string' as const,
description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.',
},
} : {},
},
/* jscpd:ignore-end */
output: {
// The foreground result wire shape mirrors dsh-tool-bash's by contract —
// consumers of one must accept the other (see the pwsh-tool-and-executor
@@ -209,6 +322,16 @@ export function apply(ctx: Context, config: Config = {}): void {
spillPath: { type: 'string' },
},
},
sandbox: {
type: 'object',
additionalProperties: false,
properties: {
mode: { type: 'string', required: true },
denied: { type: 'boolean', required: true },
enforcement: { type: 'string' },
runnerFailed: { type: 'boolean' },
},
},
},
},
],
@@ -218,18 +341,27 @@ export function apply(ctx: Context, config: Config = {}): void {
type: 'text',
text: value.kind === 'background'
? `started background task ${value.taskId}`
: renderPwshResult(value),
: renderPwshResult(value as RenderablePwshResult, escalationModes),
}],
},
/* jscpd:ignore-start -- the execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */
async execute(args: PwshToolArgs, exec) {
validatePwshArgs(args)
// Description is display metadata; workdir defaults to the caller's session.
const standingPolicy = resolveSandboxPolicy(exec)
const approvedMode = args.sandbox_permissions !== undefined && args.justification !== undefined
? await approvePwshEscalation(args.sandbox_permissions, args.justification, exec, standingPolicy)
: undefined
const policy = approvedMode === undefined
? standingPolicy
: { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode }
const workdir = resolveWorkdir(args.workdir, exec)
const request = {
command: args.command,
...workdir !== undefined ? { workdir } : {},
...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
dshEnv: ctx.bashEnv.collect(exec),
...policy !== undefined ? { sandboxPolicy: policy } : {},
}
if (args.run_in_background === true) {
// Undeclared keys are allowed, so schema omission also needs enforcement.
@@ -241,15 +373,11 @@ export function apply(ctx: Context, config: Config = {}): void {
throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
}
// The caller owns cancellation until ctx.tasks commits detached ownership.
/* v8 ignore start -- the bash twin's branch is exercised by its sandbox-approval mid-call abort;
pwsh has no approval surface, and the tool registry's pre-dispatch abort check intercepts
already-aborted signals first, so this mirror-only guard has no reachable trigger. */
if (exec.signal.aborted) {
const error = new HarnessError('tool call aborted', TOOL_ABORTED)
error.name = 'AbortError'
throw error
}
/* v8 ignore end */
// Task preflight finishes before the starter can spawn a process.
const id = tasks.start({
kind: 'pwsh',
@@ -260,7 +388,7 @@ export function apply(ctx: Context, config: Config = {}): void {
return {
cancel: () => void proc.kill(),
done: proc.done.then(() => processOutcome(proc)),
readOutput: () => renderPwshProcessRead(proc.readOutput()),
readOutput: () => renderPwshProcessRead(proc.readOutput(), proc.sandbox, escalationModes),
}
},
})

View File

@@ -1,17 +1,20 @@
/**
* Model-facing result rendering for the pwsh tool — the PowerShell twin of
* `dsh-tool-bash`'s renderer minus the sandbox surface: stdout, a marked
* stderr section, truncation notices with spill paths, then exit-status
* markers. Non-zero exits are reported, not errored — the model decides how to
* react; only infrastructure failures (spawn errors, aborts) surface as
* isError results.
* `dsh-tool-bash`'s renderer: stdout, a marked stderr section, sandbox
* denial/runner-failure markers (with the same-turn escalation hint), and
* truncation notices with spill paths, then exit-status markers. Non-zero
* exits are reported, not errored — the model decides how to react; only
* infrastructure failures (spawn errors, aborts) surface as isError
* results.
*
* @module @deepseek-ai/dsh-tool-pwsh/render
*/
import type { BashProcessRead, CollectedOutput } from '@deepseek-ai/dsh-bash'
import type { BashProcessRead, BashSandboxInfo, CollectedOutput } from '@deepseek-ai/dsh-bash'
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
import { escalationHintMarker, sandboxDenialMarker } from '@deepseek-ai/dsh-sandbox'
/* jscpd:ignore-start -- deliberate twin of dsh-tool-bash/render.ts minus the sandbox surface (Agent Note). */
/* jscpd:ignore-start -- deliberate twin of dsh-tool-bash/render.ts (Agent Note). */
/** Append the truncation notice (with the full-output spill path) to a stream's text. */
function streamText(output: CollectedOutput): string {
@@ -27,6 +30,7 @@ export interface RenderablePwshResult {
timeoutMs: number
stdout: CollectedOutput
stderr: CollectedOutput
sandbox?: BashSandboxInfo
}
/**
@@ -34,9 +38,15 @@ export interface RenderablePwshResult {
* stderr section, then exit-status markers, matching the bash tool's story —
* a clean exit (0, no signal) produces no marker.
* @param result - the completed foreground run from the executor.
* @param escalationModes - the escalation targets this composition advertises;
* non-empty adds the same-turn escalation hint after a denial marker
* (default `[]`: no hint).
* @returns the model-facing text: output body (or `(no output)`), then any timeout/signal/exit markers, each on its own line.
*/
export function renderPwshResult(result: RenderablePwshResult): string {
export function renderPwshResult(
result: RenderablePwshResult,
escalationModes: readonly SandboxMode[] = [],
): string {
const out = streamText(result.stdout)
const err = streamText(result.stderr)
@@ -49,6 +59,14 @@ export function renderPwshResult(result: RenderablePwshResult): string {
if (body.length === 0) body = '(no output)'
const markers: string[] = []
// Keep the exit marker last because parseExitStatus anchors there.
if (result.sandbox?.denied) {
markers.push(sandboxDenialMarker(result.sandbox.mode))
// Hint only when the composition exposes escalation, before the final exit marker.
if (escalationModes.length > 0) {
markers.push(escalationHintMarker('command'))
}
}
// A command may trap the termination and exit 0 after timeout; still report interruption.
if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`)
if (result.signal !== null) {
@@ -67,14 +85,28 @@ export function renderPwshResult(result: RenderablePwshResult): string {
* sees: the incremental delta, plus the lossy-read notice (with full-stream
* spill paths) when in-memory truncation dropped unread bytes.
* @param read - one incremental read from the process handle.
* @returns the delta text with any loss notice appended.
* @param sandbox - settled sandbox facts, when this was a confined process.
* @param escalationModes - escalation targets advertised by this composition.
* @returns the delta text with any loss or sandbox notice appended.
*/
export function renderPwshProcessRead(read: BashProcessRead): string {
export function renderPwshProcessRead(
read: BashProcessRead,
sandbox?: BashSandboxInfo,
escalationModes: readonly SandboxMode[] = [],
): string {
const notices: string[] = []
if (read.lossy) {
const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((path): path is string => path !== undefined)
notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(', ') : '(unavailable)'}]`)
}
if (sandbox?.runnerFailed) {
notices.push(`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`)
} else if (sandbox?.denied) {
notices.push(sandboxDenialMarker(sandbox.mode))
if (escalationModes.length > 0) {
notices.push(escalationHintMarker('command'))
}
}
if (notices.length === 0) return read.delta
return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith('\n') ? '\n' : ''}${notices.join('\n')}`
}

View File

@@ -5,13 +5,14 @@
* text, truncation, timeout, abort, nonzero exits, background handles — so
* these tests verify the schema, argument validation, workdir derivation,
* managed `DSH_*` collection, abort translation, canonical result projection,
* rendering, background task wiring, and the UI presenters. Real-pwsh behavior
* sandbox denial rendering with the escalation surface, rendering,
* background task wiring, and the UI presenters. Real-pwsh behavior
* is pinned separately in integration.spec.ts.
*/
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import { mkdtempSync } from 'node:fs'
import { mkdtempSync, realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve as resolvePath } from 'node:path'
import { CallId } from '@deepseek-ai/dsh-llm'
@@ -22,8 +23,11 @@ import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { SessionId } from '@deepseek-ai/dsh-session'
import ApprovalService from '@deepseek-ai/dsh-user-approval'
import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
import { BashExecutor } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash'
import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh'
import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env'
import type { BashProcessRead } from '@deepseek-ai/dsh-bash'
@@ -150,9 +154,106 @@ async function setupWithTasks(toolConfig: Partial<ToolPwsh.Config> = {}, dshHome
return { ctx, bash }
}
/**
* A CONFINING fake executor (`sandboxMode` advertised): the tool must resolve
* the calling session's standing policy and stamp it on the request, exactly
* like the bash tool — the per-session sandbox-policy regression surface.
* Records each confined mode and returns scriptable sandbox facts so the
* escalation and rendering surfaces are testable without a real backend.
*/
class ConfiningFakeBash extends BashExecutor {
requests: BashExecRequest[] = []
modes: Array<string | undefined> = []
override get sandboxMode() {
return 'read-only' as const
}
override resolve(request: BashExecRequest): BashExecSpec {
this.requests.push(request)
return {
command: request.command,
workdir: request.workdir ?? process.cwd(),
timeoutMs: request.timeoutMs ?? 60_000,
stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
...request.signal ? { signal: request.signal } : {},
...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},
sandboxPolicy: request.sandboxPolicy,
}
}
override async run(spec: BashExecSpec): Promise<BashRunResult> {
this.modes.push(spec.sandboxPolicy?.mode)
return runResult('ok\n', {
sandbox: {
mode: spec.sandboxPolicy?.mode ?? 'read-only',
denied: false,
...spec.command === 'without optional sandbox facts'
? {}
: { enforcement: 'full' as const, runnerFailed: false },
},
})
}
override start(spec: BashExecSpec): BashProcess {
this.modes.push(spec.sandboxPolicy?.mode)
return fakeProcess()
}
}
/** Sandboxed composition: the shared policy service + a confining executor + the pwsh tool (+ optional approval). */
async function setupSandboxed(withApproval = false) {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(LocalTaskService)
await ctx.plugin(ToolTasks)
await ctx.plugin(BashEnvPlugin)
await ctx.plugin(SandboxPolicyService, {})
await ctx.plugin(ConfiningFakeBash)
if (withApproval) await ctx.plugin(ApprovalService)
await ctx.plugin(ToolPwsh)
const bash = ctx.bash as ConfiningFakeBash
return { ctx, bash }
}
/**
* Build a fake {@link Agent} whose session log carries the sandbox-policy
* mode-override event the escalation flow evaluates against, with an
* appendable log (the approval service records decisions through
* `session.append`).
*/
function sandboxAgent(
mode?: 'read-only' | 'workspace-write' | 'danger-full-access',
ctx?: Context,
onAppend?: (type: string) => void,
): Agent {
const events: Array<{ type: string; data?: Record<string, unknown> }> = [{ type: 'turn/start' }]
if (mode !== undefined) events.push({ type: 'sandbox/mode', data: { mode } })
const id = SessionId('sandbox-session')
return {
id,
...ctx === undefined ? {} : { ctx: ctx.plugin(() => {}).ctx },
session: {
id,
header: { version: 0, id, createdAt: 0 },
events,
append: (type: string, data: Record<string, unknown>) => {
const event = { type, data }
events.push(event)
onAppend?.(type)
return event
},
},
} as unknown as Agent
}
/**
* Build a fake {@link Agent} with the shared agent/session identity, give it a
* dedicated lifecycle fiber for `Agent.ctx`, and register it in `ctx.agents`.
* The fake session carries an empty event log (the sandbox-policy resolver
* folds the log for mode overrides, mirroring a real session).
*/
function registerFakeAgent(ctx: Context, sessionId: string): Agent {
const scopeFiber = ctx.plugin(() => {})
@@ -160,7 +261,7 @@ function registerFakeAgent(ctx: Context, sessionId: string): Agent {
const agent = {
id,
ctx: scopeFiber.ctx,
session: { id, header: { version: 0, id, createdAt: 0 } },
session: { id, header: { version: 0, id, createdAt: 0 }, events: [] },
} as unknown as Agent
ctx.agents.register(agent)
return agent
@@ -397,6 +498,203 @@ describe('execution through the bash seam', () => {
})
})
describe('per-call sandbox policy resolution', () => {
it('stamps the CALLING SESSION\'s resolved policy onto the request (session cwd, not the server launch dir)', async () => {
const { ctx, bash } = await setupSandboxed()
const sessionCwd = mkdtempSync(join(tmpdir(), 'dsh-tool-pwsh-policy-'))
const agent = registerFakeAgent(ctx, 'policy-session')
Object.assign(agent.session.header, { cwd: sessionCwd })
const result = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'say hi' }, agent)
expect(result.isError).toBe(false)
// The policy's workspace root is the session cwd canonicalized by the
// policy service (realpath + resolve), NEVER the web server's launch dir;
// the calling session's identity rides along for backend per-session state.
expect(bash.requests[0]?.sandboxPolicy).toEqual({
mode: 'read-only',
workspaceRoot: resolvePath(realpathSync.native(sessionCwd)),
sessionId: 'policy-session',
})
})
it('falls back to the deployment policy without an agent, and omits the field entirely without a confining executor', async () => {
const { ctx, bash } = await setupSandboxed()
await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'say hi' })
expect(bash.requests[0]?.sandboxPolicy).toEqual({
mode: 'read-only',
workspaceRoot: resolvePath(realpathSync.native(process.cwd())),
})
// The base FakeBash advertises no sandboxMode, so the tool must not stamp
// any policy (the executor defaulting stays the executor's own).
const plain = await setup()
await call(plain.ctx, 'pwsh', { command: 'Write-Output hi', description: 'say hi' })
expect(plain.bash.requests[0]).not.toHaveProperty('sandboxPolicy')
})
it('fails load when a confining executor has no shared sandbox-policy resolver', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(BashEnvPlugin)
await ctx.plugin(ConfiningFakeBash)
await expect(ctx.plugin(ToolPwsh)).rejects.toThrow(
'tool-pwsh: the mounted bash executor confines but ctx.sandboxPolicy is missing',
)
})
})
describe('sandbox escalation through ctx.approval', () => {
const escalate = {
command: 'Write-Output ok',
description: 'test escalation',
sandbox_permissions: 'workspace-write',
justification: 'the command needs workspace writes',
}
it('advertises the sandbox fields, the escalation clause, and the confined-mode contracts', async () => {
const { ctx } = await setupSandboxed()
const schema = ctx.tools.schemas().find(item => item.name === 'pwsh')!
const properties = schema.parameters.properties as Record<string, { enum?: string[] }>
expect(properties['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
expect(schema.description).toContain('approval prompt')
expect(schema.description).toContain('ConstrainedLanguage')
expect(schema.description).toContain('named pipes')
expect(schema.description).toContain('fails with EPERM')
for (const args of [
{ command: 'Write-Output ok', description: 'd', sandbox_permissions: 'workspace-write' },
{ command: 'Write-Output ok', description: 'd', justification: 'why' },
{ command: 'Write-Output ok', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' },
]) {
expect((await call(ctx, 'pwsh', args)).isError).toBe(true)
}
})
it('the escalation fields and the confined-mode clauses stay out of sandbox-less compositions', async () => {
const { ctx } = await setup()
const schema = ctx.tools.schemas().find(item => item.name === 'pwsh')!
expect(schema.description).not.toContain('ConstrainedLanguage')
expect(schema.description).not.toContain('named pipes')
expect(schema.description).not.toContain('sandbox_permissions')
expect(schema.parameters.properties).not.toHaveProperty('sandbox_permissions')
})
it('rejects injected escalation without a sandbox and non-widening escalation without prompting', async () => {
const plain = await setup()
expect(text(await call(plain.ctx, 'pwsh', escalate))).toContain('not available in this composition')
const { ctx } = await setupSandboxed(true)
const prompted = vi.fn()
ctx.on('approval/request', () => { prompted(); return Promise.resolve<ApprovalOutcome>('allowed-once') })
const result = await call(ctx, 'pwsh', { ...escalate, sandbox_permissions: 'workspace-write' }, sandboxAgent('workspace-write'))
expect(text(result)).toContain('not strictly wider')
expect(prompted).not.toHaveBeenCalled()
const malformed = sandboxAgent()
;(malformed.session.events as unknown as Array<{ type: string; data: { mode: string } }>).push({
type: 'sandbox/mode',
data: { mode: 'unknown-mode' },
})
expect(text(await call(ctx, 'pwsh', escalate, malformed))).toContain('not strictly wider')
})
it('fails closed when approval cannot be routed', async () => {
const withoutService = await setupSandboxed()
expect(text(await call(withoutService.ctx, 'pwsh', escalate, sandboxAgent()))).toContain('no approval service')
const withService = await setupSandboxed(true)
expect(text(await call(withService.ctx, 'pwsh', escalate))).toContain('no agent to route')
expect(text(await call(withService.ctx, 'pwsh', escalate, sandboxAgent()))).toContain('no approval channel')
})
it.each([
['rejected', 'user rejected'],
['cancelled', 'was cancelled'],
] as const)('maps an approval %s to its distinct failure', async (outcome, message) => {
const { ctx, bash } = await setupSandboxed(true)
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>(outcome))
const result = await call(ctx, 'pwsh', escalate, sandboxAgent())
expect(text(result)).toContain(message)
expect(bash.modes).toEqual([])
})
it('runs a granted foreground or background call under the approved mode', async () => {
const { ctx, bash } = await setupSandboxed(true)
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const agent = sandboxAgent(undefined, ctx)
ctx.agents.register(agent)
const foreground = await ctx.tools.execute({
callId: CallId('sandbox-signal'),
name: 'pwsh',
arguments: escalate,
agent,
signal: new AbortController().signal,
})
expect(foreground.isError).toBe(false)
const background = await call(ctx, 'pwsh', { ...escalate, run_in_background: true }, agent)
expect(text(background)).toBe('started background task pwsh-1')
expect(bash.modes).toEqual(['workspace-write', 'workspace-write'])
})
it('does not publish detached work when cancellation follows the escalation grant', async () => {
const { ctx, bash } = await setupSandboxed(true)
const controller = new AbortController()
const agent = sandboxAgent(undefined, ctx, (type) => {
if (type === 'approval/decided') controller.abort()
})
ctx.agents.register(agent)
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const start = vi.spyOn(bash, 'start')
const result = await ctx.tools.execute({
callId: CallId('cancelled-escalation-background'),
name: 'pwsh',
arguments: { ...escalate, run_in_background: true },
agent,
signal: controller.signal,
})
expect(result.error).toEqual({
message: 'tool call aborted',
info: { name: 'AbortError', code: TOOL_ABORTED },
})
expect(text(result)).toBe('Error: tool call aborted')
expect(start).not.toHaveBeenCalled()
})
it('uses the session override for ordinary calls and evaluates widening against it', async () => {
const { ctx, bash } = await setupSandboxed(true)
const agent = sandboxAgent('workspace-write')
await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'ordinary' }, agent)
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
await call(ctx, 'pwsh', { ...escalate, sandbox_permissions: 'danger-full-access' }, agent)
expect(bash.modes).toEqual(['workspace-write', 'danger-full-access'])
})
it('omits sandbox facts the executor did not acquire from the canonical result', async () => {
const { ctx } = await setupSandboxed()
const result = await call(ctx, 'pwsh', {
command: 'without optional sandbox facts',
description: 'exercise optional sandbox facts',
})
if (result.isError) throw new Error('expected foreground pwsh success')
expect(result.value).toMatchObject({
kind: 'foreground',
sandbox: { mode: 'read-only', denied: false },
})
expect((result.value as { sandbox: object }).sandbox).not.toHaveProperty('enforcement')
expect((result.value as { sandbox: object }).sandbox).not.toHaveProperty('runnerFailed')
})
it('keeps the exhaustiveness backstop for a rogue approval implementation', async () => {
const { ctx } = await setupSandboxed(true)
ctx.approval.request = () => Promise.resolve('rogue' as ApprovalOutcome)
const result = await call(ctx, 'pwsh', escalate, sandboxAgent())
expect(text(result)).toContain('unreachable variant in EscalationOutcome')
})
})
describe('background execution through the task runtime', () => {
it('run_in_background acks with the task id, readable through the REAL task_output tool', async () => {
const { ctx } = await setupWithTasks()
@@ -641,6 +939,35 @@ describe('UI presentation', () => {
})
})
describe('renderPwshResult sandbox markers', () => {
const base = {
exitCode: 0,
signal: null,
timedOut: false,
timeoutMs: 1000,
stdout: { text: 'out\n', truncated: false },
stderr: { text: '', truncated: false },
}
it('a denied run reports the denial marker before the exit marker', () => {
expect(renderPwshResult({ ...base, exitCode: 2, sandbox: { mode: 'read-only', denied: true } }))
.toBe('out\n[sandbox: file access denied under read-only mode]\n[exit code: 2]')
})
it('hints only when the composition advertises escalation', () => {
const denied = { ...base, sandbox: { mode: 'read-only' as const, denied: true } }
expect(renderPwshResult(denied, ['workspace-write'])).toBe(
'out\n[sandbox: file access denied under read-only mode]\n'
+ '[sandbox: escalation available — retry this exact command once with sandbox_permissions '
+ '(the narrowest wider mode that suffices) + justification; the approval prompt asks the user]',
)
})
it('a confined run without a denial adds no sandbox marker', () => {
expect(renderPwshResult({ ...base, sandbox: { mode: 'read-only', denied: false } })).toBe('out\n')
})
})
describe('renderPwshProcessRead', () => {
const base: BashProcessRead = { delta: 'out\n', lossy: false }
@@ -677,6 +1004,20 @@ describe('renderPwshProcessRead', () => {
expect(renderPwshProcessRead({ delta: 'tail\n', lossy: true }))
.toBe('tail\n[some output was dropped from memory; full output: (unavailable)]')
})
it('appends the runner-failed notice (denial outranked)', () => {
expect(renderPwshProcessRead({ delta: 'x', lossy: false }, { mode: 'read-only', denied: true, runnerFailed: true }))
.toBe('x\n[sandbox: the sandbox runner itself failed under read-only mode — the command did not run; this is a sandbox problem, not a command failure]')
})
it('appends the denial marker and hints only when escalation is advertised', () => {
expect(renderPwshProcessRead({ delta: 'x', lossy: false }, { mode: 'read-only', denied: true }))
.toBe('x\n[sandbox: file access denied under read-only mode]')
expect(renderPwshProcessRead({ delta: 'x', lossy: false }, { mode: 'read-only', denied: true }, ['workspace-write']))
.toBe('x\n[sandbox: file access denied under read-only mode]\n'
+ '[sandbox: escalation available — retry this exact command once with sandbox_permissions '
+ '(the narrowest wider mode that suffices) + justification; the approval prompt asks the user]')
})
})
describe('processOutcome', () => {

View File

@@ -38,6 +38,18 @@
{
"path": "../../core/system-prompt"
},
{
"path": "../../bash/bash-env"
},
{
"path": "../../interaction/user-approval"
},
{
"path": "../../sandbox/sandbox"
},
{
"path": "../../sandbox/sandbox-policy"
},
{
"path": "../../support/invariants"
}

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/bundle/base/README.md
README.md: fb003908a262dc21edd3c9d49c972e487534f367
README.zh.md: 13e64db6d34374fac63bf9bfd60544fc46b86f35
README.md: 2a87b01ad4819750a58163f8c472e61ea633588e
README.zh.md: dc79895355546812aa3371487190724f169c6260

View File

@@ -4,6 +4,8 @@ English | [中文](README.zh.md)
The shared dsh core as a profile bundle: [`cordis.patch.yml`](cordis.patch.yml) inserts every base plugin row — model adapters, the shared [`agent-default-model`](../../core/agent-default-model/README.md) selection, tools, persistence, policy, settings/credentials, repository Plugins, telemetry — over the empty profile root, as the first layer of every profile's `dsh.profile.bundles` list. Later bundle layers (e.g. [`dsh-web-app`](../web-app/README.md)) and the user's profile `cordis.patch.yml` override these rows by id; a patch replaces a row's whole `config`, so mode-specific values live in mode bundles, not here. The package has no runtime API; the profile composer resolves the patch through the `dsh.bundle.patch` manifest field, never through code.
Windows hosts booting a shipped profile additionally receive [`windows.cordis.patch.yml`](windows.cordis.patch.yml): it disables the POSIX-only bash stack (`bash-sandbox`/`tool-bash`) and inserts the sandbox-confined PowerShell stack (`@deepseek-ai/dsh-pwsh-sandbox`, `@deepseek-ai/dsh-tool-pwsh`). The permission surface stays exactly as on POSIX: `sandbox`/`sandbox-policy` enforce the file-effect policy through the Windows ACL restricted-token runner (the win32 chain of `dsh-sandbox-local``@deepseek-ai/dsh-sandbox-windows-acl`), the permission switcher and the approval service run unchanged, and `fs-sandbox` keeps fencing `ctx.fs` writes — mounting `dsh-fs-local` alongside it would double-register `ctx.fs` and fail the load. The launcher applies the layer between the bundle layers and the user layers on win32 hosts; a Windows host that prefers the unconfined local pwsh executor or full access overrides these rows through its profile or home `cordis.patch.yml` (the bash-restore recipe must be complete: disable `pwsh-sandbox`/`tool-pwsh` AND re-enable `bash-sandbox`/`tool-bash` — both executor families register the same `bash` service, so an incomplete recipe fails loud at load). POSIX hosts never receive it.
The row set and its rationale are documented inline in the patch file; the [generated composition graph](../../../apps/cli/composition.md) renders it.
## Model Experience
@@ -17,3 +19,4 @@ None directly; each inserted row's package owns its effect.
## Known Limitations and Deferred Work
- **A patch replaces whole row configs** — profile overrides must restate every field a row keeps; there is no deep-merge layer.
- **The Windows temp grant is a private per-session subdirectory** — `workspace-write` confines writes to the workspace plus the session's own temp subdirectory (`<temp>\dsh-<hash>`, TMP/TEMP rewritten for confined children); `read-only` grants nothing. See `@deepseek-ai/dsh-sandbox-windows-acl`.

View File

@@ -4,6 +4,8 @@
以 profile 组合包形式交付的共享 dsh 核心:[`cordis.patch.yml`](cordis.patch.yml) 在空的 profile 根之上插入全部基础插件行——模型适配器、共享的 [`agent-default-model`](../../core/agent-default-model/README.md) 选择、工具、持久化、策略、settingscredentials、repository 插件、遥测——作为每个 profile 的 `dsh.profile.bundles` 列表中的第一层。后续的组合包层(例如 [`dsh-web-app`](../web-app/README.md))和用户 profile 的 `cordis.patch.yml` 按 id 覆盖这些行patch 会替换目标行的整个 `config`,因此模式专属的值放在各模式组合包中,而不是这里。该包没有运行时 APIprofile 组合器通过 manifest元数据清单`dsh.bundle.patch` 字段解析 patch绝不通过代码。
启动交付 profile 的 Windows 主机还会额外收到 [`windows.cordis.patch.yml`](windows.cordis.patch.yml):它禁用仅 POSIX 的 bash 栈(`bash-sandbox`/`tool-bash`),并插入沙盒受限的 PowerShell 栈(`@deepseek-ai/dsh-pwsh-sandbox``@deepseek-ai/dsh-tool-pwsh`)。权限面与 POSIX 完全一致:`sandbox`/`sandbox-policy` 通过 Windows ACL 受限令牌 runner`dsh-sandbox-local` 的 win32 链 → `@deepseek-ai/dsh-sandbox-windows-acl`)执行文件效果策略,权限切换器与 approval 服务原样运行,`fs-sandbox` 继续围栏 `ctx.fs` 写入——在其旁再挂载 `dsh-fs-local` 会重复注册 `ctx.fs` 并在加载时失败。启动器在 win32 主机上把该层应用于 bundle 层与用户层之间;偏好不限权本地 pwsh 执行器或完整访问的 Windows 主机通过其 profile 或 home 的 `cordis.patch.yml` 覆盖这些行bash 恢复配方必须完整:禁用 `pwsh-sandbox`/`tool-pwsh` 并重新启用 `bash-sandbox`/`tool-bash`——两个执行器家族注册同一个 `bash` 服务,配方不完整会在加载时 fail loud。POSIX 主机永远不会收到它。
行集合及其设计依据以行内注释写在 patch 文件里;[生成的组合图](../../../apps/cli/composition.md)负责渲染它。
## 模型体验
@@ -17,3 +19,4 @@
## 已知限制与延期工作
- **patch 会替换整行 `config`**profile 覆盖必须重述该行需要保留的每个字段;不存在深度合并层。
- **Windows 的临时目录授权是按会话的私有子目录**——`workspace-write` 把写入限制在工作区与会话自己的 temp 子目录(`<temp>\dsh-<hash>`,受限子进程的 TMP/TEMP 被改写);`read-only` 不授予任何写入。见 `@deepseek-ai/dsh-sandbox-windows-acl`

View File

@@ -65,7 +65,7 @@
- id: agent
name: '@deepseek-ai/dsh-agent'
# The transport-independent default for Agents created by front doors.
# The transport-independent default for Agents created by entry points.
# Settings may supply a saved selection; consumers read it at creation time.
- id: agent-default-model
name: '@deepseek-ai/dsh-agent-default-model'

View File

@@ -16,6 +16,7 @@
"default": "./lib/invariant.js"
},
"./cordis.patch.yml": "./cordis.patch.yml",
"./windows.cordis.patch.yml": "./windows.cordis.patch.yml",
"./src/*": "./src/*",
"./package.json": "./package.json"
},
@@ -23,6 +24,7 @@
"lib/index.js",
"lib/invariant.js",
"cordis.patch.yml",
"windows.cordis.patch.yml",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
@@ -47,6 +49,7 @@
"@deepseek-ai/dsh-compact-basic": "workspace:^",
"@deepseek-ai/dsh-compact-tool-result-prune": "workspace:^",
"@deepseek-ai/dsh-credentials-local": "workspace:^",
"@deepseek-ai/dsh-fs-local": "workspace:^",
"@deepseek-ai/dsh-fs-policy": "workspace:^",
"@deepseek-ai/dsh-fs-sandbox": "workspace:^",
"@deepseek-ai/dsh-goal": "workspace:^",
@@ -58,6 +61,7 @@
"@deepseek-ai/dsh-llm-retry": "workspace:^",
"@deepseek-ai/dsh-permission": "workspace:^",
"@deepseek-ai/dsh-plan-mode": "workspace:^",
"@deepseek-ai/dsh-pwsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-repeat-tool-guard": "workspace:^",
"@deepseek-ai/dsh-repository-plugin": "workspace:^",
"@deepseek-ai/dsh-sandbox-local": "workspace:^",
@@ -88,6 +92,7 @@
"@deepseek-ai/dsh-tool-fs": "workspace:^",
"@deepseek-ai/dsh-tool-fs-search": "workspace:^",
"@deepseek-ai/dsh-tool-goal": "workspace:^",
"@deepseek-ai/dsh-tool-pwsh": "workspace:^",
"@deepseek-ai/dsh-tool-ralph": "workspace:^",
"@deepseek-ai/dsh-tool-skill": "workspace:^",
"@deepseek-ai/dsh-tool-str-replace-editor": "workspace:^",

View File

@@ -13,13 +13,51 @@ import { entryListSchema } from '@cordisjs/plugin-include'
describe('dsh-base bundle', () => {
it('declares a parseable patch list through the dsh.bundle.patch manifest field', () => {
const root = fileURLToPath(new URL('..', import.meta.url))
const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { dsh?: { bundle?: { patch?: string } } }
const manifest = JSON.parse(
readFileSync(resolve(root, 'package.json'), 'utf8'),
) as { dsh?: { bundle?: { patch?: string } } }
expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml')
const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'), { schema: entryListSchema })
const parsed = yaml.load(
readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'),
{ schema: entryListSchema },
)
expect(Array.isArray(parsed)).toBe(true)
// The base layer is one insert list over the empty profile root.
const rows = (parsed as { insert?: { id?: string }[] }[]).flatMap(patch => patch.insert ?? [])
const rows = (parsed as { insert?: { id?: string }[] }[]).flatMap(
patch => patch.insert ?? [],
)
expect(rows.length).toBeGreaterThan(50)
expect(rows.some(row => row.id === 'agent-loop')).toBe(true)
})
it('ships the Windows platform layer as the confined pwsh roster over the ACL runner chain', () => {
const root = fileURLToPath(new URL('..', import.meta.url))
const parsed = yaml.load(
readFileSync(resolve(root, 'windows.cordis.patch.yml'), 'utf8'),
{ schema: entryListSchema },
) as {
id?: string
disabled?: boolean
insert?: { id?: string; name?: string }[]
config?: { policy?: string }
}[]
const disables = parsed
.filter(patch => patch.disabled === true)
.map(patch => patch.id)
// Only the POSIX bash stack is disabled: the Windows roster confines the
// pwsh executor through the ACL runner chain, so the sandbox/policy rows,
// the permission switcher, fs-sandbox, and the approval service all stay
// enabled exactly as on POSIX — only the shell is swapped.
expect(disables).toEqual(['bash-sandbox', 'tool-bash'])
const inserted = parsed
.flatMap(patch => patch.insert ?? [])
.map(row => row.id)
expect(inserted).toEqual(['pwsh-sandbox', 'tool-pwsh'])
// The patch no longer touches the permission/approval surface at all.
expect(parsed.find(patch => patch.id === 'approval')).toBeUndefined()
expect(parsed.find(patch => patch.id === 'permission')).toBeUndefined()
expect(parsed.find(patch => patch.id === 'sandbox')).toBeUndefined()
expect(parsed.find(patch => patch.id === 'sandbox-policy')).toBeUndefined()
expect(parsed.find(patch => patch.id === 'fs-sandbox')).toBeUndefined()
})
})

View File

@@ -0,0 +1,31 @@
# The dsh-base Windows platform layer: applied by the dsh launcher on win32
# hosts, between the bundle layers and the user layers. Windows confines
# through the ACL restricted-token runner (the win32 chain of
# dsh-sandbox-local → @deepseek-ai/dsh-sandbox-windows-acl), so the shipped
# stack is the SANDBOXED PowerShell executor plus the full permission
# surface: sandbox/sandbox-policy enforce the file-effect policy, the
# permission switcher and the approval service run exactly as on POSIX, and
# the fs row stays the base's sandboxed provider (fs-sandbox) — mounting
# dsh-fs-local alongside it would double-register ctx.fs and fail the load.
# Only the POSIX bash
# stack (bash-sandbox/tool-bash) is disabled — bash has no Windows runner.
# A Windows host that prefers the unconfined local pwsh executor or full
# access overrides these rows through its profile or home cordis.patch.yml.
# The bash-restore recipe must be complete: disable pwsh-sandbox and
# tool-pwsh AND re-enable bash-sandbox and tool-bash — both executor
# families register the same 'bash' service, so re-enabling the bash rows
# while pwsh-sandbox stays inserted fails loud at load on a duplicate
# registration.
- id: bash-sandbox
disabled: true
- id: tool-bash
disabled: true
- insert:
- id: pwsh-sandbox
name: '@deepseek-ai/dsh-pwsh-sandbox'
- id: tool-pwsh
name: '@deepseek-ai/dsh-tool-pwsh'

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/client/ui-conversation/README.md
README.md: b57f88b5a030a6c20c957e26ea32fb125f106ab4
README.zh.md: a8a8c4814086cad02c5416078f242ec92a7503d7
README.md: f684f99c9e80a02e3ccad57c9a4d7246df0b192b
README.zh.md: 61c746e35d3a221d34cf9e830a63ce5d8fa0dbfd

View File

@@ -32,7 +32,7 @@ The chat flow projects consecutive model-retry nodes across retry turns into one
The Host's placement-aware `session/queue` snapshot also carries pending steering. QueueDock filters it out, while ChatView projects it as a user-style bubble with Copy at the conversation tail; non-user next-step items (injected context) carry the `context` placement instead and render nowhere until claimed. Fork is absent here as on every user-style bubble. The Host delays steering retirement until the durable `user/message` carrying the steering has entered the mux stream. On that accepted live event, the client runtime retires the first matching current steering occurrence before publishing the snapshot; historical events cannot hide later occurrences that reuse the same `MessageId`. The bubble therefore hands off without a gap or duplicate, immediately restores Copy and the clock from the durable node — a steering bubble, like a user bubble, carries no branch action ([decision](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md)) — and survives reconnect from the same authority.
Keyboard message submission resolves delivery from the addressed session's running state and steering capability. While idle, Enter and Cmd/Ctrl+Enter both perform an ordinary Queue send. While a primary session is running, the browser-persisted General Settings preference assigns plain Enter to `Queue` (the default) or `Steer`, and Cmd/Ctrl+Enter performs the other behavior; Shift+Enter remains a newline. Addressed subagents keep both gestures on their Queue-only continuation transport even while running. The preference affects only the steer-capable busy-state gesture pair, and the send button and non-keyboard submit actions remain Queue. Composer Steer uses the existing best-effort `session.prompt(mode: 'steer')` contract: if the current next-step window closes before acceptance, AgentLoop admits the message as the next waking Queue turn without surfacing a failure or losing the draft transaction.
Keyboard message submission resolves delivery from the addressed session's running state and steering capability. While idle, Enter and Cmd/Ctrl+Enter both perform an ordinary Queue send. While a primary session is running, the browser-persisted General Settings preference assigns plain Enter to `Queue` (the default) or `Steer`, and Cmd/Ctrl+Enter performs the other behavior; Shift+Enter remains a newline. With an empty draft, Cmd/Ctrl+Enter instead steers every still-pending queued message into the running turn in FIFO order (the dock's per-row strict-steer action applied to the whole queue); plain Enter with an empty draft remains a no-op. While this whole-queue gesture is available, the textarea placeholder advertises it; a placeholder supplied by the owning surface still takes precedence. Addressed subagents keep both gestures on their Queue-only continuation transport even while running. The preference affects only the steer-capable busy-state gesture pair, and the send button and non-keyboard submit actions remain Queue. Composer Steer uses the existing best-effort `session.prompt(mode: 'steer')` contract: if the current next-step window closes before acceptance, AgentLoop admits the message as the next waking Queue turn without surfacing a failure or losing the draft transaction.
Per-session UI state for selection and the active view lives in the declared chat store (`stores.ts` `createChatStore`); the InputHub owns the composer state machine and mirrors its draft into that store for persistence. Apply passes one store handle to the strict session subtree, chat view, and details registrations, so each session shares one instance and the framework owns its lifecycle. Components are pure: the framework standard kit supplies `useSession`/`sessionId`, global `useSessions`/`useWorkspaces`, and the input machine's `useInput`/`inputActions`; store faces and inject factories supply the remaining state and callbacks.

View File

@@ -32,7 +32,7 @@ Think 行默认保持折叠,并在不展开思维链的情况下暴露实时
Host 带 placement 的 `session/queue` 快照也会携带待处理 steering。QueueDock 会将其过滤掉ChatView 则把它投影为会话流末尾带复制操作的用户样式气泡;非用户来源的 next-step 项(注入上下文)改以 `context` placement 广播,领取前不在任何界面渲染。与所有用户样式气泡一样,这里不显示 fork。Host 会等携带该 steering 的持久 `user/message` 进入 mux 流之后再退役 steering。客户端运行时接纳该实时事件时会在发布快照前退役第一个匹配的当前 steering 单次入队项;历史事件无法隐藏后来复用同一 `MessageId` 的单次入队项。气泡交接时因而不会产生空档或重复会立即从持久节点恢复复制操作与时钟——steering 气泡与 user 气泡一样不带分支操作([决策](../../../.agents/notes/implemented/simplification/2026-08-06-user-bubbles-drop-the-branch-action.md))——并能在重连后从同一权威恢复。
键盘消息提交会根据所寻址会话的运行状态和 steering 能力解析投递方式。空闲时Enter 和 Cmd/Ctrl+Enter 都执行普通 Queue 发送。主会话运行期间,浏览器持久化的 General Settings 偏好会把普通 Enter 分配为 `Queue`(默认值)或 `Steer`Cmd/Ctrl+Enter 则执行另一种行为Shift+Enter 仍然换行。已寻址 subagent 即使正在运行,也会让这两个手势都使用其仅支持 Queue 的继续执行传输。该偏好只影响支持 steering 的繁忙态手势对,发送按钮与非键盘提交操作仍使用 Queue。Composer Steer 复用现有尽力而为的 `session.prompt(mode: 'steer')`:如果当前 next-step 窗口在接纳前关闭AgentLoop 会把消息接纳为下一条唤醒 Queue 轮次,不显示失败,也不会丢失草稿事务。
键盘消息提交会根据所寻址会话的运行状态和 steering 能力解析投递方式。空闲时Enter 和 Cmd/Ctrl+Enter 都执行普通 Queue 发送。主会话运行期间,浏览器持久化的 General Settings 偏好会把普通 Enter 分配为 `Queue`(默认值)或 `Steer`Cmd/Ctrl+Enter 则执行另一种行为Shift+Enter 仍然换行。草稿为空时Cmd/Ctrl+Enter 改为按 FIFO 顺序把仍在排队的消息全部插话进运行中的轮次(把 dock 的逐条严格 steer 操作应用于整个队列);空草稿 + 普通 Enter 仍是无操作。这个整队列手势可用时,文本框 placeholder 会提示该手势owner 提供的 placeholder 仍然优先。已寻址 subagent 即使正在运行,也会让这两个手势都使用其仅支持 Queue 的继续执行传输。该偏好只影响支持 steering 的繁忙态手势对,发送按钮与非键盘提交操作仍使用 Queue。Composer Steer 复用现有尽力而为的 `session.prompt(mode: 'steer')` 约:如果当前 next-step 窗口在接纳前关闭AgentLoop 会把消息接纳为下一条唤醒 Queue 轮次,不显示失败,也不会丢失草稿事务。
逐 Session UI 状态中的选择与活跃视图位于已声明的聊天 store`stores.ts` `createChatStore`InputHub 拥有输入区状态机,并将草稿镜像到该 store 以便持久化。apply 将同一个 store handle 传给严格限定于会话的子树、聊天视图和详情注册,因此每个会话内共享一个实例,框架拥有其生命周期。组件保持纯粹:框架标准工具包提供 `useSession``sessionId`、全局 `useSessions``useWorkspaces`,以及输入状态机的 `useInput``inputActions`store 表层与 inject factory 提供其余状态和回调。

View File

@@ -159,7 +159,7 @@ export function apply(ctx: Context): void {
// The per-session input machine registry (InputService face; published as
// ctx.conversation.input by the service below sharing this one instance).
const inputHub = new InputHub(ctx)
const inputHub = new InputHub(ctx, t)
// The composer-block registry: a plugin that knows a session cannot send —
// ui-model, when no adapter serves the session's route — raises a block

View File

@@ -104,6 +104,12 @@ export interface ComposerKeyboard {
setDraft(text: string, editRange?: EditRange): void
/** Submit with an explicit delivery mode resolved by the keyboard policy. */
submit(mode: InputSubmitMode): void
/**
* Steer every still-pending queued message into the running turn (the
* empty-draft accelerated-Enter gesture; the queue dock's per-row steer
* button is the same operation applied to the whole queue).
*/
steerQueue(): void
undo(): void
redo(): void
/** Paste over the selection (sync components ride the same transaction). */

View File

@@ -39,6 +39,11 @@ export interface SessionInputDeps {
popup?: (() => PopupDismissFace | undefined) | undefined
/** Queue read face; overlaid onto InputState.queue (absent = empty). */
queue?: ObservableSnapshot<readonly QueuedMessage[]> | undefined
/**
* Steer every still-pending queued message into the running turn, in FIFO
* order (the empty-draft accelerated-Enter gesture); absent = unsupported.
*/
steerQueue?: (() => void) | undefined
/** The plain-message sink (send choreography / materialize fork — the hub owns it). */
defaultSink(text: string, imageIds: readonly DraftAttachmentId[], mode: InputSubmitMode): void
}
@@ -223,6 +228,16 @@ export class SessionInputShell implements SessionInput {
return this.deps.slash?.()?.arbitrate(key, composing) ?? 'pass'
}
/**
* Steer every still-pending queued message into the running turn (the
* empty-draft accelerated-Enter gesture). Execution belongs to the hub's
* queue choreography; absent dep = the gesture falls back to the machine's
* empty-draft no-op.
*/
steerQueue(): void {
this.deps.steerQueue?.()
}
/**
* Space adjudication over the controller's hot state.
* @returns true = a claim/insert was applied — the caller preventDefaults.

View File

@@ -10,6 +10,7 @@
*/
import type { ClientContext, ISessions, SessionBinding, SessionFace, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import type { SlashController } from '@deepseek-ai/dsh-client-ui-slash/client'
import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client'
import { queueReadFaceOf } from '../queue/store.ts'
import type { ComposerKeyboard, DraftAttachmentId, InputService, SessionInput } from './contract.ts'
import type { InputSubmitMode } from '../contract/composer-submission.ts'
@@ -36,8 +37,14 @@ interface ConversationAttachmentFace {
export class InputHub implements InputService {
private readonly shells = new Map<SessionId, SessionInputShell>()
/** @param ctx - client root context (services resolved lazily per call — boot order stays free). */
constructor(private readonly rootCtx: ClientContext) {}
/**
* @param ctx - client root context (services resolved lazily per call — boot order stays free).
* @param t - conversation-namespace translate thunk (reads the active locale at call time).
*/
constructor(
private readonly rootCtx: ClientContext,
private readonly t: TranslateNS<'conversation'>,
) {}
/**
* Resolve the facade for one session-scope ctx (InputService face).
@@ -69,6 +76,7 @@ export class InputHub implements InputService {
popup: () => this.popup(actx),
queue: queueReadFaceOf(session),
defaultSink: (text, imageIds, mode) => { this.sink(session, text, imageIds, mode) },
steerQueue: () => { void this.steerQueue(session, shell) },
})
this.shells.set(id, shell)
// The one teardown axis: listeners, shell, and map entries all ride the
@@ -159,6 +167,30 @@ export class InputHub implements InputService {
})
}
/**
* Steer every still-pending queued message into the running turn, in FIFO
* order — the same strict-steer operation as the queue dock's per-row
* button. A turn closing mid-way (`steer-unavailable`) or a row already
* claimed by the agent (`queue-item-not-found`) converges silently, while a
* genuine failure surfaces as one composer notice. Repeated triggers
* (e.g. two rapid empty-draft chords) rely on that `queue-item-not-found`
* convergence: the snapshot may still list a row the host already steered,
* and the duplicate strict steer is a silent no-op.
* @param session - the addressed host session.
* @param shell - the resident shell (notice outlet).
*/
private async steerQueue(session: SessionFace, shell: SessionInputShell): Promise<void> {
const queued = session.getSnapshot().queue.filter(item => item.placement === 'queued')
if (queued.length === 0) return
for (const item of queued) {
const result = await session.updateQueue(item.id, { kind: 'steer' })
if (result.ok) continue
if (result.error.code === 'steer-unavailable' || result.error.code === 'queue-item-not-found') return
shell.notify('error', this.t('queue.steerFailed'))
return
}
}
private controller(actx: ClientContext): SlashController | undefined {
const slash = this.rootCtx.get('slash')
return slash?.sessionOf(actx)

View File

@@ -23,6 +23,7 @@ export const zh = {
'input.commands': '命令',
'input.stop': '停止生成',
'input.send': '发送消息',
'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息',
'input.accessMode': '访问模式,当前:{name}',
'image.dropHint': '松开以添加图片',
'image.pending': '待发送图片',
@@ -180,6 +181,7 @@ export const en = {
'input.commands': 'Commands',
'input.stop': 'Stop generating',
'input.send': 'Send message',
'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages',
'input.accessMode': 'Access mode, current: {name}',
'image.dropHint': 'Drop to add images',
'image.pending': 'Pending images',

View File

@@ -109,6 +109,8 @@ export function InputBar({
// be disabled do lock it — there is no session to choose a model for.
const modelSeatLocked = removed || inert || !live
const machineBusy = input?.phase === 'adjudicating' || input?.phase === 'submitting'
const canSteerQueue = !locked && !machineBusy && !commandMenuOpen && empty && running && subagent === null
&& input.queue.some(row => row.placement === 'queued')
useEffect(() => {
if (input === undefined || inputActions === undefined) return
@@ -278,9 +280,19 @@ export function InputBar({
e.preventDefault()
if (e.repeat) return // held-down Enter must not machine-gun sends
if (locked || machineBusy) return
const accelerated = e.ctrlKey || e.metaKey
// Empty-draft accelerated Enter acts on the queue instead of the (empty)
// draft: the machine rejects empty drafts, so the gesture steers every
// still-pending queued message into the running turn (the dock's per-row
// steer button applied to the whole queue). Steering needs the same
// window as the per-row button: a running ordinary session.
if (accelerated && canSteerQueue) {
keyboard.steerQueue()
return
}
keyboard.submit(resolveSubmitMode(
running,
e.ctrlKey || e.metaKey ? 'accelerated' : 'enter',
accelerated ? 'accelerated' : 'enter',
subagent === null,
))
}
@@ -585,7 +597,12 @@ export function InputBar({
? t('placeholder.parentOffline')
: disabled
? t('placeholder.unavailable')
: planActive ? t('placeholder.plan') : t('placeholder.default'))}
// The steer hint deliberately outranks the plan placeholder:
// while it shows, the whole-queue gesture is genuinely available
// (the gate never consults plan mode), so the actionable hint wins.
: canSteerQueue
? t('placeholder.steerQueue')
: planActive ? t('placeholder.plan') : t('placeholder.default'))}
rows={2}
onChange={(event) => {
setDropError(null)

View File

@@ -59,6 +59,10 @@ interface BenchOptions {
subagent?: Exclude<ConversationSnapshot['subagent'], null>
disabled?: boolean
promptError?: ConversationSnapshot['promptError']
/** Authoritative queue rows served to the machine overlay (empty = none). */
queue?: ConversationSnapshot['queue']
/** The hub's steer-all face (empty-draft accelerated Enter). */
steerQueue?: () => void
variant?: 'hero' | 'composer'
placeholder?: string
t?: InputBarProps['t']
@@ -74,14 +78,34 @@ interface BenchOptions {
toggleCommandMenu?: (selection: { start: number; end: number }) => void
}
/** One pending queue row (the runtime snapshot shape, as the dock tests build it). */
function row(id: string): ConversationSnapshot['queue'][number] {
return {
id: id as never, messageId: `message-${id}` as never, placement: 'queued',
content: [{ type: 'text', text: id }], preview: id, text: id,
}
}
/** Real machine behind the bar entry: sink spy, no slash pipeline (plain text goes straight to the sink). */
function bench(over?: BenchOptions) {
const sink = vi.fn()
const lex = over?.lexicon
const session = createSnapshotStore<ConversationSnapshot>(snapshotOf({
running: over?.running ?? false,
subagent: over?.subagent ?? null,
removed: over?.disabled ?? false,
promptError: over?.promptError ?? null,
queue: over?.queue ?? [],
}))
type ShellDeps = ConstructorParameters<typeof SessionInputShell>[0]
const shell = new SessionInputShell({
actx: SCTX,
defaultSink: sink,
queue: {
getSnapshot: () => session.getSnapshot().queue,
subscribe: fn => session.subscribe(fn),
},
...(over?.steerQueue !== undefined ? { steerQueue: over.steerQueue } : {}),
// Lexicon-only stub: adjudication untouched (undefined slash methods are
// never reached — these benches drive plain-draft flows only).
...(lex !== undefined
@@ -94,12 +118,6 @@ function bench(over?: BenchOptions) {
})
if (over?.draft !== undefined && over.draft !== '') shell.setDraft(over.draft)
if (over?.attachments !== undefined) shell.addImages(over.attachments.map(attachment => attachment.id))
const session = createSnapshotStore<ConversationSnapshot>(snapshotOf({
running: over?.running ?? false,
subagent: over?.subagent ?? null,
removed: over?.disabled ?? false,
promptError: over?.promptError ?? null,
}))
const stop = vi.fn()
const removeImage = vi.fn((id: DraftAttachmentId) => { shell.removeImage(id) })
const menuLauncher = createSnapshotStore<string | null>(over?.commandMenuOpen === true ? 'command' : null)
@@ -164,6 +182,7 @@ function bench(over?: BenchOptions) {
return {
view, textarea, button, interruptButton, props, sink, shell, wiring: shell, session, stop, removeImage, slotCalls,
menuLauncher,
steerQueue: over?.steerQueue,
}
}
@@ -222,6 +241,57 @@ describe('image draft rail', () => {
})
describe('Enter semantics', () => {
it('advertises the empty-draft whole-queue steering gesture when it is available', () => {
const { textarea } = bench({ running: true, queue: [row('q-1')], steerQueue: vi.fn() })
expect(textarea.placeholder).toBe('Cmd/Ctrl+Enter 插话发送全部排队消息')
})
it('keeps the owning placeholder or ordinary guidance when whole-queue steering is unavailable', () => {
expect(bench({ running: true }).textarea.placeholder).toBe('给智能体发消息')
expect(bench({ queue: [row('q-1')] }).textarea.placeholder).toBe('给智能体发消息')
expect(bench({ running: true, queue: [row('q-1')], draft: '消息' }).textarea.placeholder).toBe('给智能体发消息')
expect(bench({
running: true,
queue: [row('q-1')],
subagent: {
address: { parentSessionId: 'parent' as SessionId, childSessionId: SID, mode: 'continuable' },
parentAvailable: true,
},
}).textarea.placeholder).toBe('给智能体发消息')
expect(bench({
running: true,
queue: [row('q-1')],
placeholder: '上层指定提示',
}).textarea.placeholder).toBe('上层指定提示')
// The command menu owns Enter while open: neither the hint nor the
// gesture may claim the chord.
expect(bench({
running: true,
queue: [row('q-1')],
commandMenuOpen: true,
}).textarea.placeholder).toBe('给智能体发消息')
// The steer hint intentionally outranks the plan placeholder: while it
// shows, the whole-queue gesture is genuinely available in plan mode.
expect(bench({
running: true,
queue: [row('q-1')],
plan: { active: true, pending: false },
}).textarea.placeholder).toBe('Cmd/Ctrl+Enter 插话发送全部排队消息')
})
it('an open command menu withholds the whole-queue steering gesture', () => {
const steerQueue = vi.fn()
const { textarea, sink } = bench({
running: true,
queue: [row('q-1')],
commandMenuOpen: true,
steerQueue,
})
fireEvent.keyDown(textarea, { key: 'Enter', metaKey: true })
expect(steerQueue).not.toHaveBeenCalled()
expect(sink).not.toHaveBeenCalled()
})
it('plain Enter submits queue mode through the machine; repeat and empty are suppressed', () => {
const { textarea, sink } = bench({ draft: 'hello' })
fireEvent.keyDown(textarea, { key: 'Enter' })
@@ -261,6 +331,78 @@ describe('Enter semantics', () => {
expect(busyMeta.sink).toHaveBeenCalledWith('steer with cmd', [], 'steer')
})
it('empty-draft Cmd/Ctrl+Enter steers the whole queue instead of submitting', () => {
const steerQueue = vi.fn()
const queue = [row('q-1'), row('q-2')]
const meta = bench({ running: true, queue, steerQueue })
fireEvent.keyDown(meta.textarea, { key: 'Enter', metaKey: true })
expect(meta.steerQueue).toHaveBeenCalledTimes(1)
expect(meta.sink).not.toHaveBeenCalled()
const ctrl = bench({ running: true, queue, steerQueue: vi.fn() })
fireEvent.keyDown(ctrl.textarea, { key: 'Enter', ctrlKey: true })
expect(ctrl.steerQueue).toHaveBeenCalledTimes(1)
expect(ctrl.sink).not.toHaveBeenCalled()
})
it('queue steering stays gated: idle, subagent, plain Enter, empty queue, or steering-only rows', () => {
// Idle: the gesture falls through to the machine's empty-draft no-op.
const idle = bench({ queue: [row('q-1')], steerQueue: vi.fn() })
fireEvent.keyDown(idle.textarea, { key: 'Enter', metaKey: true })
expect(idle.steerQueue).not.toHaveBeenCalled()
expect(idle.sink).not.toHaveBeenCalled()
// Plain Enter never steers the queue, even under the busy Steer preference.
const plain = bench({ running: true, busyEnter: 'steer', queue: [row('q-1')], steerQueue: vi.fn() })
fireEvent.keyDown(plain.textarea, { key: 'Enter' })
expect(plain.steerQueue).not.toHaveBeenCalled()
expect(plain.sink).not.toHaveBeenCalled()
// Subagent sessions keep the queue transport (no steering face).
const subagent = {
address: {
parentSessionId: 'parent' as SessionId,
childSessionId: SID,
mode: 'continuable' as const,
},
parentAvailable: true,
}
const child = bench({ running: true, subagent, queue: [row('q-1')], steerQueue: vi.fn() })
fireEvent.keyDown(child.textarea, { key: 'Enter', metaKey: true })
expect(child.steerQueue).not.toHaveBeenCalled()
expect(child.sink).not.toHaveBeenCalled()
// No queued rows: the empty draft stays a no-op.
const none = bench({ running: true, steerQueue: vi.fn() })
fireEvent.keyDown(none.textarea, { key: 'Enter', metaKey: true })
expect(none.steerQueue).not.toHaveBeenCalled()
expect(none.sink).not.toHaveBeenCalled()
// Pending steering rows are not the queue: nothing to flush.
const steering = bench({
running: true,
queue: [{ ...row('s-1'), placement: 'steering' }],
steerQueue: vi.fn(),
})
fireEvent.keyDown(steering.textarea, { key: 'Enter', metaKey: true })
expect(steering.steerQueue).not.toHaveBeenCalled()
expect(steering.sink).not.toHaveBeenCalled()
})
it('draft content outranks the queue: accelerated Enter steers the draft only', () => {
const steerQueue = vi.fn()
const { textarea, sink } = bench({ running: true, queue: [row('q-1')], draft: '插话', steerQueue })
fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true })
expect(sink).toHaveBeenCalledWith('插话', [], 'steer')
expect(steerQueue).not.toHaveBeenCalled()
})
it('empty-draft accelerated Enter without a steerQueue face stays a silent no-op', () => {
const { textarea, sink } = bench({ running: true, queue: [row('q-1')] })
fireEvent.keyDown(textarea, { key: 'Enter', metaKey: true })
expect(sink).not.toHaveBeenCalled()
})
it('platform undo/redo chords route to the machine, never the browser stack', () => {
const { textarea, shell } = bench({ draft: '' })
fireEvent.change(textarea, { target: { value: 'first' } })

View File

@@ -5,12 +5,13 @@
// tag probe).
import { Context } from 'cordis'
import { describe, expect, it, vi } from 'vitest'
import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
import { AttachmentId } from '@deepseek-ai/dsh-attachment'
import type { SessionFace } from '@deepseek-ai/dsh-client-runtime/client'
import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
import type { QueuedMessage, SessionFace } from '@deepseek-ai/dsh-client-runtime/client'
import { ComposerBlockRegistry } from '../src/client/input/blocks.ts'
import { InputHub } from '../src/client/input/hub.ts'
import { ConversationService, UnsupportedImageMediaTypeError } from '../src/client/service.ts'
import { zh } from '../src/client/locales.ts'
async function bench(readAttachment?: SessionFace['readAttachment']) {
const runtime = await SlotTestRuntime.create()
@@ -24,14 +25,16 @@ async function bench(readAttachment?: SessionFace['readAttachment']) {
})
// config.input is required (the apply shares its hub with the inject
// factories); the bench passes its own instance explicitly.
const hub = new InputHub(runtime.ctx, makeTranslate(zh, {}))
const fiber = runtime.ctx.plugin(ConversationService, {
input: new InputHub(runtime.ctx),
input: hub,
blocks: new ComposerBlockRegistry(),
})
await fiber.await()
const root = runtime.ctx.get('conversation') as ConversationService
const scoped = runtime.sessions.scope('s1')!.get('conversation') as ConversationService
return { runtime, fiber, root, scoped, prompt, updateQueue, cancel, loadOlder }
const shell = hub.shellFor(runtime.sessions.binding('s1')!)
return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder }
}
describe('ConversationService', () => {
@@ -135,10 +138,88 @@ describe('ConversationService', () => {
// No SessionsService at all: a bare context (the runtime always provides one).
const bare = new Context()
await bare.plugin(ConversationService, {
input: new InputHub(bare),
input: new InputHub(bare, makeTranslate(zh, {})),
blocks: new ComposerBlockRegistry(),
}).await()
const orphan = bare.get('conversation') as ConversationService
await expect(orphan.send('x')).rejects.toThrow(/sessions service unavailable/)
})
})
describe('InputHub queue steering (empty-draft accelerated Enter)', () => {
const row = (id: string): QueuedMessage => ({
id: id as never,
messageId: `message-${id}` as never,
placement: 'queued',
content: [{ type: 'text', text: id }],
preview: id,
text: id,
})
it('steers every queued row in FIFO order and leaves steering rows alone', async () => {
const b = await bench()
await b.runtime.sessions.updateSnapshot('s1', (draft) => {
draft.queue = [row('q-1'), { ...row('q-2'), placement: 'steering' }, row('q-3')]
})
b.shell.steerQueue()
await vi.waitFor(() => {
expect(b.updateQueue).toHaveBeenCalledTimes(2)
})
expect(b.updateQueue).toHaveBeenNthCalledWith(1, 'q-1', { kind: 'steer' })
expect(b.updateQueue).toHaveBeenNthCalledWith(2, 'q-3', { kind: 'steer' })
expect(b.shell.notices.getSnapshot()).toBeNull()
await b.runtime.dispose()
})
it('converges silently when the turn closes or a row is claimed mid-steer', async () => {
const b = await bench()
await b.runtime.sessions.updateSnapshot('s1', (draft) => {
draft.queue = [row('q-1'), row('q-2')]
})
// The turn closes before the second row: the flush stops, silently.
b.updateQueue.mockResolvedValueOnce({
ok: false, error: { code: 'steer-unavailable', message: 'closed', details: {} },
} as never)
b.shell.steerQueue()
await vi.waitFor(() => { expect(b.updateQueue).toHaveBeenCalledTimes(1) })
expect(b.shell.notices.getSnapshot()).toBeNull()
// A row the host already claimed (e.g. a repeated empty-draft chord):
// the duplicate strict steer is a silent no-op.
await b.runtime.sessions.updateSnapshot('s1', (draft) => {
draft.queue = [row('q-3')]
})
b.updateQueue.mockResolvedValueOnce({
ok: false, error: { code: 'queue-item-not-found', message: 'claimed', details: {} },
} as never)
b.shell.steerQueue()
await vi.waitFor(() => { expect(b.updateQueue).toHaveBeenCalledTimes(2) })
expect(b.shell.notices.getSnapshot()).toBeNull()
await b.runtime.dispose()
})
it('surfaces one notice on a genuine steer failure and stops', async () => {
const b = await bench()
await b.runtime.sessions.updateSnapshot('s1', (draft) => {
draft.queue = [row('q-1'), row('q-2')]
})
b.updateQueue.mockResolvedValueOnce({
ok: false, error: { code: 'internal', message: 'broken', details: {} },
} as never)
b.shell.steerQueue()
await vi.waitFor(() => {
expect(b.shell.notices.getSnapshot()).toEqual(
expect.objectContaining({ level: 'error', text: '插话发送失败,请重试。' }),
)
})
expect(b.updateQueue).toHaveBeenCalledTimes(1)
await b.runtime.dispose()
})
it('no-ops without queued rows', async () => {
const b = await bench()
b.shell.steerQueue()
expect(b.updateQueue).not.toHaveBeenCalled()
await b.runtime.dispose()
})
})

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/client/ui-skill/README.md
README.md: 677ac215d299fca695a6b27c564779ef1d3fd6ee
README.zh.md: 8f1f69b26a932aaa300bdda1d4ec7b2fa749fe3c
README.md: d8e88cb7b0215b06cd55a4ee9a7932ef180f572f
README.zh.md: 073a41cac95aeb96b658b075011d8212684f1c65

View File

@@ -4,7 +4,7 @@ English | [中文](README.zh.md)
Skill invocation source, browser half: registers the `/`-trigger `skill` source into `ctx.slash`. Ordinary-session candidates come from the `skill.list` RPC addressed by the per-call `ClientSessionContext` projection's `{sessionId}`, with the host resolving `cwd` from the session header. The host serves every user-invocable skill; a `modelInvocable: false` entry (a `disable-model-invocation` skill, whose only entry point is this path) wears the user-only marker as a description prefix in the active language. Catalog-addressed continuable children resolve no skill candidates locally because the existing skill RPC requires an attached session; viewing their persisted history must not activate them. Catalogs cache per ordinary session with a single-flight fetch; the scope-birth `warm` hook prewarms the session's entry and `connection/reset` clears everything. Results filter by `startsWith(query)`.
A pick lands the literal `/name ` text and the prompt ships the same literal ([slash-pipeline Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md)) — this source implements no adjudication hooks and no reference codec. Determinism lives host-side: the pre-step gesture boundary (`dsh-tool-skill`) recognizes whitespace-bounded `/name` tokens naming user-invocable skills anywhere in a user message and injects the rendered `<skill_content>` for every front end, so a menu pick, a hand-typed token, and a TUI/ACP prompt all load the skill the same way. A name shared with a host command still resolves to the command: adjudication claims the line client-side before it ever becomes a prompt — deliberate precedence, matching peer products. The list RPC rides the plugin's root-context connection captured at registration — the source never reads services off a per-call argument; draft chip visuals derive from the `lexicon` scan.
A pick lands the literal `/name ` text and the prompt ships the same literal ([slash-pipeline Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md)) — this source implements no adjudication hooks and no reference codec. Determinism lives host-side: the pre-step gesture boundary (`dsh-tool-skill`) recognizes whitespace-bounded `/name` tokens naming user-invocable skills anywhere in a user message and injects the rendered `<skill_content>` for every entry point, so a menu pick, a hand-typed token, and a TUI/ACP prompt all load the skill the same way. A name shared with a host command still resolves to the command: adjudication claims the line client-side before it ever becomes a prompt — deliberate precedence, matching peer products. The list RPC rides the plugin's root-context connection captured at registration — the source never reads services off a per-call argument; draft chip visuals derive from the `lexicon` scan.
A failed `skill.list` throws from `candidates`, which the slash shell logs and folds into a silent menu-group drop — the menu shows only pending/ready states.

View File

@@ -4,7 +4,7 @@
skill技能调用 source 的浏览器端:把 `/` 触发的 `skill` source 注册进 `ctx.slash`。普通会话的候选来自 `skill.list` RPC以每次调用的 `ClientSessionContext` 投影中的 `{sessionId}` 寻址host 从会话 header 解析 `cwd`。宿主提供每一个用户可调用的 skill`modelInvocable: false` 的条目(即 `disable-model-invocation` skill此路径是其唯一入口会以当前语言把仅限用户标记作为描述前缀带上。由目录寻址的可继续 subagent 在客户端解析为没有 skill 候选,因为现有 skill RPC 要求会话已挂载;查看其持久化历史不得激活它。目录按普通会话缓存,拉取走 single-flightscope 创建时的 `warm` 钩子预热该会话的缓存项,`connection/reset` 清空全部缓存。结果按 `startsWith(query)` 过滤。
pick 会落下字面文本 `/name `,提示词发出的就是同一段字面文本([slash 流水线 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md))——本 source 不实现任何裁决钩子,也没有引用 codec。确定性在宿主侧pre-step 手势边界(`dsh-tool-skill`)识别用户消息中任意位置、以空白为界、指名用户可调用 skill 的 `/name` token并为每一种前端注入渲染后的 `<skill_content>`,因此菜单 pick、手动键入的 token 与 TUI/ACPAgent Client Protocol提示词都以同一种方式加载 skill。与宿主命令同名的名称仍解析为命令裁决在客户端把该行认领走它根本不会成为提示词——这是有意的优先级与同行产品一致。列表 RPC 使用插件注册时捕获的根上下文连接——source 绝不从每次调用的参数上读取服务;草稿 chip 视觉由 `lexicon` 扫描派生。
pick 会落下字面文本 `/name `,提示词发出的就是同一段字面文本([slash 流水线 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md))——本 source 不实现任何裁决钩子,也没有引用 codec。确定性在宿主侧pre-step 手势边界(`dsh-tool-skill`)识别用户消息中任意位置、以空白为界、指名用户可调用 skill 的 `/name` token并为每个入口注入渲染后的 `<skill_content>`,因此菜单 pick、手动键入的 token 与 TUI/ACPAgent Client Protocol提示词都以同一种方式加载 skill。与宿主命令同名的名称仍解析为命令裁决在客户端把该行认领走它根本不会成为提示词——这是有意的优先级与同行产品一致。列表 RPC 使用插件注册时捕获的根上下文连接——source 绝不从每次调用的参数上读取服务;草稿 chip 视觉由 `lexicon` 扫描派生。
`skill.list` 失败时 `candidates` 抛出异常slash 壳层记录日志并折叠为静默的菜单组丢弃——菜单只显示 pendingready 状态。

View File

@@ -8,7 +8,7 @@
* determinism
* lives host-side — the pre-step boundary (`dsh-tool-skill`) recognizes a
* leading `/name` naming a user-invocable skill and injects the rendered
* body for every front end, including `disable-model-invocation` skills the
* body for every entry point, including `disable-model-invocation` skills the
* model-side catalog never lists (issue #1470). The RPC rides the plugin's
* root-context connection captured at registration — the source never reads
* services off a per-call argument. Draft chip visuals derive from
@@ -167,7 +167,7 @@ export function apply(ctx: ClientContext): void {
// lands plain text and the prompt ships the same
// literal. Determinism lives host-side — the host's
// pre-step boundary (dsh-tool-skill) recognizes the leading /name and
// injects the rendered body for every front end. A name shared with a
// injects the rendered body for every entry point. A name shared with a
// host command still resolves to the command: adjudication claims the
// line client-side before it ever becomes a prompt.
return { text: `/${candidate.name} ` }

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/core/README.md
README.md: 8349371ab565f2e9e735cd959026936c7ec44081
README.md: 504686f8563f073fc8261c88275a5cdd172dd060
README.zh.md: e19c446584cfac75cb50833fa01586688b9c7c92

View File

@@ -11,10 +11,10 @@ The session log, system-prompt assembly, tool registry, agent vocabulary, deploy
| [`system-prompt/`](system-prompt/README.md) | Prompt and tool-schema assembly registry | `ctx.systemPrompt` |
| [`tools/`](tools/README.md) | Scoped tool registry and execution pipeline | `ctx.tools` |
| [`agent/`](agent/README.md) | Agent interface, registry, and event vocabulary | `ctx.agents` |
| [`agent-default-model/`](agent-default-model/README.md) | Default model selection shared by Agent front doors | `ctx.agentDefaultModel` |
| [`agent-default-model/`](agent-default-model/README.md) | Default model selection shared by Agent entry points | `ctx.agentDefaultModel` |
| [`agent-loop/`](agent-loop/README.md) | Default concrete agent driver | `ctx.agentLoop` |
`scope` supplies the shared scoping primitive. `agent` owns the public contract, while `agent-loop` is its default implementation; extension plugins depend on the seam so the driver remains swappable. `agent-default-model` owns the deployment selection an Agent front door uses only when a session has no selection of its own.
`scope` supplies the shared scoping primitive. `agent` owns the public contract, while `agent-loop` is its default implementation; extension plugins depend on the seam so the driver remains swappable. `agent-default-model` owns the deployment selection an Agent entry point uses only when a session has no selection of its own.
Runnable compositions belong to [`examples/agent-spine-demo`](../examples/agent-spine-demo/README.md); this group owns only the swappable spine pieces.

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/core/agent-default-model/README.md
README.md: 02bcc9be3adee2293a20b3ae87ddaf4d52e70deb
README.md: 98bc7d082e62a764868f8acd323c4617e9839e61
README.zh.md: 807b612bd25e49aa318c13c8c8dc7595a6459080

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
The deployment default used when a front door creates an Agent that has no session-local model selection. `AgentDefaultModelService` provides `ctx.agentDefaultModel`; direct front doors such as `dsh run` and Host-backed front doors such as ApiProxy read the same service instead of owning parallel provider/model defaults.
The deployment default used when an entry point creates an Agent that has no session-local model selection. `AgentDefaultModelService` provides `ctx.agentDefaultModel`; direct entry points such as `dsh run` and Host-backed entry points such as ApiProxy read the same service instead of owning parallel provider/model defaults.
The plugin config requires `{ provider, model }`. That composition entry is the base of the `agent-default-model` Settings section; a mounted settings provider layers the user's choice over it and changes are visible on the next `currentSelection()` read. `reasoningEffort` belongs to the Settings section but deliberately not to plugin config: a complete saved selection can clear an effort when the next selected model has none, while a composition value would be inherited again.
@@ -13,7 +13,7 @@ The service does not validate catalog membership. A provider route may serve an
## Model Experience
Indirectly, through the provider/model selection supplied to a front door; request assembly and adapters own the model-visible request.
Indirectly, through the provider/model selection supplied to an entry point; request assembly and adapters own the model-visible request.
#### KV Cache effect
@@ -21,5 +21,5 @@ Changing the default affects only Agents that subsequently resolve from it. An e
## Known Limitations and Deferred Work
- The service owns one process-wide default; per-session selection remains the front door's responsibility.
- The service owns one process-wide default; per-session selection remains the entry point's responsibility.
- Without a settings provider, `saveSelection()` cannot retain a selection for a later Agent.

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-agent-default-model",
"description": "Default model selection shared by Agent front doors",
"description": "Default model selection shared by Agent entry points",
"version": "0.0.1",
"private": true,
"type": "module",

View File

@@ -92,7 +92,7 @@ export class AgentDefaultModelService extends Service {
/**
* Save the complete default model selection. A deployment without a settings
* provider keeps its composition entry.
* @param next - resolved selection accepted by a front door.
* @param next - resolved selection accepted by an entry point.
* @returns fulfillment after the optional settings write settles.
*/
async saveSelection(next: ModelSelection): Promise<void> {

View File

@@ -1,5 +1,5 @@
/**
* Agent-scoped model selection shared by interactive front doors.
* Agent-scoped model selection shared by runtime entry points.
* @module @deepseek-ai/dsh-agent/model-selection
*/
@@ -33,7 +33,7 @@ export interface ModelSelectionRef {
* the selected model's provider/default behavior.
*
* @param agentCtx - The selected Agent's scoped context.
* @param selection - Mutable selection owned by the calling front door.
* @param selection - Mutable selection owned by the calling entry point.
* @returns Disposer for both scoped waterfall listeners.
*/
export function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void {

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/examples/README.md
README.md: 2d672dcc307bb280cf3803f29128eba4988a8da0
README.zh.md: 24f64096dda0ccdac51afb90754ae25950750b89
README.md: d8369b1e263e72c7b0ac1687c3b14a5d723ab944
README.zh.md: acb402e925f692beaacbe0ab4e029691d664dbe8

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling the spine and a front door by hand. These are **demo / reference** packages — the `-demo` npm suffix marks each one as non-product surface, readable straight off the package name. The runnable leaves under the repo-root [`examples/`](../../examples/AGENTS.md) and the [Python SDK runtime](../../python/sdk-runtime/README.md) are the consumers; each is just its swappable backends plus one bundle entry.
Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling the spine and an entry point by hand. These are **demo / reference** packages — the `-demo` npm suffix marks each one as non-product surface, readable straight off the package name. The runnable leaves under the repo-root [`examples/`](../../examples/AGENTS.md) and the [Python SDK runtime](../../python/sdk-runtime/README.md) are the consumers; each is just its swappable backends plus one bundle entry.
| Package | npm name | Role |
|---|---|---|
@@ -10,8 +10,8 @@ Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling
| [`acp-demo/`](acp-demo/README.md) | `@deepseek-ai/dsh-acp-demo` | ACP automation application bundle |
| [`jsonrpc-demo/`](jsonrpc-demo/README.md) | `@deepseek-ai/dsh-jsonrpc-demo` | External-config JSON-RPC runtime |
`agent-spine-demo` is the shared bundle; `acp-demo` adds its automation front door, while `jsonrpc-demo` boots a deployment-owned plugin tree. Product one-shot execution belongs to `dsh run`; no package in this directory provides it.
`agent-spine-demo` is the shared bundle; `acp-demo` adds its automation entry point, while `jsonrpc-demo` boots a deployment-owned plugin tree. Product one-shot execution belongs to `dsh run`; no package in this directory provides it.
These packages are not product API. Product seams and front doors remain in their owning groups; demo bundles select concrete compositions.
These packages are not product API. Product seams and entry points remain in their owning groups; demo bundles select concrete compositions.
Do not confuse this group with the repo-root [`examples/`](../../examples/AGENTS.md): that directory holds the runnable `cordis.yml` **leaves**; this group holds the **bundles** those leaves load.

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
预先组合的插件 bundle组合包供轻量叶节点 `cordis.yml` 加载,无需手工组装主干和前端入口。这些是 **演示/参考**npm 名称的 `-demo` 后缀把每个包标为非产品表层,直接查看包名即可辨认。仓库根目录 [`examples/`](../../examples/AGENTS.md) 下的可运行叶节点与 [Python SDK runtime](../../python/sdk-runtime/README.md) 是消费方;每个叶节点都只包含可替换后端和一个组合包入口。
预先组合的插件 bundle组合包供轻量叶节点 `cordis.yml` 加载,无需手工组装主干和运行入口。这些是 **演示/参考**npm 名称的 `-demo` 后缀把每个包标为非产品表层,直接查看包名即可辨认。仓库根目录 [`examples/`](../../examples/AGENTS.md) 下的可运行叶节点与 [Python SDK runtime](../../python/sdk-runtime/README.md) 是消费方;每个叶节点都只包含可替换后端和一个组合包入口。
| 包 | npm 名称 | 角色 |
|---|---|---|
@@ -12,6 +12,6 @@
`agent-spine-demo` 是共享组合包;`acp-demo` 添加自动化入口,`jsonrpc-demo` 则启动由部署方拥有的插件树。产品单次执行由 `dsh run` 提供;本目录没有任何包提供该功能。
这些包不是产品 API。产品 seam 与前端入口仍位于各自的归属组;演示组合包选择具体组合。
这些包不是产品 API。产品 seam 与产品入口仍位于各自的归属组;演示组合包选择具体组合。
不要将此组与仓库根目录的 [`examples/`](../../examples/AGENTS.md) 混淆:该目录存放可运行的 `cordis.yml` **叶节点**;此组存放这些叶节点加载的 **组合包**

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/examples/acp-demo/README.md
README.md: 395ab230146568989c4e6d1361218efb72d857e7
README.zh.md: 667fc1a794eba15c7754ad9887f8083d3643f3e6
README.md: edc45c9857a631cef72eb41b1a98c390f112291e
README.zh.md: c2946aa3d1feaed558408cf0921e2480c031187d

View File

@@ -55,4 +55,4 @@ Append-only per session; the app adds no request-prefix content itself.
- **JSONL persistence is fixed** — a different backend requires another composition.
- **Sibling plugins can corrupt stdout** — the app cannot prevent another entry from writing non-protocol bytes.
- **Fresh automation sessions only** — resume and human interaction belong to other front doors.
- **Fresh automation sessions only** — resume and human interaction belong to other entry points.

View File

@@ -55,4 +55,4 @@ ACPAgent Client Protocol自动化服务器应用默认 agent智能
- **JSONL 持久化固定不变**:使用其他后端需要另一种组合。
- **同级插件可能破坏 stdout**:应用无法阻止另一个条目写入非协议字节。
- **只支持新建自动化会话**:恢复和人工交互属于其他前端入口。
- **只支持新建自动化会话**:恢复和人工交互属于其他运行入口。

View File

@@ -71,7 +71,7 @@ export interface Config {
goals?: agentCore.GoalConfig | false
}
// Each front door owns a complete, directly readable config schema; extracting
// Each entry point owns a complete, directly readable config schema; extracting
// the common fields would make two small app contracts depend on a new facade.
/* jscpd:ignore-start */
export const Config: z<Config> = z.object({
@@ -114,7 +114,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
const spine = ctx.plugin(agentCore, { ...agentCore.pickSpineConfig(config), goals })
await spine
yield spine.dispose
// Same rationale as the Config schema above: each front door forwards its own
// Same rationale as the Config schema above: each entry point forwards its own
// persistence passthroughs rather than sharing a facade with stdio-demo.
/* jscpd:ignore-start */
const persistence = ctx.plugin(SessionPersistenceJsonl, {

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/examples/agent-spine-demo/README.md
README.md: cfec2c46ada8ed97aef44fb1d4145ddecdeecab1
README.zh.md: d482ea9ca7034874383472050a8c837bea5bfaad
README.md: cf0dc2ecd6e51eb872be75dfe6d80a5338605195
README.zh.md: e5a8672d494e0c456aa820641e685d00be624445

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
The **default executor-less, UI-less agent spine** as ONE Cordis bundle plugin. It loads the fixed set of services every harness agent needs, including the local skill provider, and forwards the loop's `agents` list as its own config — so an app package composes a working agent by adding only a front door and the swappable backends.
The **default executor-less, UI-less agent spine** as ONE Cordis bundle plugin. It loads the fixed set of services every harness agent needs, including the local skill provider, and forwards the loop's `agents` list as its own config — so an app package composes a working agent by adding only an entry point and the swappable backends.
Read this package for the whole plugin tree and its composition order.
@@ -41,15 +41,15 @@ Read this package for the whole plugin tree and its composition order.
## What it deliberately leaves OUTSIDE the bundle
The spine is everything COMMON to every front door. The swappable and front-door-coupled pieces stay out, picked by whatever loads the bundle:
The spine is everything COMMON to every entry point. The swappable and entry-point-coupled pieces stay out, picked by whatever loads the bundle:
- **the LLM adapter** — the bundle ships the abstract `llm` service; the leaf registers a concrete adapter on `ctx.llm` (`llm-deepseek`, `llm-pi-ai`, `llm-replay`).
- **model-backed session-title providers** — the bundle mounts the fallback service with overridable example limits (5 words, 40 fallback bytes, 80 accepted-title bytes); a leaf may opt into exactly one first-message or all-messages LLM provider.
- **the bash executor** — the bundle ships `tool-bash` (the consumer schema); the leaf provides `ctx.bash` (`bash-local` or a sandboxed impl).
- **non-local skill providers** — the bundle ships the skill registry, the local filesystem provider, and the `skill` tool; deployments can add other providers such as embedded or remote catalogs as siblings.
- **front-door + per-app infrastructure** — headless, ACP, and JSON-RPC app packages own transport, stdout, and reload choices. `timer` stays in the spine because it is common and stdout-silent.
- **entry point + per-app infrastructure** — headless, ACP, and JSON-RPC app packages own transport, stdout, and reload choices. `timer` stays in the spine because it is common and stdout-silent.
This applies the [Service Definition / Service provider / Consumer separation](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) at the composition level: the bundle owns the shared spine, the leaf owns the backends, the app package owns the front door.
This applies the [Service Definition / Service provider / Consumer separation](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) at the composition level: the bundle owns the shared spine, the leaf owns the backends, the app package owns the entry point.
## Config
@@ -65,9 +65,9 @@ For example, `{ invariants: { enabled: true, package_allowlist: ['^@deepseek-ai/
## Why a code bundle, not a shared YAML include
A YAML include can deduplicate config but cannot own a bin or provide front-door defaults. The ACP app package makes protocol-pure stdout wiring the default, though a leaf can still add an unsafe logger. Bundle children register services in the root isolate-keyed store, so injected leaf siblings see them without load-order coupling.
A YAML include can deduplicate config but cannot own a bin or provide entry-point defaults. The ACP app package makes protocol-pure stdout wiring the default, though a leaf can still add an unsafe logger. Bundle children register services in the root isolate-keyed store, so injected leaf siblings see them without load-order coupling.
The retry policy may repeat a failed request in a new numbered step. Retry status, provider errors, and failed partial chunks stay outside model history; each provider attempt can still incur billing, always mode has no attempt limit, front doors derive usage across every logged step, and the reconstructed request preserves the prior prefix for provider cache reuse.
The retry policy may repeat a failed request in a new numbered step. Retry status, provider errors, and failed partial chunks stay outside model history; each provider attempt can still incur billing, always mode has no attempt limit, entry points derive usage across every logged step, and the reconstructed request preserves the prior prefix for provider cache reuse.
## Model Experience

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
**默认的不含执行器、不含 UI 的 agent智能体主干** 作为一个 Cordis 组合包插件。它加载每个 harness agent 所需的固定服务集合,包括本地 skill技能提供方并将循环的 `agents` 列表作为自身配置转发。因此应用包package只需添加前端入口和可替换后端,就能组合出可工作的 agent。
**默认的不含执行器、不含 UI 的 agent智能体主干** 作为一个 Cordis 组合包插件。它加载每个 harness agent 所需的固定服务集合,包括本地 skill技能提供方并将循环的 `agents` 列表作为自身配置转发。因此应用包package只需添加入口和可替换后端就能组合出可工作的 agent。
阅读此包可了解完整插件树及其组合顺序。
@@ -41,15 +41,15 @@
## 有意留在组合包外的组件
主干包含每个前端入口都共有的全部组件。可替换组件和与前端入口耦合的组件留在外部,由加载组合包的一方选择:
主干包含每个入口都共有的全部组件。可替换组件和与入口耦合的组件留在外部,由加载组合包的一方选择:
- **LLM大语言模型适配器**:组合包交付抽象 `llm` 服务;叶节点在 `ctx.llm` 上注册具体适配器(`llm-deepseek``llm-pi-ai``llm-replay`)。
- **基于模型的会话标题提供方**组合包挂载带可覆盖示例限制的后备服务5 个词、40 个后备字节、80 个可接受标题字节);叶节点可以恰好选用一个首消息或全消息 LLM 提供方。
- **bash 执行器**:组合包交付 `tool-bash`(消费方 schema叶节点提供 `ctx.bash``bash-local` 或沙箱化实现)。
- **非本地 skill 提供方**:组合包交付 skill 注册表、本地文件系统提供方和 `skill` 工具;部署可以把嵌入式目录或远程目录等其他提供方作为同级插件添加。
- **前端入口与各应用基础设施**无头、ACPAgent Client Protocol和 JSON-RPC 应用包负责传输、stdout 与重新加载选择。`timer` 保留在主干中,因为它是共有组件且不写 stdout。
- **入口与各应用基础设施**无头、ACPAgent Client Protocol和 JSON-RPC 应用包负责传输、stdout 与重新加载选择。`timer` 保留在主干中,因为它是共有组件且不写 stdout。
这里在组合层应用 [Service DefinitionService providerConsumer 的职责分离](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md):组合包拥有共享主干,叶节点拥有后端,应用包拥有前端入口。
这里在组合层应用 [Service DefinitionService providerConsumer 的职责分离](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md):组合包拥有共享主干,叶节点拥有后端,应用包拥有入口。
## 配置
@@ -65,9 +65,9 @@ import type { Config } from '@deepseek-ai/dsh-agent-spine-demo'
## 为何使用代码组合包,而非共享 YAML include
YAML include 可以去重配置,却无法拥有 bin 或提供前端入口默认值。ACP 应用包默认接出协议纯净的 stdout但叶节点仍可添加不安全的 logger。组合包子节点把服务注册到根 isolate-keyed store因此叶节点的同级插件无需依赖加载顺序即可通过注入看到它们。
YAML include 可以去重配置,却无法拥有 bin 或提供入口默认值。ACP 应用包默认接出协议纯净的 stdout但叶节点仍可添加不安全的 logger。组合包子节点把服务注册到根 isolate-keyed store因此叶节点的同级插件无需依赖加载顺序即可通过注入看到它们。
重试策略可能在新的编号步骤中重复失败的请求。重试状态、提供方错误和失败的部分分片不进入模型历史每次提供方尝试仍可能产生计费always 模式没有尝试次数上限;前端入口从所有已记录步骤推导用量;重建的请求保留先前前缀,以便复用提供方缓存。
重试策略可能在新的编号步骤中重复失败的请求。重试状态、提供方错误和失败的部分分片不进入模型历史每次提供方尝试仍可能产生计费always 模式没有尝试次数上限;入口从所有已记录步骤推导用量;重建的请求保留先前前缀,以便复用提供方缓存。
## 模型体验

View File

@@ -165,7 +165,7 @@ export const Config = z.intersect([
]) as unknown as z<Config>
/**
* Copy the bundle-owned fields from an app config without leaking front-door settings.
* Copy the bundle-owned fields from an app config without leaking entry-point settings.
* @param config - App config containing the shared spine fields.
* @returns The fields accepted by this bundle, preserving optional absence.
*/

View File

@@ -236,7 +236,7 @@ describe('dsh-agent-spine-demo bundle', () => {
}
})
it('loads and configures bounded request recovery for every bundled front door', async () => {
it('loads and configures bounded request recovery for every bundled entry point', async () => {
const adapter = new TransientOnceAdapter()
const ctx = await mount({ workspaceContext: false })
ctx.llm.registerAdapter(['mock'], adapter)
@@ -704,9 +704,9 @@ describe('dsh-agent-spine-demo bundle', () => {
await ctx.fiber.dispose()
})
it('picks shared spine config without leaking front-door fields', () => {
it('picks shared spine config without leaking entry-point fields', () => {
const appConfig = {
model: 'front-door-only',
model: 'entrypoint-only',
includeHarnessIdentity: false,
persona: 'You are merged.',
toolOrder: ['zulu'],

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/feedback/command-feedback/README.md
README.md: e2eb6d4cf2b40e83efad1fa158edd72578658f56
README.md: d7849e25fc62897e4ac6793f40bdc139adf9ba3d
README.zh.md: c3b7b59d90d924de6042aeac1e7eec39457c6c83

View File

@@ -56,4 +56,4 @@ Independent of the model request path. Recording appends to the session log only
- **No structured fields** — an entry is one free-text string with no category, severity, or referenced-event link, so feedback cannot be filtered by subject without re-reading its text.
- **No amend or withdraw** — the session log is append-only and this package adds no tombstone, so a mistaken entry stays recorded and can only be superseded by a later one.
- **No explicit durability barrier** — the acknowledgement follows the append, not a flush, so an entry recorded immediately before a crash can be lost with any other unflushed tail. Feedback is not worth forcing a synchronous disk write for; a consumer that needs one awaits `ctx.sessions.flush(session)`.
- **Web only in the shipped front doors** — headless mode, ACP automation, and JSON-RPC do not provide a command adapter, so `/feedback` is unavailable there.
- **Web only among the shipped entry points** — headless mode, ACP automation, and JSON-RPC do not provide a command adapter, so `/feedback` is unavailable there.

View File

@@ -143,7 +143,7 @@ export function apply(ctx: Context, config: Config): void {
const groups: MatcherGroup[] = parsed[point] ?? []
const outputs: HookOutput[] = []
// Run the hook in the agent's session workspace (the `session/new` cwd on the session
// header), not the executor or front-door process's launch dir.
// header), not the executor or entry-point process's launch dir.
const workdir = opts.agent?.session.header.cwd
// CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session
// workspace (the same dir the hook runs in).

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/host/apiproxy/README.md
README.md: 98fcdda155286feb23aaf294cab76529ce31cfc1
README.zh.md: 8cfa7e527a327d9c342a5cf6cf28163f5b45df1c
README.md: c29f30b85c5579f278ac9b40a0422347502eeb8f
README.zh.md: 92b866bafd71902c55bf0bad14c6b9e761421cf8

View File

@@ -50,13 +50,13 @@ The `agentPreset.list` domain exposes the deployment's preset roster so a browse
`agentPreset.read`, `copy`, `openDocument`, and `remove` manage the compositions themselves. `read` reports the text with its `trust`, for the read-only viewer. Authoring is copy-only: `copy` takes `{ from, agentPreset, name? }` — two ids the Host resolves against its own roots plus an optional display name — and copies the source's whole directory, so no composition text crosses the wire and a copy is exactly as loadable as its source; an uncontainable or already-taken id answers `agent-preset-invalid`, and `remove` refuses a shipped preset as `agent-preset-read-only`. `openDocument` hands one locally authored preset's DIRECTORY to the platform opener — the request carries an id, never a path, so no browser payload can select an arbitrary filesystem target; where the deployment has no native opener the reply is `{ opened: false, path }` for the surface to show as text, a shipped preset is refused like `remove`, and the gateway's `nativeOpen` config pins the capability where platform detection (`canOpenNativePath`) would mislead. These four are loopback-pinned in [`dsh-client-connection`](../../client/connection/README.md): a composition names the plugins a session runs, so reading one is reconnaissance, and copy/remove/openDocument manage the roster and drive the host desktop. `list` and `select` stay ordinary — the roster carries ids and trust and every preset picker needs it, and choosing a preset grants nothing `session.create`'s own `agentPreset` did not, over a default that already carries bash. `list` reports two path-free capability flags: `authorable`, whether the deployment configures a root a new preset could be copied to, and `hasDocument`, whether `openDocument` would open natively rather than answer a path.
The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the composer's menu: it returns every user-invocable skill with its `modelInvocable` flag, so menus can mark user-only (`disable-model-invocation`) entries whose only entry point the slash gesture is. Listing is the skill domain's only RPC — invocation itself is an ordinary `session.prompt` whose whitespace-bounded `/name` tokens `dsh-tool-skill` recognizes at the pre-step boundary and answers with injected `<skill_content>` context, so every front end (web, TUI, ACP, hand-typed text) shares one deterministic path with no dedicated invocation wire. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream. Command handlers may legitimately outlast the 30-second transport health deadline, so `command.execute` carries only caller/connection cancellation; that signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing.
The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the composer's menu: it returns every user-invocable skill with its `modelInvocable` flag, so menus can mark user-only (`disable-model-invocation`) entries whose only invocation path is the slash gesture. Listing is the skill domain's only RPC — invocation itself is an ordinary `session.prompt` whose whitespace-bounded `/name` tokens `dsh-tool-skill` recognizes at the pre-step boundary and answers with injected `<skill_content>` context, so every entry point (Web, TUI, and ACP) shares one deterministic path—including for hand-typed text—with no dedicated invocation wire. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream. Command handlers may legitimately outlast the 30-second transport health deadline, so `command.execute` carries only caller/connection cancellation; that signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing.
The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves the namespaces addressed by registered configurable providers (`ctx.llm.listConfigurableProviders()`) plus a small explicit allowlist — the Web preference `permission` and the product-owned `ui-onboarding`; adding a Settings registration alone never makes it remotely readable or writable. Any other namespace answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, the section's `revision`, and the boolean `hasDocument` capability flag. The browser receives no Host path: pathless `settings.openDocument` asks the provider to materialize its document and then hands the Host-resolved result to the native opener, so no browser payload can select an arbitrary filesystem target. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. `llm.discoverModels` interrogates a provider endpoint the page is still drafting: `settingsNs` selects the adapter family that knows how to read the listing, and the endpoint, protocol, and key come from the form rather than from storage. It writes nothing — the reply is candidates, and only a later `settings.mutate` decides what a route serves — so its `apiKey` is the third payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`. The host never stores or returns it; like the other two it does ride the client's outgoing envelope, which `subscribeEnvelopes()` observers can see, and redacting that tap is a configuration-plane-wide change rather than this method's to make alone. Every refusal (an unserved namespace, a protocol with no readable listing, an unreachable endpoint, a rejected credential) folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. Three invalidation frames keep every surface converged without polling: `host/settings-changed {ns}` (`settings/document-updated` passthrough, so a raw change whose resolved value is unchanged still reaches clients), `host/credentials-changed {ref}` (reference names only, never values), and `host/models-changed` — fired by `llm/adapters-updated` and by a change to a configurable-provider namespace, whose settings carry that provider's catalog and endpoint; a `permission` or `ui-onboarding` change emits only its settings invalidation. The browser carrier restricts the whole configuration plane, reads and native actions included (`settings.describe`/`openDocument`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin.
## Carrier layer (`/client` + root)
`AbstractApiClient` holds every protocol invariant — rpcId minting, envelope wrap/unwrap, zod parsing, SSE frame decoding, unary timeout, microtask-batched envelope observation (`subscribeEnvelopes`) — while platform subclasses supply only the `doFetch` transport aspect. `InProcessApiClient` over `toFetchHandler(api)` remains the isomorphic point for callers and carrier tests that need the full wire serialization/validation path without a network. Product `dsh run` is a direct core front door and does not mount this package.
`AbstractApiClient` holds every protocol invariant — rpcId minting, envelope wrap/unwrap, zod parsing, SSE frame decoding, unary timeout, microtask-batched envelope observation (`subscribeEnvelopes`) — while platform subclasses supply only the `doFetch` transport aspect. `InProcessApiClient` over `toFetchHandler(api)` remains the isomorphic point for callers and carrier tests that need the full wire serialization/validation path without a network. Product `dsh run` is a direct core entry point and does not mount this package.
## Model Experience

View File

@@ -50,7 +50,7 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr
`agentPreset.read``copy``openDocument``remove` 负责管理组装本身。`read` 返回文本连同它的 `trust`,供只读查看器使用。创作只有复制一种写入:`copy` 接收 `{ from, agentPreset, name? }`——两个由 Host 对照自身根目录解析的 id 加一个可选显示名——并整目录复制来源,因此组装文本不经过传输层,副本与其来源同等可加载;不可约束或已被占用的 id 回答 `agent-preset-invalid``remove` 对随附 preset 回答 `agent-preset-read-only``openDocument` 把一个本地创作 preset 的**目录**交给平台打开器——请求只携带 id、绝不携带路径因此没有任何浏览器载荷能选中任意文件系统目标部署没有原生打开器时回答 `{ opened: false, path }` 供界面以文本展示,随附 preset 与 `remove` 一样被拒绝,而网关的 `nativeOpen` 配置可在平台探测(`canOpenNativePath`)失真处钉死该能力。这四个方法在 [`dsh-client-connection`](../../client/connection/README.md) 中被固定在环回地址:组装指明了一个会话所运行的插件,因此读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面。`list``select` 保持为普通方法——名单只携带 id 与信任级别,每个 preset 选择器都需要它;而选择一个 preset 并不比 `session.create` 自带的 `agentPreset` 多给任何能力,何况默认 preset 本就带着 bash。`list` 报告两个不含路径的能力标志:`authorable`,即部署是否配置了可供复制新 preset 的根目录;`hasDocument`,即 `openDocument` 会原生打开、还是回答一个路径。
`command.*``skill.*` 领域向客户端暴露宿主命令注册表和 skill技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent被服务的会话必有 Agent`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于 composer 的菜单:它返回每一个用户可调用的 skill 及其 `modelInvocable` 标志,让菜单能够标出仅限用户(`disable-model-invocation`)的条目——斜杠手势是这类条目唯一的入口。列表是 skill 领域唯一的 RPC——调用本身就是一次普通的 `session.prompt``dsh-tool-skill` 会在 pre-step 边界识别其中以空白为界的 `/name` token并以注入的 `<skill_content>` 上下文作答,因此每一种前端web、TUIACPAgent Client Protocol、手动键入的文本)共享同一条确定性路径,没有专设的调用协议。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载。命令处理器运行超过 30 秒的传输健康时限仍属正常,因此 `command.execute` 仅携带调用方/连接取消信号;该信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。
`command.*``skill.*` 领域向客户端暴露宿主命令注册表和 skill技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent被服务的会话必有 Agent`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于 composer 的菜单:它返回每一个用户可调用的 skill 及其 `modelInvocable` 标志,让菜单能够标出仅限用户(`disable-model-invocation`)的条目——斜杠手势是这类条目唯一的调用路径。列表是 skill 领域唯一的 RPC——调用本身就是一次普通的 `session.prompt``dsh-tool-skill` 会在 pre-step 边界识别其中以空白为界的 `/name` token并以注入的 `<skill_content>` 上下文作答,因此所有入口Web、TUIACPAgent Client Protocol共享同一条确定性路径手动键入的文本也走该路径,且没有专设的调用协议。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载。命令处理器运行超过 30 秒的传输健康时限仍属正常,因此 `command.execute` 仅携带调用方/连接取消信号;该信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。
`settings.*``credentials.*``llm.*` 领域是配置页协议。settings 领域服务于已注册可配置提供方所指向的 namespace`ctx.llm.listConfigurableProviders()`),并额外服务于一份小型、显式的 allowlist——Web 偏好 `permission` 与产品持有的 `ui-onboarding`;仅新增一项 Settings 注册,绝不会使其可被远程读取或写入。其他任何 namespace 都只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable``credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected``llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate``credentials.set`且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据都折叠为 `model-discovery-failed`其消息是适配器自己的文本details 点名被询问的端点,绝不点名所提供的凭据。三个失效帧让每个面无需轮询即保持收敛:`host/settings-changed {ns}``settings/document-updated` 透传,因此解析值未变的原始变更同样能到达客户端)、`host/credentials-changed {ref}`(只带引用名,绝不带值),以及 `host/models-changed`——它由 `llm/adapters-updated` 和可配置提供方 namespace 的变更触发,因为该提供方的设置正承载着它的目录与端点;`permission``ui-onboarding` 变更只会发出自身的 settings 失效通知。浏览器载体把整个配置面(含读取与原生操作:`settings.describe`/`openDocument`/`update`/`replace`/`mutate``credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。

View File

@@ -8,7 +8,7 @@
* routes — physical carriers wrap `ctx.apiProxy` themselves.
*
* The gateway consumes `ctx.agentDefaultModel`, the transport-independent default
* shared with direct front doors. Switching models persists through that
* shared with direct entry points. Switching models persists through that
* service; sessions that have already logged a selection remain unchanged.
*/

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/plan/plan-mode/README.md
README.md: 6c8ba23b76e83665d4f8dcb5ecb41689347f6423
README.md: c404cfa73024804bc9f166cfb84fa5f87f723459
README.zh.md: 275a87669802f38cd98886236ca63a09ffb3e410

View File

@@ -18,7 +18,7 @@ The review question declares the `plan-review` presentation intent, naming `Appr
When `ctx.commands` is composed, the package registers `/plan [message]` and reserves the exact argument `off` for direct exit. Bare `/plan` selects plan mode; any other non-empty argument selects it first and is then submitted through `agent.steer()`, so it becomes the next step's ordinary logged user message under plan guidance. `/plan off` selects inactive without sending model input; it also cancels a pending entry before plan mode reaches a request.
The Web client consumes the plugin-owned `/plan` command; other front doors may drive the same service directly without defining a second mode vocabulary.
The Web client consumes the plugin-owned `/plan` command; other entry points may drive the same service directly without defining a second mode vocabulary.
## Session projection

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/preset/agent-presets/README.md
README.md: ed640cf053ac595dfb9c20c226f3c2ff34db93f6
README.zh.md: 4e6fc0a4cf0db4b14b136cbad9f73eee64d9c170
README.md: b6d469b26a0254adc654e5cc49d3df2d10817b2d
README.zh.md: 60c7bc695c27bf2c0169a0e405aa84aa711b9b21

View File

@@ -55,6 +55,8 @@ A row's **package name** resolves from the host composition, not from the preset
A **relative** path still resolves from the preset's own directory, so a preset's own plugin files and skill directories travel with it.
An **absolute** filesystem path keeps its own location. The mount converts it to a `file:` URL before ESM import so POSIX paths and Windows drive-letter or UNC paths use a specifier Node accepts.
### Display metadata
A preset may publish display text in an optional `preset.yml` beside its composition:

View File

@@ -55,6 +55,8 @@ agent 工厂的 `setup(agentCtx)` 钩子是唯一受支持的调用点。只有
**相对**路径仍从 preset 自身的目录解析,因此 preset 自带的插件文件与 skill 目录会随它一同迁移。
**绝对**文件系统路径则保留其自身位置。挂载会先将它转换为 `file:` URL 再交给 ESM 导入,从而使 POSIX 路径和 Windows 盘符或 UNC 路径都采用 Node 能够接受的说明符。
### 展示用元信息
preset 可以在组装文件旁的可选 `preset.yml` 里发布展示文本:

View File

@@ -14,6 +14,7 @@
* @module @deepseek-ai/dsh-agent-presets/mount
*/
import { isAbsolute } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Context, type Fiber } from 'cordis'
import { Include } from '@cordisjs/plugin-include'
@@ -69,21 +70,25 @@ class PresetTree extends Include {
* where Node's upward `node_modules` walk never reaches the harness's own
* dependencies, so every `@deepseek-ai/dsh-*` row would fail to import. The
* mount records the host composition's base instead, which is inside the
* installed harness, and bare names resolve from there.
* installed harness, and bare names resolve from there. An absolute
* filesystem path names neither base and becomes a file URL before Node's
* ESM loader receives it, which is required for drive-letter paths on
* Windows.
* @param name - the module specifier from the row.
* @param getOuterStack - the loader's stack composer for import diagnostics.
* @returns the imported module, or the `cordis:` builtin.
*/
override import(name: string, getOuterStack?: () => string[]): unknown {
const specifier = isAbsolute(name) ? pathToFileURL(name).href : name
const base = harnessBase.get(this.config)
/* v8 ignore next -- every PresetTree is constructed by `mountPreset`, which records the base first */
if (base === undefined) return super.import(name, getOuterStack)
if (base === undefined) return super.import(specifier, getOuterStack)
if (name.startsWith('.') || name.startsWith('cordis:')) return super.import(name, getOuterStack)
const internal = this.ctx.loader.internal
/* v8 ignore next -- Node always supplies the internal module loader; the branch keeps a
hypothetical embedder from losing the row's name in a resolution error. */
if (internal === undefined) return super.import(name, getOuterStack)
return internal.import(name, base, {})
if (internal === undefined) return super.import(specifier, getOuterStack)
return internal.import(specifier, base, {})
}
/**

View File

@@ -65,20 +65,23 @@ describe('copying a preset', () => {
expect(listed.find(preset => preset.id === 'mine')?.trust).toBe('user')
})
it('copies the whole directory, execute bits kept and group/other stripped', async () => {
it('copies the whole directory and tightens POSIX modes', async () => {
await seedPreset(userRoot, 'source', {
extras: { 'skills/demo/SKILL.md': '# demo\n', 'skills/demo/run.sh': '#!/bin/sh\n' },
})
await chmod(join(userRoot, 'source', 'skills', 'demo', 'run.sh'), 0o755)
if (process.platform !== 'win32') {
await chmod(join(userRoot, 'source', 'skills', 'demo', 'run.sh'), 0o755)
}
await ctx.agentPresets.copy('source', 'mine')
expect(await readFile(join(userRoot, 'mine', 'skills', 'demo', 'SKILL.md'), 'utf8')).toBe('# demo\n')
// A preset may ship runnable helpers; the copy keeps them runnable for the
// owner while withdrawing the world-readability of the install.
expect((await stat(join(userRoot, 'mine', 'skills', 'demo', 'run.sh'))).mode & 0o777).toBe(0o700)
expect((await stat(join(userRoot, 'mine', 'skills', 'demo', 'SKILL.md'))).mode & 0o777).toBe(0o600)
expect((await stat(join(userRoot, 'mine'))).mode & 0o777).toBe(0o700)
// Windows mode bits are synthetic and cannot represent the inherited DACL.
if (process.platform !== 'win32') {
expect((await stat(join(userRoot, 'mine', 'skills', 'demo', 'run.sh'))).mode & 0o777).toBe(0o700)
expect((await stat(join(userRoot, 'mine', 'skills', 'demo', 'SKILL.md'))).mode & 0o777).toBe(0o600)
expect((await stat(join(userRoot, 'mine'))).mode & 0o777).toBe(0o700)
}
})
it('keeps the source description but never its name or order', async () => {

View File

@@ -1,14 +1,37 @@
import { chmod, mkdtemp, mkdir, writeFile } from 'node:fs/promises'
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { COMPOSITION_FILE, discoverPresets, scanRoot } from '@deepseek-ai/dsh-agent-presets'
const fsHarness = vi.hoisted(() => ({
nextReadError: undefined as NodeJS.ErrnoException | undefined,
}))
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return {
...actual,
readFile: (async (path: unknown, ...rest: never[]) => {
const error = fsHarness.nextReadError
if (error !== undefined) {
fsHarness.nextReadError = undefined
throw error
}
return (actual.readFile as (path: unknown, ...args: never[]) => Promise<unknown>)(path, ...rest)
}) as typeof actual.readFile,
}
})
const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), 'fixtures')
const SYSTEM = { path: join(FIXTURES, 'system'), trust: 'system' as const }
const USER = { path: join(FIXTURES, 'user'), trust: 'user' as const }
beforeEach(() => {
fsHarness.nextReadError = undefined
})
describe('display order', () => {
it('puts declared order first, then everything else by id', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-order-'))
@@ -177,10 +200,11 @@ describe('composition health', () => {
await mkdir(join(root, 'sealed'))
const path = join(root, 'sealed', COMPOSITION_FILE)
await writeFile(path, '[]\n')
await chmod(path, 0o000)
fsHarness.nextReadError = Object.assign(new Error('EACCES: injected read failure'), { code: 'EACCES' })
const [preset] = await scanRoot({ path: root, trust: 'user' })
expect(fsHarness.nextReadError).toBeUndefined()
expect(preset?.broken).toMatch(/cannot be read/)
})

View File

@@ -1,4 +1,4 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
@@ -11,7 +11,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import AgentRegistry, { assembleContextFor, type Agent } from '@deepseek-ai/dsh-agent'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import AgentPresets, {
COMPOSITION_FILE, leakedServices, livePresetMounts, mountPreset, PresetMountError, serviceForAgent,
} from '@deepseek-ai/dsh-agent-presets'
@@ -84,6 +84,23 @@ beforeEach(async () => {
})
describe('composing an agent from a preset', () => {
it('hands an absolute plugin path to Node as a file URL', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-preset-absolute-plugin-'))
const presetDir = join(root, 'absolute')
const plugin = join(FIXTURES, 'plugins', 'contribute.js')
await mkdir(presetDir)
await writeFile(
join(presetDir, COMPOSITION_FILE),
`- id: only\n name: ${plugin}\n config:\n tool: absolute\n`,
)
const scoped = await harness({ default: 'absolute', roots: [{ path: root, trust: 'user' }] })
const imported = vi.spyOn(scoped.loader.internal!, 'import')
await agentOn(scoped, 'sess-absolute-plugin')
expect(imported).toHaveBeenCalledWith(pathToFileURL(plugin).href, expect.any(String), {})
})
it('gives each session only its own preset\'s tools', async () => {
const alpha = await agentOn(ctx, 'sess-alpha', 'standard')
const beta = await agentOn(ctx, 'sess-beta', 'minimal')
@@ -525,6 +542,34 @@ describe('editing a composition file', () => {
expect(livePresetMounts().filter(mount => mount.presetId === 'raced')).toHaveLength(2)
})
it('keeps a newer generation pointer when a stale refresh loses the swap race', async () => {
const { scoped, path } = await editable('guarded-refresh')
const preset = await scoped.agentPresets.resolve('guarded-refresh')
await agentOn(scoped, 'sess-guarded-refresh-seed', 'guarded-refresh')
const service = scoped.agentPresets as unknown as {
standing: Map<string, Promise<{
key: unknown
scope: unknown
stamp: { mtimeMs: number; size: number }
}>>
ensureStanding(current: typeof preset): Promise<unknown>
}
const stalePromise = service.standing.get(preset.id)!
const stale = await stalePromise
await writeFile(path, rowFor('afterwards'))
const { mtimeMs, size } = await stat(path)
const newer = { ...stale, stamp: { mtimeMs, size } }
const newerPromise = Promise.resolve(newer)
// `await pending` yields before the guarded delete, letting the winning
// refresher replace the pointer deterministically instead of by timing.
const refresh = service.ensureStanding(preset)
service.standing.set(preset.id, newerPromise)
expect(await refresh).toBe(newer)
expect(service.standing.get(preset.id)).toBe(newerPromise)
})
it('hands a host reader the standing key without starting an agent', async () => {
const { scoped } = await editable('cold-read')

View File

@@ -215,7 +215,7 @@ describe('LocalPtyBackend startup rollback', () => {
expect(initialized).toHaveBeenCalledWith(undefined)
expect((ctx.sandbox as RecordingSandbox).calls).toEqual([{
argv: ['/bin/bash', '-i'],
policy: { mode: 'workspace-write', workspaceRoot: '/workspace' },
policy: { mode: 'workspace-write', sessionId: 'agent', workspaceRoot: '/workspace' },
}])
})
@@ -247,7 +247,7 @@ describe('LocalPtyBackend startup rollback', () => {
})
expect((ctx.sandbox as RecordingSandbox).calls).toEqual([{
argv: ['/bin/bash', '-i'],
policy: { mode: 'workspace-write', workspaceRoot: '/session-workspace' },
policy: { mode: 'workspace-write', sessionId: 'agent', workspaceRoot: '/session-workspace' },
}])
})

View File

@@ -142,7 +142,7 @@ describe('pty-local real shell', () => {
const created = await ctx.pty.spawn(agent, { type: 'shell' })
expect(sandbox.calls).toEqual([{
argv: ['/bin/bash', '--noprofile', '--norc', '-i'],
policy: { mode: 'workspace-write', workspaceRoot: realpathSync.native(root) },
policy: { mode: 'workspace-write', workspaceRoot: realpathSync.native(root), sessionId: 'agent-workspace-write' },
}])
await fiber.dispose()
expect(ctx.pty.listBackends()).toEqual([])

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-sandbox-local",
"description": "Local process-sandbox backends for the DeepSeek Harness sandbox seam: bwrap, the npm-distributed landlock-run launcher, or macOS Seatbelt — functionally probed, fail-closed",
"description": "Local process-sandbox backends for the DeepSeek Harness sandbox seam: bwrap, the npm-distributed landlock-run launcher, macOS Seatbelt, or the Windows ACL restricted-token runner — functionally probed, fail-closed",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -28,9 +28,11 @@
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-llm": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"@deepseek-ai/dsh-session": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"dependencies": {
"@deepseek-ai/dsh-sandbox-windows-acl": "workspace:^",
"@deepseek-ai/node-addon-landlock-run": "workspace:*",
"schemastery": "^3.18.0"
},
@@ -38,6 +40,7 @@
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -1,12 +1,29 @@
/**
* Local sandbox backend. It selects the platform runner chain (Linux bwrap then
* Landlock; macOS Seatbelt), functionally probes competing candidates once, and
* reports each wrap's enforcement and stderr classification facts. Missing or unusable
* confinement fails closed rather than returning the original argv.
* Landlock; macOS Seatbelt; Windows the ACL restricted-token runner), functionally probes
* competing candidates once, and reports each wrap's enforcement and stderr
* classification facts. Missing or unusable confinement fails closed rather
* than returning the original argv.
*
* The windows-acl rung additionally owns the write grants: the write SID is
* the per-WORKSPACE identity derived from the canonical workspace path
* (`workspaceWriteSid`), and the private temp subdirectory is DERIVED per
* session (session id + workspace — nothing stored). The
* workspace-root ACE materializes once per workspace per server lifetime
* and STANDS (the cross-session reuse cache — the exact-ACE skip makes
* every later provision O(1) instead of re-propagating the tree per
* session); the private-temp ACEs are revoked on dispose. The runner
* receives `--write-sid` (the derived identity; its presence marks the
* seam-managed contract) and stops managing DACLs itself.
* @module @deepseek-ai/dsh-sandbox-local
*/
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
LAUNCHER_BIN,
LAUNCHER_FAILURE_EXIT,
@@ -18,6 +35,8 @@ import z from 'schemastery'
import { assertNever } from '@deepseek-ai/dsh-llm'
import { SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { AclWriteGrant, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl'
import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts'
/** Plugin config. All optional — `static Config` supplies the defaults. */
@@ -70,6 +89,46 @@ function defaultProbeSeatbelt(seatbeltExec: string, timeoutMs: number): boolean
return probe.status === 0
}
/**
* Functional windows-acl probe: run the runner in read-only mode (zero grants,
* no ACL mutation) around `cmd /c exit 0` — exit 0 means the runner created
* the restricted token and spawned the child under it. The win32 chain is a
* sole candidate, so the product never probes; the probe exists for override
* chains and mirrors the other rungs' shape.
*/
function defaultProbeWindowsAcl(runnerInvocation: string[], timeoutMs: number): boolean {
const program = runnerInvocation[0]
if (program === undefined) return false
const probe = spawnSync(program, [
...runnerInvocation.slice(1),
'--workspace', tmpdir(), '--temp', tmpdir(), '--mode', 'read-only',
'--', 'cmd', '/c', 'exit', '0',
], {
timeout: timeoutMs,
stdio: 'ignore',
})
return probe.status === 0
}
/**
* The session's private temp subdirectory: `<tmpdir>\dsh-<16 hex>`, derived
* from the session id and its workspace instead of stored. The same session
* and workspace always name the same directory — a resumed session
* re-grants it (the exact-ACE skip keeps that O(1)) — while a fork's
* different session id names a fresh one. The name is predictable to anyone
* who knows the session id (the confined command sees it as
* `DSH_SESSION_ID`), so the provider creates the directory EXCLUSIVELY and
* rejects reparse points: a pre-placed entry fails the first confined run
* loudly, and cannot redirect the grant onto a foreign object.
* @param sessionId - the policy's calling-session identity.
* @param workspaceRoot - the resolved policy root.
* @returns the session's private temp subdirectory path.
*/
export function sessionTempDir(sessionId: SessionId, workspaceRoot: string): string {
const digest = createHash('sha256').update(String(sessionId)).update('\0').update(workspaceRoot).digest('hex')
return join(tmpdir(), `dsh-${digest.slice(0, 16)}`)
}
/** Test hook: inject probe verdicts / a fake launcher / a platform without real runners. */
export interface SandboxInternals {
/** Replaces `process.platform` for chain selection (exercise any platform's chain from any host). */
@@ -86,10 +145,18 @@ export interface SandboxInternals {
landlockLauncher?: string
/** Replaces the `sandbox-exec` executable the probe and wraps invoke (a fake script). */
seatbeltExec?: string
/** Replaces the resolved windows-acl runner argv prefix (a fake runner). */
windowsAclRunnerArgs?: string[]
/** Replaces the resolved windows-acl runner built entry path (a fake lib/runner.js location). */
windowsAclRunnerEntry?: string
/** Replaces the functional windows-acl probe (the win32 chain's sole rung — only consulted if that chain ever grows). */
probeWindowsAcl?: () => boolean
/** Replaces the private-temp-directory removal at provider dispose (a throwing fake exercises the cleanup-failure path). */
rmTempDir?: (path: string) => void
}
/** The chain's verdict: which runner confines, and how completely it enforces. */
type SelectedRunner = { runner: 'bwrap' | 'landlock' | 'seatbelt'; enforcement: SandboxEnforcement }
type SelectedRunner = { runner: 'bwrap' | 'landlock' | 'seatbelt' | 'windows-acl'; enforcement: SandboxEnforcement }
/**
* The runner chain per platform — selection is BY PLATFORM first, probes
@@ -103,11 +170,10 @@ type SelectedRunner = { runner: 'bwrap' | 'landlock' | 'seatbelt'; enforcement:
const PLATFORM_CHAINS: Record<string, readonly SelectedRunner['runner'][]> = {
linux: ['bwrap', 'landlock'],
darwin: ['seatbelt'],
// Reserved slot, deliberately empty: Windows support fills it with a confinement runner
// (AppContainer / restricted-token family, shipped from its own repository on the
// landlock-run template) plus a SelectedRunner['runner'] union member — the switches'
// assertNever guards then walk the implementer to every site.
win32: [],
// The Windows restricted-token runner (@deepseek-ai/dsh-sandbox-windows-acl):
// a sole candidate, selected without a probe — its execution-time refusal
// fails closed through its stderr signature (windows-acl-run:) and exit 127.
win32: ['windows-acl'],
}
/**
@@ -123,6 +189,13 @@ const STATIC_ENFORCEMENT: Record<SelectedRunner['runner'], SandboxEnforcement> =
bwrap: 'full',
landlock: 'full',
seatbelt: 'full',
// 'full' is the SUPPORTED-SURFACE promise: on NTFS both restricting lists
// close every ambient write (INTERACTIVE/LOCAL and Authenticated Users are
// absent from both — pinned by the runner's Public-probe and CIM-denial
// regressions). FAT-class (non-ACL) targets are declared unsupported
// (warn-only) in the backend README — outside the promise, not an
// exception to it.
'windows-acl': 'full',
}
/**
@@ -145,15 +218,26 @@ const DENIAL_SIGNATURES = {
bwrap: ['read-only file system'],
landlock: ['permission denied'],
seatbelt: ['operation not permitted'],
// pwsh/.NET: "Access to the path '...' is denied."; cmd: "Access is denied.";
// node EACCES: "permission denied".
'windows-acl': ['access is denied', 'access to the path', 'permission denied'],
runnerCommand: ['read-only file system', 'permission denied'],
} as const satisfies Record<SelectedRunner['runner'] | 'runnerCommand', readonly string[]>
/** The windows-acl runner's documented failure exit (its own RUNNER_FAILURE_EXIT contract, distinct from Landlock's 125). */
const WINDOWS_ACL_RUNNER_FAILURE_EXIT = 127
/**
* Runner-owned fatal diagnostics. Landlock has a versioned exit-125 plus
* fatal-line launcher-failure contract. Bubblewrap's current fatal paths exit
* 1 but its public contract does not reserve that status, while sandbox-exec
* publishes no launcher-failure status; those backends remain signature-only.
* Keep the Landlock tuple aligned with the assembled snapshot fixture at
* The windows-acl runner prints `windows-acl-run: <detail>` on every
* runner-side failure and exits 127 — the rule is exit-gated on that status
* so a confined command that merely PRINTS the signature (or a runner
* cleanup failure reported on a non-zero child exit) is never misclassified
* as "the command did not run". Keep the Landlock tuple aligned with the
* assembled snapshot fixture at
* `examples/acp-agent/tests/fixtures/partial-landlock-sandbox.ts`.
*/
const RUNNER_FAILURE_RULES = {
@@ -164,12 +248,15 @@ const RUNNER_FAILURE_RULES = {
informationalLines: [`${LAUNCHER_BIN}: partial enforcement (older Landlock ABI)`],
}],
seatbelt: [{ fatalSignatures: ['sandbox-exec: '] }],
'windows-acl': [{ allowedExitCodes: [WINDOWS_ACL_RUNNER_FAILURE_EXIT], fatalSignatures: ['windows-acl-run: '] }],
} as const satisfies Record<SelectedRunner['runner'], readonly RunnerFailureRule[]>
/**
* Local process-sandbox provider. Registers as `ctx.sandbox`. Stateless
* apart from the cached chain verdict — it spawns nothing but the one-time
* probes, so there is no disposal work beyond cordis' own.
* Local process-sandbox provider. Registers as `ctx.sandbox`. Caches the
* chain verdict and, on the windows-acl rung, the write grants
* ({@link AclWriteGrant}: the standing workspace-root grant per workspace
* and the revocable private-temp grant per session, the latter revoked on
* provider dispose); the one-time probes spawn nothing else.
*/
export class LocalSandboxProvider extends SandboxProvider {
// Inline schema call: the config catalog walks `static Config` statically.
@@ -187,6 +274,16 @@ export class LocalSandboxProvider extends SandboxProvider {
private readonly probeTimeoutMs: number
/** Cached chain verdict; undefined until the first confined wrap needs it. */
private selectedRunner: SelectedRunner | 'unavailable' | undefined
/**
* Server-lifetime write grants (windows-acl rung): the STANDING
* workspace-root grant per workspace (its ACE is the cross-session reuse
* cache and outlives the provider — never revoked) and the REVOCABLE
* private-temp grant per session (revoked on provider dispose).
*/
private readonly workspaceGrants = new Map<string, AclWriteGrant>()
private readonly tempGrants = new Map<string, AclWriteGrant>()
/** Session id → the private temp directory this provider created (removed on dispose). */
private readonly tempDirs = new Map<string, string>()
constructor(ctx: Context, config: Config) {
super(ctx)
@@ -208,6 +305,13 @@ export class LocalSandboxProvider extends SandboxProvider {
this.configuredRunnerFailureSignatures = runnerFailureSignatures
this.probeTimeoutMs = config.probeTimeoutMs as number
assertPositiveFinite('probeTimeoutMs', this.probeTimeoutMs)
// The temp grants are revoked with the provider: a clean server
// shutdown leaves no temp ACEs behind (workspace ACEs stand by design —
// the reuse cache; an unclean shutdown leaves them for the next
// provision's exact-ACE skip).
ctx.effect(() => () => {
this.revokeAclGrants()
})
}
/**
@@ -246,10 +350,154 @@ export class LocalSandboxProvider extends SandboxProvider {
case 'bwrap': return ['bwrap', ...bwrapProfileArgs(policy)]
case 'landlock': return [this.landlockLauncher(), ...landlockProfileArgs(policy)]
case 'seatbelt': return [this.seatbeltExec(), ...seatbeltProfileArgs(policy)]
case 'windows-acl': return this.windowsAclRunnerArgv(policy)
default: return assertNever(runner)
}
}
/**
* The windows-acl runner argv for one policy. With a calling session (the
* policy's `sessionId`), the write grants are materialized once per server
* lifetime — the standing workspace-root grant per workspace and the
* revocable private-temp grant per session — and the runner receives
* `--write-sid` (the workspace-derived identity; its presence marks the
* seam-managed DACL contract) plus, under workspace-write, the session's
* PRIVATE temp subdirectory (derived from session id + workspace) — it
* grants nothing and revokes nothing. Agentless calls pass the ambient
* temp root and no `--write-sid`: the runner self-manages its DACLs.
* @param policy - the resolved per-call policy.
* @returns the runner invocation.
*/
private windowsAclRunnerArgv(policy: SandboxPolicy): string[] {
const sessionId = policy.sessionId
if (sessionId === undefined) {
return [
...this.windowsAclRunnerInvocation(),
'--workspace', policy.workspaceRoot,
'--temp', tmpdir(),
'--mode', policy.mode,
]
}
this.materializeAclGrant(sessionId, policy.workspaceRoot, policy.mode)
return [
...this.windowsAclRunnerInvocation(),
'--workspace', policy.workspaceRoot,
// Workspace-write sessions confine their temp writes to the PRIVATE
// per-session subdirectory (bwrap --tmpfs /tmp semantics); read-only
// runs pass the ambient temp root — the runner validates it exists
// but grants nothing. The derived write SID is the per-workspace
// identity; the flag's presence marks the seam-managed DACL contract.
'--temp', policy.mode === 'workspace-write' ? sessionTempDir(sessionId, policy.workspaceRoot) : tmpdir(),
'--mode', policy.mode,
'--write-sid', workspaceWriteSid(policy.workspaceRoot),
]
}
/**
* Materialize the session's ACEs once per server lifetime: lazily at its
* first confined execution, reused for every later call (the map hits are
* the whole call). The write SID is the per-workspace identity derived
* from the workspace. Workspace-write grants the workspace root STANDING
* (the ACE outlives every session — the reuse cache) and the session's
* private temp subdirectory REVOCABLY — the directory is derived from
* session id + workspace, created here EXCLUSIVELY (a pre-existing entry
* or a reparse point fails the first confined run loudly, so the grant
* never lands on a foreign object); read-only materializes NOTHING — its
* token alone restricts every write, and the standing grant from an
* earlier workspace-write period is KEPT through a downgrade (never
* revoked): the read-only restricted token carries no write SID (the
* read-only list), so the ACE is inert there, while the map hit keeps the
* re-upgrade free of re-propagation. Fail-closed: a half-materialized
* temp grant is revoked before the error propagates.
* @param sessionId - the policy's calling-session identity.
* @param workspaceRoot - the resolved policy root.
* @param mode - the policy mode (grants exist only under workspace-write).
*/
private materializeAclGrant(sessionId: SessionId, workspaceRoot: string, mode: ConfinedSandboxMode): void {
if (mode === 'read-only') return
const writeSid = workspaceWriteSid(workspaceRoot)
const tempDir = sessionTempDir(sessionId, workspaceRoot)
if (!this.workspaceGrants.has(workspaceRoot)) {
const grant = AclWriteGrant.create(writeSid)
try {
grant.add(workspaceRoot, true)
} catch (error) {
// Free the SID; a standing ACE (if the apply succeeded before a
// post-apply throw) is the intended end state, not an error
// artifact — nothing to revoke.
try {
grant.dispose()
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], 'sandbox-local windows-acl workspace grant failed and its cleanup also failed')
}
throw error
}
this.workspaceGrants.set(workspaceRoot, grant)
}
if (this.tempGrants.has(sessionId)) return
const grant = AclWriteGrant.create(writeSid)
// The directory is removed again in the catch only when THIS confine
// created it — a pre-existing entry (EEXIST) is a foreign object and is
// never deleted.
let created = false
try {
// Exclusive creation (no `recursive`): a pre-existing entry OR a
// reparse point both fail EEXIST — the grant never lands on a foreign
// object.
mkdirSync(tempDir)
created = true
grant.add(tempDir)
} catch (error) {
if (created) rmSync(tempDir, { recursive: true, force: true })
// Revoke whatever stands and free the SID — never leave a half-grant
// behind a failed confine (the runner never runs).
try {
grant.dispose()
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], 'sandbox-local windows-acl temp grant materialization failed and its cleanup also failed')
}
throw error
}
this.tempGrants.set(sessionId, grant)
this.tempDirs.set(sessionId, tempDir)
}
/**
* Dispose every write grant (provider dispose): the revocable temp ACEs
* are revoked, the private temp directories this provider created are
* removed, and every SID allocation is freed; the standing workspace ACEs
* stay (the reuse cache). Cleanup failures are reported, not thrown:
* cordis teardown must not be aborted by grant cleanup. A crash skips all
* of it — the next resume then fails loudly at the exclusive creation and
* OS temp hygiene (or manual removal) recovers.
*/
private revokeAclGrants(): void {
if (this.workspaceGrants.size === 0 && this.tempGrants.size === 0) return
const failures: unknown[] = []
for (const grant of [...this.workspaceGrants.values(), ...this.tempGrants.values()]) {
try {
grant.dispose()
} catch (error) {
failures.push(error)
}
}
const rmTempDir = this.internals.rmTempDir ?? ((dir: string) => { rmSync(dir, { recursive: true, force: true }) })
for (const dir of this.tempDirs.values()) {
try {
rmTempDir(dir)
} catch (error) {
failures.push(error)
}
}
this.workspaceGrants.clear()
this.tempGrants.clear()
this.tempDirs.clear()
if (failures.length > 0) {
this.ctx.logger.warn(`sandbox-local: windows-acl grant cleanup completed with ${failures.length} failure(s)`)
for (const error of failures) this.ctx.logger.warn(error)
}
}
/**
* Resolve which runner confines commands, once, for the provider's
* lifetime: this platform's chain ({@link PLATFORM_CHAINS}), its sole
@@ -296,6 +544,11 @@ export class LocalSandboxProvider extends SandboxProvider {
const probe = this.internals.probeSeatbelt ?? (exec => defaultProbeSeatbelt(exec, this.probeTimeoutMs))
return probe(this.seatbeltExec()) ? 'full' : 'unusable'
}
case 'windows-acl': {
const probe = this.internals.probeWindowsAcl
?? (() => defaultProbeWindowsAcl(this.windowsAclRunnerInvocation(), this.probeTimeoutMs))
return probe() ? 'full' : 'unusable'
}
default: return assertNever(runner)
}
}
@@ -309,6 +562,21 @@ export class LocalSandboxProvider extends SandboxProvider {
private seatbeltExec(): string {
return this.internals.seatbeltExec ?? 'sandbox-exec'
}
/**
* The windows-acl runner argv prefix: the built lib/runner.js entry when
* present (production), else the package source through tsx (development).
* The prefix stays `[node, runner, ...]` — a future native-exe runner keeps
* the same argv contract and only swaps these entries.
*/
private windowsAclRunnerInvocation(): string[] {
const override = this.internals.windowsAclRunnerArgs
if (override !== undefined) return override
const builtEntry = this.internals.windowsAclRunnerEntry ?? fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-sandbox-windows-acl/runner'))
if (existsSync(builtEntry)) return [process.execPath, builtEntry]
const sourceEntry = fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-sandbox-windows-acl/src/runner.ts'))
return [process.execPath, '--import', 'tsx/esm', sourceEntry]
}
}
export default LocalSandboxProvider

View File

@@ -0,0 +1,404 @@
/**
* windows-acl write grants: the SERVER-LIFETIME ACE materialization
* (standing workspace grant per workspace, revocable private-temp grant per
* session) plus the derived private-temp identity, through the REAL
* LocalSandboxProvider.confine(). Win32 surface mocked at the package
* boundary (the workspace-derived SID mocked to a constant); the real-FFI
* grant behavior lives in sandbox-windows-acl's win32 tests.
*/
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { SessionId } from '@deepseek-ai/dsh-session'
import { LocalSandboxProvider, sessionTempDir } from '@deepseek-ai/dsh-sandbox-local'
/** Cross-file state shared with the vi.mock factory (hoisting contract). */
const mockState = vi.hoisted(() => ({
grants: [] as Array<{ writeSid: string; added: Array<{ path: string; standing: boolean }>; disposed: boolean }>,
addFailure: undefined as Error | undefined,
/** Restricts {@link addFailure} to this path (undefined = every add throws). */
addFailurePath: undefined as string | undefined,
disposeFailure: undefined as Error | undefined,
}))
vi.mock('@deepseek-ai/dsh-sandbox-windows-acl', () => {
class MockAclWriteGrant {
readonly writeSid: string
readonly added: Array<{ path: string; standing: boolean }> = []
disposed = false
constructor(writeSid: string) {
this.writeSid = writeSid
mockState.grants.push(this)
}
static create(writeSid: string): MockAclWriteGrant {
return new MockAclWriteGrant(writeSid)
}
add(path: string, standing = false): void {
if (mockState.addFailure !== undefined && (mockState.addFailurePath === undefined || mockState.addFailurePath === path)) {
throw mockState.addFailure
}
this.added.push({ path, standing })
}
dispose(): void {
if (mockState.disposeFailure !== undefined) throw mockState.disposeFailure
this.disposed = true
}
}
return { AclWriteGrant: MockAclWriteGrant, workspaceWriteSid: () => 'S-1-4-42-42' }
})
/** The workspace-derived write SID the mock pins for every workspace. */
const DERIVED_SID = 'S-1-4-42-42'
async function setup() {
const ctx = new Context()
const fiber = await ctx.plugin(LocalSandboxProvider, {})
const sandbox = ctx.sandbox as LocalSandboxProvider
sandbox.internals = { platform: 'win32', windowsAclRunnerArgs: ['node', 'windows-acl-runner.js'] }
return { ctx, sandbox, fiber }
}
/** A workspace root the policy carries. */
function workspaceRoot(): string {
return mkdtempSync(join(tmpdir(), 'dsh-acl-grants-ws-'))
}
describe('windows-acl write grants (LocalSandboxProvider)', () => {
const scratch: string[] = []
beforeEach(() => {
mockState.grants = []
mockState.addFailure = undefined
mockState.addFailurePath = undefined
mockState.disposeFailure = undefined
})
const cleanup = () => {
for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true })
}
it('workspace-write: first confine materializes ONCE (standing workspace + revocable private temp), the derived temp dir rides the argv', async () => {
try {
const { sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const tempDir = sessionTempDir(SessionId('sess-1'), ws)
scratch.push(tempDir)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-1') }
const confined = sandbox.confine(['pwsh', '/Command', 'x'], policy)
expect(confined.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tempDir,
'--mode', 'workspace-write',
'--write-sid', DERIVED_SID,
'--',
'pwsh', '/Command', 'x',
])
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: ws, standing: true }], // standing: the reuse cache, never revoked
disposed: false,
})
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: tempDir, standing: false }],
disposed: false,
})
expect(existsSync(tempDir)).toBe(true) // created exclusively
// Reuse: the second confine is the map hits.
sandbox.confine(['pwsh', '/Command', 'x'], policy)
expect(mockState.grants).toHaveLength(2)
await fiber.dispose()
// dispose() runs on BOTH grants: the standing workspace ACE is left in
// place (the mock marks it disposed only as instance teardown).
expect(mockState.grants[0]!.disposed).toBe(true)
expect(mockState.grants[1]!.disposed).toBe(true)
} finally {
cleanup()
}
})
it('mode switch: read-only materializes nothing, the upgrade materializes ONCE with the derived SID, the downgrade keeps the standing grant', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const tempDir = sessionTempDir(SessionId('sess-switch'), ws)
scratch.push(tempDir)
const readOnly: SandboxPolicy = { mode: 'read-only', workspaceRoot: ws, sessionId: SessionId('sess-switch') }
const workspaceWrite: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-switch') }
// read-only first: nothing materialized, ambient temp.
const confinedRo = sandbox.confine(['true'], readOnly)
expect(confinedRo.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tmpdir(), // NOT the private subdir: read-only grants nothing
'--mode', 'read-only',
'--write-sid', DERIVED_SID,
'--',
'true',
])
expect(mockState.grants).toHaveLength(0)
expect(existsSync(tempDir)).toBe(false)
// Upgrade: first workspace-write materializes with the derived SID.
const upgraded = sandbox.confine(['true'], workspaceWrite)
expect(upgraded.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tempDir,
'--mode', 'workspace-write',
'--write-sid', DERIVED_SID,
'--',
'true',
])
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]).toMatchObject({ writeSid: DERIVED_SID, added: [{ path: ws, standing: true }], disposed: false })
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: tempDir, standing: false }],
disposed: false,
})
expect(existsSync(tempDir)).toBe(true)
// Reuse: map hits.
sandbox.confine(['true'], workspaceWrite)
expect(mockState.grants).toHaveLength(2)
// Downgrade: standing grant KEPT (inert under read-only, free re-upgrade).
sandbox.confine(['true'], readOnly)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false)
} finally {
cleanup()
}
})
it('resume: a fresh provider derives the SAME temp dir for the same session and workspace and re-grants it', async () => {
try {
const ws = workspaceRoot()
scratch.push(ws)
const first = await setup()
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('resumed') }
const firstConfined = first.sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
// Clean restart: dispose revokes the temp ACE and removes the private
// temp directory, so the fresh provider's exclusive creation succeeds.
await first.fiber.dispose()
mockState.grants = []
const second = await setup()
const secondConfined = second.sandbox.confine(['true'], policy)
expect(secondConfined.argv).toEqual(firstConfined.argv)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: sessionTempDir(SessionId('resumed'), ws), standing: false }],
})
await second.fiber.dispose()
} finally {
cleanup()
}
})
it('fork: a different session id derives a DIFFERENT private temp identity over the same workspace', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const parentPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('parent') }
const childPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('child') }
sandbox.confine(['true'], parentPolicy)
const parentTemp = sessionTempDir(SessionId('parent'), ws)
scratch.push(parentTemp)
sandbox.confine(['true'], childPolicy)
const childTemp = sessionTempDir(SessionId('child'), ws)
scratch.push(childTemp)
// Fresh temp identity, NOT the parent's (the workspace SID is shared by
// derivation — the workspace is the same, so the standing grant is the
// map hit and only the child's temp grant joins).
expect(childTemp).not.toBe(parentTemp)
expect(mockState.grants).toHaveLength(3)
expect(mockState.grants[2]).toMatchObject({ added: [{ path: childTemp, standing: false }] })
} finally {
cleanup()
}
})
it('creates the private temp dir EXCLUSIVELY: a pre-existing entry or a reparse point fails EEXIST, never receiving the temp grant', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
// Pre-existing entry: exclusive mkdir throws EEXIST instead of adopting it.
const preexisting = sessionTempDir(SessionId('preexisting'), ws)
mkdirSync(preexisting)
scratch.push(preexisting)
const prePolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('preexisting') }
expect(() => sandbox.confine(['true'], prePolicy)).toThrow(/EEXIST/)
// The standing workspace grant is the intended end state and stays; the
// failed temp grant self-disposes.
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false)
expect(mockState.grants[1]!.disposed).toBe(true) // self-revoked
// Reparse point: same EEXIST (exclusive mkdir never follows links).
const target = mkdtempSync(join(tmpdir(), 'dsh-acl-junction-target-'))
scratch.push(target)
const linkPath = sessionTempDir(SessionId('reparse'), ws)
symlinkSync(target, linkPath)
scratch.push(linkPath)
const linkPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('reparse') }
expect(() => sandbox.confine(['true'], linkPolicy)).toThrow(/EEXIST/)
// Same workspace as the preexisting case: the standing workspace grant
// is the map hit (not recreated) — only the failed temp grant joins.
expect(mockState.grants).toHaveLength(3)
expect(mockState.grants[2]!.disposed).toBe(true)
// Temp-side cleanup failure: the standing workspace grant stays (map
// hit), the exclusive mkdir fails, AND the temp grant's dispose also
// fails — the temp cleanup AggregateError propagates.
mockState.grants = []
mockState.disposeFailure = new Error('temp cleanup exploded')
const dupTemp = sessionTempDir(SessionId('temp-cleanup-fail'), ws)
mkdirSync(dupTemp)
scratch.push(dupTemp)
const dupPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('temp-cleanup-fail') }
expect(() => sandbox.confine(['true'], dupPolicy)).toThrow(/temp grant materialization failed and its cleanup also failed/)
expect(mockState.grants).toHaveLength(1) // only the failed temp grant (the workspace grant was the map hit)
} finally {
cleanup()
}
})
it('a grant failure mid-materialization disposes the failed grant and rethrows (AggregateError when the cleanup also fails)', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
scratch.push(sessionTempDir(SessionId('sess-add-fail'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-add-fail') }
// add() throws on the FIRST (workspace) grant: cleanup dispose() runs, original error propagates.
mockState.addFailure = new Error('grant exploded')
expect(() => sandbox.confine(['true'], policy)).toThrow('grant exploded')
expect(mockState.grants).toHaveLength(1)
expect(mockState.grants[0]!.disposed).toBe(true)
// add() AND dispose() both throw: AggregateError.
mockState.grants = []
mockState.addFailure = new Error('grant exploded again')
mockState.disposeFailure = new Error('cleanup exploded')
expect(() => sandbox.confine(['true'], policy)).toThrow(AggregateError)
} finally {
cleanup()
}
})
it('a temp add failure after the exclusive mkdir removed the half-created directory again', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const tempDir = sessionTempDir(SessionId('sess-temp-add-fail'), ws)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-temp-add-fail') }
// The workspace grant succeeds; only the TEMP grant's add throws (the
// path-targeted failure keeps the workspace branch intact).
mockState.addFailurePath = tempDir
mockState.addFailure = new Error('temp add exploded')
expect(() => sandbox.confine(['true'], policy)).toThrow('temp add exploded')
expect(existsSync(tempDir)).toBe(false) // the half-created directory is removed again
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false) // the standing workspace grant stays
expect(mockState.grants[1]!.disposed).toBe(true) // the failed temp grant self-disposes
} finally {
cleanup()
}
})
it('agentless calls stay self-managed: no --write-sid, the ambient temp root, no grants', async () => {
try {
const { sandbox, fiber } = await setup()
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: '/ws' }
const confined = sandbox.confine(['pwsh', '/Command', 'x'], policy)
expect(confined.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', '/ws',
'--temp', tmpdir(),
'--mode', 'workspace-write',
'--',
'pwsh', '/Command', 'x',
])
expect(mockState.grants).toHaveLength(0)
await fiber.dispose()
} finally {
cleanup()
}
})
it('a failing dispose at provider teardown is reported via ctx.logger.warn and never thrown into teardown', async () => {
try {
const { ctx, sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
scratch.push(sessionTempDir(SessionId('sess-dispose'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-dispose') }
sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
mockState.disposeFailure = new Error('revoke exploded')
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
await fiber.dispose()
// BOTH grants (standing workspace + revocable temp) fail their dispose.
expect(warn).toHaveBeenCalledWith(expect.stringContaining('cleanup completed with 2 failure(s)'))
expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'revoke exploded' }))
} finally {
cleanup()
}
})
it('a failing private-temp removal at provider teardown is reported via ctx.logger.warn and never thrown into teardown', async () => {
try {
const { ctx, sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
scratch.push(sessionTempDir(SessionId('sess-rm-fail'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-rm-fail') }
sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
sandbox.internals.rmTempDir = () => { throw new Error('rm exploded') }
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
await fiber.dispose()
// Both grants dispose cleanly; only the directory removal fails.
expect(warn).toHaveBeenCalledWith(expect.stringContaining('cleanup completed with 1 failure(s)'))
expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'rm exploded' }))
} finally {
cleanup()
}
})
it('sessionTempDir derives the same well-shaped name for the same session and workspace, distinct otherwise', () => {
const base = sessionTempDir(SessionId('sess-a'), '/ws/a')
expect(basename(base)).toMatch(/^dsh-[0-9a-f]{16}$/)
expect(sessionTempDir(SessionId('sess-a'), '/ws/a')).toBe(base)
expect(sessionTempDir(SessionId('sess-b'), '/ws/a')).not.toBe(base) // different session
expect(sessionTempDir(SessionId('sess-a'), '/ws/b')).not.toBe(base) // different workspace
// The separator prevents id/workspace collisions from merging inputs.
expect(sessionTempDir(SessionId('ab'), '/ws/c')).not.toBe(sessionTempDir(SessionId('a'), '/ws/bc'))
})
})

View File

@@ -209,13 +209,10 @@ describe('the platform chains', () => {
expect(probeSeatbelt).not.toHaveBeenCalled()
})
it('win32 is a reserved EMPTY chain: fails closed identically until a Windows runner fills it', async () => {
// The slot exists so Windows support is an additive fill-in (chain entry
// + runner union member), never a redesign — and reserving it must not
// weaken the fail-closed end in the meantime.
const { sandbox } = await setup({}, { platform: 'win32' })
expect(() => sandbox.confine(['true'], RO)).toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
})
// The win32 chain's argv contract, denial dialect, and runner-failure rules
// live in @deepseek-ai/dsh-sandbox-windows-acl/tests/provider-chain.spec.ts
// (platform-independent assertions that run in every CI lane, including
// Windows where this package's POSIX-only suites are excluded).
it('caches the verdict for the provider lifetime: one chain walk across wraps', async () => {
const probeBwrap = vi.fn(() => true)
@@ -368,3 +365,63 @@ describe('the default seatbelt probe (sandbox-exec contract)', () => {
expect(() => sandbox.confine(['true'], RO)).toThrow(expect.objectContaining({ code: SANDBOX_UNAVAILABLE }))
})
})
describe('the windows-acl probe (runner invocation contract)', () => {
// The product chain reaches windows-acl only unprobed (win32's sole
// candidate), so the probe case and the runner-entry resolution are pinned
// through the chain seam, mirroring the seatbelt default-probe contract.
it('selects the rung when the injected probe passes, speaking the ACL dialect', async () => {
const probeWindowsAcl = vi.fn(() => true)
const { sandbox } = await setup({}, {
chain: ['windows-acl', 'bwrap'],
probeWindowsAcl,
probeBwrap: () => false,
windowsAclRunnerArgs: ['node', 'windows-acl-runner.js'],
})
const confined = sandbox.confine(['true'], RO)
expect(probeWindowsAcl).toHaveBeenCalledTimes(1)
expect(confined.argv.slice(-4)).toEqual(['--mode', 'read-only', '--', 'true'])
expect(confined.enforcement).toBe('full')
expect(confined.denialSignatures).toEqual(['access is denied', 'access to the path', 'permission denied'])
expect(confined.runnerFailureRules).toEqual([{ allowedExitCodes: [127], fatalSignatures: ['windows-acl-run: '] }])
})
it('reads a failing probe as unusable and walks to the next rung', async () => {
const probeWindowsAcl = vi.fn(() => false)
const { sandbox } = await setup({}, { chain: ['windows-acl', 'bwrap'], probeWindowsAcl, probeBwrap: () => true })
const confined = sandbox.confine(['true'], RO)
expect(confined.argv[0]).toBe('bwrap')
expect(probeWindowsAcl).toHaveBeenCalledTimes(1)
})
it('runs the REAL default probe against the resolved runner invocation when none is injected', async () => {
// The default probe spawns the exact runner argv confine would use — the
// runner source through tsx on a lib-less checkout. The windows-acl
// runner cannot init off win32, so the probe reads unusable and the walk
// falls through to the injected bwrap verdict on every host.
const { sandbox } = await setup({}, { chain: ['windows-acl', 'bwrap'], probeBwrap: () => true })
const confined = sandbox.confine(['true'], RO)
expect(confined.argv[0]).toBe('bwrap')
}, 30_000)
it('reads an empty runner invocation as unusable (the probe\'s empty-argv guard)', async () => {
// windowsAclRunnerInvocation always yields [node, ...] in product; an
// override returning [] exercises the default probe's empty-argv guard.
const { sandbox } = await setup({}, { chain: ['windows-acl', 'bwrap'], probeBwrap: () => true, windowsAclRunnerArgs: [] })
const confined = sandbox.confine(['true'], RO)
expect(confined.argv[0]).toBe('bwrap')
})
it('prefers the built lib/runner.js entry when the resolved file exists', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-fake-acl-entry-'))
const builtEntry = join(dir, 'runner.js')
writeFileSync(builtEntry, '')
const { sandbox } = await setup({}, {
chain: ['windows-acl', 'bwrap'],
probeWindowsAcl: () => true,
windowsAclRunnerEntry: builtEntry,
})
const confined = sandbox.confine(['true'], RO)
expect(confined.argv.slice(0, 2)).toEqual([process.execPath, builtEntry])
})
})

View File

@@ -28,6 +28,10 @@ const platformPackageName = `@deepseek-ai/node-addon-landlock-run-linux-${proces
/** The harness closure the consumer needs; native tarballs are packed through their mode-preserving release script. */
const WORKSPACE_CLOSURE = [
'packages/sandbox/sandbox-local',
// sandbox-local's win32 chain rung is a runtime dependency: a packed
// consumer resolves it like any other @deepseek-ai peer (koffi arrives
// from the registry).
'packages/sandbox/sandbox-windows-acl',
'packages/sandbox/sandbox',
'packages/llm/llm',
'packages/attachment/attachment',

View File

@@ -26,6 +26,12 @@
{
"path": "../sandbox"
},
{
"path": "../sandbox-windows-acl"
},
{
"path": "../../core/session"
},
{
"path": "../../support/invariants"
}

View File

@@ -137,6 +137,7 @@ export class SandboxPolicyService extends Service {
return {
mode: request.mode ?? (session === undefined ? undefined : this.overrideOf(session)) ?? this.defaultMode,
workspaceRoot: resolveWorkspaceRoot(session?.header.cwd ?? this.workspaceRoot),
...session === undefined ? {} : { sessionId: session.id },
}
}

View File

@@ -69,10 +69,12 @@ describe('SandboxPolicyService', () => {
expect(ctx.sandboxPolicy.resolve({ session: first })).toEqual({
mode: 'workspace-write',
workspaceRoot: resolve('/projects/first'),
sessionId: 'sess-first',
})
expect(ctx.sandboxPolicy.resolve({ session: second })).toEqual({
mode: 'read-only',
workspaceRoot: resolve('/projects/second'),
sessionId: 'sess-second',
})
expect(ctx.sandboxPolicy.overrideOf(first)).toBeUndefined()
expect(ctx.sandboxPolicy.overrideOf(second)).toBe('read-only')
@@ -98,6 +100,7 @@ describe('SandboxPolicyService', () => {
expect(ctx.sandboxPolicy.resolve({ session: session('sess-symlink-parent', cwd) })).toEqual({
mode: 'workspace-write',
workspaceRoot: realpathSync.native(physical),
sessionId: 'sess-symlink-parent',
})
} finally {
rmSync(root, { recursive: true, force: true })
@@ -111,6 +114,7 @@ describe('SandboxPolicyService', () => {
expect(ctx.sandboxPolicy.resolve({ session: active, mode: 'danger-full-access' })).toEqual({
mode: 'danger-full-access',
workspaceRoot: resolve('/projects/approved'),
sessionId: 'sess-approved',
})
})

View File

@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/sandbox/sandbox-windows-acl/README.md
README.md: b13160f7490878143c719ca617936b74ffd298af
README.zh.md: 9895449f6f416ad971bbbfff700c9fd62ad99c44

View File

@@ -0,0 +1,91 @@
# @deepseek-ai/dsh-sandbox-windows-acl
English | [中文](README.zh.md)
Windows write-restriction sandbox backend for the [harness sandbox seam](../sandbox/): a Node.js/[koffi](https://koffi.dev/) port of the mechanism in [huoyaoyuan/windows-acl-restrict-poc](https://github.com/huoyaoyuan/windows-acl-restrict-poc) (`10e4dfb`, the fixed revision), mounted as the win32 rung of the [`@deepseek-ai/dsh-sandbox-local`](../sandbox-local/) chain (`workspace-write` / `read-only` modes); the same package carries the Linux/macOS backends.
Mechanism in one line: the caller's token is duplicated into a `WRITE_RESTRICTED` token whose restricting SIDs include a write SID (`S-1-4-x-y`) whose Write ACEs exist only on the workspace and the session's private temp directory. The write SID is the per-WORKSPACE identity, derived deterministically from the canonical workspace path (`workspaceWriteSid`), so the workspace-root ACE materializes once per workspace per machine — every later session, call, or restart hits the exact-ACE skip — instead of once per session (see [The confinement runner](#the-confinement-runner)). Windows then grants a write only where BOTH the caller's normal access AND the restricting-SID intersection allow it — the write SID is the write allowlist, and it grants nothing anywhere else on the system; the token's write check also inherits the ambient write ACEs of the OTHER restricting SIDs (the keep-alive group logon SID + Everyone — the Modes section below is the complete boundary).
Building directly on the raw ACL mechanism is the recorded design choice: it implements both confinement modes without the problems the rejected container options carry — see the [design note](../../../.agents/notes/implemented/feature/2026-08-08-windows-acl-restricted-token-sandbox.md) ([mxc](https://github.com/microsoft/mxc/blob/main/docs/process-container/os-version-support.md) needs an OS floor of Windows 11 24H2 and wholesale host DACL writes for arbitrary-path reads; AppContainer cannot do arbitrary-path reads at all).
## Usage
```ts
import { AclSandbox, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl'
const workspaceRoot = process.cwd()
// mode selects the token's restricting-SID list (see Modes below) and must
// match the grant shape: read-only pairs with zero grants. workspace-write
// REQUIRES the workspace's write SID — the per-workspace identity.
const sandbox = new AclSandbox({ writableDirs: [workspaceRoot], writeSid: workspaceWriteSid(workspaceRoot), mode: 'workspace-write' })
await sandbox.init() // throws on ANY Win32 failure — never spawns unrestricted
const child = sandbox.spawn({ command: 'pwsh', args: ['-NoProfile', '-Command', '...'], cwd: workspaceRoot })
const { stdout, stderr, exitCode } = await child.wait()
sandbox.dispose() // revokes the revocable (temp) grant, keeps the standing workspace ACE; reports every cleanup failure
```
A direct `AclSandbox` grants the workspace ACEs STANDING (dispose() leaves them — they are the cross-instance reuse cache) and the temp ACE revocably (dispose() revokes it, so an inheritable ACE never outlives the instance on the ambient temp root). The server-side reuse is the `AclWriteGrant` class: `add(path, standing)` per directory, `dispose()` revokes the revocable paths and frees the SID — see the runner contract below. Every Win32 API call in this package is checked; failures throw `Win32Error` carrying the API name, the exact Win32 code, the `FormatMessageW` system text, and the failing path/context. This is deliberate: the POC ignored every return value and, when `CreateRestrictedToken` failed, silently ran the child with the FULL unrestricted token (fail-open). This port fails closed by construction.
## The confinement runner
The seam-facing shape is the **runner entry** (`./runner`), the argv-prefix wrapper `@deepseek-ai/dsh-sandbox-local` spawns in place of the caller's command — the same architecture as bwrap/landlock-run/sandbox-exec, so the sandbox seam's `confine()` contract needs no change. Stable argv contract:
```sh
node runner.js --workspace <dir> --temp <dir> --mode <read-only|workspace-write> [--write-sid <S-1-4-…>] -- <argv...>
```
The runner creates the restricted token, spawns the wrapped argv under it with the caller's stdio passed straight through (the caller's pipes, made inheritable around the spawn — Node clears stdio inheritability at startup, which raw spawns must compensate for), wraps the child in a `KILL_ON_JOB_CLOSE` job (a dead runner kills the child), ignores its own console Ctrl+C so the child handles its own, mirrors the child's exit code, and revokes its temp grant on exit (workspace ACEs stand). Every runner-side failure prints `windows-acl-run: <detail>` to stderr and exits 127 — the seam's `RUNNER_FAILURE_RULES` match that signature, so a runner refusal is never mistaken for a denial.
**Workspace grant reuse** (`--write-sid`): the write SID is DERIVED from the workspace path — no SID or temp-dir state is stored anywhere (the previous per-session random SID and its tamper surface are gone). The seam materializes the workspace ACE STANDING (once per workspace per server lifetime, never revoked — it is the reuse cache) and the temp ACE revocably (revoked on provider dispose), both lazily at the session's first confined execution. The session's private temp subdirectory is DERIVED from the session id + workspace (sha256, 16 hex) instead of stored: a resumed session derives the same directory and re-grants it (the exact-ACE skip keeps that O(1)), while a fork's different session id derives a fresh one. The directory is created EXCLUSIVELY — a pre-existing entry or a reparse point fails the first confined run loudly, so the grant never lands on a foreign object — and removed again on provider dispose. Under `--write-sid` the runner neither grants nor revokes (`manageDacls: false`) — the flag's presence marks the seam-managed contract, its value is the derived SID; without it (standalone use) the runner self-manages with the SAME derived SID (workspace ACEs standing, temp ACE revocable per call). Re-granting after a restart is idempotent: `grantWrite` reads the current DACL and SKIPS the `SetNamedSecurityInfoW` apply when the exact ACE already stands (that apply eagerly re-propagates the identical ACE across the whole tree — minutes on large workspaces). Standing ACEs from an unclean shutdown need no garbage collection — they ARE the cache; the same derived SID re-hits them forever. Known cost: materializing the grant on a big workspace tree blocks for the full eager propagation once per workspace per machine (the first confined write ever on this host).
Modes (the token's restricting-SID list follows the mode; the keep-alive group is logon SID + Everyone in BOTH modes — early DLL init dies with `0xC0000142` and CNG crashes pwsh with `0xE0434352` without them):
- `workspace-write` (logon SID, Everyone, write SID): the workspace and the session's PRIVATE temp subdirectory carry the write-SID Write grant; every other write is denied by the token intersection.
- `read-only` (logon SID, Everyone — NO write SID): STRICT zero grants — nothing is writable. The write SID stays OUT of the list on purpose: the standing workspace grant ACE from an earlier workspace-write period (a `/permission` downgrade, or a crash-resumed session) remains INERT under read-only because the write-restricted pass-2 check grants only what the restricting list carries — while the standing ACE keeps the re-upgrade free of re-propagation. NUL writes are AMBIENT, not granted: the device DACL grants Everyone read+write+execute (`0x1201BF`), so openers whose mask fits it (cmd `> NUL`, node `\\.\NUL`) can write it in BOTH modes — the sandbox cannot zero-grant the NUL device while Everyone stays in the keep-alive group. `Set-Content NUL` fails in both modes (a PowerShell/.NET-layer effect, pinned by the read-only suite — the device DACL is not the denying party); PowerShell's `> $null` redirection keeps working (it discards without opening NUL).
Authenticated Users is absent from BOTH lists — the WMI namespace security check fails (`0x80041003`), so CIM cmdlets and `Get-ComputerInfo` (which silently returns incomplete results rather than an error) are unavailable in EVERY confined mode, and the C:\-root tree-creation escape (standing `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both — the model-facing surface documents that contract, not a prompt promise. INTERACTIVE/LOCAL are absent from BOTH lists too: the host's Public tree grants write to INTERACTIVE, so Public writes are denied — pinned by the runner's ambient-writable Public-probe regression (see the design note).
The `AclSandbox` class (`tempDir: null` disables the temp grant) remains the programmatic API for direct spawns; `AclWriteGrant` is the server-side materialization half of the grant lifecycle.
## Header verification
All constants, signatures, and struct layouts were verified against the Windows headers on the development machine (MinGW `winnt.h` / `accctrl.h` / `aclapi.h` / `securitybaseapi.h` / `sddl.h` / `processthreadsapi.h` / `fileapi.h` / `namedpipeapi.h` / `synchapi.h` / `winbase.h`) and are cross-checked at runtime by [`verify/abi-probe.cpp`](verify/abi-probe.cpp) (sizes, offsets, enum values, static asserts):
```sh
g++ -std=c++20 -municode -O2 -o abi-probe.exe verify/abi-probe.cpp -ladvapi32 && ./abi-probe.exe
```
The koffi struct definitions assert their sizes against the probe at module load, so a header/koffi layout drift fails loudly instead of corrupting memory.
## Verified boundaries (inherent to restricted tokens, not this port)
- **Writes are restricted; reads, network, and process visibility are not.** `WRITE_RESTRICTED` intersects write accesses only, so a confined child can read any caller-readable file and open sockets. `read-only` mode therefore cannot be expressed by this mechanism alone; pair it with a read-side policy or an AppContainer/`S-1-15-2` capability token for stronger confinement.
- **Console isolation is unavailable.** Under the restricted token, children created with `CREATE_NO_WINDOW` / `CREATE_NEW_CONSOLE` die during DLL initialization with `STATUS_DLL_INIT_FAILED` (`0xC0000142`). The POC tried to fix this by adding the console logon SID (`S-1-2-1`) to the restricting list; on Windows 11 26200 `CreateWellKnownSid(WinLocalLogonSid)` fails with `ERROR_INVALID_PARAMETER` (87), the correct `WinConsoleLogonSid` yields a valid `S-1-2-1` but the child still dies, and the POC's final revision removed both the SID and console isolation. Children therefore share the host console; stdio redirection is pipe-based and unaffected.
- **ACL grants are standing directory mutations.** They persist if the process dies mid-run; workspace ACEs are standing BY DESIGN (never revoked — the reuse cache), temp ACEs are revoked by `dispose()` (`init()` also revokes an already-applied temp grant when a later step fails). The POC's documented manual cleanup (`icacls <dir> /remove '*S-1-4-…'`) fails on this platform with `ERROR_NONE_MAPPED` (1332) — revoke through this module instead. An unclean shutdown needs no self-healing for the workspace ACE: the derived SID re-hits the standing ACE on the next provision (skipping the apply); the write-SID ACE never accumulates a second identity per restart because the identity IS the workspace.
- **Granted directories must be caller-owned.** The owner's implicit `WRITE_DAC` is what lets the sandbox edit the DACL without elevation.
- **The temp grant follows `GetTempPathW`** — pass `tempDir` explicitly whenever possible. `GetTempPathW` reads the NATIVE environment block, which host runtimes that manage `process.env` through worker pools may not keep in sync (verified with vitest: a worker-side `process.env.TMP` change never reached the native block). The seam passes the session's PRIVATE subdirectory (`<temp>\dsh-<16 hex>` derived from the session id + workspace, created exclusively — a pre-existing entry or reparse point fails loudly); a defaulted grant landing on the real temp dir inherits `(OI)(CI)` over every subdirectory of temp, silently widening the allowlist — point it at a per-sandbox directory instead.
- **The confined child's temp root is private per session** (workspace-write + `--write-sid`): the runner rewrites TMP/TEMP via `SetEnvironmentVariableW` to the session's private subdirectory before the spawn and the child inherits the rewritten block (bwrap `--tmpfs /tmp` semantics). Read-only leaves the ambient temp entries untouched — writes there are denied anyway. The subdirectory is removed on provider dispose; after a crash it may survive as plain `%TEMP%` litter until OS temp hygiene (or manual removal) reclaims it — a later resume then fails loudly at the exclusive creation.
- **`whoami` and token-inspection cmdlets fail under the restricted token.** `GetTokenInformation` on the duplicate is partially unavailable to the child, so `whoami /all` reports errors — diagnostic noise of the restriction scheme, not an operational failure; the denial surfaces that matter (file writes) are unaffected.
## Model Experience
Indirectly, through [`dsh-bash-sandbox`](../../bash/bash-sandbox/README.md), [`dsh-pwsh-sandbox`](../../bash/pwsh-sandbox/README.md), and their tools, which render this backend's enforcement and denial facts (the confined stderr the tool layer classifies through `denialSignatures`) while the [`dsh-sandbox`](../sandbox/README.md) seam owns the `SANDBOX_UNAVAILABLE` text and runner selection.
#### KV Cache effect
None directly; the denial surface belongs to the tool layer.
## Known Limitations and Deferred Work
- **One write allowlist per workspace** — the write SID is the unit of the allowlist and IS the workspace identity; reusing one sandbox instance across two workspaces widens both grants to both roots (the same SID would then name two roots). Create one instance per workspace root — the seam does exactly this, keyed by the workspace path.
- **Cleanup is best-effort by design** — `dispose()` attempts every temp revocation and aggregates failures into an `AggregateError`; a cleanup failure leaves a standing (but write-SID-only) temp ACE that this process's next `init()`/`dispose()` cycle or `icacls` (via the ACE, not the trustee name) can still remove.
- **Standing workspace ACEs are invisible residue.** Renaming a workspace derives a new SID; the old ACEs on the old path stay (inert, write-SID-only). A future cleanup command may reap them; nothing re-propagates because of them.
- **NULL-DACL directories are not identity-preserving under grant+revoke.** A directory with a NULL DACL (rare — Windows-created directories carry real DACLs) means "everyone full control"; `grantWrite` builds the new ACL from that null, and the revoke round-trip leaves an EMPTY (deny-all) DACL rather than the original NULL DACL. The POC shares the behavior; real workspace and temp directories carry real DACLs, so this stays a documented edge rather than a guarded path.
- **Piped stdio capture is impossible for confined grandchildren (the named-pipe default SD template).** libuv's pipe stdio uses NAMED pipes; `CreateNamedPipeW` without security attributes installs the Win32 layer's user-mode default SD template (built by KernelBase — owner/SYSTEM/Admins full, Everyone/ANONYMOUS read-only, the fixed template [MS documents](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights)) — NOT the token default DACL, which is what the kernel applies to a raw SD-null create — so the client-end open requests write access no restricting SID is granted: `spawn(..., { stdio: 'pipe' })` inside a confined process fails with EPERM, the POC-documented "no output redirection" boundary of WRITE_RESTRICTED tokens. Inherited (`inherit`/fd) and ignored (`ignore`) stdio spawns work, and anonymous pipes (CreatePipe — a token-default-DACL consumer, e.g. PowerShell pipelines) work because the restricted token's default DACL carries a full-access restricting-SID ACE (set at init). A confined process therefore cannot capture a grandchild's output through a pipe; tools that must capture output cannot run confined.
- **Grant materialization is an eager full-tree propagation.** `SetNamedSecurityInfoW` on a directory with inheritable ACEs walks every descendant immediately (NOT lazily per access — measured at tens of seconds on large workspace trees plus the real temp root). The per-workspace identity pays it once per workspace per machine (lazily at the first confined execution ever, skipped entirely on every later provision when the exact ACE stands). If a workspace is huge, the first confined write on this host is correspondingly slow.
- **Resuming one session concurrently in two server processes fails the second at its first confined write.** Both processes derive the same private temp directory; the second one's exclusive creation hits the first one's directory and fails loudly. Single-writer session usage (the normal deployment) never sees this.
- **Read-side confinement and network policy are out of scope** — `WRITE_RESTRICTED` intersects write accesses only; pair this backend with a read-side policy for stronger confinement.
- **Wide-directory and FAT-volume warnings are deferred; FAT-class targets stay writable.** The UI-side warnings for granting unusually wide directories or FAT-class (non-ACL) volumes are not yet implemented, and a FAT volume as a grant ROOT simply fails the grant loudly (no ACL support). A FAT-class target OUTSIDE the granted roots is different: it has no security descriptors, so the restricted token's write check passes (Everyone sits in both lists) and such targets are writable under BOTH confined modes. FAT is treated as a legacy residue — unsupported and not engineered around; this warn-only posture is documented here rather than mitigated.
- **Both confined modes run `pwsh` in ConstrainedLanguage.** The restricted token trips PowerShell's lockdown detection, so under `read-only` AND `workspace-write` the language mode is ConstrainedLanguage: `Add-Type` (C# compile, P/Invoke), non-core .NET static calls (`[System.IO.*]::`, `[math]::`, `[Environment]::`), COM objects, and reflection fail with `Cannot create type` / `Cannot invoke method` ("only core types") errors, and `$ExecutionContext.SessionState.LanguageMode = 'FullLanguage'` is refused. Core cmdlets, core types (`[string]`, `[datetime]`, `[regex]`, `[guid]`), `-f` formatting, and property access keep working. The `pwsh` tool description teaches this contract to the model; `danger-full-access` calls run unconfined at FullLanguage.

View File

@@ -0,0 +1,93 @@
# @deepseek-ai/dsh-sandbox-windows-acl
[English](README.md) | 中文
面向 [harness 沙盒 seam](../sandbox/) 的 Windows 写入限制沙盒后端:一个 Node.js/[koffi](https://koffi.dev/) 实现的、对 [huoyaoyuan/windows-acl-restrict-poc](https://github.com/huoyaoyuan/windows-acl-restrict-poc)`10e4dfb`,修复后的修订)机制的移植,挂载为 [`@deepseek-ai/dsh-sandbox-local`](../sandbox-local/) 链的 win32 一级(`workspace-write` / `read-only` 两种模式Linux/macOS 后端在同一包中。
一句话机制:把调用者令牌复制为 `WRITE_RESTRICTED` 受限令牌,其 restricting SIDs 中加入一个写入 SID`S-1-4-x-y`),该 SID 的 Write ACE 只存在于工作区与会话的私有临时目录上。写入 SID 是**按工作区**的身份,由规范工作区路径确定性派生(`workspaceWriteSid`),因此工作区根目录 ACE 每台机器每个工作区只物化一次——之后每次会话、调用、重启都命中精确 ACE 跳过——而不是每会话一次(见[隔离 runner](#the-confinement-runner))。此后 Windows 只在「调用者正常权限」与「restricting SID 交集」同时允许时才放行写入——写入 SID 就是写入白名单,而它在系统其余位置不授予任何权限;令牌的写检查还会继承**其他** restricting SID 的环境写 ACE保活组登录 SID + Everyone——下文「模式」段是完整边界
直接构建在原生 ACL 机制上是记录在案的设计选择:它实现两种隔离模式,且不背负被否决的容器方案的问题——见[设计笔记](../../../.agents/notes/implemented/feature/2026-08-08-windows-acl-restricted-token-sandbox.md)[mxc](https://github.com/microsoft/mxc/blob/main/docs/process-container/os-version-support.md) 要求 Windows 11 24H2 的 OS 下限,且任意路径读取需要整体改写宿主 DACLAppContainer 根本无法任意路径读取)。
## 用法
```ts
import { AclSandbox, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl'
const workspaceRoot = process.cwd()
// mode selects the token's restricting-SID list (see Modes below) and must
// match the grant shape: read-only pairs with zero grants. workspace-write
// REQUIRES the workspace's write SID — the per-workspace identity.
const sandbox = new AclSandbox({ writableDirs: [workspaceRoot], writeSid: workspaceWriteSid(workspaceRoot), mode: 'workspace-write' })
await sandbox.init() // throws on ANY Win32 failure — never spawns unrestricted
const child = sandbox.spawn({ command: 'pwsh', args: ['-NoProfile', '-Command', '...'], cwd: workspaceRoot })
const { stdout, stderr, exitCode } = await child.wait()
sandbox.dispose() // revokes the revocable (temp) grant, keeps the standing workspace ACE; reports every cleanup failure
```
直接使用 `AclSandbox` 时,工作区 ACE 以**常驻**方式授予(`dispose()` 保留它们——它们是跨实例的复用缓存),临时 ACE 以**可回收**方式授予(`dispose()` 撤销它,这样可继承 ACE 不会在环境临时根目录上比实例活得更久)。服务端复用则是 `AclWriteGrant` 类:每个目录一次 `add(path, standing)``dispose()` 撤销可回收路径并释放 SID——见下方 runner 契约。本包中的每个 Win32 API 调用都有检查;失败抛出 `Win32Error`,携带 API 名、精确 Win32 错误码、`FormatMessageW` 系统文本和失败的路径/上下文。这是刻意的POC 忽略每个返回值,当 `CreateRestrictedToken` 失败时用完整无限制令牌静默运行子进程fail-open。本移植从构造上 fail-closed。
<a id="the-confinement-runner"></a>
## 隔离 runner
面向 seam 的形态是 **runner 入口**`./runner``@deepseek-ai/dsh-sandbox-local` 在调用者命令的位置 spawn 的 argv 前缀包装——与 bwrap/landlock-run/sandbox-exec 同一架构,因此沙盒 seam 的 `confine()` 契约无需改动。稳定的 argv 契约:
```sh
node runner.js --workspace <dir> --temp <dir> --mode <read-only|workspace-write> [--write-sid <S-1-4-…>] -- <argv...>
```
runner 创建受限令牌,在它之下 spawn 包装后的 argv调用者的 stdio 直接透传(调用者的管道在 spawn 前后被设为可继承——Node 在启动时清除 stdio 可继承性,裸 spawn 必须补偿这一点),把子进程包进 `KILL_ON_JOB_CLOSE` jobrunner 死亡则子进程死亡),忽略自身的控制台 Ctrl+C 让子进程自行处理,镜像子进程的退出码,并在退出时撤销其临时授权(工作区 ACE 常驻)。每个 runner 侧失败都会向 stderr 打印 `windows-acl-run: <detail>` 并以 127 退出——seam 的 `RUNNER_FAILURE_RULES` 匹配该签名,因此 runner 拒绝永远不会被误判为拒绝授权。
**按工作区授权复用**`--write-sid`):写入 SID 从工作区路径**派生**——任何地方都不存储 SID 或临时目录状态(先前每会话随机 SID 及其篡改面已移除。seam 把工作区 ACE **常驻**物化(每个工作区每服务器生命周期一次,绝不撤销——它就是复用缓存),把临时 ACE **可回收**物化(提供方 dispose 时撤销),两者都在会话首次受限执行时惰性进行。会话的私有临时子目录由会话 id + 工作区**派生**sha256、16 位 hex而非存储恢复的会话派生同一个目录并重新授权精确 ACE 跳过使这一步保持 O(1)),而 fork 的不同会话 id 会派生出一个全新的目录。该目录以**独占**方式创建——已存在条目或重解析点会让首次受限运行大声失败,因此授权永远不会落到外部对象上——并在提供方 dispose 时再次移除。传入 `--write-sid` 时 runner 既不授权也不回收(`manageDacls: false`)——该标志的存在标记 seam 管理的契约,其值即派生 SID不传它独立使用时 runner 用**同一个**派生 SID 自行管理(工作区 ACE 常驻,临时 ACE 每次调用可回收)。重启后重新授权是幂等的:`grantWrite` 读取当前 DACL当完全相同的 ACE 已存在时跳过 `SetNamedSecurityInfoW` 的应用(该应用会把相同的 ACE 急切地重新传播到整棵树——大型工作区上以分钟计)。异常关闭遗留的 ACE 无需垃圾回收——它们**就是**缓存;同一个派生 SID 永远重新命中它们。已知代价:在大型工作区树上物化授权会阻塞整次急切传播,每台机器每个工作区一次(该主机上的第一次受限写入)。
模式(令牌的 restricting-SID 列表随模式而变;保活组登录 SID + Everyone 在**两种**模式下都存在——没有它们早期 DLL 初始化会以 `0xC0000142` 死亡、CNG 会让 pwsh 以 `0xE0434352` 崩溃):
- `workspace-write`(登录 SID、Everyone、写入 SID工作区与会话的**私有**临时子目录携带写入 SID 的 Write 授权;其余写全部被令牌交集拒绝。
- `read-only`(登录 SID、Everyone——**不含**写入 SID**严格零授权**——没有任何可写位置。写入 SID 有意留在列表**之外**:先前 workspace-write 时期留下的常驻授权 ACE`/permission` 降级,或崩溃后恢复的会话)在 read-only 下保持**失效**,因为 write-restricted 的 pass-2 检查只授予 restricting 列表所携带的内容——而常驻 ACE 让重新升级免于重新传播。NUL 写入是**环境性**的、不是被授权的:设备 DACL 授予 Everyone 读+写+执行(`0x1201BF`因此访问掩码落在其内的打开者cmd 的 `> NUL`、node 的 `\\.\NUL`)在**两种**模式下都能写——只要 Everyone 还在保活组里,沙盒就无法把 NUL 设备归零。`Set-Content NUL` 在两种模式下都失败PowerShell/.NET 层效应,由 read-only 套件钉住——拒绝方不是设备 DACLPowerShell 的 `> $null` 重定向不受影响(它直接丢弃、不打开 NUL
Authenticated Users 在**两种**列表中都不存在——WMI 命名空间安全检查失败(`0x80041003`),因此 CIM cmdlet 与 `Get-ComputerInfo`(它静默返回不完整结果而非报错)在**所有**受限模式下都不可用,且 C:\-root 树创建逃逸(常驻的 `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACE在两种模式下都被关闭——面向模型的表面记录的是该契约而不是提示词承诺。INTERACTIVE/LOCAL 在两种列表中同样不存在:宿主的 Public 树向 INTERACTIVE 授予写权限,因此 Public 写入被拒绝——由 runner 的环境可写 Public 探针回归测试钉住(见设计笔记)。
`AclSandbox` 类(`tempDir: null` 禁用临时授权)仍是直接 spawn 的编程 API`AclWriteGrant` 是授权生命周期的服务端物化一半。
## 头部验证
所有常量、签名与结构体布局都在开发机上对照 Windows 头文件MinGW `winnt.h` / `accctrl.h` / `aclapi.h` / `securitybaseapi.h` / `sddl.h` / `processthreadsapi.h` / `fileapi.h` / `namedpipeapi.h` / `synchapi.h` / `winbase.h`)验证过,并在运行时由 [`verify/abi-probe.cpp`](verify/abi-probe.cpp)(大小、偏移、枚举值、静态断言)交叉检查:
```sh
g++ -std=c++20 -municode -O2 -o abi-probe.exe verify/abi-probe.cpp -ladvapi32 && ./abi-probe.exe
```
koffi 结构体定义在模块加载时对照探针断言其大小,因此头文件/koffi 布局漂移会大声失败而不是破坏内存。
## 已验证边界(受限令牌固有,非本移植引入)
- **写入受限;读取、网络与进程可见性不受限。** `WRITE_RESTRICTED` 只交叉检查写访问,因此受限子进程可以读取调用者可读的任何文件并打开套接字。`read-only` 模式因而不能仅靠该机制表达;将其与读侧策略或 AppContainer/`S-1-15-2` capability 令牌配对以获得更强隔离。
- **控制台隔离不可用。** 在受限令牌下,以 `CREATE_NO_WINDOW` / `CREATE_NEW_CONSOLE` 创建的子进程在 DLL 初始化期间以 `STATUS_DLL_INIT_FAILED``0xC0000142`死亡。POC 尝试把控制台登录 SID`S-1-2-1`)加入 restricting 列表来修复;在 Windows 11 26200 上 `CreateWellKnownSid(WinLocalLogonSid)``ERROR_INVALID_PARAMETER`87失败正确的 `WinConsoleLogonSid` 能产出合法 `S-1-2-1` 但子进程仍然死亡POC 的最终修订同时移除了该 SID 与控制台隔离。子进程因此共享宿主控制台stdio 重定向走管道,不受影响。
- **ACL 授权是对真实目录的驻留改动。** 进程中途死亡会留下授权;工作区 ACE **按设计**常驻(绝不撤销——复用缓存),临时 ACE 由 `dispose()` 撤销(后续步骤失败时 `init()` 也会撤销已应用的临时授权。POC 注释里的手工清理命令(`icacls <dir> /remove '*S-1-4-…'`)在本平台实测失败(`ERROR_NONE_MAPPED` 1332——请通过本模块回收。工作区 ACE 在异常关闭后无需自愈:派生 SID 在下一次供给时重新命中常驻 ACE跳过应用写入 SID ACE 不会因每次重启而累积第二个身份,因为身份**就是**工作区。
- **被授权目录必须由调用者拥有。** 所有者的隐式 `WRITE_DAC` 是沙盒无需提权即可编辑 DACL 的原因。
- **临时授权跟随 `GetTempPathW`**——尽可能显式传 `tempDir``GetTempPathW` 读取**原生**环境块,而通过 worker 池管理 `process.env` 的宿主运行时可能没有与之保持同步vitest 实测worker 侧的 `process.env.TMP` 变更从未到达原生块。seam 传入会话的**私有**子目录(`<temp>\dsh-<16 hex>`,由会话 id + 工作区派生、独占创建——已存在条目或重解析点会大声失败);默认授权落在真实临时目录上会让 `(OI)(CI)` 继承到临时目录的每个子目录,静默扩大白名单——请改指向每个沙盒的目录。
- **受限子进程的临时根目录按会话私有**workspace-write + `--write-sid`runner 在 spawn 之前用 `SetEnvironmentVariableW` 把 TMP/TEMP 改写为会话的私有子目录子进程继承改写后的环境块bwrap `--tmpfs /tmp` 的语义。read-only 保持环境中的临时目录条目不动——那里的写入反正会被拒绝。子目录在提供方 dispose 时移除;崩溃后它可能作为普通 `%TEMP%` 垃圾存活,直到 OS 的临时目录卫生(或手动删除)将其回收——之后的恢复会在独占创建处大声失败。
- **受限令牌下 `whoami` 与令牌检查 cmdlet 会失败。** 子进程对复制令牌的 `GetTokenInformation` 部分不可用,因此 `whoami /all` 报错——这是限制方案的诊断噪音,不是运行故障;真正重要的拒绝面(文件写入)不受影响。
## Model Experience
间接地通过 [`dsh-bash-sandbox`](../../bash/bash-sandbox/README.md)、[`dsh-pwsh-sandbox`](../../bash/pwsh-sandbox/README.md) 及其工具呈现:它们渲染此后端的强制与拒绝事实(工具层通过 `denialSignatures` 分类的受限 stderr而 [`dsh-sandbox`](../sandbox/README.md) seam 拥有 `SANDBOX_UNAVAILABLE` 文本与 runner 选择。
#### KV Cache 影响
无直接影响;拒绝面属于工具层。
## Known Limitations and Deferred Work
- **每个工作区一个写入白名单** —— 写入 SID 是白名单的基本单位,且**就是**工作区身份;同一沙盒实例跨两个工作区复用时,两个根目录会互相扩大授权面(同一个 SID 将命名两个根。请按工作区根目录各建一个实例——seam 正是这样做的,以工作区路径为键。
- **清理尽力而为** —— `dispose()` 会尝试全部临时撤销并把失败聚合为 `AggregateError`;清理失败只会留下仅含写入 SID 的临时 ACE本进程下次 `init()`/`dispose()` 循环或 `icacls`(按 ACE 而非受托者名)仍可清除。
- **常驻工作区 ACE 是不可见残留。** 工作区改名会派生新的 SID旧路径上的旧 ACE 留在原地(失效、仅含写入 SID。未来的清理命令可以回收它们它们不会引起任何重新传播。
- **NULL-DACL 目录在 grant+revoke 往返下不保持身份。** 带 NULL DACL 的目录罕见——Windows 创建的目录都带真实 DACL意味着「所有人完全控制」`grantWrite` 从该 null 构建新 ACL撤销往返后留下的是 EMPTY全部拒绝DACL 而非原始 NULL DACL。POC 行为相同;真实工作区与临时目录都带真实 DACL因此这仍是记录在案的边界情形而非守护路径。
- **受限孙进程的管道 stdio 捕获不可用named pipe 的默认 SD 模板)。** libuv 的管道 stdio 用的是 NAMED pipe不带安全属性调用 `CreateNamedPipeW` 时,其默认安全描述符不是内核的模板,而是 Win32 层在用户态安装的默认 SD 模板(由 KernelBase 构建——owner/SYSTEM/Admins 全权Everyone/ANONYMOUS 只读,即 [MS 文档](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights)记载的固定模板)——**不是**令牌默认 DACL后者才是内核在原始 SD-null 创建时应用的)——因此 client 端打开所请求的写访问没有任何 restricting SID 被授予:受限进程内 `spawn(..., { stdio: 'pipe' })` 以 EPERM 失败,这是 POC 记载的 WRITE_RESTRICTED「无法重定向输出」边界。继承`inherit`/fd与忽略`ignore`stdio 的 spawn 可用匿名管道CreatePipe——令牌默认 DACL 的消费者,例如 PowerShell 的管道)因受限令牌默认 DACL 携带 restricting SID 全权 ACEinit 时写入)而可用。受限进程因此无法用管道捕获孙进程输出;必须捕获输出的工具无法在受限下运行。
- **授权物化是急切的全树传播。** 在带可继承 ACE 的目录上调用 `SetNamedSecurityInfoW` 会立即遍历每个后代(**不是**按访问惰性进行——大型工作区树上实测数十秒,加上真实临时根目录)。按工作区身份每台机器每个工作区只付一次(在首次受限执行时惰性进行,之后每次供给在精确 ACE 常驻时完全跳过)。如果工作区巨大,该主机上的第一次受限写入相应变慢。
- **两个服务器进程并发恢复同一会话时,第二个会在其首次受限写入处失败。** 两个进程派生同一个私有临时目录;第二个的独占创建撞上第一个的目录并大声失败。单写者会话用法(常规部署)永远不会遇到。
- **读侧隔离与网络策略不在范围内** —— `WRITE_RESTRICTED` 只交叉检查写访问;将此后端与读侧策略配对以获得更强隔离。
- **宽目录与 FAT 卷警告已推迟FAT 类目标保持可写。** 对异常宽的目录或 FAT 类(非 ACL卷的 UI 侧警告尚未实现,且 FAT 卷作为授权**根**只会大声失败(无 ACL 支持)。授权根**之外**的 FAT 类目标则不同它没有安全描述符因此受限令牌的写检查通过Everyone 在两种列表中都在)——此类目标在**两种**受限模式下都可写。FAT 被视为遗留残留——不受支持、不围绕它设计;此处记录的是这种仅警告的立场,而非缓解措施。
- **两种受限模式都运行 ConstrainedLanguage 的 `pwsh`。** 受限令牌会触发 PowerShell 的锁定检测,因此在 `read-only` **和** `workspace-write` 下语言模式都是 ConstrainedLanguage`Add-Type`C# 编译、P/Invoke、非核心 .NET 静态调用(`[System.IO.*]::``[math]::``[Environment]::`、COM 对象与反射以 `Cannot create type` / `Cannot invoke method`「only core types」错误失败`$ExecutionContext.SessionState.LanguageMode = 'FullLanguage'` 被拒绝。核心 cmdlet、核心类型`[string]``[datetime]``[regex]``[guid]`)、`-f` 格式化与属性访问保持可用。`pwsh` 工具描述向模型传授该契约;`danger-full-access` 调用不受限地在 FullLanguage 下运行。

View File

@@ -0,0 +1,45 @@
{
"name": "@deepseek-ai/dsh-sandbox-windows-acl",
"description": "Windows ACL write-restriction sandbox backend (restricted-token spawn with orphan-SID write allowlist) for the DeepSeek Harness sandbox seam",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./runner": {
"types": "./lib/types/runner.d.ts",
"default": "./lib/runner.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/runner.js",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-invariants": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"dependencies": {
"koffi": "^3.1.0"
},
"devDependencies": {
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-pwsh-local": "workspace:^",
"@deepseek-ai/dsh-sandbox-local": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,271 @@
/**
* ACL editing helpers: grant/revoke the orphan write SID on a directory via
* SetEntriesInAclW + SetNamedSecurityInfoW (the same calls the POC uses, with
* the failure handling the POC lacks). Every API call is checked and every
* failure is reported with the API name, the exact Win32 code, the formatted
* system text, and the affected path.
*
* Concurrency: grants are read-merge-write against the directory's CURRENT
* DACL, and the whole get-merge-set sequence runs under a per-path exclusive
* LockFileEx lock (see {@link withPathLock}) so concurrent sandbox instances
* cannot clobber each other's ACEs.
* @module @deepseek-ai/dsh-sandbox-windows-acl/acl
*/
import { createHash } from 'node:crypto'
import { mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { allocOverlapped, allocPtrSlot, decodePtr, decodeUint8At, decodeUint16At, decodeUint32At, getTempPath, isInvalidHandle, isNullPtr, ptrAddress, sameSidAt, throwLastError, throwWin32 } from './ffi.ts'
import type { NativePtr, Win32Bindings } from './ffi.ts'
import * as abi from './win32-abi.ts'
/**
* Pack one EXPLICIT_ACCESS_W (48 bytes, layout verified by abi-probe.cpp):
* perms@0, mode@4, inheritance@8, Trustee@16 { pMultipleTrustee@16,
* MultipleTrusteeOperation@24, TrusteeForm@28, TrusteeType@32, ptstrName@40 }.
* `permissions` is the access mask; the POC passes 0 for REVOKE_ACCESS, which
* removes every ACE for the trustee.
* @param sidPtr - the trustee SID the entry names.
* @param mode - the access mode (GRANT_ACCESS or REVOKE_ACCESS).
* @param permissions - the access mask to grant (0 for REVOKE_ACCESS).
* @returns the packed entry buffer.
*/
export function buildExplicitAccess(sidPtr: NativePtr, mode: number, permissions: number): Buffer {
const entry = Buffer.alloc(abi.EXPLICIT_ACCESS_W_SIZE)
entry.writeUInt32LE(permissions, 0) // grfAccessPermissions
entry.writeUInt32LE(mode, 4) // grfAccessMode
entry.writeUInt32LE(abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT, 8) // grfInheritance: OI|CI
entry.writeUInt32LE(abi.NO_MULTIPLE_TRUSTEE, 24) // Trustee.MultipleTrusteeOperation
entry.writeUInt32LE(abi.TRUSTEE_IS_SID, 28) // Trustee.TrusteeForm
entry.writeUInt32LE(abi.TRUSTEE_IS_UNKNOWN, 32) // Trustee.TrusteeType
entry.writeBigUInt64LE(ptrAddress(sidPtr), 40) // Trustee.ptstrName = the orphan SID
return entry
}
/**
* One lock file per protected path: `<GetTempPathW()>\dsh-acl-locks\<first 16
* hex of sha256(lowercased path)>.lock`. The lock root derives from
* GetTempPathW (never from runner argv or DSH_HOME), and the lowercasing
* maps Windows's case-insensitive path spellings onto one lock.
* @param api - the binding table.
* @param path - the protected directory (absolute).
* @returns the lock file path for that directory.
*/
export function lockFilePath(api: Win32Bindings, path: string): string {
const digest = createHash('sha256').update(path.toLowerCase()).digest('hex').slice(0, 16)
return join(getTempPath(api), 'dsh-acl-locks', `${digest}.lock`)
}
/**
* Run `action` holding the per-path exclusive lock: CreateFileW
* (OPEN_ALWAYS, shared read/write but NOT delete — a deletable lock file
* could be removed and recreated under the holder, letting two processes
* hold "the same" lock), then a one-byte LockFileEx
* (LOCKFILE_EXCLUSIVE_LOCK, zeroed OVERLAPPED = lock from offset 0 on the
* synchronous handle — see allocOverlapped for why not NULL), then
* UnlockFileEx + CloseHandle. Fail-closed: open/lock/unlock/close failures
* throw like every other Win32 call in this package; an `action` failure
* still unlocks (best-effort) and rethrows the original error.
* @param api - the binding table.
* @param path - the protected directory (absolute).
* @param action - the get-merge-set sequence to serialize.
* @returns the action's result.
*/
export function withPathLock<T>(api: Win32Bindings, path: string, action: () => T): T {
const lockPath = lockFilePath(api, path)
mkdirSync(dirname(lockPath), { recursive: true })
const handle = api.createFileW(
lockPath,
abi.GENERIC_READ | abi.GENERIC_WRITE,
abi.FILE_SHARE_READ | abi.FILE_SHARE_WRITE,
null, abi.OPEN_ALWAYS, 0, null,
)
if (isInvalidHandle(handle)) throwLastError(api, 'CreateFileW', lockPath)
const overlapped = allocOverlapped() // stays zeroed: offset 0, hEvent NULL
if (api.lockFileEx(handle, abi.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, overlapped) === 0) {
const win32Code = api.getLastError()
api.closeHandle(handle) // best-effort on the lock-failure path
throwWin32(api, 'LockFileEx', win32Code, lockPath)
}
let result: T
try {
result = action()
} catch (error) {
// Best-effort release on the action-failure path: cleanup failures must
// not mask the action's error.
api.unlockFileEx(handle, 0, 1, 0, overlapped)
api.closeHandle(handle)
throw error
}
if (api.unlockFileEx(handle, 0, 1, 0, overlapped) === 0) {
const win32Code = api.getLastError()
api.closeHandle(handle) // best-effort on the unlock-failure path
throwWin32(api, 'UnlockFileEx', win32Code, lockPath)
}
if (api.closeHandle(handle) === 0) throwLastError(api, 'CloseHandle', `lock file ${lockPath}`)
return result
}
/**
* Read the directory's current explicit DACL via GetNamedSecurityInfoW.
* Allocation contract (the POC's RevokeAccess, minus its missing checks): the
* returned ACL pointer sits INSIDE the security descriptor allocation — only
* the descriptor may be LocalFree'd, and it must not be freed before
* SetEntriesInAclW has consumed the ACL. Freeing the ACL pointer itself
* corrupts the heap (verified the hard way).
* @param api - the binding table.
* @param path - the directory whose DACL is read.
* @returns the current explicit DACL (null when the directory carries none) and its owning descriptor.
*/
function readCurrentDacl(api: Win32Bindings, path: string): { oldAcl: NativePtr | null; descriptor: NativePtr | null } {
const ownerSlot = allocPtrSlot()
const groupSlot = allocPtrSlot()
const daclSlot = allocPtrSlot()
const saclSlot = allocPtrSlot()
const descriptorSlot = allocPtrSlot()
const readResult = api.getNamedSecurityInfoW(
path, abi.SE_FILE_OBJECT, abi.DACL_SECURITY_INFORMATION,
ownerSlot, groupSlot, daclSlot, saclSlot, descriptorSlot,
)
if (readResult !== abi.ERROR_SUCCESS) throwWin32(api, 'GetNamedSecurityInfoW', readResult, path)
return { oldAcl: decodePtr(daclSlot), descriptor: decodePtr(descriptorSlot) }
}
/**
* Shared tail of grantWrite and revokeWrite: merge `entry` into `oldAcl`
* (null = no explicit DACL yet; SetEntriesInAclW builds one from scratch),
* free the descriptor before applying the merged ACL, apply it, then free the
* merged ACL — checking every call and reporting with the caller's label.
* @param api - the binding table.
* @param path - the directory the DACL edit applies to.
* @param entry - the EXPLICIT_ACCESS_W to merge (grant or revoke).
* @param oldAcl - the current explicit DACL (from {@link readCurrentDacl}).
* @param descriptor - the descriptor allocation owning `oldAcl`.
* @param label - the caller's name for error details.
*/
function mergeAndApply(
api: Win32Bindings,
path: string,
entry: Buffer,
oldAcl: NativePtr | null,
descriptor: NativePtr | null,
label: string,
): void {
const newAclSlot = allocPtrSlot()
const mergeResult = api.setEntriesInAclW(1, entry, oldAcl, newAclSlot)
if (mergeResult !== abi.ERROR_SUCCESS) {
if (descriptor !== null) api.localFree(descriptor) // frees the ACL block too
throwWin32(api, 'SetEntriesInAclW', mergeResult, `${label}(${path})`)
}
const newAcl = decodePtr(newAclSlot)
if (newAcl === null) {
if (descriptor !== null) api.localFree(descriptor)
throwWin32(api, 'SetEntriesInAclW', api.getLastError(), `${label}(${path}): null new ACL`)
}
// The descriptor block (oldAcl included) is dead after the merge — free it
// before applying, exactly like the POC.
const freedDescriptor = descriptor !== null ? api.localFree(descriptor) : null
const applyResult = api.setNamedSecurityInfoW(
path, abi.SE_FILE_OBJECT, abi.DACL_SECURITY_INFORMATION,
null, null, newAcl, null,
)
const freedNew = api.localFree(newAcl)
if (applyResult !== abi.ERROR_SUCCESS) throwWin32(api, 'SetNamedSecurityInfoW', applyResult, `${label}(${path})`)
if (freedDescriptor !== null && !isNullPtr(freedDescriptor)) throwLastError(api, 'LocalFree', `${label}(${path}) descriptor`)
if (!isNullPtr(freedNew)) throwLastError(api, 'LocalFree', `${label}(${path}) new ACL`)
}
/**
* True when the explicit DACL already carries the EXACT write grant this
* module would add (Allow ACE, OI|CI inheritance, {@link abi.GRANT_MASK}, the
* orphan SID). Every field is read through koffi.decode at pointer offsets —
* no memcpy, no pointer arithmetic. The ACE's SID is INLINE (embedded in the
* ACE after the 4-byte mask — there is no pointer to read; reading one
* yields garbage addresses and crashed EqualSid, verified by gdb), so it is
* compared field-by-field against the orphan SID through bounded offset
* reads ({@link sameSidAt}). A malformed header reads as "no exact grant"
* so the caller falls back to the merge-apply path, which owns the robust
* failure handling.
* @param oldAcl - the current explicit DACL pointer (from {@link readCurrentDacl}).
* @param sidPtr - the orphan write SID to match.
* @returns whether the exact grant ACE is already present.
*/
function hasExactGrant(oldAcl: NativePtr, sidPtr: NativePtr): boolean {
const aclSize = decodeUint16At(oldAcl, 2)
const aceCount = decodeUint16At(oldAcl, 4)
if (aclSize < 8 || aclSize > 1_048_576) return false // implausible: fall back to the merge path
let offset = 8 // the first ACE follows the 8-byte ACL header
for (let index = 0; index < aceCount; index++) {
// ACE_HEADER: AceType@0, AceFlags@1, AceSize@2 (WORD);
// ACCESS_ALLOWED_ACE: Mask@4, inline SID@8.
const aceSize = decodeUint16At(oldAcl, offset + 2)
if (aceSize < 8 || offset + aceSize > aclSize) return false // implausible: fall back to the merge path
const exact = decodeUint8At(oldAcl, offset) === abi.ACCESS_ALLOWED_ACE_TYPE
&& decodeUint8At(oldAcl, offset + 1) === abi.SUB_CONTAINERS_AND_OBJECTS_INHERIT
&& decodeUint32At(oldAcl, offset + 4) === abi.GRANT_MASK
if (exact && sameSidAt(oldAcl, offset + 8, sidPtr, 0)) return true
offset += aceSize
}
return false
}
/**
* Grant `GRANT_MASK` (Write+Delete, displays as "Modify") to the orphan SID
* on `path`, inheriting to subcontainers and objects. Idempotent: when the
* directory's current explicit DACL already carries the exact ACE (the
* per-session grant surviving from a previous server lifetime), the
* SetNamedSecurityInfoW apply is SKIPPED — it would otherwise re-propagate
* the identical ACE across the whole tree (eager inheritance; minutes on
* large workspaces). Otherwise read-merge-write: the new ACE merges into the
* directory's CURRENT explicit DACL (same shape as {@link revokeWrite}), so
* pre-existing explicit ACEs survive. Runs under the per-path lock. The
* directory must be owned by the caller (owner implicit WRITE_DAC) — same
* precondition as the POC.
* @param api - the binding table.
* @param path - the directory whose DACL gains the grant (the workspace or temp root).
* @param sidPtr - the orphan write SID the ACE names.
*/
export function grantWrite(api: Win32Bindings, path: string, sidPtr: NativePtr): void {
withPathLock(api, path, () => {
const { oldAcl, descriptor } = readCurrentDacl(api, path)
if (oldAcl !== null && hasExactGrant(oldAcl, sidPtr)) {
// The exact ACE stands: releasing the descriptor is the whole operation.
if (descriptor !== null) {
const freed = api.localFree(descriptor)
if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', `grantWrite(${path}) descriptor`)
}
return
}
mergeAndApply(api, path, buildExplicitAccess(sidPtr, abi.GRANT_ACCESS, abi.GRANT_MASK), oldAcl, descriptor, 'grantWrite')
})
}
/**
* Remove every ACE for the orphan SID from the directory DACL (REVOKE_ACCESS
* merge — other entries are preserved). Returns whether an ACE removal was
* attempted (false when the directory carries no DACL at all).
*
* Runs under the per-path lock (the whole get-merge-set sequence); the
* descriptor/ACL allocation contract lives on {@link readCurrentDacl}.
* @param api - the binding table.
* @param path - the directory whose DACL loses the orphan-SID ACEs.
* @param sidPtr - the orphan write SID whose ACEs are removed.
* @returns whether an ACE removal was attempted (false when the directory carries no DACL at all).
*/
export function revokeWrite(api: Win32Bindings, path: string, sidPtr: NativePtr): boolean {
return withPathLock(api, path, () => {
const { oldAcl, descriptor } = readCurrentDacl(api, path)
if (oldAcl === null) {
if (descriptor !== null) {
const freed = api.localFree(descriptor)
if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', `revokeWrite(${path}) descriptor`)
}
return false
}
mergeAndApply(api, path, buildExplicitAccess(sidPtr, abi.REVOKE_ACCESS, 0), oldAcl, descriptor, 'revokeWrite')
return true
})
}

View File

@@ -0,0 +1,21 @@
/**
* Fail-closed Win32 error type. Every backend API failure raises this with the
* API name and the exact Win32 code; the original POC silently ignored every
* failed call and would run children UNRESTRICTED (fail-open) — that is the
* failure mode this class exists to prevent.
* @module @deepseek-ai/dsh-sandbox-windows-acl/errors
*/
export class Win32Error extends Error {
/** The failing Win32 API name, e.g. `CreateRestrictedToken`. */
readonly api: string
/** The Win32 error code (`GetLastError` for BOOL APIs, the HRESULT-style return for ACL APIs). */
readonly win32Code: number
constructor(api: string, win32Code: number, detail?: string) {
super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`)
this.name = 'Win32Error'
this.api = api
this.win32Code = win32Code
}
}

View File

@@ -0,0 +1,510 @@
/**
* Lazy koffi bindings for the Win32 ACL-sandbox backend. Koffi loads lazily so
* non-Windows processes never open Win32 libraries. Every function signature
* below was verified against the MinGW Windows headers on this machine
* (winnt.h / accctrl.h / aclapi.h / securitybaseapi.h / sddl.h /
* processthreadsapi.h / fileapi.h / namedpipeapi.h / synchapi.h / winbase.h);
* struct layouts are asserted at load time against verify/abi-probe.cpp.
* @module @deepseek-ai/dsh-sandbox-windows-acl/ffi
*/
import koffi from 'koffi'
import { Win32Error } from './errors.ts'
import * as abi from './win32-abi.ts'
/** Branded koffi 3 native pointer. Koffi 3 pointers are BigInt values; the brand keeps them out of numeric contexts. */
declare const nativePtr: unique symbol
/** Koffi 3 native pointer (a BigInt address), branded so it cannot silently enter numeric contexts. */
export type NativePtr = bigint & { readonly [nativePtr]: true }
/**
* True for NULL pointers, however koffi returns them (null or 0n).
* @param value - a pointer as koffi may hand it back (pointer, null, or 0n).
* @returns a type guard narrowing to the NULL shapes.
*/
export function isNullPtr(value: NativePtr | null | undefined): value is null | undefined {
return value === null || value === undefined || (value as bigint) === 0n
}
/**
* True for CreateFileW's INVALID_HANDLE_VALUE failure marker (-1, which
* koffi hands back as the unsigned 64-bit all-ones pointer).
* @param handle - the handle CreateFileW returned.
* @returns whether the handle signals failure.
*/
export function isInvalidHandle(handle: NativePtr | null | undefined): boolean {
if (isNullPtr(handle)) return true
return (handle as bigint) === 0xFFFFFFFFFFFFFFFFn || (handle as bigint) === -1n
}
type Ptr = ReturnType<typeof koffi.pointer>
/** Field subset written into a zeroed STARTUPINFOW (layout verified: size 104). */
export interface StartupInfoInput {
cb: number
dwFlags: number
hStdInput: NativePtr
hStdOutput: NativePtr
hStdError: NativePtr
}
/** Decoded PROCESS_INFORMATION (layout verified: size 24). */
export interface ProcessInfoOutput {
hProcess: NativePtr | null
hThread: NativePtr | null
dwProcessId: number
dwThreadId: number
}
/** The lazy koffi binding table: every Win32 call the ACL backend uses, signature-verified against the real headers. */
export interface Win32Bindings {
// ---- process / token handles --------------------------------------------
openProcess(desiredAccess: number, inheritHandle: number, pid: number): NativePtr
openProcessToken(process: NativePtr, desiredAccess: number, tokenHandle: NativePtr): number
closeHandle(handle: NativePtr): number
// ---- errors / diagnostics ------------------------------------------------
getLastError(): number
formatMessageW(flags: number, source: null, messageId: number, languageId: number, buffer: Buffer, size: number, args: null): number
// ---- memory --------------------------------------------------------------
localAlloc(flags: number, bytes: number): NativePtr
localFree(memory: NativePtr): NativePtr
// ---- SIDs ----------------------------------------------------------------
convertStringSidToSidW(stringSid: string, sid: NativePtr): number
createWellKnownSid(type: number, domainSid: null, sid: NativePtr, size: NativePtr): number
isValidSid(sid: NativePtr): number
getLengthSid(sid: NativePtr): number
copySid(length: number, destination: NativePtr, source: NativePtr): number
// ---- token information ---------------------------------------------------
getTokenInformation(token: NativePtr, cls: number, info: Buffer | null, length: number, needed: NativePtr): number
setTokenInformation(token: NativePtr, cls: number, info: Buffer, length: number): number
// ---- restricted token ----------------------------------------------------
createRestrictedToken(
existing: NativePtr, flags: number,
disableCount: number, disableSids: null,
deletePrivilegeCount: number, privilegesToDelete: null,
restrictCount: number, restrictingSids: Buffer,
newToken: NativePtr,
): number
// ---- ACL editing ---------------------------------------------------------
setEntriesInAclW(count: number, entries: Buffer, oldAcl: NativePtr | null, newAcl: NativePtr): number
setNamedSecurityInfoW(
path: string, objectType: number, information: number,
owner: null, group: null, dacl: NativePtr | null, sacl: null,
): number
getNamedSecurityInfoW(
path: string, objectType: number, information: number,
owner: NativePtr, group: NativePtr, dacl: NativePtr, sacl: NativePtr, descriptor: NativePtr,
): number
// ---- environment / io ----------------------------------------------------
getTempPathW(length: number, buffer: Buffer): number
createFileW(
fileName: string, desiredAccess: number, shareMode: number, attributes: null,
creationDisposition: number, flagsAndAttributes: number, templateFile: null,
): NativePtr
lockFileEx(file: NativePtr, flags: number, reserved: number, bytesLow: number, bytesHigh: number, overlapped: NativePtr): number
unlockFileEx(file: NativePtr, reserved: number, bytesLow: number, bytesHigh: number, overlapped: NativePtr): number
createPipe(readHandle: NativePtr, writeHandle: NativePtr, attributes: null, size: number): number
setHandleInformation(handle: NativePtr, mask: number, flags: number): number
createProcessAsUserW(
token: NativePtr, applicationName: null, commandLine: string,
processAttributes: null, threadAttributes: null,
inheritHandles: number, creationFlags: number, environment: null,
currentDirectory: string | null, startupInfo: NativePtr, processInfo: NativePtr,
): number
setEnvironmentVariableW(name: string, value: string): number
readFile(file: NativePtr, buffer: Buffer, count: number, bytesRead: NativePtr, overlapped: null): number
peekNamedPipe(
pipe: NativePtr, buffer: null, size: number,
bytesRead: NativePtr, totalAvail: NativePtr, leftThisMessage: NativePtr,
): number
waitForSingleObject(handle: NativePtr, milliseconds: number): number
getExitCodeProcess(process: NativePtr, exitCode: NativePtr): number
resumeThread(thread: NativePtr): number
// ---- job object (runner kill-on-close) -----------------------------------
createJobObjectW(attributes: null, name: null): NativePtr
setInformationJobObject(job: NativePtr, cls: number, information: Buffer, length: number): number
assignProcessToJobObject(job: NativePtr, process: NativePtr): number
// Terminate a suspended child that could not be placed in the kill-on-close
// job — closing handles alone would leave it hanging forever.
terminateProcess(process: NativePtr, exitCode: number): number
// ---- console -------------------------------------------------------------
// HandlerRoutine=null + add=1 makes this process ignore CTRL+C (wincon.h):
// the runner survives console Ctrl+C so the child handles its own and the
// runner can clean up grants after the child exits.
setConsoleCtrlHandler(handler: null, add: number): number
getStdHandle(stdHandle: number): NativePtr
}
const PVOID: Ptr = koffi.pointer('void')
const PPVOID: Ptr = koffi.pointer(PVOID)
/** koffi STARTUPINFOW layout; its size is asserted against abi.STARTUPINFOW_SIZE at load. */
export const STARTUPINFOW = koffi.struct('STARTUPINFOW', {
cb: 'uint32',
lpReserved: 'str16',
lpDesktop: 'str16',
lpTitle: 'str16',
dwX: 'uint32',
dwY: 'uint32',
dwXSize: 'uint32',
dwYSize: 'uint32',
dwXCountChars: 'uint32',
dwYCountChars: 'uint32',
dwFillAttribute: 'uint32',
dwFlags: 'uint32',
wShowWindow: 'uint16',
cbReserved2: 'uint16',
lpReserved2: koffi.pointer('uint8'),
hStdInput: PVOID,
hStdOutput: PVOID,
hStdError: PVOID,
})
/** koffi PROCESS_INFORMATION layout; its size is asserted against abi.PROCESS_INFORMATION_SIZE at load. */
export const PROCESS_INFORMATION = koffi.struct('PROCESS_INFORMATION', {
hProcess: PVOID,
hThread: PVOID,
dwProcessId: 'uint32',
dwThreadId: 'uint32',
})
if (STARTUPINFOW.size !== abi.STARTUPINFOW_SIZE) {
throw new Error(`STARTUPINFOW layout mismatch: koffi computed ${STARTUPINFOW.size}, header probe says ${abi.STARTUPINFOW_SIZE}`)
}
if (PROCESS_INFORMATION.size !== abi.PROCESS_INFORMATION_SIZE) {
throw new Error(`PROCESS_INFORMATION layout mismatch: koffi computed ${PROCESS_INFORMATION.size}, header probe says ${abi.PROCESS_INFORMATION_SIZE}`)
}
/**
* Allocate one pointer-sized slot (for `T **` out-parameters).
* @returns the allocated slot pointer.
*/
export function allocPtrSlot(): NativePtr {
const value: unknown = koffi.alloc(PVOID, 1)
return value as NativePtr
}
/**
* Allocate one uint32 slot.
* @returns the allocated slot pointer.
*/
export function allocUint32(): NativePtr {
const value: unknown = koffi.alloc('uint32', 1)
return value as NativePtr
}
/**
* Write a uint32 value into a slot pointer.
* @param slot - the slot allocated by {@link allocUint32}.
* @param value - the uint32 to encode.
*/
export function encodeUint32(slot: NativePtr, value: number): void {
koffi.encode(slot, 'uint32', value)
}
/**
* Decode the pointer stored in a pointer-sized slot (NULL becomes null).
* @param slot - the pointer-sized slot holding the out-parameter value.
* @returns the decoded pointer, or null for NULL.
*/
export function decodePtr(slot: NativePtr): NativePtr | null {
const value: unknown = koffi.decode(slot, PVOID)
if (isNullPtr(value as NativePtr | null | undefined)) return null
return value as NativePtr
}
/**
* Decode a uint32 at a slot pointer.
* @param slot - the uint32 slot holding the out-parameter value.
* @returns the decoded uint32.
*/
export function decodeUint32(slot: NativePtr): number {
const value: unknown = koffi.decode(slot, 'uint32')
return value as number
}
/**
* Cast a koffi pointer to its numeric address (bigint, used for raw struct packing).
* @param ptr - the koffi pointer.
* @returns the pointer's numeric address.
*/
export function ptrAddress(ptr: NativePtr): bigint {
return koffi.address(ptr)
}
/**
* Allocate a raw byte block (used for SID copies and variable-length arrays).
* @param length - the block size in bytes.
* @returns the allocated block pointer.
*/
export function allocBytes(length: number): NativePtr {
const value: unknown = koffi.alloc('uint8', length)
return value as NativePtr
}
/**
* Allocate one zeroed OVERLAPPED (32 bytes on x64: Internal@0, InternalHigh@8,
* Offset@16, OffsetHigh@20, hEvent@24). LockFileEx/UnlockFileEx receive this
* instead of a NULL lpOverlapped: koffi 3.1.1 crashes on NULL there, and a
* zeroed OVERLAPPED on a synchronous file handle is the documented equivalent
* (the byte range locks from offset 0, hEvent stays NULL).
* @returns the zeroed block pointer.
*/
export function allocOverlapped(): NativePtr {
return allocBytes(32)
}
/**
* Decode a pointer VALUE stored in memory at `buffer[offset]` (e.g. TOKEN_GROUPS entries).
* @param buffer - the buffer holding the pointer value.
* @param offset - byte offset of the pointer inside the buffer.
* @returns the decoded pointer, or null for NULL.
*/
export function decodePtrAt(buffer: Buffer, offset: number): NativePtr | null {
const value: unknown = koffi.decode(buffer, offset, PVOID)
if (isNullPtr(value as NativePtr | null | undefined)) return null
return value as NativePtr
}
/**
* Decode a uint8 at a native pointer plus byte offset — the ACL walk's
* field-read primitive (koffi.decode with an offset, no memcpy, no pointer
* arithmetic).
* @param ptr - the native pointer to read from.
* @param offset - byte offset from the pointer.
* @returns the decoded uint8.
*/
export function decodeUint8At(ptr: NativePtr, offset: number): number {
const value: unknown = koffi.decode(ptr, offset, 'uint8')
return value as number
}
/**
* Decode a uint16 at a native pointer plus byte offset (see {@link decodeUint8At}).
* @param ptr - the native pointer to read from.
* @param offset - byte offset from the pointer.
* @returns the decoded uint16.
*/
export function decodeUint16At(ptr: NativePtr, offset: number): number {
const value: unknown = koffi.decode(ptr, offset, 'uint16')
return value as number
}
/**
* Decode a uint32 at a native pointer plus byte offset (see {@link decodeUint8At}).
* @param ptr - the native pointer to read from.
* @param offset - byte offset from the pointer.
* @returns the decoded uint32.
*/
export function decodeUint32At(ptr: NativePtr, offset: number): number {
const value: unknown = koffi.decode(ptr, offset, 'uint32')
return value as number
}
/**
* Compare two SIDs field-by-field via BOUNDED offset reads (revision, count,
* identifier authority, subauthorities up to the count) — never a fixed-size
* struct decode, which would read past a short SID allocation (a SID with
* fewer than 8 subauthorities is smaller than `SID_STRUCT`). An implausible
* subauthority count reads as unequal.
* @param left - pointer to one SID (offset 0).
* @param leftOffset - byte offset of the SID structure within `left`.
* @param right - pointer to the other SID.
* @param rightOffset - byte offset of the SID structure within `right`.
* @returns whether the SIDs are identical.
*/
export function sameSidAt(left: NativePtr, leftOffset: number, right: NativePtr, rightOffset: number): boolean {
const leftRevision = decodeUint8At(left, leftOffset)
const rightRevision = decodeUint8At(right, rightOffset)
if (leftRevision !== rightRevision) return false
const leftCount = decodeUint8At(left, leftOffset + 1)
const rightCount = decodeUint8At(right, rightOffset + 1)
if (leftCount !== rightCount || leftCount > abi.SID_MAX_SUB_AUTHORITIES) return false
for (let index = 0; index < 6; index++) {
if (decodeUint8At(left, leftOffset + 2 + index) !== decodeUint8At(right, rightOffset + 2 + index)) return false
}
for (let index = 0; index < leftCount; index++) {
if (decodeUint32At(left, leftOffset + 8 + index * 4) !== decodeUint32At(right, rightOffset + 8 + index * 4)) return false
}
return true
}
/**
* Allocate a zeroed STARTUPINFOW.
* @returns the allocated struct pointer.
*/
export function allocStartupInfo(): NativePtr {
const value: unknown = koffi.alloc(STARTUPINFOW, 1)
return value as NativePtr
}
/**
* Write the stdio-relevant fields into a zeroed STARTUPINFOW (others stay default-initialized).
* @param startupInfo - the allocated STARTUPINFOW to encode into.
* @param fields - the field subset to write.
*/
export function encodeStartupInfo(startupInfo: NativePtr, fields: StartupInfoInput): void {
koffi.encode(startupInfo, STARTUPINFOW, fields)
}
/**
* Allocate a zeroed PROCESS_INFORMATION.
* @returns the allocated struct pointer.
*/
export function allocProcessInfo(): NativePtr {
const value: unknown = koffi.alloc(PROCESS_INFORMATION, 1)
return value as NativePtr
}
/**
* Decode a PROCESS_INFORMATION after CreateProcessAsUserW.
* @param processInfo - the PROCESS_INFORMATION filled by the spawn call.
* @returns the decoded handle/id fields.
*/
export function decodeProcessInfo(processInfo: NativePtr): ProcessInfoOutput {
const value: unknown = koffi.decode(processInfo, PROCESS_INFORMATION)
return value as ProcessInfoOutput
}
let cached: Win32Bindings | undefined
function bindings(): Win32Bindings {
if (cached !== undefined) return cached
const kernel32 = koffi.load('kernel32.dll')
const advapi32 = koffi.load('advapi32.dll')
// Each binding shape is verified by verify/abi-probe.cpp against the real
// Windows headers and exercised end-to-end by tests/probe.spec.ts; the
// single cast keeps the per-binding noise out of this table.
const bind = (lib: ReturnType<typeof koffi.load>, name: string, result: Ptr | string, args: Array<Ptr | string>): unknown =>
lib.func('__stdcall', name, result, args)
cached = {
openProcess: bind(kernel32, 'OpenProcess', PVOID, ['uint32', 'int', 'uint32']),
openProcessToken: bind(advapi32, 'OpenProcessToken', 'int', [PVOID, 'uint32', PPVOID]),
closeHandle: bind(kernel32, 'CloseHandle', 'int', [PVOID]),
getLastError: bind(kernel32, 'GetLastError', 'uint32', []),
formatMessageW: bind(kernel32, 'FormatMessageW', 'uint32', ['uint32', PVOID, 'uint32', 'uint32', PVOID, 'uint32', PVOID]),
localAlloc: bind(kernel32, 'LocalAlloc', PVOID, ['uint32', 'size_t']),
localFree: bind(kernel32, 'LocalFree', PVOID, [PVOID]),
convertStringSidToSidW: bind(advapi32, 'ConvertStringSidToSidW', 'int', ['str16', PPVOID]),
createWellKnownSid: bind(advapi32, 'CreateWellKnownSid', 'int', ['int', PVOID, PVOID, koffi.pointer('uint32')]),
isValidSid: bind(advapi32, 'IsValidSid', 'int', [PVOID]),
getLengthSid: bind(advapi32, 'GetLengthSid', 'uint32', [PVOID]),
copySid: bind(advapi32, 'CopySid', 'int', ['uint32', PVOID, PVOID]),
getTokenInformation: bind(advapi32, 'GetTokenInformation', 'int', [PVOID, 'int', PVOID, 'uint32', koffi.pointer('uint32')]),
setTokenInformation: bind(advapi32, 'SetTokenInformation', 'int', [PVOID, 'int', PVOID, 'uint32']),
createRestrictedToken: bind(advapi32, 'CreateRestrictedToken', 'int', [PVOID, 'uint32', 'uint32', PVOID, 'uint32', PVOID, 'uint32', PVOID, PPVOID]),
setEntriesInAclW: bind(advapi32, 'SetEntriesInAclW', 'uint32', ['uint32', PVOID, PVOID, PPVOID]),
setNamedSecurityInfoW: bind(advapi32, 'SetNamedSecurityInfoW', 'uint32', ['str16', 'int', 'uint32', PVOID, PVOID, PVOID, PVOID]),
getNamedSecurityInfoW: bind(advapi32, 'GetNamedSecurityInfoW', 'uint32', ['str16', 'int', 'uint32', PPVOID, PPVOID, PPVOID, PPVOID, PPVOID]),
getTempPathW: bind(kernel32, 'GetTempPathW', 'uint32', ['uint32', PVOID]),
// fileapi.h line ~64: HANDLE CreateFileW(LPCWSTR, DWORD, DWORD,
// LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE).
createFileW: bind(kernel32, 'CreateFileW', PVOID, ['str16', 'uint32', 'uint32', PVOID, 'uint32', 'uint32', PVOID]),
// fileapi.h lines ~177/~185: BOOL LockFileEx(HANDLE, DWORD, DWORD, DWORD,
// DWORD, LPOVERLAPPED); BOOL UnlockFileEx(HANDLE, DWORD, DWORD, DWORD,
// LPOVERLAPPED). lpOverlapped is NULL for synchronous locking.
lockFileEx: bind(kernel32, 'LockFileEx', 'int', [PVOID, 'uint32', 'uint32', 'uint32', 'uint32', PVOID]),
unlockFileEx: bind(kernel32, 'UnlockFileEx', 'int', [PVOID, 'uint32', 'uint32', 'uint32', PVOID]),
createPipe: bind(kernel32, 'CreatePipe', 'int', [PPVOID, PPVOID, PVOID, 'uint32']),
setHandleInformation: bind(kernel32, 'SetHandleInformation', 'int', [PVOID, 'uint32', 'uint32']),
createProcessAsUserW: bind(advapi32, 'CreateProcessAsUserW', 'int', [
PVOID, 'str16', 'str16', PVOID, PVOID, 'int', 'uint32', PVOID, 'str16',
koffi.pointer(STARTUPINFOW), koffi.pointer(PROCESS_INFORMATION),
]),
setEnvironmentVariableW: bind(kernel32, 'SetEnvironmentVariableW', 'int', ['str16', 'str16']),
readFile: bind(kernel32, 'ReadFile', 'int', [PVOID, PVOID, 'uint32', koffi.pointer('uint32'), PVOID]),
peekNamedPipe: bind(kernel32, 'PeekNamedPipe', 'int', [PVOID, PVOID, 'uint32', koffi.pointer('uint32'), koffi.pointer('uint32'), koffi.pointer('uint32')]),
waitForSingleObject: bind(kernel32, 'WaitForSingleObject', 'uint32', [PVOID, 'uint32']),
getExitCodeProcess: bind(kernel32, 'GetExitCodeProcess', 'int', [PVOID, koffi.pointer('uint32')]),
resumeThread: bind(kernel32, 'ResumeThread', 'uint32', [PVOID]),
createJobObjectW: bind(kernel32, 'CreateJobObjectW', PVOID, [PVOID, 'str16']),
setInformationJobObject: bind(kernel32, 'SetInformationJobObject', 'int', [PVOID, 'int', PVOID, 'uint32']),
assignProcessToJobObject: bind(kernel32, 'AssignProcessToJobObject', 'int', [PVOID, PVOID]),
terminateProcess: bind(kernel32, 'TerminateProcess', 'int', [PVOID, 'uint32']),
setConsoleCtrlHandler: bind(kernel32, 'SetConsoleCtrlHandler', 'int', [PVOID, 'int']),
getStdHandle: bind(kernel32, 'GetStdHandle', PVOID, ['int']),
} as unknown as Win32Bindings
return cached
}
/**
* Resolve the lazy Win32 bindings (throws the first binding failure, fail-closed).
* @returns the cached binding table.
*/
export function win32(): Promise<Win32Bindings> {
return Promise.resolve(bindings())
}
/**
* Resolve the lazy Win32 bindings SYNCHRONOUSLY — the sandbox seam's
* server-side per-session grant materializes ACEs inside the synchronous
* `confine()` call, which cannot await. Same cached table as {@link win32}
* (the underlying koffi loads are synchronous; the async wrapper exists for
* the runner's await-shaped call sites).
* @returns the cached binding table.
*/
export function win32Sync(): Win32Bindings {
return bindings()
}
/**
* Turn a Win32 error code into readable text via FormatMessageW.
* @param api - the binding table.
* @param win32Code - the error code to format.
* @returns the formatted message text, or '' when formatting fails.
*/
export function errorText(api: Win32Bindings, win32Code: number): string {
const buffer = Buffer.alloc(1024)
const length = api.formatMessageW(
abi.FORMAT_MESSAGE_FROM_SYSTEM | abi.FORMAT_MESSAGE_IGNORE_INSERTS,
null, win32Code, 0, buffer, buffer.length / 2, null,
)
if (length === 0) return ''
return buffer.subarray(0, length * 2).toString('utf16le').trim()
}
/**
* Read the process temp directory via GetTempPathW (fileapi.h line ~188).
* Defensive against an overlong system temp path: GetTempPathW reports the
* REQUIRED length (including NUL) without writing the buffer when it is too
* small, so a reported length beyond the buffer's capacity means the buffer
* was never filled and must not be decoded.
* @param api - the binding table.
* @returns the NUL-terminated temp path decoded as a string.
*/
export function getTempPath(api: Win32Bindings): string {
const buffer = Buffer.alloc((abi.MAX_PATH + 1) * 2)
const length = api.getTempPathW(buffer.length / 2, buffer)
if (length === 0) throwLastError(api, 'GetTempPathW')
if (length > buffer.length / 2) {
throw new Win32Error('GetTempPathW', abi.ERROR_INSUFFICIENT_BUFFER, `required ${length} chars exceed the ${buffer.length / 2}-char buffer; nothing was written`)
}
return buffer.subarray(0, length * 2).toString('utf16le')
}
/**
* Throw a Win32Error for a BOOL-style API failure. MUST be called immediately
* after the failed call so GetLastError is not clobbered by other Win32 calls.
* @param api - the binding table.
* @param name - the failed API's name for the error message.
* @param detail - optional detail overriding the formatted system message.
* @returns never — always throws.
*/
export function throwLastError(api: Win32Bindings, name: string, detail?: string): never {
const win32Code = api.getLastError()
throw new Win32Error(name, win32Code, detail ?? errorText(api, win32Code))
}
/**
* Throw a Win32Error for an HRESULT-style API return value (the value IS the error code).
* @param api - the binding table.
* @param name - the failed API's name for the error message.
* @param win32Code - the API's returned error code.
* @param detail - optional detail overriding the formatted system message.
* @returns never — always throws.
*/
export function throwWin32(api: Win32Bindings, name: string, win32Code: number, detail?: string): never {
throw new Win32Error(name, win32Code, detail ?? errorText(api, win32Code))
}

View File

@@ -0,0 +1,107 @@
/**
* Server-side per-session write grant: the ACE materialization half of the
* sandbox seam's per-session grant reuse. The seam (sandbox-local) holds ONE
* {@link AclWriteGrant} per session for the server process's lifetime —
* created lazily at the session's first confined execution, reused (never
* re-applied) for every later call, revoked on provider dispose. The durable
* half (the session's SID and paths surviving a restart) lives in the
* session log, owned by the seam; this module owns only the native half: the
* parsed SID pointer and the standing ACEs.
*
* Fail-closed: `add` throws on any grant failure and the caller disposes the
* instance (revoking every path granted so far); `dispose` revokes every
* standing grant and reports every cleanup failure.
* @module @deepseek-ai/dsh-sandbox-windows-acl/grant
*/
import { grantWrite, revokeWrite } from './acl.ts'
import { allocPtrSlot, decodePtr, isNullPtr, throwLastError, win32Sync } from './ffi.ts'
import type { NativePtr, Win32Bindings } from './ffi.ts'
/**
* One write SID's server-lifetime grant materialization: the parsed SID
* pointer plus every directory whose DACL currently carries its ACE.
* Workspace paths are added STANDING (their ACEs are the cross-session reuse
* cache and outlive the grant — dispose() skips revoking them, or the next
* provision would re-propagate the whole tree); temp paths are revocable
* (dispose() revokes them — an inheritable ACE must not outlive its
* session's temp directory). Create with {@link AclWriteGrant.create};
* dispose revokes the revocable paths and frees the SID.
*/
export class AclWriteGrant {
/** The write SID in SDDL string form. */
readonly writeSid: string
private readonly api: Win32Bindings
private readonly sidPtr: NativePtr
private readonly revocablePaths: string[] = []
private readonly standingPaths: string[] = []
private constructor(api: Win32Bindings, sidPtr: NativePtr, writeSid: string) {
this.api = api
this.sidPtr = sidPtr
this.writeSid = writeSid
}
/**
* Parse the SID string and open the binding table (lazily, once per
* server). Fail-closed: any failure throws — nothing is granted yet.
* @param writeSid - the orphan write SID string (`S-1-4-x-y`).
* @param api - optional already-resolved bindings (tests).
* @returns the ready grant (no ACEs yet).
*/
static create(writeSid: string, api?: Win32Bindings): AclWriteGrant {
const bindings = api ?? win32Sync()
const sidSlot = allocPtrSlot()
if (bindings.convertStringSidToSidW(writeSid, sidSlot) === 0) {
throwLastError(bindings, 'ConvertStringSidToSidW', writeSid)
}
const sidPtr = decodePtr(sidSlot)
if (sidPtr === null) throwLastError(bindings, 'ConvertStringSidToSidW', `null SID for ${writeSid}`)
return new AclWriteGrant(bindings, sidPtr, writeSid)
}
/**
* Grant the write ACE on one directory (idempotent: an already-standing
* exact ACE skips the eager full-tree re-propagation — see
* {@link grantWrite}) and record the path for {@link dispose} unless it is
* standing. The path is recorded BEFORE the grant: a post-apply throw (a
* LocalFree failure after SetNamedSecurityInfoW succeeded) must still
* revoke it, and revoking an ungranted path is a no-op merge. Callers
* treat a throw as a failed materialization and dispose the instance to
* revoke the paths granted so far.
* @param path - the directory whose DACL gains the grant.
* @param standing - the ACE outlives this grant (the workspace reuse
* cache; dispose() skips revoking it). Default false (revoked on
* dispose — the temp-directory lifecycle).
*/
add(path: string, standing = false): void {
;(standing ? this.standingPaths : this.revocablePaths).push(path)
grantWrite(this.api, path, this.sidPtr)
}
/** Every directory currently carrying the grant, in grant order. */
get paths(): readonly string[] {
return [...this.standingPaths, ...this.revocablePaths]
}
/** Revoke every revocable grant (standing ACEs stay) and free the SID; reports every cleanup failure. */
dispose(): void {
const failures: unknown[] = []
for (const path of this.revocablePaths) {
try {
revokeWrite(this.api, path, this.sidPtr)
} catch (error) {
failures.push(error)
}
}
try {
const freed = this.api.localFree(this.sidPtr)
if (!isNullPtr(freed)) throwLastError(this.api, 'LocalFree', 'write SID')
} catch (error) {
failures.push(error)
}
if (failures.length > 0) {
throw new AggregateError(failures, `AclWriteGrant dispose completed with ${failures.length} cleanup failure(s)`)
}
}
}

View File

@@ -0,0 +1,386 @@
/**
* Windows ACL write-restriction sandbox backend for the DeepSeek Harness
* sandbox seam. Mirrors the mechanism of github.com/huoyaoyuan/
* windows-acl-restrict-poc @ 10e4dfb (the fixed revision): a WRITE_RESTRICTED
* token whose restricting SIDs include a write SID (`S-1-4-x-y`) that only
* this sandbox adds to the target directories' DACLs — the intersection
* check then allows writes exactly where that SID has a Write ACE, and
* nowhere else the write SID is concerned (the token's write check ALSO
* inherits the ambient write ACEs of the other restricting SIDs — the
* keep-alive group logon SID + Everyone; Authenticated Users, INTERACTIVE,
* and LOCAL are absent from both lists — see the seam's dual-list contract
* in `packages/sandbox/sandbox-local` and the package README's Modes section
* for the complete boundary). The write SID is the per-WORKSPACE identity
* ({@link workspaceWriteSid}): deterministic from the canonical workspace
* path, so the workspace-root ACE materializes once per workspace per
* machine and every later provision hits the exact-ACE skip — the
* grant-reuse story the per-session random SID paid a full tree propagation
* per session for. Unlike the POC, every API failure throws with the API
* name and exact Win32 code; a child is NEVER spawned unrestricted.
*
* Known boundaries (inherent to restricted tokens, not this port):
* - writes are restricted; reads, network, and process visibility are NOT
* (WRITE_RESTRICTED intersects only write accesses);
* - console isolation is unavailable — children share the host console
* (CREATE_NO_WINDOW / CREATE_NEW_CONSOLE children die with
* STATUS_DLL_INIT_FAILED under the restriction);
* - the temp directory and every writable directory must be owned by the
* caller (owner-implicit WRITE_DAC);
* - grants are standing ACE mutations on real directories. WORKSPACE grants
* are deliberately never revoked — the ACE is the cross-session reuse
* cache (revoking would force the next session to re-propagate the whole
* tree). TEMP grants are revocable: dispose() removes them so a standing
* inheritable ACE never outlives its session's temp directory (an
* inheritable ACE on the ambient temp root would otherwise widen the
* SID's write reach to every future temp file). With `manageDacls: false`
* the CALLER owns the DACLs (the sandbox seam's grant reuse):
* init()/dispose() skip grant/revoke entirely and the caller must not
* revoke under live children.
* @module @deepseek-ai/dsh-sandbox-windows-acl
*/
import { existsSync, statSync } from 'node:fs'
import { resolve } from 'node:path'
import { grantWrite, revokeWrite } from './acl.ts'
import { Win32Error } from './errors.ts'
import { allocPtrSlot, decodePtr, getTempPath, isNullPtr, throwLastError, win32 } from './ffi.ts'
import type { NativePtr, Win32Bindings } from './ffi.ts'
import { drainPipe, spawnSandboxed, spawnSandboxedInherited, waitForExit } from './spawn.ts'
import { createRestrictedToken, findLogonSid, makeWellKnownSid, openCurrentProcessToken, setTokenDefaultDaclGrant } from './token.ts'
import * as abi from './win32-abi.ts'
export { quoteArg } from './spawn.ts'
export { AclWriteGrant } from './grant.ts'
export { workspaceWriteSid } from './workspace-sid.ts'
export { Win32Error } from './errors.ts'
/** Construction options: the write allowlist, the optional temp grant, and the orphan SID identity. */
export interface AclSandboxOptions {
/** Directories the confined child may write into (must exist and be caller-owned). */
writableDirs: readonly string[]
/**
* Temp directory to also grant; defaults to GetTempPathW() at init time.
* Pass null for read-only confinement: NO temp grant (strict zero grant on
* the filesystem; the NUL device stays ambient-writable via Everyone — see
* README).
*/
tempDir?: string | null
/**
* The write SID forming the workspace-write allowlist: REQUIRED under
* workspace-write, ignored (and must be absent) under read-only. Callers
* derive it from the workspace via {@link workspaceWriteSid} — the identity
* is per workspace, not per sandbox instance, so the workspace-root ACE
* outlives every instance and later provisions hit the exact-ACE skip.
*/
writeSid?: string
/**
* The file-effect mode this instance confines under — selects the
* restricted token's restricting-SID list (I for read-only, J for
* workspace-write) and MUST match the grant shape: read-only pairs with
* zero grants. The runner validates the argv-borne mode string at its
* boundary; this typed seam trusts the union.
*/
mode: 'read-only' | 'workspace-write'
/**
* Whether this instance owns its DACL grants (default true). False means
* the CALLER has already materialized the ACEs (the sandbox seam's
* per-session grant reuse): init()/dispose() skip grant/revoke entirely —
* the caller holds the grants for its own lifetime and revokes them.
*/
manageDacls?: boolean
}
/** Per-spawn options: the program, its argv/cwd, and the stdio shape. */
export interface AclSandboxSpawnOptions {
/** Program to run (resolved via PATH search when unqualified, like CreateProcess). */
command: string
/** Arguments, quoted per CommandLineToArgvW rules. */
args?: readonly string[]
/** Working directory; defaults to the caller's cwd. */
cwd?: string
/**
* 'pipe' (default): capture stdout/stderr via anonymous pipes.
* 'inherit': the child inherits the caller's stdio directly (runner usage —
* bytes flow straight through), always wrapped in a kill-on-close job so the
* child dies with the caller; stdout/stderr in the result are empty.
*/
stdio?: 'pipe' | 'inherit'
}
/** A settled confined child: captured stdio and the exit code. */
export interface AclSandboxChildResult {
stdout: Buffer
stderr: Buffer
exitCode: number
}
/** A running confined child: its pid and a settlement promise. */
export interface AclSandboxChild {
/** Child process id. */
pid: number
/** Resolve stdout/stderr and the exit code once the child exits. */
wait(): Promise<AclSandboxChildResult>
}
/**
* One write-restricted sandbox instance: token + write-SID grants + spawn.
* `init()` is fail-closed — any Win32 failure revokes the revocable (temp)
* grants and throws; `dispose()` revokes the temp grants, leaves the
* standing workspace ACEs in place (the cross-instance reuse cache), frees
* every allocation, and reports every cleanup failure. With
* `manageDacls: false` the caller owns the grants (the sandbox seam's grant
* reuse): init() applies none and dispose() revokes none.
*/
export class AclSandbox {
/** Absolute writable directories (constructor-validated). */
readonly writableDirs: string[]
/** The write SID string whose ACEs form the write allowlist (workspace-write only). */
readonly writeSid: string | undefined
/** The file-effect mode — the restricted token's restricting-SID list selection. */
readonly mode: 'read-only' | 'workspace-write'
private readonly tempDirOption: string | null | undefined
private readonly manageDacls: boolean
private tempDirResolved: string | null | undefined
private api: Win32Bindings | undefined
private token: NativePtr | undefined
private writeSidPtr: NativePtr | undefined
/** The well-known/logon SID allocations init() makes; freed by dispose() alongside the write SID. */
private sidAllocations: NativePtr[] = []
private grantedPaths: string[] = []
constructor(options: AclSandboxOptions) {
this.mode = options.mode
this.manageDacls = options.manageDacls ?? true
this.writableDirs = options.writableDirs.map((directory) => {
const absolute = resolve(directory)
if (!existsSync(absolute) || !statSync(absolute).isDirectory()) {
throw new Error(`AclSandbox writable dir does not exist or is not a directory: ${absolute}`)
}
return absolute
})
this.tempDirOption = options.tempDir
this.writeSid = options.writeSid
if (this.mode === 'workspace-write' && this.writeSid === undefined) {
throw new Error('AclSandbox workspace-write requires a write SID — derive it from the workspace via workspaceWriteSid()')
}
}
/** Resolved temp directory (available after init; null when temp grants are disabled). */
get tempDir(): string | null | undefined {
return this.tempDirResolved
}
/** Create the restricted token and apply the orphan-SID grants. Idempotent-unsafe: once per instance. */
async init(): Promise<void> {
if (this.api !== undefined) throw new Error('AclSandbox is already initialized')
const api = await win32()
const currentToken = openCurrentProcessToken(api)
try {
// Read-only runs carry no write SID (its restricting list has no
// orphan): nothing to parse, nothing to grant.
let writeSidPtr: NativePtr | undefined
if (this.writeSid !== undefined) {
const sidSlot = allocPtrSlot()
if (api.convertStringSidToSidW(this.writeSid, sidSlot) === 0) {
throwLastError(api, 'ConvertStringSidToSidW', this.writeSid)
}
const parsedSid = decodePtr(sidSlot)
if (parsedSid === null) throw new Win32Error('ConvertStringSidToSidW', api.getLastError(), this.writeSid)
this.writeSidPtr = parsedSid
writeSidPtr = parsedSid
}
const tempDir = this.tempDirOption === null
? null
: this.tempDirOption !== undefined ? this.tempDirOption : getTempPath(api)
if (tempDir !== null) {
if (!existsSync(tempDir) || !statSync(tempDir).isDirectory()) {
throw new Error(`AclSandbox temp dir does not exist or is not a directory: ${tempDir}`)
}
this.tempDirResolved = tempDir
}
// manageDacls: false — the caller (the sandbox seam's grant) already
// materialized the ACEs; this instance must neither add nor remove any.
// When this instance owns the DACLs, writableDir ACEs are STANDING (the
// per-workspace reuse cache — dispose() never revokes them, or the next
// provision would re-propagate the whole tree) and the temp ACE is
// REVOCABLE (dispose() removes it — an inheritable ACE on the ambient
// temp root must not outlive the instance, or it would widen the SID's
// write reach to every future temp file).
if (this.manageDacls) {
if (writeSidPtr !== undefined) {
for (const path of this.writableDirs) {
grantWrite(api, path, writeSidPtr)
}
if (tempDir !== null) {
// Record BEFORE granting: grantWrite can throw after a successful
// apply (a LocalFree failure), and the fail-closed catch must still
// revoke that path (revoking an ungranted path is a no-op merge).
this.grantedPaths.push(tempDir)
grantWrite(api, tempDir, writeSidPtr)
}
}
}
const logonSid = findLogonSid(api, currentToken)
this.sidAllocations.push(logonSid)
const worldSid = makeWellKnownSid(api, abi.WinWorldSid)
this.sidAllocations.push(worldSid)
const restricted = createRestrictedToken(
api, currentToken, logonSid, writeSidPtr,
{ world: worldSid },
this.mode,
)
// The restricted token's default DACL still names only the user's
// ambient SIDs — none of the restricting SIDs. Every NEW object the
// confined process creates (anonymous stdio pipes, sync objects) takes
// its DACL from that default, so the write pass-2 check would deny
// pipe creation (ERROR_ACCESS_DENIED; Node EPERM) and break every
// piped-stdio grandchild spawn. Merge a full-access ACE for a
// restricting SID (the write SID under workspace-write, Everyone under
// read-only): new-object creation stays gated by the parent object's
// DACL, while the new object's own DACL passes pass-2.
setTokenDefaultDaclGrant(api, restricted, writeSidPtr ?? worldSid)
this.token = restricted
if (api.closeHandle(currentToken) === 0) throwLastError(api, 'CloseHandle', 'current process token')
this.api = api
} catch (error) {
// Best-effort close on the failure path (last error already captured in `error`).
api.closeHandle(currentToken)
// Fail-closed cleanup: never leave a revocable (temp) grant or SID
// allocation behind a failed init. Standing workspace ACEs are NOT
// revoked — they are the intended end state (the reuse cache), not an
// error artifact.
const cleanupFailures: unknown[] = []
const writeSidPtr = this.writeSidPtr
if (writeSidPtr !== undefined) {
for (const path of this.grantedPaths) {
try {
revokeWrite(api, path, writeSidPtr)
} catch (cleanupError) {
cleanupFailures.push(cleanupError)
}
}
}
for (const sidPtr of this.sidAllocations.splice(0)) {
try {
const freed = api.localFree(sidPtr)
if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', 'init SID allocation')
} catch (cleanupError) {
cleanupFailures.push(cleanupError)
}
}
if (cleanupFailures.length > 0) {
throw new AggregateError(
[error, ...cleanupFailures],
`AclSandbox init failed and ${cleanupFailures.length} grant revocation(s) also failed`,
)
}
throw error
}
}
/**
* Spawn a process under the restricted token. Fails closed: throws on every
* Win32 failure; the child is never created unrestricted. With
* `stdio: 'inherit'` the child shares the caller's stdio directly and is
* placed in a kill-on-close job (dies with the caller). Call dispose() only
* after all children have exited — revoking grants under a live child
* removes its remaining write allowance.
* @param options - the program, argv/cwd, and stdio shape.
* @returns the running child.
*/
spawn(options: AclSandboxSpawnOptions): AclSandboxChild {
const api = this.api
const token = this.token
if (api === undefined || token === undefined) throw new Error('AclSandbox is not initialized: call init() first')
const args = options.args ?? []
const cwd = options.cwd ?? process.cwd()
if (options.stdio === 'inherit') {
const native = spawnSandboxedInherited(api, token, { command: options.command, args, cwd })
let exitCodePromise: Promise<number> | undefined
return {
pid: native.pid,
wait: async () => {
exitCodePromise ??= Promise.resolve(waitForExit(api, native.process))
const exitCode = await exitCodePromise
if (api.closeHandle(native.job) === 0) throwLastError(api, 'CloseHandle', 'kill-on-close job')
return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), exitCode }
},
}
}
const native = spawnSandboxed(api, token, { command: options.command, args, cwd })
const stdout = drainPipe(api, native.stdoutRead)
const stderr = drainPipe(api, native.stderrRead)
// waitForExit is deliberately NOT started here: WaitForSingleObject blocks
// the thread and would starve the drains while the child is still running
// (pipe-buffer deadlock). The drains resolve only after the child closed
// its pipe ends — by then the wait returns immediately.
let exitCodePromise: Promise<number> | undefined
return {
pid: native.pid,
wait: async () => {
const stdoutBuffer = await stdout
const stderrBuffer = await stderr
exitCodePromise ??= Promise.resolve(waitForExit(api, native.process))
return { stdout: stdoutBuffer, stderr: stderrBuffer, exitCode: await exitCodePromise }
},
}
}
/**
* Revoke the revocable (temp) grants, free the SID, close the token; the
* standing workspace ACEs stay (the reuse cache). Reports every cleanup
* failure.
*/
dispose(): void {
const api = this.api
if (api === undefined) return
const failures: unknown[] = []
const writeSidPtr = this.writeSidPtr
if (writeSidPtr !== undefined) {
if (this.manageDacls) {
for (const path of this.grantedPaths) {
try {
revokeWrite(api, path, writeSidPtr)
} catch (error) {
failures.push(error)
}
}
}
try {
const freed = api.localFree(writeSidPtr)
if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', 'write SID')
} catch (error) {
failures.push(error)
}
}
const token = this.token
if (token !== undefined) {
try {
if (api.closeHandle(token) === 0) throwLastError(api, 'CloseHandle', 'restricted token')
} catch (error) {
failures.push(error)
}
}
for (const sidPtr of this.sidAllocations.splice(0)) {
try {
const freed = api.localFree(sidPtr)
if (!isNullPtr(freed)) throwLastError(api, 'LocalFree', 'init SID allocation')
} catch (error) {
failures.push(error)
}
}
this.api = undefined
this.token = undefined
this.writeSidPtr = undefined
this.grantedPaths = []
if (failures.length > 0) {
throw new AggregateError(failures, `AclSandbox dispose completed with ${failures.length} cleanup failure(s)`)
}
}
}

View File

@@ -0,0 +1,31 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-sandbox-windows-acl`.
* @module @deepseek-ai/dsh-sandbox-windows-acl/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-sandbox-windows-acl'
/** Cordis companion plugin name. */
export const name = 'sandbox-windows-acl-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: this package exposes no independent event sequence or
* mutable data relation beyond the fail-closed contracts it enforces at each
* Win32 call boundary.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -0,0 +1,196 @@
/**
* The windows-acl confinement runner: the argv-prefix wrapper the sandbox
* seam spawns in place of the caller's command. It creates the
* WRITE_RESTRICTED token with the workspace write-SID allowlist, spawns the
* wrapped argv under it with the CALLER'S stdio inherited (bytes flow
* straight through), mirrors the child's exit code, and revokes its temp
* grant on exit (workspace ACEs stay standing as the reuse cache).
*
* Stable argv contract (the seam builds it; a native-exe replacement would
* keep the same contract):
* [node, runner.js, '--workspace', <dir>, '--temp', <dir>,
* '--mode', <read-only|workspace-write>,
* ['--write-sid', <S-1-4-…>], '--', <argv...>]
*
* Modes:
* - workspace-write: the workspace and temp directories carry the orphan-SID
* Write grant; every other write is denied by the token intersection.
* - read-only: STRICT zero grants — no directory is writable, not even the
* NUL device (`> $null` fails with access denied); the restricting list
* carries no orphan SID, so a standing grant ACE from an earlier
* workspace-write period stays inert. BOTH modes drop Authenticated Users
* (CIM unavailable — documented in README) and INTERACTIVE/LOCAL (the
* Public tree writes are denied); the two lists share the keep-alive group
* (logon SID, EVERYONE) and differ only by the orphan.
*
* `--write-sid`: the seam's grant contract — the CALLER has already
* materialized the write-SID ACEs (the seam's workspace + private-temp
* grants, server lifetime) and owns their revocation, so the runner neither
* grants nor revokes (manageDacls: false). The carried SID is the
* per-workspace identity ({@link workspaceWriteSid}) — the seam derives it
* from the policy root; the flag's PRESENCE is the seam-managed marker (its
* value must equal the workspace-derived SID). Absent `--write-sid`
* (standalone/test use) the runner self-manages grants per invocation with
* the same workspace-derived SID (its workspace ACEs are standing — the
* reuse cache — and its temp ACE is revoked on exit). With `--write-sid` in
* workspace-write mode, the runner rewrites the TMP/TEMP entries of its OWN
* environment (SetEnvironmentVariableW) to the `--temp` directory — a
* PRIVATE per-session temp subdirectory the seam provisions (bwrap `--tmpfs
* /tmp` semantics) — and the child inherits the rewritten block (lpEnvironment
* NULL; an explicit block through koffi trips ERROR_INVALID_PARAMETER in
* CreateProcessAsUserW, verified empirically). Read-only leaves the ambient
* temp entries untouched (writes there are denied anyway).
*
* Failure contract: every runner-side failure (bad args, missing
* directories, token/grant/spawn errors) prints `windows-acl-run: <detail>`
* to stderr and exits 127 — the seam's RUNNER_FAILURE_RULES matches that
* signature. The child is NEVER spawned unrestricted.
* @module @deepseek-ai/dsh-sandbox-windows-acl/runner
*/
import { existsSync, statSync } from 'node:fs'
import { win32 } from './ffi.ts'
import { AclSandbox } from './index.ts'
import { workspaceWriteSid } from './workspace-sid.ts'
const RUNNER_SIGNATURE = 'windows-acl-run'
const RUNNER_FAILURE_EXIT = 127
class RunnerFailure extends Error {}
/** Print the runner-failure signature line and unwind. */
function fail(detail: string): never {
process.stderr.write(`${RUNNER_SIGNATURE}: ${detail}\n`)
throw new RunnerFailure(detail)
}
interface ParsedArgs {
workspace: string
temp: string
mode: 'read-only' | 'workspace-write'
writeSid: string | undefined
command: string
args: string[]
}
function parseArgs(raw: string[]): ParsedArgs {
let workspace: string | undefined
let temp: string | undefined
let mode: string | undefined
let writeSid: string | undefined
let index = 0
for (; index < raw.length; index++) {
const token = raw[index]
if (token === '--') {
index++
break
}
index++
const value = raw[index]
if (value === undefined) fail(`missing value after ${token}`)
switch (token) {
case '--workspace': workspace = value; break
case '--temp': temp = value; break
case '--mode': mode = value; break
case '--write-sid': writeSid = value; break
default: fail(`unknown argument: ${token}`)
}
}
if (workspace === undefined) fail('missing --workspace')
if (temp === undefined) fail('missing --temp')
if (mode !== 'read-only' && mode !== 'workspace-write') fail(`unknown mode: ${String(mode)}`)
const argv = raw.slice(index)
const command = argv[0]
if (command === undefined) fail('missing command after --')
return { workspace, temp, mode, writeSid, command, args: argv.slice(1) }
}
function requireDirectory(label: string, path: string): void {
if (!existsSync(path) || !statSync(path).isDirectory()) {
fail(`${label} is not an existing directory: ${path}`)
}
}
async function main(): Promise<number> {
const parsed = parseArgs(process.argv.slice(2))
// Both directories are validated in both modes: a provider bug that passes
// a bogus root must fail loudly at the runner boundary, never mid-child.
requireDirectory('--workspace', parsed.workspace)
requireDirectory('--temp', parsed.temp)
const api = await win32()
// Ignore this process's own CTRL+C: the confined child (same console) keeps
// handling its own; the runner must survive to revoke grants and mirror the
// child's exit code.
if (api.setConsoleCtrlHandler(null, 1) === 0) {
fail(`SetConsoleCtrlHandler failed (Win32 ${api.getLastError()})`)
}
// The write SID is the per-workspace identity in BOTH flows; the flag's
// presence (seam-derived, or the self-managed derivation) selects who
// owns the DACLs below.
const writeSid = parsed.mode === 'workspace-write' ? parsed.writeSid ?? workspaceWriteSid(parsed.workspace) : undefined
const sandbox = new AclSandbox({
writableDirs: parsed.mode === 'workspace-write' ? [parsed.workspace] : [],
tempDir: parsed.mode === 'workspace-write' ? parsed.temp : null,
mode: parsed.mode,
...writeSid === undefined ? {} : { writeSid },
// With --write-sid the seam owns the DACLs (workspace + private-temp
// grants): this invocation must neither add nor revoke ACEs.
manageDacls: parsed.writeSid === undefined,
})
await sandbox.init()
// The seam's per-session temp contract: under --write-sid, workspace-write
// children see the PRIVATE per-session temp subdirectory through TMP/TEMP
// (bwrap --tmpfs /tmp semantics). The runner rewrites its OWN environment
// (SetEnvironmentVariableW) and the child inherits the block; self-managed
// and read-only runs keep the ambient entries.
if (parsed.mode === 'workspace-write' && parsed.writeSid !== undefined) {
if (api.setEnvironmentVariableW('TMP', parsed.temp) === 0) {
fail(`SetEnvironmentVariableW TMP failed (Win32 ${api.getLastError()})`)
}
if (api.setEnvironmentVariableW('TEMP', parsed.temp) === 0) {
fail(`SetEnvironmentVariableW TEMP failed (Win32 ${api.getLastError()})`)
}
}
try {
const child = sandbox.spawn({
command: parsed.command,
args: parsed.args,
stdio: 'inherit',
})
const result = await child.wait()
return result.exitCode
} finally {
// Cleanup failures must not mask the child's exit code: report and keep going.
try {
sandbox.dispose()
} catch (error) {
process.stderr.write(`${RUNNER_SIGNATURE}: cleanup: ${error instanceof Error ? error.message : String(error)}\n`)
}
}
}
main().then(
(exitCode) => {
// Exit-code mirroring is full-width on Windows, verified empirically on
// this machine (Windows 11 build 26200, Node 24): a child that exits
// with the NTSTATUS 0xC0000005 (STATUS_ACCESS_VIOLATION) is read back
// by GetExitCodeProcess as the uint32 3221225477, and after
// process.exitCode = 3221225477 the parent observes exactly
// 3221225477 (spawnSync status). PowerShell's $LASTEXITCODE and cmd
// print the signed view (-1073741819), but no truncation or masking
// happens anywhere in the chain — the mirror contract holds for the
// full 32-bit range, so no re-mapping is needed.
process.exitCode = exitCode
},
(error: unknown) => {
if (!(error instanceof RunnerFailure)) {
process.stderr.write(`${RUNNER_SIGNATURE}: ${error instanceof Error ? error.message : String(error)}\n`)
}
process.exitCode = RUNNER_FAILURE_EXIT
},
)

View File

@@ -0,0 +1,357 @@
/**
* Restricted-process spawning: anonymous pipes for stdio, STARTUPINFOW with
* STARTF_USESTDHANDLES, CreateProcessAsUserW under the restricted token, then
* asynchronous pipe draining and exit waiting. Console isolation
* (CREATE_NO_WINDOW / CREATE_NEW_CONSOLE) is intentionally absent: under this
* restriction scheme hidden-console children die with STATUS_DLL_INIT_FAILED
* (0xC0000142) — verified empirically, see win32-abi.ts. Stdio redirection is
* pipe-based and unaffected; the child shares the host console.
* @module @deepseek-ai/dsh-sandbox-windows-acl/spawn
*/
import { allocPtrSlot, allocProcessInfo, allocStartupInfo, allocUint32, decodePtr, decodeProcessInfo, decodeUint32, encodeStartupInfo, isNullPtr, throwLastError, throwWin32 } from './ffi.ts'
import type { NativePtr, Win32Bindings } from './ffi.ts'
import * as abi from './win32-abi.ts'
/**
* Quote one argument per the CommandLineToArgvW parsing rules: backslashes
* are doubled only before a quote character — including the closing quote
* this function appends, so a trailing backslash run is doubled as well
* (otherwise an odd run would escape the closing quote into a literal
* character and corrupt the rest of the command line). Mirrors the CRT
* ArgvQuote behavior Microsoft documents for command-line arguments.
* @param argument - one argv entry to quote.
* @returns the quoted entry (bare when quoting is unnecessary).
*/
export function quoteArg(argument: string): string {
if (argument === '') return '""'
if (!/[\s"]/u.test(argument)) return argument
let quoted = '"'
for (let index = 0; index < argument.length; index++) {
let backslashes = 0
while (index < argument.length && argument.charAt(index) === '\\') {
backslashes++
index++
}
if (index === argument.length) {
// Trailing backslash run: doubled so it cannot escape the closing quote.
quoted += '\\'.repeat(backslashes * 2)
} else if (argument.charAt(index) === '"') {
quoted += '\\'.repeat(backslashes * 2 + 1) + '"'
} else {
quoted += '\\'.repeat(backslashes) + argument.charAt(index)
}
}
return quoted + '"'
}
/**
* Build the single command line CreateProcess parses from program + argv.
* @param program - the executable (argv[0]).
* @param args - the remaining argv entries.
* @returns the joined, quoted command line.
*/
export function buildCommandLine(program: string, args: readonly string[]): string {
return [program, ...args].map(quoteArg).join(' ')
}
interface PipePair {
read: NativePtr
write: NativePtr
}
function createPipe(api: Win32Bindings): PipePair {
const readSlot = allocPtrSlot()
const writeSlot = allocPtrSlot()
if (api.createPipe(readSlot, writeSlot, null, 0) === 0) throwLastError(api, 'CreatePipe')
const read = decodePtr(readSlot)
const write = decodePtr(writeSlot)
if (read === null || write === null) throwLastError(api, 'CreatePipe', 'null pipe handle')
return { read, write }
}
function setInheritable(api: Win32Bindings, handle: NativePtr, label: string): void {
if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
throwLastError(api, 'SetHandleInformation', label)
}
}
/** A confined child spawned with piped stdio: process handle plus the pipe read ends to drain. */
export interface SpawnedNative {
pid: number
process: NativePtr
stdoutRead: NativePtr
stderrRead: NativePtr
}
/**
* Create a process under the restricted token with piped stdio. The child's
* stdin is closed immediately (EOF), matching the POC; stdout/stderr read ends
* are returned for draining. The child inherits the caller's environment block
* (lpEnvironment NULL); the caller rewrites entries through
* SetEnvironmentVariableW before spawning (the runner's per-session temp
* contract) — passing an explicit block through koffi trips
* ERROR_INVALID_PARAMETER in CreateProcessAsUserW (verified empirically).
* @param api - the binding table.
* @param token - the restricted token the child runs under.
* @param options - command, args, and working directory.
* @returns the spawned child's handles.
*/
export function spawnSandboxed(
api: Win32Bindings,
token: NativePtr,
options: { command: string; args: readonly string[]; cwd: string },
): SpawnedNative {
const stdIn = createPipe(api)
const stdOut = createPipe(api)
const stdErr = createPipe(api)
// Child side of each pipe must be inheritable (POC lines 262-268).
setInheritable(api, stdIn.read, 'stdin read end')
setInheritable(api, stdOut.write, 'stdout write end')
setInheritable(api, stdErr.write, 'stderr write end')
const startupInfo = allocStartupInfo()
encodeStartupInfo(startupInfo, {
cb: abi.STARTUPINFOW_SIZE,
dwFlags: abi.STARTF_USESTDHANDLES,
hStdInput: stdIn.read,
hStdOutput: stdOut.write,
hStdError: stdErr.write,
})
const processInfo = allocProcessInfo()
const commandLine = buildCommandLine(options.command, options.args)
const created = api.createProcessAsUserW(
token, null, commandLine,
null, null,
1, // bInheritHandles: required for redirection
0, // no creation flags: suspended/no-window variants are unusable under the restriction
null, options.cwd,
startupInfo, processInfo,
)
// Capture the failure before CloseHandle calls clobber GetLastError, then
// close every pipe handle created so far — the six-close contract this test
// surface pins (tests/failure-paths.spec.ts).
if (created === 0) {
const win32Code = api.getLastError()
api.closeHandle(stdIn.read)
api.closeHandle(stdIn.write)
api.closeHandle(stdOut.read)
api.closeHandle(stdOut.write)
api.closeHandle(stdErr.read)
api.closeHandle(stdErr.write)
throwWin32(api, 'CreateProcessAsUserW', win32Code, `command: ${options.command}, cwd: ${options.cwd}`)
}
const info = decodeProcessInfo(processInfo)
const processHandle = info.hProcess
const threadHandle = info.hThread
if (processHandle === null || threadHandle === null) {
throw new Error(`CreateProcessAsUserW succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
}
// Host-side cleanup: child handles are now duplicated in the child; the
// host closes its copies so ReadFile sees EOF when the child exits.
api.closeHandle(stdIn.read)
api.closeHandle(stdOut.write)
api.closeHandle(stdErr.write)
api.closeHandle(stdIn.write)
api.closeHandle(threadHandle)
return {
pid: info.dwProcessId,
process: processHandle,
stdoutRead: stdOut.read,
stderrRead: stdErr.read,
}
}
/**
* Drain one pipe read end to a Buffer via non-blocking PeekNamedPipe polling.
* @param api - the binding table.
* @param handle - the pipe read end to drain (closed when done).
* @returns the complete pipe contents.
*/
export async function drainPipe(api: Win32Bindings, handle: NativePtr): Promise<Buffer> {
const chunks: Buffer[] = []
for (;;) {
const bytesReadSlot = allocUint32()
const totalAvailSlot = allocUint32()
const leftThisMessageSlot = allocUint32()
const peeked = api.peekNamedPipe(handle, null, 0, bytesReadSlot, totalAvailSlot, leftThisMessageSlot)
if (peeked === 0) {
const win32Code = api.getLastError()
if (win32Code === abi.ERROR_BROKEN_PIPE || win32Code === abi.ERROR_NO_DATA) break // child closed its end: clean EOF
throwLastError(api, 'PeekNamedPipe', `drain failure after ${chunks.length} chunk(s)`)
}
const available = decodeUint32(totalAvailSlot)
if (available > 0) {
const chunk = Buffer.alloc(available)
const readSlot = allocUint32()
if (api.readFile(handle, chunk, chunk.length, readSlot, null) === 0) {
throwLastError(api, 'ReadFile', `drain failure after ${chunks.length} chunk(s)`)
}
chunks.push(chunk.subarray(0, decodeUint32(readSlot)))
}
// Small backoff instead of setImmediate: a bare next-tick would busy-poll
// the pipe at full event-loop speed while the child produces no output.
await new Promise<void>(resolve => setTimeout(resolve, 1))
}
api.closeHandle(handle)
return Buffer.concat(chunks)
}
/**
* Wait for process exit and return its exit code. Call only after both drains
* have resolved — the drains finish when the child closed its pipe ends, i.e.
* the child has already exited, so this wait returns immediately. Calling it
* earlier would block the event loop and starve the drains (the pipe-buffer
* deadlock the POC comments warn about).
* @param api - the binding table.
* @param process - the child process handle (closed when done).
* @returns the child's exit code.
*/
export function waitForExit(api: Win32Bindings, process: NativePtr): number {
const waitResult = api.waitForSingleObject(process, abi.INFINITE)
if (waitResult === 0xFFFFFFFF) throwLastError(api, 'WaitForSingleObject')
const exitCodeSlot = allocUint32()
if (api.getExitCodeProcess(process, exitCodeSlot) === 0) throwLastError(api, 'GetExitCodeProcess')
api.closeHandle(process)
return decodeUint32(exitCodeSlot)
}
/**
* Create a kill-on-close job object (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE at
* LimitFlags offset 16 of JOBOBJECT_EXTENDED_LIMIT_INFORMATION, layout
* verified by abi-probe.cpp). When the caller dies with the job handle open,
* Windows terminates every process in the job — the orphan-child backstop.
* The caller keeps the returned handle open for the child's lifetime.
*/
function createKillOnCloseJob(api: Win32Bindings): NativePtr {
const job = api.createJobObjectW(null, null)
if (isNullPtr(job)) throwLastError(api, 'CreateJobObjectW')
const information = Buffer.alloc(abi.JOBOBJECT_EXTENDED_LIMIT_SIZE)
information.writeUInt32LE(abi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, abi.JOBOBJECT_EXTENDED_LIMIT_FLAGS_OFFSET)
if (api.setInformationJobObject(job, abi.JobObjectExtendedLimitInformation, information, information.length) === 0) {
const win32Code = api.getLastError()
api.closeHandle(job)
throwWin32(api, 'SetInformationJobObject', win32Code)
}
return job
}
/** A confined child spawned with inherited stdio: process handle plus its kill-on-close job. */
export interface SpawnedInherited {
pid: number
process: NativePtr
/** Kill-on-close job the child was placed in; caller closes it after the child exits. */
job: NativePtr
}
/**
* Create a process under the restricted token whose stdio passes straight
* through to the caller's pipes. This is the runner shape: the harness spawns
* the runner with piped stdio, and the runner's confined child writes to
* those same pipes.
*
* Node clears the inheritability of its stdio handles at startup
* (uv_disable_stdio_inheritance), so raw spawns must re-enable the inherit
* bit around the call (libuv instead duplicates the handles; re-enabling is
* equivalent here and cheaper) and pass them explicitly via
* STARTF_USESTDHANDLES — otherwise the child receives INVALID std handles
* ("The handle is invalid", verified the hard way). The child starts
* suspended so it can be assigned to a kill-on-close job before it runs.
* @param api - the binding table.
* @param token - the restricted token the child runs under.
* @param options - command, args, and working directory.
* @returns the spawned child's handles and job.
*/
export function spawnSandboxedInherited(
api: Win32Bindings,
token: NativePtr,
options: { command: string; args: readonly string[]; cwd: string },
): SpawnedInherited {
const job = createKillOnCloseJob(api)
const stdIn = api.getStdHandle(abi.STD_INPUT_HANDLE)
const stdOut = api.getStdHandle(abi.STD_OUTPUT_HANDLE)
const stdErr = api.getStdHandle(abi.STD_ERROR_HANDLE)
if (isNullPtr(stdIn) || isNullPtr(stdOut) || isNullPtr(stdErr)) {
api.closeHandle(job)
throwLastError(api, 'GetStdHandle', 'null standard handle')
}
const makeInheritable = (handle: NativePtr, label: string): void => {
if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
throwLastError(api, 'SetHandleInformation', `${label} (enable inherit)`)
}
}
const restoreInherit = (handle: NativePtr): void => {
// Best-effort hygiene: the runner spawns nothing else; failures here must
// not mask the child outcome, so the result is deliberately unchecked.
api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, 0)
}
makeInheritable(stdIn, 'stdin')
makeInheritable(stdOut, 'stdout')
makeInheritable(stdErr, 'stderr')
const startupInfo = allocStartupInfo()
encodeStartupInfo(startupInfo, {
cb: abi.STARTUPINFOW_SIZE,
dwFlags: abi.STARTF_USESTDHANDLES,
hStdInput: stdIn,
hStdOutput: stdOut,
hStdError: stdErr,
})
const processInfo = allocProcessInfo()
const commandLine = buildCommandLine(options.command, options.args)
const created = api.createProcessAsUserW(
token, null, commandLine,
null, null,
1, // bInheritHandles: the re-enabled std handles must be inheritable
abi.CREATE_SUSPENDED, // suspended so job assignment precedes any execution
null, options.cwd,
startupInfo, processInfo,
)
restoreInherit(stdIn)
restoreInherit(stdOut)
restoreInherit(stdErr)
if (created === 0) {
const win32Code = api.getLastError()
api.closeHandle(job)
throwWin32(api, 'CreateProcessAsUserW', win32Code, `command: ${options.command}, cwd: ${options.cwd}`)
}
const info = decodeProcessInfo(processInfo)
const processHandle = info.hProcess
const threadHandle = info.hThread
if (processHandle === null || threadHandle === null) {
api.closeHandle(job)
throw new Error(`CreateProcessAsUserW succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
}
if (api.assignProcessToJobObject(job, processHandle) === 0) {
// The child was created suspended and is NOT in the kill-on-close job:
// closing handles would leave it suspended forever. Terminate it first,
// then drop the handles and throw.
const win32Code = api.getLastError()
api.terminateProcess(processHandle, 1)
api.closeHandle(threadHandle)
api.closeHandle(processHandle)
api.closeHandle(job)
throwWin32(api, 'AssignProcessToJobObject', win32Code, `pid ${info.dwProcessId}`)
}
if (api.resumeThread(threadHandle) === 0xFFFFFFFF) {
// Closing the job triggers kill-on-close, so the suspended child dies
// instead of hanging until this process exits; the process/thread handles
// must go too.
const win32Code = api.getLastError()
api.closeHandle(threadHandle)
api.closeHandle(processHandle)
api.closeHandle(job)
throwWin32(api, 'ResumeThread', win32Code, `pid ${info.dwProcessId}`)
}
api.closeHandle(threadHandle)
return { pid: info.dwProcessId, process: processHandle, job }
}

View File

@@ -0,0 +1,220 @@
/**
* Restricted-token construction: open the current process token, extract its
* logon SID, build the well-known SIDs, and call CreateRestrictedToken with
* the POC's restricting-SID allowlist. Every API call is checked; any failure
* throws with the API name and the exact Win32 code — the original POC ignored
* all of these and silently ran children with the FULL, unrestricted token.
* @module @deepseek-ai/dsh-sandbox-windows-acl/token
*/
import { allocBytes, allocPtrSlot, allocUint32, decodePtr, decodePtrAt, decodeUint32, encodeUint32, isNullPtr, ptrAddress, throwLastError, throwWin32 } from './ffi.ts'
import type { NativePtr, Win32Bindings } from './ffi.ts'
import { buildExplicitAccess } from './acl.ts'
import * as abi from './win32-abi.ts'
/**
* Open the current process's access token with the rights
* CreateRestrictedToken requires (the POC's OpenProcessToken call; the token
* handle is obtained through a real OpenProcess handle because the
* GetCurrentProcess() pseudo-handle is not addressable through koffi).
* @param api - the binding table.
* @returns the opened token handle.
*/
export function openCurrentProcessToken(api: Win32Bindings): NativePtr {
const processHandle = api.openProcess(abi.PROCESS_QUERY_INFORMATION, 0, process.pid)
if (isNullPtr(processHandle)) throwLastError(api, 'OpenProcess', `pid ${process.pid}`)
const tokenSlot = allocPtrSlot()
const opened = api.openProcessToken(
processHandle,
abi.TOKEN_QUERY | abi.TOKEN_DUPLICATE | abi.TOKEN_ADJUST_DEFAULT | abi.TOKEN_ASSIGN_PRIMARY,
tokenSlot,
)
if (opened === 0) {
const win32Code = api.getLastError()
api.closeHandle(processHandle) // best-effort on the error path
throwWin32(api, 'OpenProcessToken', win32Code, `pid ${process.pid}`)
}
if (api.closeHandle(processHandle) === 0) throwLastError(api, 'CloseHandle', 'OpenProcess process handle')
const token = decodePtr(tokenSlot)
if (token === null) throwWin32(api, 'OpenProcessToken', api.getLastError(), 'null token handle')
return token
}
/**
* Find and copy the token's logon session SID (S-1-5-5-x-y, attribute
* SE_GROUP_LOGON_ID). The restricted token needs it for WinSta0/desktop and
* other per-logon objects; the POC extracts it the same way.
* @param api - the binding table.
* @param token - the token whose groups are scanned.
* @returns a copied logon SID (thrown when the token carries none).
*/
export function findLogonSid(api: Win32Bindings, token: NativePtr): NativePtr {
const neededSlot = allocUint32()
api.getTokenInformation(token, abi.TokenGroups, null, 0, neededSlot) // expected to fail with ERROR_INSUFFICIENT_BUFFER
const needed = decodeUint32(neededSlot)
if (needed === 0) throwLastError(api, 'GetTokenInformation', 'TokenGroups size query')
if (needed < abi.TOKEN_GROUPS_OFFSET) throwWin32(api, 'GetTokenInformation', api.getLastError(), `implausible TokenGroups size ${needed}`)
const groups = Buffer.alloc(needed)
if (api.getTokenInformation(token, abi.TokenGroups, groups, groups.length, neededSlot) === 0) {
throwLastError(api, 'GetTokenInformation', 'TokenGroups')
}
const groupCount = groups.readUInt32LE(0)
for (let index = 0; index < groupCount; index++) {
const sidPtr = decodePtrAt(groups, abi.TOKEN_GROUPS_OFFSET + index * abi.SID_AND_ATTRIBUTES_SIZE)
const attributes = groups.readUInt32LE(abi.TOKEN_GROUPS_OFFSET + index * abi.SID_AND_ATTRIBUTES_SIZE + 8)
// >>> 0: JS bitwise & is signed 32-bit; SE_GROUP_LOGON_ID has bit 31 set.
const isLogonId = ((attributes & abi.SE_GROUP_LOGON_ID) >>> 0) === (abi.SE_GROUP_LOGON_ID >>> 0)
if (sidPtr === null || !isLogonId) continue
const sidLength = api.getLengthSid(sidPtr)
if (sidLength === 0) throwLastError(api, 'GetLengthSid', `logon SID group ${index}`)
const copy = allocBytes(sidLength)
if (api.copySid(sidLength, copy, sidPtr) === 0) throwLastError(api, 'CopySid', `logon SID group ${index}`)
return copy
}
throw new Error(`CreateRestrictedToken prerequisite failed: no logon SID found among ${groupCount} token groups`)
}
/**
* Create one well-known SID (68-byte buffer) and assert its validity.
* @param api - the binding table.
* @param type - the WELL_KNOWN_SID_TYPE to create.
* @returns the created SID pointer.
*/
export function makeWellKnownSid(api: Win32Bindings, type: number): NativePtr {
const sid = allocBytes(abi.SECURITY_MAX_SID_SIZE)
const sizeSlot = allocUint32()
encodeUint32(sizeSlot, abi.SECURITY_MAX_SID_SIZE)
if (api.createWellKnownSid(type, null, sid, sizeSlot) === 0) {
throwLastError(api, 'CreateWellKnownSid', `type ${type}`)
}
if (api.isValidSid(sid) === 0) throwLastError(api, 'IsValidSid', `CreateWellKnownSid type ${type}`)
return sid
}
/**
* Merge one full-access allow ACE for `sidPtr` into the token's DEFAULT DACL
* — the DACL every NEW object the token holder creates (without an explicit
* security descriptor) takes. The restricted token inherits the user's
* default DACL verbatim, which names no restricting SID: a new anonymous pipe
* (child stdio) therefore fails the write pass-2 check at creation
* (ERROR_ACCESS_DENIED; Node surfaces it as spawn EPERM), breaking every
* piped-stdio grandchild spawn. The merged ACE names a RESTRICTING SID (the
* write SID under workspace-write, Everyone under read-only), so each new
* object's own DACL passes pass-2 while object creation itself stays gated by
* the parent container's DACL (files outside the granted trees remain
* uncreatable). Fails closed: any Win32 failure throws before the spawn.
* @param api - the binding table.
* @param token - the restricted token to adjust (requires TOKEN_ADJUST_DEFAULT).
* @param sidPtr - the restricting SID whose full-access ACE joins the default DACL.
*/
export function setTokenDefaultDaclGrant(api: Win32Bindings, token: NativePtr, sidPtr: NativePtr): void {
const neededSlot = allocUint32()
api.getTokenInformation(token, abi.TokenDefaultDacl, null, 0, neededSlot) // expected to fail with ERROR_INSUFFICIENT_BUFFER
const needed = decodeUint32(neededSlot)
if (needed === 0) throwLastError(api, 'GetTokenInformation', 'TokenDefaultDacl size query')
const buffer = Buffer.alloc(needed)
if (api.getTokenInformation(token, abi.TokenDefaultDacl, buffer, buffer.length, neededSlot) === 0) {
throwLastError(api, 'GetTokenInformation', 'TokenDefaultDacl')
}
const currentDacl = decodePtrAt(buffer, 0)
if (currentDacl === null) {
throw new Error('setTokenDefaultDaclGrant: the token carries no default DACL to extend')
}
const newDaclSlot = allocPtrSlot()
const result = api.setEntriesInAclW(
1,
buildExplicitAccess(sidPtr, abi.GRANT_ACCESS, abi.FILE_ALL_ACCESS),
currentDacl,
newDaclSlot,
)
if (result !== abi.ERROR_SUCCESS) throwWin32(api, 'SetEntriesInAclW', result, 'default DACL merge')
const newDacl = decodePtr(newDaclSlot)
if (newDacl === null) throwWin32(api, 'SetEntriesInAclW', result, 'null merged default DACL')
// TOKEN_DEFAULT_DACL { PACL DefaultDacl; } — the struct is exactly the
// pointer; SetTokenInformation copies the ACL before returning.
const info = Buffer.alloc(8)
info.writeBigUInt64LE(newDacl, 0)
if (api.setTokenInformation(token, abi.TokenDefaultDacl, info, info.length) === 0) {
const win32Code = api.getLastError()
api.localFree(newDacl)
throwWin32(api, 'SetTokenInformation', win32Code, 'TokenDefaultDacl')
}
api.localFree(newDacl)
}
/** Pack `SID_AND_ATTRIBUTES[count]` (16-byte stride; Attributes stay 0). */
function buildRestrictingSids(sids: readonly NativePtr[]): Buffer {
const buffer = Buffer.alloc(abi.SID_AND_ATTRIBUTES_SIZE * sids.length)
sids.forEach((sid, index) => {
buffer.writeBigUInt64LE(ptrAddress(sid), abi.SID_AND_ATTRIBUTES_SIZE * index)
})
return buffer
}
/** The well-known SID packed into every restricted token's restricting list. */
export interface RestrictingSidSet {
world: NativePtr
}
/**
* Create the write-restricted token with the mode-selected restricting list
* (verified on Win11 26200, see the POC-worktree restrict-variant harness):
* - read-only: [logon SID, EVERYONE]
* - workspace-write: [logon SID, EVERYONE, orphan]
*
* The logon SID + EVERYONE keep-alive group is shared by both modes: early
* DLL init dies with 0xC0000142 and CNG (`\Device\CNG` write trustee —
* pwsh crashes 0xE0434352) fails without them. The write SID joins ONLY
* workspace-write — read-only carries no write SID, so a standing grant ACE
* from an earlier workspace-write period (a `/permission` mode downgrade, or
* a crash-resumed session) stays INERT under read-only: the WRITE_RESTRICTED
* pass-2 check grants only what the restricting list carries, keeping
* read-only strictly zero-grant even with stale ACEs standing, while the
* unrevoked ACE keeps the re-upgrade free (the grant's exact-ACE skip — no
* re-propagation). Authenticated Users is absent from BOTH lists: the WMI
* namespace security check fails (0x80041003), so CIM is unavailable in
* every confined mode, and the C:\-root tree-creation escape (standing
* `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both — documented in
* README. INTERACTIVE/LOCAL are absent from BOTH lists too — the host's
* Public tree grants write to INTERACTIVE, so removing it closes that
* escape. S-1-2-1 (console logon) is intentionally absent: see win32-abi.ts
* for the verified failure modes. FAILS CLOSED: any failure throws — never
* spawn unrestricted.
* @param api - the binding table.
* @param currentToken - the process token to restrict.
* @param logonSid - the copied logon session SID.
* @param writeSid - the write SID forming the write allowlist (workspace-write only; absent under read-only).
* @param known - the well-known SIDs entering the restricting list.
* @param mode - selects the restricting list (workspace-write adds the write SID).
* @returns the restricted token handle.
*/
export function createRestrictedToken(
api: Win32Bindings,
currentToken: NativePtr,
logonSid: NativePtr,
writeSid: NativePtr | undefined,
known: RestrictingSidSet,
mode: 'read-only' | 'workspace-write',
): NativePtr {
const restrictingSids = buildRestrictingSids(mode === 'read-only'
? [logonSid, known.world]
: writeSid === undefined
? (() => { throw new Error('createRestrictedToken: workspace-write restricting list requires the write SID') })()
: [logonSid, known.world, writeSid])
const tokenSlot = allocPtrSlot()
const created = api.createRestrictedToken(
currentToken,
abi.DISABLE_MAX_PRIVILEGE | abi.LUA_TOKEN | abi.WRITE_RESTRICTED,
0, null, // no SIDs disabled
0, null, // no privileges deleted
restrictingSids.length / abi.SID_AND_ATTRIBUTES_SIZE,
restrictingSids,
tokenSlot,
)
if (created === 0) throwLastError(api, 'CreateRestrictedToken', `restricting SIDs: ${restrictingSids.length / abi.SID_AND_ATTRIBUTES_SIZE}`)
const token = decodePtr(tokenSlot)
if (token === null) throwWin32(api, 'CreateRestrictedToken', api.getLastError(), 'null token handle')
return token
}

View File

@@ -0,0 +1,258 @@
/**
* Windows ABI constants for the ACL-sandbox backend.
*
* Every value was verified against the actual MinGW Windows headers on this
* machine (C:\Strawberry\c\x86_64-w64-mingw32\include\) and cross-checked at
* runtime by verify/abi-probe.cpp (same numbers; static_asserts passed).
* Regenerate the probe with:
* g++ -std=c++20 -municode -O2 -o abi-probe.exe abi-probe.cpp -ladvapi32 && .\abi-probe.exe
*
* The port intentionally excludes two pieces of the original POC
* (github.com/huoyaoyuan/windows-acl-restrict-poc @ 10e4dfb), both verified
* empirically on Windows 11 build 26200:
* - S-1-2-1 (console logon SID) in the restricting list: the POC created it
* via CreateWellKnownSid(WinLocalLogonSid) which fails here with
* ERROR_INVALID_PARAMETER (87), leaving a garbage SID that makes
* CreateRestrictedToken fail with ERROR_INVALID_SID (1337); using the
* correct WinConsoleLogonSid does produce a valid S-1-2-1, but the child
* then still dies with STATUS_DLL_INIT_FAILED (0xC0000142) whenever
* CREATE_NO_WINDOW / CREATE_NEW_CONSOLE is used.
* - Console isolation: under this restriction scheme a hidden console is not
* attainable, so children share the host console (stdio redirection is
* pipe-based and unaffected).
* @module @deepseek-ai/dsh-sandbox-windows-acl/win32-abi
*/
// ---- winnt.h ---------------------------------------------------------------
// TOKEN_* access rights (winnt.h lines ~3928)
/** TOKEN_ASSIGN_PRIMARY: required to create a process with the token (CreateProcessAsUser). */
export const TOKEN_ASSIGN_PRIMARY = 0x0001
/** TOKEN_DUPLICATE: required to duplicate a token (DuplicateTokenEx). */
export const TOKEN_DUPLICATE = 0x0002
/** TOKEN_QUERY: required to read token information (GetTokenInformation). */
export const TOKEN_QUERY = 0x0008
/** TOKEN_ADJUST_DEFAULT: required to change a token's default DACL. */
export const TOKEN_ADJUST_DEFAULT = 0x0080
// SID_AND_ATTRIBUTES.Attributes flags (winnt.h lines ~3446)
/**
* SE_GROUP_LOGON_ID: marks a token group SID as the logon SID (compared with
* `>>> 0` — the flag's high bit makes it negative as a signed 32-bit number).
*/
export const SE_GROUP_LOGON_ID = 0xC0000000
// Generic file access (winnt.h lines ~5893-5913):
// FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES
// | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE
/** STANDARD_RIGHTS_WRITE (== READ_CONTROL): the standard-rights component of generic write access. */
export const STANDARD_RIGHTS_WRITE = 0x00020000 // == READ_CONTROL
/** FILE_GENERIC_WRITE: every file-write permission bit plus SYNCHRONIZE. */
export const FILE_GENERIC_WRITE = 0x00120116
/** DELETE: remove or rename the object (winnt.h line ~3009). */
export const DELETE = 0x00010000
/** FILE_DELETE_CHILD: remove or rename a directory's children (winnt.h line ~5907). */
export const FILE_DELETE_CHILD = 0x0040
// The POC granted FILE_GENERIC_WRITE minus READ_CONTROL, which displays as
// "Write" in Explorer/icacls (windows-acl-restrict-poc.cpp line 16). The
// sandbox grant adds DELETE and FILE_DELETE_CHILD so confined
// delete/rename/git operations inside the granted trees pass the token's
// access check too; Write+DELETE displays as "Modify" in icacls.
// WRITE_DAC/WRITE_OWNER stay OUT deliberately — granting them would let the
// child take ownership or rewrite DACLs and escape the allowlist (the
// security boundary).
/**
* GRANT_MASK: FILE_GENERIC_WRITE minus READ_CONTROL plus DELETE and
* FILE_DELETE_CHILD — the write+delete access mask the orphan-SID ACEs grant
* (displays as "Modify" in Explorer/icacls). WRITE_DAC/WRITE_OWNER are
* deliberately excluded: they would let the confined child take ownership or
* rewrite DACLs.
*/
export const GRANT_MASK = (FILE_GENERIC_WRITE | DELETE | FILE_DELETE_CHILD) & ~STANDARD_RIGHTS_WRITE // 0x00110156
/**
* FILE_ALL_ACCESS (winnt.h line ~2789: STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE
* | 0x1FF): full file-object access. The mask of the ACE merged into the
* restricted token's DEFAULT DACL — the token holder must keep full access to
* every NEW object it creates (pipes included), and the ACE must name a
* restricting SID so the write pass-2 check passes at creation.
*/
export const FILE_ALL_ACCESS = 0x1F01FF
// CreateRestrictedToken flags (winnt.h lines ~4284)
/** DISABLE_MAX_PRIVILEGE: strip the token's maximum-privilege elevation so the confined child cannot escalate. */
export const DISABLE_MAX_PRIVILEGE = 0x1
/** LUA_TOKEN: produce a limited-user (filtered admin) token. */
export const LUA_TOKEN = 0x4
/** WRITE_RESTRICTED: intersect write access with the restricting SIDs' ACL grants — the sandbox's core mechanism. */
export const WRITE_RESTRICTED = 0x8
// WELL_KNOWN_SID_TYPE (winnt.h lines ~3369-3407)
/** WinWorldSid: S-1-1-0 (Everyone) — the only well-known SID the restricted tokens use (keep-alive group; see token.ts). */
export const WinWorldSid = 1
// TOKEN_INFORMATION_CLASS (winnt.h line ~3963: TokenUser=1, TokenGroups=2)
/** TokenGroups: GetTokenInformation class returning the token's group SIDs. */
export const TokenGroups = 2
/** TokenDefaultDacl: the token's default DACL — the DACL every NEW object created without an explicit SD takes. */
export const TokenDefaultDacl = 6
// SECURITY_INFORMATION (winnt.h line ~4293)
/** DACL_SECURITY_INFORMATION: read/write only the DACL of a security descriptor. */
export const DACL_SECURITY_INFORMATION = 0x00000004
// PROCESS access rights (winnt.h lines ~4364)
/** PROCESS_QUERY_INFORMATION: read exit status and times of a process handle. */
export const PROCESS_QUERY_INFORMATION = 0x0400
// ---- accctrl.h -------------------------------------------------------------
// SE_OBJECT_TYPE (accctrl.h line ~22: SE_UNKNOWN_OBJECT_TYPE=0, SE_FILE_OBJECT=1)
/** SE_FILE_OBJECT: the trustee path names a filesystem object. */
export const SE_FILE_OBJECT = 1
// TRUSTEE_FORM / TRUSTEE_TYPE (accctrl.h lines ~38-55): both enums start at 0
/** TRUSTEE_IS_UNKNOWN: TRUSTEE_TYPE unknown (TrusteeForm carries the shape). */
export const TRUSTEE_IS_UNKNOWN = 0
/** TRUSTEE_IS_SID: TRUSTEE_FORM — Trustee.ptstrName is a SID pointer. */
export const TRUSTEE_IS_SID = 0
/** NO_MULTIPLE_TRUSTEE: Trustee.pMultipleTrustee is null. */
export const NO_MULTIPLE_TRUSTEE = 0
// ACCESS_MODE (accctrl.h line ~127: NOT_USED_ACCESS=0, GRANT_ACCESS=1, REVOKE_ACCESS=4)
/** GRANT_ACCESS: SetEntriesInAclW adds the entry as an allow ACE. */
export const GRANT_ACCESS = 1
/** REVOKE_ACCESS: SetEntriesInAclW removes the matching allow ACE. */
export const REVOKE_ACCESS = 4
// grfInheritance (accctrl.h lines ~137-142)
/**
* SUB_CONTAINERS_AND_OBJECTS_INHERIT: the ACE applies to the directory, its
* subdirectories, and files (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE).
*/
export const SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3 // == OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
// ---- winbase.h -------------------------------------------------------------
/**
* STARTF_USESTDHANDLES: STARTUPINFOW dwFlags — the child uses the hStd*
* handles, required because Node clears stdio inheritability at startup.
*/
export const STARTF_USESTDHANDLES = 0x00000100
/** HANDLE_FLAG_INHERIT: SetHandleInformation flag re-enabling handle inheritance for the spawned child's stdio handles. */
export const HANDLE_FLAG_INHERIT = 0x1
/** INFINITE: never-timeout wait value. */
export const INFINITE = 0xFFFFFFFF
/** MAX_PATH: legacy path length bound. */
export const MAX_PATH = 260
// winbase.h line ~410: the confined child starts suspended so the runner can
// assign it to the kill-on-close job before any of its code runs.
/** CREATE_SUSPENDED: create the child with its primary thread suspended until ResumeThread. */
export const CREATE_SUSPENDED = 0x4
// winbase.h lines ~497-499: GetStdHandle selectors.
/** STD_INPUT_HANDLE: GetStdHandle selector for the standard input. */
export const STD_INPUT_HANDLE = -10
/** STD_OUTPUT_HANDLE: GetStdHandle selector for the standard output. */
export const STD_OUTPUT_HANDLE = -11
/** STD_ERROR_HANDLE: GetStdHandle selector for the standard error. */
export const STD_ERROR_HANDLE = -12
// FormatMessageW flags (winbase.h lines ~1446-1469)
/** FORMAT_MESSAGE_FROM_SYSTEM: format the message from the system message table. */
export const FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
/** FORMAT_MESSAGE_IGNORE_INSERTS: skip insert-sequence substitution. */
export const FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
// ---- error codes -----------------------------------------------------------
/** ERROR_SUCCESS: the operation succeeded. */
export const ERROR_SUCCESS = 0
/** ERROR_INSUFFICIENT_BUFFER: a size-probe call succeeded but needs a larger buffer. */
export const ERROR_INSUFFICIENT_BUFFER = 122
/** ERROR_BROKEN_PIPE: the pipe's other end has closed. */
export const ERROR_BROKEN_PIPE = 109
/** ERROR_NO_DATA: the pipe is being closed. */
export const ERROR_NO_DATA = 232
/** ERROR_LOCK_VIOLATION: a byte-range lock conflicts with an existing lock (winerror.h line ~78). */
export const ERROR_LOCK_VIOLATION = 33
// ---- lock files (fileapi.h / minwinbase.h / winnt.h) -----------------------
// CreateFileW dwDesiredAccess for the ACL lock files: plain read+write is
// enough to take byte-range locks.
/** GENERIC_READ: generic read access (winnt.h line ~3028). */
export const GENERIC_READ = 0x80000000
/** GENERIC_WRITE: generic write access (winnt.h line ~3029). */
export const GENERIC_WRITE = 0x40000000
// CreateFileW dwShareMode: the lock file is shared for read/write but NOT
// for delete — if a locked file could be deleted and recreated underneath the
// lock holder, two processes could hold "the same" lock on different files.
/** FILE_SHARE_READ: other opens may read (winnt.h line ~5949). */
export const FILE_SHARE_READ = 0x00000001
/** FILE_SHARE_WRITE: other opens may write (winnt.h line ~5950). */
export const FILE_SHARE_WRITE = 0x00000002
/** FILE_SHARE_DELETE: other opens may delete (winnt.h line ~5951) — deliberately NOT used for lock files. */
export const FILE_SHARE_DELETE = 0x00000004
/** OPEN_ALWAYS: create the lock file if absent, open it otherwise (fileapi.h line ~21). */
export const OPEN_ALWAYS = 4
// LockFileEx dwFlags (minwinbase.h lines ~180-181, included by winbase.h).
/** LOCKFILE_EXCLUSIVE_LOCK: request an exclusive byte-range lock. */
export const LOCKFILE_EXCLUSIVE_LOCK = 0x2
/** LOCKFILE_FAIL_IMMEDIATELY: fail with ERROR_LOCK_VIOLATION instead of waiting. */
export const LOCKFILE_FAIL_IMMEDIATELY = 0x1
// ACE_HEADER.AceType (winnt.h lines ~3449-3463)
/** ACCESS_ALLOWED_ACE_TYPE: an access-allowed ACE granting the mask to the trustee. */
export const ACCESS_ALLOWED_ACE_TYPE = 0
// SID structure (winnt.h line ~280 SID_IDENTIFIER_AUTHORITY; line ~286
// #define SID_MAX_SUB_AUTHORITIES 15).
/** SID_MAX_SUB_AUTHORITIES: the most subauthorities a SID may carry. */
export const SID_MAX_SUB_AUTHORITIES = 15
// ACE_HEADER.AceFlags (winnt.h lines ~3477-3524): inherited ACEs shown when
// reading a DACL are marked with this bit and are not part of the explicit
// DACL edits this module makes.
/** INHERITED_ACE: the ACE was inherited from the parent object, not stored explicitly. */
export const INHERITED_ACE = 0x10
// ---- job object (winnt.h lines ~4859-4866, ~5138, ~5190-5199) --------------
// JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: the child dies when the runner's last
// job handle closes — the orphan-child backstop for the runner design.
/** JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: the child dies when the runner's last job handle closes — the orphan-child backstop. */
export const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
// JOBOBJECTINFOCLASS: JobObjectBasicAccountingInformation=1, ..., ExtendedLimit=9.
/** JobObjectExtendedLimitInformation: JOBOBJECTINFOCLASS for the extended limit structure. */
export const JobObjectExtendedLimitInformation = 9
// sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION), verified by abi-probe.
/** sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION), verified by abi-probe. */
export const JOBOBJECT_EXTENDED_LIMIT_SIZE = 144
// LimitFlags offset inside JOBOBJECT_EXTENDED_LIMIT_INFORMATION
// (BasicLimitInformation@0 + PerProcessUserTimeLimit@0 + PerJobUserTimeLimit@8),
// verified by abi-probe.
/**
* LimitFlags offset inside JOBOBJECT_EXTENDED_LIMIT_INFORMATION
* (BasicLimitInformation@0 + PerProcessUserTimeLimit@0 +
* PerJobUserTimeLimit@8), verified by abi-probe.
*/
export const JOBOBJECT_EXTENDED_LIMIT_FLAGS_OFFSET = 16
// ---- ABI layout, verified by verify/abi-probe.cpp (x64) --------------------
/** SECURITY_MAX_SID_SIZE: maximum SID byte size. */
export const SECURITY_MAX_SID_SIZE = 68
/** SID_AND_ATTRIBUTES stride: { PSID Sid @0 (8); DWORD Attributes @8 (4) } + pad. */
export const SID_AND_ATTRIBUTES_SIZE = 16
/** TOKEN_GROUPS.Groups[] starts at offset 8 (GroupCount @0 + alignment). */
export const TOKEN_GROUPS_OFFSET = 8
/** sizeof(EXPLICIT_ACCESS_W): perms@0 mode@4 inheritance@8 Trustee@16. */
export const EXPLICIT_ACCESS_W_SIZE = 48
/** Trustee offset inside EXPLICIT_ACCESS_W. */
export const TRUSTEE_W_OFFSET = 16
/** ptstrName offset inside TRUSTEE_W (=> 40 inside EXPLICIT_ACCESS_W). */
export const TRUSTEE_W_PTSTRNAME_OFFSET = 24
/** sizeof(STARTUPINFOW), verified by abi-probe. */
export const STARTUPINFOW_SIZE = 104
/** sizeof(PROCESS_INFORMATION), verified by abi-probe. */
export const PROCESS_INFORMATION_SIZE = 24

Some files were not shown because too many files have changed in this diff Show More