Files
deepseek-harness/docs/subsystems/sandbox.md
T
LegGasai c9b9859b74 Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers
The lower branch removed `rootOf` and the `workspaceRoot` projection: a Session
has one directory, read through `ctx.workingDirectory.get`. This merge moves the
consumers of this branch to that read.

- sandbox-policy, workspace-files, and workspace-changes read `get`; the
  `recordedRootOf` read is removed. With the working-directory service mounted,
  a Session without a header directory is bounded by that service's default
  directory.
- The skill catalog, sidebar terminals, project instructions, `@` file
  candidates, the LSP workspace, and skill lookup return to the lower branch's
  code, which already reads the directory.
- The client helper exports `selectSessionDirectory` and `sessionDirectory`
  in place of the `{ root, cwd }` pair; `WorkspaceChangesSummary` keeps `cwd`,
  now the directory the turn started in.
- A stored `working-directory/change` inside the project moves the write
  boundary and file views with the directory; one outside returns to the project.
2026-11-16 22:33:13 +08:00

17 KiB

Process Sandbox

English | 中文

The process-sandbox seam of dsh-sandbox wraps a same-world subprocess argv in a file-effect policy without coupling consumers to a platform runner. dsh-sandbox-local supplies Linux bwrap/Landlock, macOS Seatbelt, and the Windows ACL restricted-token backend; dsh-bash-sandbox and dsh-pwsh-sandbox consume it. dsh-sandbox-ssh applies the same policy through a remote backend paired with the SSH filesystem and subprocess providers.

Source: packages/sandbox/sandbox/src/index.ts

Modes and enforcement

SandboxMode governs filesystem effects only. read-only asks the backend to deny writes — the POSIX runners additionally grant the /dev/null sink their shells require, while the Windows ACL runner grants no explicit writable root and reports partial enforcement for its ambient ACL gaps; workspace-write permits writes under the workspace root, extra directories where supported, and the backend's promised temp area; danger-full-access bypasses confinement. Windows subprocesses ignore extra directory grants; the harness file tools enforce them independently. Network and process visibility are outside this vocabulary.

/**
 * File-effect policy for confined processes. `read-only` permits only required
 * sinks such as `/dev/null`; `workspace-write` also permits the workspace,
 * explicit extra roots where supported, and backend-defined temp areas; `danger-full-access` bypasses confinement. Network
 * and process visibility are outside this vocabulary.
 */
type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access'

Only the first two modes can be sent to a provider. A danger-full-access consumer spawns its original argv and does not call ctx.sandbox.

/** A confining (non-`danger-full-access`) mode — the modes a {@link SandboxPolicy} can carry. */
type ConfinedSandboxMode = Exclude<SandboxMode, 'danger-full-access'>

Enforcement is a reported fact. full means the backend governs every file effect promised by the mode; partial means an active backend or older kernel ABI governs only a subset, so consumers that require the absolute promise must reject or surface that distinction. Older Landlock ABIs and the Windows ACL runner's hard-link, unconfined-read, and AppContainer-ACL boundaries are current partial cases.

/**
 * Enforcement completeness for this host. `partial` means an active backend or
 * older kernel ABI cannot govern every promised file effect; callers requiring
 * an absolute boundary must not treat it as `full`.
 */
type SandboxEnforcement = 'full' | 'partial'

Per-call policy

The complete execution policy is resolved and carried per capability call. It includes danger-full-access so a consumer can resolve policy once before deciding whether to bypass confinement. Normal tool calls derive workspaceRoot from the calling session's immutable cwd; deployment configuration supplies the agentless fallback and shared additional write grants. Live Session registrations add effect-scoped directories to subsequent resolutions. The resolver preserves absolute execution-world spelling. Enforcing providers canonicalize the root where the files exist, so a cwd containing symlink/.. identifies the directory where the paired subprocess provider actually runs.

/**
 * The complete file-effect policy resolved for one capability call. The root
 * is carried even under modes that do not consume it so callers can resolve
 * policy once before choosing the enforcement path.
 */
interface SandboxExecutionPolicy {
  /** The file-effect mode this execution runs under. */
  mode: SandboxMode
  /** Absolute root directory `workspace-write` may write under. */
  workspaceRoot: string
  /**
   * Extra physical absolute directories `workspace-write` may also write under.
   * Absence means none. The enforcing host rejects missing, non-directory, and
   * symlinked entries on each call. Remote paths are checked on the remote host.
   * Windows process confinement ignores these; harness filesystem operations honor them.
   * These grant nothing under `read-only` or `danger-full-access`.
   */
  additionalWritableRoots?: readonly string[]
  /**
   * Opaque identity of the calling session (the branded `dsh-session`
   * SessionId). Backends key per-session state off it (e.g. windows-acl gives
   * each live session/workspace pair a random private temp directory and SID,
   * while the workspace SID and standing grant remain per-workspace); absent
   * for agentless calls, which fall back to per-call backend state.
   */
  sessionId?: SessionId
}

ctx.sandboxPolicy.resolve() accepts the active session and, for an approved retry, an explicit mode. The service owns precedence and root fallback so bash and fs do not repeat it.

/** Inputs that select the sandbox policy for one capability call. */
interface SandboxPolicyRequest {
  /** Calling session; its workspace root becomes the workspace boundary. */
  session?: Session
  /** Explicit approved mode override, which outranks session policy. */
  mode?: SandboxMode
  /**
   * Checkout that bounds this call instead of the session's workspace root: Host maintenance of a
   * checkout the session does not work in, such as removing or restoring the session's worktree from
   * its source repository while the session's own root is that worktree. The session's mode and
   * registered grants still apply. Never reachable from model input.
   */
  root?: string
}

Only a confined execution reaches ctx.sandbox; its provider policy narrows the mode while retaining the same root. This permits concurrent sessions, consumers, and one-shot escalated retries to ask the same provider for different boundaries without mutating provider state.

/**
 * What one confined execution is allowed to touch — carried PER CALL, not
 * fixed on the provider: two consumers may confine under different policies
 * at the same instant (bash under `read-only` while a confined child agent
 * needs its state directory writable), and an approved escalated retry is a
 * new call with a wider policy. Defaulting/resolution is an explicit step at
 * the consumer boundary; the provider treats the policy as fully specified.
 */
interface SandboxPolicy extends SandboxExecutionPolicy {
  /** The file-effect mode this execution runs under. */
  mode: ConfinedSandboxMode
}

Wrapped argv and classification dialects

RunnerFailureRule combines evidence that a runner failed before executing the command. A consumer requires a nonzero exit, the optional allowed-exit-code gate, and a case-insensitive fatal signature within one remaining stderr line. Case-insensitive exact full-line informational exclusions are removed first, so a benign runner notice cannot prove failure by itself. The matched line remains available as error detail; classification does not rewrite stderr.

/**
 * Evidence that identifies a sandbox runner failing before it executes the
 * wrapped command. A consumer first applies {@link allowedExitCodes} when
 * present, removes {@link informationalLines} by case-insensitive exact line
 * equality, then matches {@link fatalSignatures} case-insensitively within
 * each remaining stderr line. Exit status alone never proves runner failure.
 */
interface RunnerFailureRule {
  /** Nonzero process exit codes on which this rule may match; omitted permits any nonzero exit. */
  allowedExitCodes?: readonly number[]
  /** Non-empty substrings identifying a fatal runner diagnostic on one stderr line. */
  fatalSignatures: readonly string[]
  /** Benign stderr lines excluded by exact full-line equality before fatal matching. */
  informationalLines?: readonly string[]
}

ConfinedArgv is what the consumer spawns. Besides the replacement argv, it carries the backend's enforcement fact and two orthogonal stderr classifiers. denialSignatures identify the confined command being blocked while the sandbox works correctly. runnerFailureRules identify the sandbox runner refusing or failing before it executes the command; consumers check these first and surface a sandbox infrastructure failure, never an ordinary task failure.

/**
 * A {@link SandboxProvider.confine} result: the argv to spawn in place of
 * the caller's own, plus the enforcement completeness the selected backend
 * achieves for it.
 */
interface ConfinedArgv {
  /** The wrapped argv (runner, profile, separator, then the caller's argv). */
  argv: string[]
  /** How completely the selected backend enforces the policy's file effects. */
  enforcement: SandboxEnforcement
  /**
   * The selected backend's denial DIALECT: the case-insensitive stderr
   * substrings a file effect denied by THIS backend produces (EROFS text
   * under bwrap's read-only binds, EACCES under Landlock, EPERM under
   * Seatbelt). A consumer that infers denials from a failed run's stderr
   * matches against exactly these rather than a cross-backend union — the
   * union claims denials a given backend never produces.
   */
  denialSignatures: readonly string[]
  /**
   * Structured runner-failure evidence rules. Consumers require a matching
   * fatal stderr line (after informational exclusions) and any rule-specific
   * exit-code gate before checking denial signatures: runner failure means the
   * command never ran, while denial means confinement worked and blocked it.
   */
  runnerFailureRules: readonly RunnerFailureRule[]
}

The local provider owns operator configuration and maps its runner dialect into these rules. The sandboxed bash consumer owns spawn and result attribution.

Provider and fail-closed errors

await ctx.sandbox.confine(argv, policy, signal) resolves policy paths and returns a ConfinedArgv from the execution world, or rejects with SandboxUnavailableError and code SANDBOX_UNAVAILABLE when no usable backend exists, or with SandboxPreparationError (SANDBOX_PREPARATION_FAILED, SANDBOX_INVALID_TEMP_ROOT) when the provider cannot prepare host state for the mode. The optional signal cancels resolution before launch. Consumers may also classify a failure while spawning or observing the returned argv; that attribution belongs to the consumer contract. Silent unconfined passthrough is never legal for a confined policy.

Provider selection, probing, caching, and backend-specific enforcement reports belong to the local provider.

Cordis API

Generated from source by scripts/gen-cordis-catalog.ts (verified fresh by pnpm run verify-cordis-catalog in doc-sync; regenerate with pnpm run gen-cordis-catalog) — the language sides differ only in locale-specific paired document paths. Signature blocks use a ts cordis-catalog fence and keep the original source JSDoc; dispatch modes are defined in the primer, and the framework-inherited ctx API lives in cordis-api/inherited.md.

ctx.sandbox — SandboxProvider (abstract seam)

Abstract process-sandbox service. confine must return enforcing argv or fail closed at wrap or runner-execution time; silent unconfined passthrough is forbidden. Functional probes arbitrate multi-runner chains and may be skipped for a sole candidate, whose own refusal remains the fail-closed end.

/**
 * Wrap `argv` so it executes confined under `policy` on this host; the
 * caller spawns the returned argv in place of its own.
 * @param argv - the exact argv the caller is about to spawn (program plus
 *   arguments), NOT a shell string — a shell-shaped consumer passes
 *   `['bash', '-c', command]`.
 * @param policy - the file-effect policy this execution runs under,
 *   carried per call (see {@link SandboxPolicy}).
 * @param signal - cancellation while the provider resolves the policy and runner.
 * @returns the argv to spawn instead, plus the enforcement completeness
 *   the selected backend achieves for it.
 */
abstract confine(argv: readonly string[], policy: SandboxPolicy, signal?: AbortSignal): Promise<ConfinedArgv>

Source: packages/sandbox/sandbox/src/index.ts

ctx.sandboxPolicy — SandboxPolicyService

The sandbox-policy service (ctx.sandboxPolicy). Owns the deployment default mode, fallback workspace root, session-scoped directory grants, and request-time policy section. Tool layers call resolve for each execution so a session's mode log and workspace root travel together to every enforcing capability.

A session's workspace root comes from the working-directory service when it is mounted: the checkout the Session works in, which a worktree relocation moves. A linked checkout keeps its Git administration directory and the repository's common directory outside that root; prepare derives them through the execution-world filesystem once per root, and resolve adds the derived directories to additionalWritableRoots. Tool executions await that derivation in tools/pre-execute; Session creation and every directory change start it early.

/**
 * Resolve the complete policy for one capability call. An approved explicit
 * mode outranks the session's last `sandbox/mode` event, which outranks the
 * deployment default. A session's workspace root is its workspace-write
 * boundary, and the Git administration directories {@link prepare} derived
 * for that root join the configured extra writable directories; the
 * configured root is the fallback for agentless calls and, without the
 * working-directory service, sessions without a header directory, and a
 * requested `root` replaces the session's root for the call. Configured extra
 * roots, this Session's active registrations, and the derived Git directories
 * are snapshotted together; existing operations and processes keep their
 * policy.
 * @param request - optional session, approved mode override, and root override.
 * @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories.
 * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the selected root is relative or
 *   contains a NUL byte.
 */
resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy

/**
 * Permit writes under one directory in this Session's future workspace-write
 * operations. The calling context owns the effect; disposal removes only this
 * registration. Other grants to the directory remain effective. Existing
 * operations and persistent processes retain their resolved permissions.
 * Grants are runtime-only and must be registered again after resume or fork.
 * On Windows, only harness file tools honor extra grants; process permissions stay unchanged.
 * @param session - exact live Session receiving the grant; other Sessions and agentless calls are unaffected.
 * @param directory - absolute execution-world path; execution rejects missing, non-directory, or symlinked paths.
 * @returns the exact Cordis effect disposer for this registration.
 * @throws when the directory is relative or contains a NUL byte.
 */
registerWritableRoot(session: Session, directory: string): () => void

/**
 * Read the session override without applying the deployment default.
 * @param session - session whose log supplies the override.
 * @returns the last logged mode, or `undefined` without one.
 */
overrideOf(session: Session): SandboxMode | undefined

/**
 * Derive the Git administration directories of the session's workspace root
 * so the next {@link resolve} grants them: a linked checkout's `.git` file
 * names `<common>/worktrees/<name>`, whose `commondir` names the repository's
 * common directory and whose `gitdir` names the checkout's `.git` again; only
 * that layout grants the common directory, since the checkout's own `.git`
 * pointer is writable under workspace-write. Any other layout, a root without
 * `.git`, and a common directory containing the root add nothing. One
 * derivation runs per root and its result is kept once the layout was read,
 * so a pointer written later does not widen the policy until a Host operation
 * moves a Session's workspace to that root again; a derived directory that disappears is
 * derived again, and a failed read is logged once per root and retried on
 * the next call.
 * @param request - session whose workspace root is inspected, or the root {@link resolve} would select
 * for the same request.
 * @param signal - caller cancellation, checked before and after the shared derivation.
 * @returns the derived directories outside the root, canonical in the execution world.
 */
async prepare(request: Pick<SandboxPolicyRequest, 'session' | 'root'>, signal?: AbortSignal): Promise<readonly string[]>

Types: Session

Source: packages/sandbox/sandbox-policy/src/index.ts