@deepseek-ai/dsh-sandbox-local 0.2.2-rc.1 → 0.2.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -27,8 +27,8 @@
27
27
  en: 7282c9ec77fd6f01
28
28
  zh: 10e385a9489105e3
29
29
  /deepseek-ai-dsh-sandbox-local/use-this-package/failures-and-recovery:
30
- en: 9b648f1bfdd55e76
31
- zh: d9265bdf2e272581
30
+ en: 3859a87c6122a1bf
31
+ zh: 55d7be15527f0347
32
32
  /deepseek-ai-dsh-sandbox-local/understand-the-implementation:
33
33
  en: 15db6ec303151ccc
34
34
  zh: 91f62c1f64192f92
@@ -54,8 +54,8 @@
54
54
  en: e290ccc9b3c92c08
55
55
  zh: 469589ac12cdadab
56
56
  /deepseek-ai-dsh-sandbox-local/known-limitations-and-deferred-work:
57
- en: 7cd5c6a4cc971803
58
- zh: 4e4f495b654d95c5
57
+ en: 08b89c59db310961
58
+ zh: b505db4148754f94
59
59
  /deepseek-ai-dsh-sandbox-local/known-limitations-and-deferred-work/dev-note:
60
60
  en: cc273320f6a1beaf
61
61
  zh: 5c57a312ddc50651
package/README.md CHANGED
@@ -56,7 +56,7 @@ With the provider mounted, a command runs under the mode you resolve per call. E
56
56
 
57
57
  An unsupported platform or an unusable runner fails closed: `confine()` rejects with `SANDBOX_UNAVAILABLE` and names the runner options for the platform, and the consumer surfaces that error rather than running the command unconfined. A runner that starts but refuses its profile is identified by its fatal stderr signature and exit code, so a broken sandbox is not mistaken for a denied command. The `runnerCommand` override is an operator assertion: it skips functional probes and assumes the configured runner implements the bwrap-compatible profile honestly.
58
58
 
59
- Seatbelt, bwrap, and Landlock include the policy's explicit `additionalWritableRoots` under `workspace-write`. Read-only ignores those grants. Invalid extra directories raise `SANDBOX_INVALID_ROOT` before the command starts.
59
+ Seatbelt, bwrap, and Landlock include the policy's explicit `additionalWritableRoots` under `workspace-write`. Read-only ignores those grants. Missing paths, non-directories, symlinked directories, and other inspection failures raise `SANDBOX_INVALID_ROOT` before the command starts. The Windows ACL backend does not inspect these extra roots and keeps workspace and private-temp access only. Its per-session preparation rejects with `SandboxPreparationError` before the command starts: `SANDBOX_INVALID_TEMP_ROOT` when the host temp root lies inside the workspace, and `SANDBOX_PREPARATION_FAILED` when a SID, ACL grant, or private temp directory cannot be created, with the `Win32Error` or Node error as `cause` and partial grants rolled back.
60
60
 
61
61
  -----
62
62
 
@@ -130,7 +130,7 @@ No direct invalidation; the named consumers own any request-prefix changes.
130
130
 
131
131
  These limits define when the provider is a poor fit or needs special operational care. They are current package constraints, not a general platform comparison or a task backlog.
132
132
 
133
- - **Windows extra roots** — Windows ACL rejects every workspace-write subprocess carrying extra directories with `SANDBOX_UNSUPPORTED_POLICY`, before grants or child creation. Filesystem tools can enforce these grants independently. Remove the extra grants or use a supported host for process operations.
133
+ - **Windows extra roots** — Additional directory grants apply to the harness `write` and `edit` tools only. PowerShell, terminals, PTC, and other sandboxed processes retain workspace and private-temp access under `workspace-write`. Extra grants do not change their ACLs or block their execution; see the [decision](../../../.agents/notes/implemented/architecture/2026-10-29-windows-file-tool-directory-grants.md).
134
134
  - **Windows ACL enforcement is partial** — NTFS hard links alias one file object across workspace and external paths, reads stay unconfined, and a tree another AppContainer tool has ACL'd with a package SID is unreadable to the Low-integrity child. The provider reports `enforcement: 'partial'` rather than overstating that boundary as full.
135
135
  - **Landlock may be partial** — older supported kernel ABIs confine only the access classes they expose, reported as `enforcement: 'partial'` rather than overstated as full.
136
136
  - **Seatbelt depends on deprecated `sandbox-exec`** — macOS still ships it, but this provider cannot replace or probe that private policy engine if Apple removes it.
package/README.zh.md CHANGED
@@ -56,7 +56,7 @@ kind: "package-reference"
56
56
 
57
57
  不受支持的平台或不可用的 runner 会拒绝执行:`confine()` 以 `SANDBOX_UNAVAILABLE` 拒绝 并列出该平台的 runner 选项,消费方会呈现该错误,而不是让命令不受限制地运行。启动后拒绝自身 profile 的 runner 由其致命 stderr 签名与退出码识别,因此损坏的沙箱不会被误认为被拒绝的命令。`runnerCommand` 覆盖是操作方断言:它跳过功能探测,并假定配置的 runner 诚实实现与 bwrap 兼容的 profile。
58
58
 
59
- Seatbelt、bwrap 和 Landlock 在 `workspace-write` 下包含策略显式指定的 `additionalWritableRoots`。只读模式忽略这些授权。无效的额外目录会在命令启动前触发 `SANDBOX_INVALID_ROOT`。
59
+ Seatbelt、bwrap 和 Landlock 在 `workspace-write` 下包含策略显式指定的 `additionalWritableRoots`。只读模式忽略这些授权。不存在的路径、非目录、符号链接目录和其他检查失败会在命令启动前触发 `SANDBOX_INVALID_ROOT`。Windows ACL 后端不检查这些额外根目录,仅保留工作区与私有临时目录访问权限。其按 session 的准备阶段会在命令启动前以 `SandboxPreparationError` 拒绝:主机临时根目录位于工作区内时为 `SANDBOX_INVALID_TEMP_ROOT`;无法创建 SID、ACL 授权或私有临时目录时为 `SANDBOX_PREPARATION_FAILED`,以 `Win32Error` 或 Node 错误作为 `cause`,并回滚已创建的部分授权。
60
60
 
61
61
  -----
62
62
 
@@ -130,7 +130,7 @@ Windows 档为每个工作区保留一个确定性写入 SID 和常驻 ACE,同
130
130
 
131
131
  这些限制说明提供方何时不合适,或何时需要特别运维。它们是当前包约束,不是通用平台对比或任务积压。
132
132
 
133
- - **Windows 额外根目录**——Windows ACL 在授权或创建子进程前,以 `SANDBOX_UNSUPPORTED_POLICY` 拒绝所有携带额外目录的 workspace-write 子进程。文件系统工具可独立执行这些授权。运行进程操作前,请移除额外授权或使用支持此功能的主机。
133
+ - **Windows 额外根目录**——额外目录授权仅适用于 Harness 的 `write` 与 `edit` 工具。PowerShell、终端、PTC 及其他受沙箱限制的进程在 `workspace-write` 下保留工作区与私有临时目录访问权限。额外授权不修改其 ACL,也不阻塞其执行;参见[决策](../../../.agents/notes/implemented/architecture/2026-10-29-windows-file-tool-directory-grants.zh.md)。
134
134
  - **Windows ACL 只能实现部分强制执行**——NTFS 硬链接会使工作区路径与外部路径指向同一个文件对象,读取仍不受限,且被其他 AppContainer 工具以包 SID 标记过的目录树对 Low 完整性子进程不可读。提供方报告 `enforcement: 'partial'`,而不会把该边界夸大为完整强制执行。
135
135
  - **Landlock 可能只实现部分强制执行**——较旧且受支持的内核 ABI 只能限制自身公开的访问类别,因此报告 `enforcement: 'partial'`,不会夸大为完整强制执行。
136
136
  - **Seatbelt 依赖已弃用的 `sandbox-exec`**——macOS 仍会提供它,但若 Apple 移除该私有策略引擎,该提供方无法替换或探测。
package/lib/index.js CHANGED
@@ -5,8 +5,8 @@ import { join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { LAUNCHER_BIN, LAUNCHER_FAILURE_EXIT, grantArgs, launcherPath, probe } from "@deepseek-ai/node-addon-system/landlock-run";
7
7
  import z from "@deepseek-ai/schemastery";
8
- import { SandboxProvider, SandboxUnavailableError, SandboxUnsupportedPolicyError, canonicalPath, workspaceWritableRoots, writableRoots } from "@deepseek-ai/dsh-sandbox";
9
- import { AclWriteGrant, assertTempRootOutsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from "@deepseek-ai/dsh-sandbox-windows-acl";
8
+ import { SandboxPreparationError, SandboxProvider, SandboxUnavailableError, canonicalPath, workspaceWritableRoots, writableRoots } from "@deepseek-ai/dsh-sandbox";
9
+ import { AclWriteGrant, isTempRootInsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from "@deepseek-ai/dsh-sandbox-windows-acl";
10
10
  import { assertNever } from "@deepseek-ai/dsh-util-values";
11
11
  //#region lib/types/profiles.js
12
12
  /**
@@ -99,6 +99,18 @@ function seatbeltProfileArgs(policy) {
99
99
  * readable by the Low-integrity child.
100
100
  * @module @deepseek-ai/dsh-sandbox-local
101
101
  */
102
+ /**
103
+ * Classify one failed Windows ACL preparation step; the platform failure, or an
104
+ * `AggregateError` of it and its cleanup failures, becomes the `cause`.
105
+ * @param step - the preparation step, as the message names it.
106
+ * @param error - the step's own failure, typically a `Win32Error` or Node errno error.
107
+ * @param cleanupFailures - rollback failures that followed it.
108
+ * @returns the coded preparation failure.
109
+ */
110
+ function aclPreparationFailure(step, error, cleanupFailures = []) {
111
+ const failed = cleanupFailures.length === 0 ? `${step} failed` : `${step} failed and its cleanup also failed`;
112
+ return new SandboxPreparationError(`sandbox-local: windows-acl ${failed}: ${String(error)}. The command did not run; check that the current user can change permissions on the workspace and temp directories, or run with danger-full-access.`, "SANDBOX_PREPARATION_FAILED", { cause: cleanupFailures.length === 0 ? error : new AggregateError([error, ...cleanupFailures], `sandbox-local windows-acl ${failed}`) });
113
+ }
102
114
  /** Probe whether `bwrap` can create the profile; the provider caches the bounded result. */
103
115
  function defaultProbeBwrap(timeoutMs) {
104
116
  return spawnSync("bwrap", [
@@ -353,11 +365,12 @@ var LocalSandboxProvider = class extends SandboxProvider {
353
365
  * `--temp-write-sid` and grants nothing itself. Agentless workspace-write
354
366
  * calls pass the ambient temp ROOT and no SID flags: the runner creates and
355
367
  * removes a random private child directory for that one invocation.
368
+ * Additional directory grants apply only to harness filesystem operations
369
+ * on Windows; process confinement keeps the workspace and private temp grants.
356
370
  * @param policy - the resolved per-call policy.
357
371
  * @returns the runner invocation.
358
372
  */
359
373
  windowsAclRunnerArgv(policy) {
360
- if (policy.mode === "workspace-write" && (policy.additionalWritableRoots?.length ?? 0) > 0) throw new SandboxUnsupportedPolicyError("Windows ACL confinement does not support additional writable directories; remove the extra grants or use a supported host");
361
374
  const sessionId = policy.sessionId;
362
375
  if (sessionId === void 0 || policy.mode === "read-only") return [
363
376
  ...this.windowsAclRunnerInvocation(),
@@ -391,32 +404,51 @@ var LocalSandboxProvider = class extends SandboxProvider {
391
404
  * SID to enter it. A fresh provider always chooses a new path; crash
392
405
  * residue therefore cannot collide with or authorize a resumed session.
393
406
  * Fail-closed: a half-materialized temp grant is revoked and its directory
394
- * removed before the error propagates.
407
+ * removed before the error propagates. A temp root inside the workspace
408
+ * throws `SandboxPreparationError` `SANDBOX_INVALID_TEMP_ROOT` before any ACL
409
+ * change; any other failure throws `SANDBOX_PREPARATION_FAILED` with the
410
+ * platform error as `cause`.
395
411
  * @param sessionId - the policy's calling-session identity.
396
412
  * @param workspaceRoot - the resolved policy root.
397
413
  * @returns the pair's private temp directory and write capability.
398
414
  */
399
415
  materializeAclGrant(sessionId, workspaceRoot) {
400
- assertTempRootOutsideWorkspace(workspaceRoot, tmpdir());
416
+ let tempInsideWorkspace;
417
+ try {
418
+ tempInsideWorkspace = isTempRootInsideWorkspace(workspaceRoot, tmpdir());
419
+ } catch (error) {
420
+ throw aclPreparationFailure("workspace and temp directory resolution", error);
421
+ }
422
+ if (tempInsideWorkspace) throw new SandboxPreparationError(`sandbox-local: windows-acl temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tmpdir()}. A private temp directory there would inherit the workspace grant, so the command did not run. Set TEMP and TMP to a directory outside the workspace, or open a workspace that does not contain the temp directory.`, "SANDBOX_INVALID_TEMP_ROOT");
401
423
  const writeSid = workspaceWriteSid(workspaceRoot);
402
424
  if (!this.workspaceGrants.has(workspaceRoot)) {
403
- const grant = AclWriteGrant.create(writeSid);
425
+ let grant;
426
+ try {
427
+ grant = AclWriteGrant.create(writeSid);
428
+ } catch (error) {
429
+ throw aclPreparationFailure("workspace grant", error);
430
+ }
404
431
  try {
405
432
  grant.add(workspaceRoot, true);
406
433
  } catch (error) {
407
434
  try {
408
435
  grant.dispose();
409
436
  } catch (cleanupError) {
410
- throw new AggregateError([error, cleanupError], "sandbox-local windows-acl workspace grant failed and its cleanup also failed");
437
+ throw aclPreparationFailure("workspace grant", error, [cleanupError]);
411
438
  }
412
- throw error;
439
+ throw aclPreparationFailure("workspace grant", error);
413
440
  }
414
441
  this.workspaceGrants.set(workspaceRoot, grant);
415
442
  }
416
443
  const key = JSON.stringify([String(sessionId), workspaceRoot]);
417
444
  const existing = this.tempCapabilities.get(key);
418
445
  if (existing !== void 0) return existing;
419
- const tempDir = mkdtempSync(join(tmpdir(), "dsh-"));
446
+ let tempDir;
447
+ try {
448
+ tempDir = mkdtempSync(join(tmpdir(), "dsh-"));
449
+ } catch (error) {
450
+ throw aclPreparationFailure("private temp directory creation", error);
451
+ }
420
452
  const tempSid = tempWriteSid(tempDir);
421
453
  let grant;
422
454
  try {
@@ -434,8 +466,7 @@ var LocalSandboxProvider = class extends SandboxProvider {
434
466
  } catch (cleanupError) {
435
467
  cleanupFailures.push(cleanupError);
436
468
  }
437
- if (cleanupFailures.length > 0) throw new AggregateError([error, ...cleanupFailures], "sandbox-local windows-acl temp grant materialization failed and its cleanup also failed");
438
- throw error;
469
+ throw aclPreparationFailure("temp grant materialization", error, cleanupFailures);
439
470
  }
440
471
  const capability = {
441
472
  dir: tempDir,
@@ -128,6 +128,8 @@ export declare class LocalSandboxProvider extends SandboxProvider {
128
128
  * `--temp-write-sid` and grants nothing itself. Agentless workspace-write
129
129
  * calls pass the ambient temp ROOT and no SID flags: the runner creates and
130
130
  * removes a random private child directory for that one invocation.
131
+ * Additional directory grants apply only to harness filesystem operations
132
+ * on Windows; process confinement keeps the workspace and private temp grants.
131
133
  * @param policy - the resolved per-call policy.
132
134
  * @returns the runner invocation.
133
135
  */
@@ -140,7 +142,10 @@ export declare class LocalSandboxProvider extends SandboxProvider {
140
142
  * SID to enter it. A fresh provider always chooses a new path; crash
141
143
  * residue therefore cannot collide with or authorize a resumed session.
142
144
  * Fail-closed: a half-materialized temp grant is revoked and its directory
143
- * removed before the error propagates.
145
+ * removed before the error propagates. A temp root inside the workspace
146
+ * throws `SandboxPreparationError` `SANDBOX_INVALID_TEMP_ROOT` before any ACL
147
+ * change; any other failure throws `SANDBOX_PREPARATION_FAILED` with the
148
+ * platform error as `cause`.
144
149
  * @param sessionId - the policy's calling-session identity.
145
150
  * @param workspaceRoot - the resolved policy root.
146
151
  * @returns the pair's private temp directory and write capability.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;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M,CAAC,GAAG,CAAA,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,CAAA,IAAI,CAAC,GAAG,CAAA;AACrF,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAqB;IACvD,MAAM,KAAK,GAAG,CAAC,aAAa,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,+BAA+B,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;IAClI,MAAM,KAAK,GAAG,aAAa,CAAC,MAAM,CAAC,CAAA;IACnC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrB,KAAK,CAAC,IAAI,CAAC,sBAAsB,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,YAAY,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IACnG,CAAC;IACD,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AAChC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-sandbox-local",
3
3
  "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",
4
- "version": "0.2.2-rc.1",
4
+ "version": "0.2.2-rc.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,25 +25,28 @@
25
25
  "files": [
26
26
  "locale/*.json",
27
27
  "lib/index.js",
28
- "lib/types/**/*.d.ts"
28
+ "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src"
29
32
  ],
30
33
  "license": "MIT",
31
34
  "peerDependencies": {
32
35
  "@deepseek-ai/cordis": "~4.1.0",
33
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
34
- "@deepseek-ai/dsh-sandbox": "0.2.2-rc.1",
35
- "@deepseek-ai/dsh-session": "0.2.2-rc.1"
36
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
37
+ "@deepseek-ai/dsh-sandbox": "0.2.2-rc.3",
38
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3"
36
39
  },
37
40
  "dependencies": {
38
- "@deepseek-ai/dsh-sandbox-windows-acl": "0.2.2-rc.1",
39
- "@deepseek-ai/dsh-util-values": "0.2.2-rc.1",
41
+ "@deepseek-ai/dsh-sandbox-windows-acl": "0.2.2-rc.3",
42
+ "@deepseek-ai/dsh-util-values": "0.2.2-rc.3",
40
43
  "@deepseek-ai/node-addon-system": "~0.1.2",
41
44
  "@deepseek-ai/schemastery": "~3.19.0"
42
45
  },
43
46
  "devDependencies": {
44
47
  "@deepseek-ai/cordis": "~4.1.0",
45
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
46
- "@deepseek-ai/dsh-sandbox": "0.2.2-rc.1",
47
- "@deepseek-ai/dsh-session": "0.2.2-rc.1"
48
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
49
+ "@deepseek-ai/dsh-sandbox": "0.2.2-rc.3",
50
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3"
48
51
  }
49
52
  }
package/src/index.ts ADDED
@@ -0,0 +1,626 @@
1
+ /**
2
+ * Local sandbox backend. It selects the platform runner chain (Linux bwrap then
3
+ * Landlock; macOS Seatbelt; Windows the ACL restricted-token runner), functionally probes
4
+ * competing candidates once, and reports each wrap's enforcement and stderr
5
+ * classification facts. Missing or unusable confinement fails closed rather
6
+ * than returning the original argv.
7
+ *
8
+ * The windows-acl rung additionally owns the write grants: the write SID is
9
+ * the per-WORKSPACE identity derived from the canonical workspace path
10
+ * (`workspaceWriteSid`), while every live session receives a RANDOM private
11
+ * temp directory and its own derived capability (`tempWriteSid`). The
12
+ * workspace-root ACE materializes once per workspace per server lifetime
13
+ * and STANDS (the cross-session reuse cache — the exact-ACE skip makes
14
+ * every later provision O(1) instead of re-propagating the tree per
15
+ * session); the private-temp ACEs are revoked on dispose. The runner
16
+ * receives both SIDs (their presence marks the seam-managed contract) and
17
+ * stops managing DACLs itself. The rung reports partial enforcement because
18
+ * NTFS hard links alias one file object across paths, reads stay unconfined,
19
+ * and a tree another AppContainer tool has ACL'd with a package SID is not
20
+ * readable by the Low-integrity child.
21
+ * @module @deepseek-ai/dsh-sandbox-local
22
+ */
23
+
24
+ import { spawnSync } from 'node:child_process'
25
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
26
+ import { tmpdir } from 'node:os'
27
+ import { join } from 'node:path'
28
+ import { fileURLToPath } from 'node:url'
29
+ import {
30
+ LAUNCHER_BIN,
31
+ LAUNCHER_FAILURE_EXIT,
32
+ launcherPath as landlockLauncherPath,
33
+ probe as defaultProbeLandlock,
34
+ } from '@deepseek-ai/node-addon-system/landlock-run'
35
+ import { Context } from '@deepseek-ai/cordis'
36
+ import z from '@deepseek-ai/schemastery'
37
+ import { SandboxPreparationError, SandboxProvider, SandboxUnavailableError, canonicalPath } from '@deepseek-ai/dsh-sandbox'
38
+ import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
39
+ import type { SessionId } from '@deepseek-ai/dsh-session'
40
+ import { AclWriteGrant, isTempRootInsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl'
41
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
42
+ import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts'
43
+
44
+ /**
45
+ * Classify one failed Windows ACL preparation step; the platform failure, or an
46
+ * `AggregateError` of it and its cleanup failures, becomes the `cause`.
47
+ * @param step - the preparation step, as the message names it.
48
+ * @param error - the step's own failure, typically a `Win32Error` or Node errno error.
49
+ * @param cleanupFailures - rollback failures that followed it.
50
+ * @returns the coded preparation failure.
51
+ */
52
+ function aclPreparationFailure(step: string, error: unknown, cleanupFailures: readonly unknown[] = []): SandboxPreparationError {
53
+ const failed = cleanupFailures.length === 0 ? `${step} failed` : `${step} failed and its cleanup also failed`
54
+ return new SandboxPreparationError(
55
+ `sandbox-local: windows-acl ${failed}: ${String(error)}. The command did not run; `
56
+ + 'check that the current user can change permissions on the workspace and temp directories, or run with danger-full-access.',
57
+ 'SANDBOX_PREPARATION_FAILED',
58
+ { cause: cleanupFailures.length === 0 ? error : new AggregateError([error, ...cleanupFailures], `sandbox-local windows-acl ${failed}`) },
59
+ )
60
+ }
61
+
62
+ /** Plugin config. All optional — `static Config` supplies the defaults. */
63
+ export interface Config {
64
+ /**
65
+ * Override the runner argv; bwrap-compatible profile arguments are appended. A
66
+ * non-empty override asserts full enforcement and skips built-in selection and
67
+ * probing. A runner that starts but refuses its profile must be identifiable by
68
+ * {@link runnerFailureSignatures}. Consumers classify a spawn rejection only after
69
+ * confirming the workdir is usable. `ENOENT` or `EACCES` identifies the runner when
70
+ * `error.path` equals argv[0] and `error.syscall` is `spawn` or `spawn <runner>`, or
71
+ * when `error.path` is absent and `error.syscall` is exactly `spawn <runner>`.
72
+ */
73
+ runnerCommand?: string[]
74
+ /**
75
+ * Case-insensitive stderr substrings emitted when a configured
76
+ * {@link runnerCommand} refuses its profile before executing the wrapped
77
+ * command. Required and non-empty with `runnerCommand`; rejected without
78
+ * it. Each entry is a non-empty, single-line, case-insensitive substring
79
+ * covering the executable runner's own failure dialect.
80
+ */
81
+ runnerFailureSignatures?: string[]
82
+ /** Positive timeout for each functional probe; zero would mean unbounded to Node. */
83
+ probeTimeoutMs?: number
84
+ }
85
+
86
+ /** Probe whether `bwrap` can create the profile; the provider caches the bounded result. */
87
+ function defaultProbeBwrap(timeoutMs: number): boolean {
88
+ const probe = spawnSync('bwrap', [...bwrapProfileArgs({ mode: 'read-only', workspaceRoot: '/' }), '--', 'true'], {
89
+ timeout: timeoutMs,
90
+ stdio: 'ignore',
91
+ })
92
+ return probe.status === 0
93
+ }
94
+
95
+ /**
96
+ * Functional Seatbelt probe: apply the real `read-only` profile through
97
+ * `sandbox-exec -p` and run `true` under it — exit 0 means the kernel
98
+ * accepted and enforced the profile (`sandbox-exec` exits non-zero when
99
+ * `sandbox_init` refuses it). A missing `sandbox-exec` (every non-macOS
100
+ * host) fails the spawn and probes `unusable`, exactly like the other
101
+ * rungs' absent binaries. Apple marks the CLI deprecated but ships it on
102
+ * every macOS; if it ever disappears, this probe is what fails closed.
103
+ */
104
+ function defaultProbeSeatbelt(seatbeltExec: string, timeoutMs: number): boolean {
105
+ const probe = spawnSync(seatbeltExec, [...seatbeltProfileArgs({ mode: 'read-only', workspaceRoot: '/' }), '--', 'true'], {
106
+ timeout: timeoutMs,
107
+ stdio: 'ignore',
108
+ })
109
+ return probe.status === 0
110
+ }
111
+
112
+ /**
113
+ * Functional windows-acl probe: run the runner in read-only mode (zero grants,
114
+ * no ACL mutation) around `cmd /c exit 0` — exit 0 means the runner created
115
+ * the restricted token and spawned the child under it. The win32 chain is a
116
+ * sole candidate, so the product never probes; the probe exists for override
117
+ * chains and mirrors the other rungs' shape.
118
+ */
119
+ function defaultProbeWindowsAcl(runnerInvocation: string[], timeoutMs: number): boolean {
120
+ const program = runnerInvocation[0]
121
+ if (program === undefined) return false
122
+ const probe = spawnSync(program, [
123
+ ...runnerInvocation.slice(1),
124
+ '--workspace', tmpdir(), '--temp', tmpdir(), '--mode', 'read-only',
125
+ '--', 'cmd', '/c', 'exit', '0',
126
+ ], {
127
+ timeout: timeoutMs,
128
+ stdio: 'ignore',
129
+ })
130
+ return probe.status === 0
131
+ }
132
+
133
+ /** Test hook: inject probe verdicts / a fake launcher / a platform without real runners. */
134
+ export interface SandboxInternals {
135
+ /** Replaces `process.platform` for chain selection (exercise any platform's chain from any host). */
136
+ platform?: string
137
+ /** Replaces the platform's chain wholesale (walk mechanics — e.g. probing a rung the product chains only reach unprobed). */
138
+ chain?: readonly SelectedRunner['runner'][]
139
+ /** Replaces the functional `bwrap` probe (the Linux chain's first rung). */
140
+ probeBwrap?: () => boolean
141
+ /** Replaces the functional Landlock launcher probe (the Linux chain's second rung). */
142
+ probeLandlock?: (launcher: string) => SandboxEnforcement | 'unusable'
143
+ /** Replaces the functional Seatbelt probe (the darwin chain's sole rung — only consulted if that chain ever grows). */
144
+ probeSeatbelt?: (seatbeltExec: string) => boolean
145
+ /** Replaces the resolved `landlock-run` launcher path (a fake launcher script). */
146
+ landlockLauncher?: string
147
+ /** Replaces the `sandbox-exec` executable the probe and wraps invoke (a fake script). */
148
+ seatbeltExec?: string
149
+ /** Replaces the resolved windows-acl runner argv prefix (a fake runner). */
150
+ windowsAclRunnerArgs?: string[]
151
+ /** Replaces the resolved windows-acl runner built entry path (a fake lib/runner.js location). */
152
+ windowsAclRunnerEntry?: string
153
+ /** Replaces the functional windows-acl probe (the win32 chain's sole rung — only consulted if that chain ever grows). */
154
+ probeWindowsAcl?: () => boolean
155
+ /** Replaces the private-temp-directory removal at provider dispose (a throwing fake exercises the cleanup-failure path). */
156
+ rmTempDir?: (path: string) => void
157
+ }
158
+
159
+ /** The chain's verdict: which runner confines, and how completely it enforces. */
160
+ type SelectedRunner = { runner: 'bwrap' | 'landlock' | 'seatbelt' | 'windows-acl'; enforcement: SandboxEnforcement }
161
+
162
+ /** One live session/workspace pair's private temp directory and capability. */
163
+ interface AclTempCapability {
164
+ dir: string
165
+ writeSid: string
166
+ grant: AclWriteGrant
167
+ }
168
+
169
+ /**
170
+ * The runner chain per platform — selection is BY PLATFORM first, probes
171
+ * second: a platform's chain is probed in preference order only when it has
172
+ * MORE than one candidate (probing arbitrates; it does not re-validate a
173
+ * choice that has no alternative). A platform with no chain fails closed at
174
+ * `confine()`. Linux prefers `bwrap` (its mount profile is closest to the
175
+ * mode vocabulary) over the Landlock launcher; darwin has exactly one
176
+ * candidate, selected without any probe.
177
+ */
178
+ const PLATFORM_CHAINS: Record<string, readonly SelectedRunner['runner'][]> = {
179
+ linux: ['bwrap', 'landlock'],
180
+ darwin: ['seatbelt'],
181
+ // The Windows restricted-token runner (@deepseek-ai/dsh-sandbox-windows-acl):
182
+ // a sole candidate, selected without a probe — its execution-time refusal
183
+ // fails closed through its stderr signature (windows-acl-run:) and exit 127.
184
+ win32: ['windows-acl'],
185
+ }
186
+
187
+ /**
188
+ * Enforcement completeness a rung claims when selected WITHOUT a probe (a
189
+ * chain of one). `bwrap` and Seatbelt govern every promised file effect by
190
+ * construction, so the claim is a profile fact; `landlock` is listed for the
191
+ * table's totality but is unreachable without a probe (the Linux chain has
192
+ * two rungs, so it is only ever selected through its probe, whose report is
193
+ * what distinguishes full from per-ABI-partial — and the launcher additionally
194
+ * self-reports partial enforcement on stderr at every confined run).
195
+ */
196
+ const STATIC_ENFORCEMENT: Record<SelectedRunner['runner'], SandboxEnforcement> = {
197
+ bwrap: 'full',
198
+ landlock: 'full',
199
+ seatbelt: 'full',
200
+ // Everyone stays in both restricting lists for process initialization, but
201
+ // the Low label denies the write authority it used to confer. NTFS hard
202
+ // links still alias a granted workspace file to a path outside it, reads
203
+ // stay unconfined, and an AppContainer-ACL'd tree is unreadable to the
204
+ // child: the backend enforces the remaining ACL-addressable surface but
205
+ // must not advertise the absolute promise.
206
+ 'windows-acl': 'partial',
207
+ }
208
+
209
+ /**
210
+ * A probe bound must be a positive finite number: Node treats
211
+ * `spawnSync({ timeout: 0 })` as NO timeout, so an unvalidated 0 would
212
+ * silently mean "unbounded" — the opposite of what the field promises.
213
+ */
214
+ function assertPositiveFinite(name: string, value: number): void {
215
+ if (!Number.isFinite(value) || value <= 0) {
216
+ throw new Error(`sandbox-local: ${name} must be a positive finite number`)
217
+ }
218
+ }
219
+
220
+ /**
221
+ * The denial dialect each runner's kernel speaks — the case-insensitive stderr substrings a
222
+ * denied file effect produces under it, carried on every wrap (the seam's
223
+ * `ConfinedArgv.denialSignatures`).
224
+ */
225
+ const DENIAL_SIGNATURES = {
226
+ bwrap: ['read-only file system'],
227
+ landlock: ['permission denied'],
228
+ seatbelt: ['operation not permitted'],
229
+ // pwsh/.NET: "Access to the path '...' is denied."; cmd: "Access is denied.";
230
+ // Node EACCES: "permission denied"; EPERM: "operation not permitted".
231
+ 'windows-acl': ['access is denied', 'access to the path', 'permission denied', 'operation not permitted'],
232
+ runnerCommand: ['read-only file system', 'permission denied'],
233
+ } as const satisfies Record<SelectedRunner['runner'] | 'runnerCommand', readonly string[]>
234
+
235
+ /** The windows-acl runner's documented failure exit (its own RUNNER_FAILURE_EXIT contract, distinct from Landlock's 125). */
236
+ const WINDOWS_ACL_RUNNER_FAILURE_EXIT = 127
237
+
238
+ /**
239
+ * Runner-owned fatal diagnostics. Landlock has a versioned exit-125 plus
240
+ * fatal-line launcher-failure contract. Bubblewrap's current fatal paths exit
241
+ * 1 but its public contract does not reserve that status, while sandbox-exec
242
+ * publishes no launcher-failure status; those backends remain signature-only.
243
+ * The windows-acl runner prints `windows-acl-run: <detail>` on every
244
+ * runner-side failure and exits 127 — the rule is exit-gated on that status
245
+ * so a confined command that merely PRINTS the signature (or a runner
246
+ * cleanup failure reported on a non-zero child exit) is never misclassified
247
+ * as "the command did not run". Keep the Landlock tuple aligned with the
248
+ * assembled snapshot fixture at
249
+ * `packages/test-support/session-snapshot/tests/fixtures/partial-landlock-sandbox.ts`.
250
+ */
251
+ const RUNNER_FAILURE_RULES = {
252
+ bwrap: [{ fatalSignatures: ['bwrap: '] }],
253
+ landlock: [{
254
+ allowedExitCodes: [LAUNCHER_FAILURE_EXIT],
255
+ fatalSignatures: [`${LAUNCHER_BIN}: `],
256
+ informationalLines: [`${LAUNCHER_BIN}: partial enforcement (older Landlock ABI)`],
257
+ }],
258
+ seatbelt: [{ fatalSignatures: ['sandbox-exec: '] }],
259
+ 'windows-acl': [{ allowedExitCodes: [WINDOWS_ACL_RUNNER_FAILURE_EXIT], fatalSignatures: ['windows-acl-run: '] }],
260
+ } as const satisfies Record<SelectedRunner['runner'], readonly RunnerFailureRule[]>
261
+
262
+ /**
263
+ * Local process-sandbox provider. Registers as `ctx.sandbox`. Caches the
264
+ * chain verdict and, on the windows-acl rung, the write grants
265
+ * ({@link AclWriteGrant}: the standing workspace-root grant per workspace
266
+ * and the revocable private-temp grant per live session/workspace pair, the
267
+ * latter revoked on provider dispose); the one-time probes spawn nothing
268
+ * else.
269
+ */
270
+ export class LocalSandboxProvider extends SandboxProvider {
271
+ // Inline schema call: the config catalog walks `static Config` statically.
272
+ static Config: z<Config> = z.object({
273
+ runnerCommand: z.array(z.string()).default([]),
274
+ runnerFailureSignatures: z.array(z.string()).default([]),
275
+ probeTimeoutMs: z.natural().default(5_000),
276
+ })
277
+
278
+ /** Test hook (mirrors the bash executors' `internals`). */
279
+ internals: SandboxInternals = {}
280
+
281
+ private readonly runnerCommand: string[] | undefined
282
+ private readonly configuredRunnerFailureSignatures: string[]
283
+ private readonly probeTimeoutMs: number
284
+ /** Cached chain verdict; undefined until the first confined wrap needs it. */
285
+ private selectedRunner: SelectedRunner | 'unavailable' | undefined
286
+ /**
287
+ * Server-lifetime write grants (windows-acl rung): the STANDING
288
+ * workspace-root grant per workspace (its ACE is the cross-session reuse
289
+ * cache and outlives the provider — never revoked) and the REVOCABLE
290
+ * private-temp grant per live session/workspace pair (revoked on provider
291
+ * dispose).
292
+ */
293
+ private readonly workspaceGrants = new Map<string, AclWriteGrant>()
294
+ private readonly tempCapabilities = new Map<string, AclTempCapability>()
295
+
296
+ constructor(ctx: Context, config: Config) {
297
+ super(ctx)
298
+ // The schema (static Config) defaults every field — the casts record
299
+ // those runtime facts. An empty runnerCommand means "not configured":
300
+ // use the platform chain.
301
+ const runner = config.runnerCommand as string[]
302
+ const runnerFailureSignatures = config.runnerFailureSignatures as string[]
303
+ if (runner.length === 0 && runnerFailureSignatures.length > 0) {
304
+ throw new Error('sandbox-local: runnerFailureSignatures requires runnerCommand')
305
+ }
306
+ if (runner.length > 0 && runnerFailureSignatures.length === 0) {
307
+ throw new Error('sandbox-local: runnerCommand requires at least one runnerFailureSignatures entry')
308
+ }
309
+ if (runnerFailureSignatures.some(signature => signature.trim().length === 0 || /[\r\n]/u.test(signature))) {
310
+ throw new Error('sandbox-local: runnerFailureSignatures entries must be non-empty single-line strings')
311
+ }
312
+ this.runnerCommand = runner.length > 0 ? runner : undefined
313
+ this.configuredRunnerFailureSignatures = runnerFailureSignatures
314
+ this.probeTimeoutMs = config.probeTimeoutMs as number
315
+ assertPositiveFinite('probeTimeoutMs', this.probeTimeoutMs)
316
+ // An operator-supplied runner does not use the ACL backend. The registry
317
+ // remains optional and may be mounted after this provider.
318
+ /* v8 ignore next 3 -- Windows-only registration; the Linux coverage lane cannot take this branch */
319
+ if (process.platform === 'win32' && this.runnerCommand === undefined) {
320
+ ctx.inject(['skills'], (skillsCtx) => { registerAclDiagnosisSkill(skillsCtx) })
321
+ }
322
+ // The temp grants are revoked with the provider: a clean server
323
+ // shutdown leaves no temp ACEs behind (workspace ACEs stand by design —
324
+ // the reuse cache; an unclean shutdown leaves them for the next
325
+ // provision's exact-ACE skip).
326
+ ctx.effect(() => () => {
327
+ this.revokeAclGrants()
328
+ })
329
+ }
330
+
331
+ /**
332
+ * Wrap `argv` in the selected runner's invocation for `policy` — the configured
333
+ * `runnerCommand` when present (the operator's assertion, no probe), else the platform
334
+ * chain's runner speaking its own profile dialect.
335
+ *
336
+ * @param argv - the exact argv the caller is about to spawn.
337
+ * @param policy - the file-effect policy this execution runs under.
338
+ * @param signal - cancellation before policy resolution or grant creation.
339
+ * @returns the wrapped argv plus the selected backend's enforcement completeness, denial
340
+ * signatures, and structured runner-failure rules; throws the fail-closed
341
+ * `SANDBOX_UNAVAILABLE` error when the platform has no usable runner.
342
+ */
343
+ async confine(argv: readonly string[], policy: SandboxPolicy, signal?: AbortSignal): Promise<ConfinedArgv> {
344
+ signal?.throwIfAborted()
345
+ policy = { ...policy, workspaceRoot: canonicalPath(policy.workspaceRoot) }
346
+ if (this.runnerCommand !== undefined) {
347
+ return Promise.resolve<ConfinedArgv>({
348
+ argv: [...this.runnerCommand, ...bwrapProfileArgs(policy), '--', ...argv],
349
+ enforcement: 'full',
350
+ denialSignatures: DENIAL_SIGNATURES.runnerCommand,
351
+ runnerFailureRules: [{ fatalSignatures: this.configuredRunnerFailureSignatures }],
352
+ })
353
+ }
354
+ const selected = this.selectRunner(policy.mode)
355
+ const runnerArgv = this.runnerArgv(selected.runner, policy)
356
+ return Promise.resolve<ConfinedArgv>({
357
+ argv: [...runnerArgv, '--', ...argv],
358
+ enforcement: selected.enforcement,
359
+ denialSignatures: DENIAL_SIGNATURES[selected.runner],
360
+ runnerFailureRules: RUNNER_FAILURE_RULES[selected.runner],
361
+ })
362
+ }
363
+
364
+ /** The selected rung's runner invocation (program + profile arguments) for one policy. */
365
+ private runnerArgv(runner: SelectedRunner['runner'], policy: SandboxPolicy): string[] {
366
+ switch (runner) {
367
+ case 'bwrap': return ['bwrap', ...bwrapProfileArgs(policy)]
368
+ case 'landlock': return [this.landlockLauncher(), ...landlockProfileArgs(policy)]
369
+ case 'seatbelt': return [this.seatbeltExec(), ...seatbeltProfileArgs(policy)]
370
+ case 'windows-acl': return this.windowsAclRunnerArgv(policy)
371
+ default: return assertNever(runner)
372
+ }
373
+ }
374
+
375
+ /**
376
+ * The windows-acl runner argv for one policy. With a calling session (the
377
+ * policy's `sessionId`) under workspace-write, the grants are materialized
378
+ * once per provider lifetime — the standing workspace-root grant per
379
+ * workspace and a revocable, RANDOM private-temp capability per live
380
+ * session/workspace pair. The runner receives `--write-sid` plus
381
+ * `--temp-write-sid` and grants nothing itself. Agentless workspace-write
382
+ * calls pass the ambient temp ROOT and no SID flags: the runner creates and
383
+ * removes a random private child directory for that one invocation.
384
+ * Additional directory grants apply only to harness filesystem operations
385
+ * on Windows; process confinement keeps the workspace and private temp grants.
386
+ * @param policy - the resolved per-call policy.
387
+ * @returns the runner invocation.
388
+ */
389
+ private windowsAclRunnerArgv(policy: SandboxPolicy): string[] {
390
+ const sessionId = policy.sessionId
391
+ if (sessionId === undefined || policy.mode === 'read-only') {
392
+ return [
393
+ ...this.windowsAclRunnerInvocation(),
394
+ '--workspace', policy.workspaceRoot,
395
+ '--temp', tmpdir(),
396
+ '--mode', policy.mode,
397
+ ]
398
+ }
399
+ const temp = this.materializeAclGrant(sessionId, policy.workspaceRoot)
400
+ return [
401
+ ...this.windowsAclRunnerInvocation(),
402
+ '--workspace', policy.workspaceRoot,
403
+ '--temp', temp.dir,
404
+ '--mode', policy.mode,
405
+ '--write-sid', workspaceWriteSid(policy.workspaceRoot),
406
+ '--temp-write-sid', temp.writeSid,
407
+ ]
408
+ }
409
+
410
+ /**
411
+ * Materialize one workspace-write policy's ACEs once per provider
412
+ * lifetime. The workspace SID and standing root grant are shared by the
413
+ * workspace. The temp directory is random and carries a distinct SID, so
414
+ * another session on the same workspace cannot use the shared workspace
415
+ * SID to enter it. A fresh provider always chooses a new path; crash
416
+ * residue therefore cannot collide with or authorize a resumed session.
417
+ * Fail-closed: a half-materialized temp grant is revoked and its directory
418
+ * removed before the error propagates. A temp root inside the workspace
419
+ * throws `SandboxPreparationError` `SANDBOX_INVALID_TEMP_ROOT` before any ACL
420
+ * change; any other failure throws `SANDBOX_PREPARATION_FAILED` with the
421
+ * platform error as `cause`.
422
+ * @param sessionId - the policy's calling-session identity.
423
+ * @param workspaceRoot - the resolved policy root.
424
+ * @returns the pair's private temp directory and write capability.
425
+ */
426
+ private materializeAclGrant(sessionId: SessionId, workspaceRoot: string): AclTempCapability {
427
+ let tempInsideWorkspace: boolean
428
+ try {
429
+ tempInsideWorkspace = isTempRootInsideWorkspace(workspaceRoot, tmpdir())
430
+ } catch (error) {
431
+ throw aclPreparationFailure('workspace and temp directory resolution', error)
432
+ }
433
+ if (tempInsideWorkspace) {
434
+ throw new SandboxPreparationError(
435
+ `sandbox-local: windows-acl temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tmpdir()}. `
436
+ + 'A private temp directory there would inherit the workspace grant, so the command did not run. '
437
+ + 'Set TEMP and TMP to a directory outside the workspace, or open a workspace that does not contain the temp directory.',
438
+ 'SANDBOX_INVALID_TEMP_ROOT',
439
+ )
440
+ }
441
+ const writeSid = workspaceWriteSid(workspaceRoot)
442
+ if (!this.workspaceGrants.has(workspaceRoot)) {
443
+ let grant: AclWriteGrant
444
+ try {
445
+ grant = AclWriteGrant.create(writeSid)
446
+ } catch (error) {
447
+ throw aclPreparationFailure('workspace grant', error)
448
+ }
449
+ try {
450
+ grant.add(workspaceRoot, true)
451
+ } catch (error) {
452
+ // Free the SID; a standing ACE (if the apply succeeded before a
453
+ // post-apply throw) is the intended end state, not an error
454
+ // artifact — nothing to revoke.
455
+ try {
456
+ grant.dispose()
457
+ } catch (cleanupError) {
458
+ throw aclPreparationFailure('workspace grant', error, [cleanupError])
459
+ }
460
+ throw aclPreparationFailure('workspace grant', error)
461
+ }
462
+ this.workspaceGrants.set(workspaceRoot, grant)
463
+ }
464
+ const key = JSON.stringify([String(sessionId), workspaceRoot])
465
+ const existing = this.tempCapabilities.get(key)
466
+ if (existing !== undefined) return existing
467
+ let tempDir: string
468
+ try {
469
+ tempDir = mkdtempSync(join(tmpdir(), 'dsh-'))
470
+ } catch (error) {
471
+ throw aclPreparationFailure('private temp directory creation', error)
472
+ }
473
+ const tempSid = tempWriteSid(tempDir)
474
+ let grant: AclWriteGrant | undefined
475
+ try {
476
+ grant = AclWriteGrant.create(tempSid)
477
+ grant.add(tempDir)
478
+ } catch (error) {
479
+ const cleanupFailures: unknown[] = []
480
+ if (grant !== undefined) {
481
+ try {
482
+ grant.dispose()
483
+ } catch (cleanupError) {
484
+ cleanupFailures.push(cleanupError)
485
+ }
486
+ }
487
+ try {
488
+ this.removeTempDir(tempDir)
489
+ } catch (cleanupError) {
490
+ cleanupFailures.push(cleanupError)
491
+ }
492
+ throw aclPreparationFailure('temp grant materialization', error, cleanupFailures)
493
+ }
494
+ const capability = { dir: tempDir, writeSid: tempSid, grant }
495
+ this.tempCapabilities.set(key, capability)
496
+ return capability
497
+ }
498
+
499
+ /**
500
+ * Dispose every write grant (provider dispose): the revocable temp ACEs
501
+ * are revoked, the private temp directories this provider created are
502
+ * removed, and every SID allocation is freed; the standing workspace ACEs
503
+ * stay (the reuse cache). Cleanup failures are reported, not thrown:
504
+ * cordis teardown must not be aborted by grant cleanup. A crash skips all
505
+ * of it, but a new provider never reuses the residue's random path or SID;
506
+ * OS temp hygiene (or manual removal) eventually reclaims it.
507
+ */
508
+ private revokeAclGrants(): void {
509
+ if (this.workspaceGrants.size === 0 && this.tempCapabilities.size === 0) return
510
+ const failures: unknown[] = []
511
+ for (const grant of [...this.workspaceGrants.values(), ...[...this.tempCapabilities.values()].map(capability => capability.grant)]) {
512
+ try {
513
+ grant.dispose()
514
+ } catch (error) {
515
+ failures.push(error)
516
+ }
517
+ }
518
+ for (const { dir } of this.tempCapabilities.values()) {
519
+ try {
520
+ this.removeTempDir(dir)
521
+ } catch (error) {
522
+ failures.push(error)
523
+ }
524
+ }
525
+ this.workspaceGrants.clear()
526
+ this.tempCapabilities.clear()
527
+ if (failures.length > 0) {
528
+ this.ctx.logger.warn(`sandbox-local: windows-acl grant cleanup completed with ${failures.length} failure(s)`)
529
+ for (const error of failures) this.ctx.logger.warn(error)
530
+ }
531
+ }
532
+
533
+ /** Remove one provider-owned private temp directory (injectable for cleanup tests). */
534
+ private removeTempDir(dir: string): void {
535
+ const remove = this.internals.rmTempDir ?? ((path: string) => { rmSync(path, { recursive: true, force: true }) })
536
+ remove(dir)
537
+ }
538
+
539
+ /**
540
+ * Resolve which runner confines commands, once, for the provider's
541
+ * lifetime: this platform's chain ({@link PLATFORM_CHAINS}), its sole
542
+ * candidate selected directly, multiple candidates arbitrated by
543
+ * functional probes in chain order. Fail closed when the platform has no
544
+ * chain or no candidate passes — the command never runs.
545
+ */
546
+ private selectRunner(mode: ConfinedSandboxMode): SelectedRunner {
547
+ this.selectedRunner ??= this.chainVerdict()
548
+ if (this.selectedRunner === 'unavailable') throw new SandboxUnavailableError(mode)
549
+ return this.selectedRunner
550
+ }
551
+
552
+ /** Walk this platform's chain: sole candidate unprobed, several probed in order, none usable → unavailable. */
553
+ private chainVerdict(): SelectedRunner | 'unavailable' {
554
+ const chain = this.internals.chain ?? PLATFORM_CHAINS[this.internals.platform ?? process.platform] ?? []
555
+ const [first, ...rest] = chain
556
+ if (first === undefined) return 'unavailable'
557
+ // A sole candidate needs no arbitration; its execution-time refusal still fails closed.
558
+ if (rest.length === 0) return { runner: first, enforcement: STATIC_ENFORCEMENT[first] }
559
+ for (const runner of chain) {
560
+ const enforcement = this.probeRunner(runner)
561
+ if (enforcement !== 'unusable') return { runner, enforcement }
562
+ }
563
+ return 'unavailable'
564
+ }
565
+
566
+ /** One rung's functional probe (each at most once, via the chain walk). */
567
+ private probeRunner(runner: SelectedRunner['runner']): SandboxEnforcement | 'unusable' {
568
+ // bwrap's mount profile and Seatbelt's deny-file-write* profile govern
569
+ // every promised file effect by construction, so their passing probes
570
+ // are always full enforcement; the Landlock launcher's probe report
571
+ // distinguishes full from per-ABI-partial, while windows-acl is always
572
+ // partial for its documented hard-link, unconfined-read, and
573
+ // AppContainer-ACL boundaries.
574
+ switch (runner) {
575
+ case 'bwrap': {
576
+ const probe = this.internals.probeBwrap ?? (() => defaultProbeBwrap(this.probeTimeoutMs))
577
+ return probe() ? 'full' : 'unusable'
578
+ }
579
+ case 'landlock': {
580
+ const probe = this.internals.probeLandlock ?? (launcher => defaultProbeLandlock(launcher, { timeoutMs: this.probeTimeoutMs }))
581
+ return probe(this.landlockLauncher())
582
+ }
583
+ case 'seatbelt': {
584
+ const probe = this.internals.probeSeatbelt ?? (exec => defaultProbeSeatbelt(exec, this.probeTimeoutMs))
585
+ return probe(this.seatbeltExec()) ? 'full' : 'unusable'
586
+ }
587
+ case 'windows-acl': {
588
+ const probe = this.internals.probeWindowsAcl
589
+ ?? (() => defaultProbeWindowsAcl(this.windowsAclRunnerInvocation(), this.probeTimeoutMs))
590
+ return probe() ? 'partial' : 'unusable'
591
+ }
592
+ default: return assertNever(runner)
593
+ }
594
+ }
595
+
596
+ /** The Landlock launcher to probe and exec (test hook over the resolved one). */
597
+ private landlockLauncher(): string {
598
+ return this.internals.landlockLauncher ?? landlockLauncherPath()
599
+ }
600
+
601
+ /** The `sandbox-exec` executable to probe and exec (test hook over the system one). */
602
+ private seatbeltExec(): string {
603
+ return this.internals.seatbeltExec ?? 'sandbox-exec'
604
+ }
605
+
606
+ /**
607
+ * The windows-acl runner argv prefix: the built lib/runner.js entry when
608
+ * present (production), else the package source through tsx (development).
609
+ * Pin the source loader and TypeScript paths to this installation, independently
610
+ * of target cwd or environment overrides.
611
+ * The prefix stays `[node, runner, ...]` — a future native-exe runner keeps
612
+ * the same argv contract and only swaps these entries.
613
+ */
614
+ private windowsAclRunnerInvocation(): string[] {
615
+ const override = this.internals.windowsAclRunnerArgs
616
+ if (override !== undefined) return override
617
+ const builtEntry = this.internals.windowsAclRunnerEntry ?? fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-sandbox-windows-acl/runner'))
618
+ if (existsSync(builtEntry)) return [process.execPath, builtEntry]
619
+ const sourceEntry = fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-sandbox-windows-acl/src/runner.ts'))
620
+ const sourceConfig = fileURLToPath(new URL('../../../../tsconfig.base.json', import.meta.url))
621
+ const registration = `import { register } from ${JSON.stringify(import.meta.resolve('tsx/esm/api'))}; register({ tsconfig: ${JSON.stringify(sourceConfig)} });`
622
+ return [process.execPath, '--import', `data:text/javascript,${encodeURIComponent(registration)}`, sourceEntry]
623
+ }
624
+ }
625
+
626
+ export default LocalSandboxProvider
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Internal platform-profile builders for the local sandbox provider.
3
+ *
4
+ * @module @deepseek-ai/dsh-sandbox-local/profiles
5
+ */
6
+
7
+ import { grantArgs as landlockGrantArgs } from '@deepseek-ai/node-addon-system/landlock-run'
8
+ import { workspaceWritableRoots, writableRoots } from '@deepseek-ai/dsh-sandbox'
9
+ import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
10
+
11
+ /**
12
+ * Build the bwrap profile arguments for one file-effect policy.
13
+ * @param policy - file-effect policy to express as bwrap mounts.
14
+ * @returns profile arguments before the trailing separator and command argv.
15
+ */
16
+ export function bwrapProfileArgs(policy: SandboxPolicy): string[] {
17
+ const args = ['--ro-bind', '/', '/', '--dev', '/dev', '--unshare-pid', '--proc', '/proc', '--die-with-parent']
18
+ if (policy.mode === 'workspace-write') {
19
+ args.push('--tmpfs', '/tmp')
20
+ for (const root of workspaceWritableRoots(policy)) args.push('--bind', root, root)
21
+ }
22
+ return args
23
+ }
24
+
25
+ /**
26
+ * Build the Landlock launcher grants for one file-effect policy.
27
+ * @param policy - file-effect policy to express as Landlock allow-list grants.
28
+ * @returns launcher grant arguments before the trailing separator and command argv.
29
+ */
30
+ export function landlockProfileArgs(policy: SandboxPolicy): string[] {
31
+ const readWrite = ['/dev/null']
32
+ if (policy.mode === 'workspace-write') {
33
+ readWrite.push('/tmp', ...workspaceWritableRoots(policy))
34
+ }
35
+ return landlockGrantArgs({ readOnly: ['/'], readWrite })
36
+ }
37
+
38
+ /** Quote one path as an SBPL string literal. */
39
+ function sbplString(path: string): string {
40
+ return `"${path.replaceAll('\\', String.raw`\\`).replaceAll('"', String.raw`\"`)}"`
41
+ }
42
+
43
+ /**
44
+ * Build the sandbox-exec arguments and SBPL profile for one policy. The
45
+ * workspace-owned writable roots (workspace plus explicit extra directories)
46
+ * come from the shared {@link writableRoots} helper (canonical, deduplicated)
47
+ * so the Seatbelt grant and the in-process fs fence
48
+ * (`@deepseek-ai/dsh-fs-sandbox`) can never drift apart; the helper adds the
49
+ * documented Seatbelt temp areas.
50
+ * @param policy - file-effect policy to express as an SBPL profile.
51
+ * @returns sandbox-exec arguments before the trailing separator and command argv.
52
+ */
53
+ export function seatbeltProfileArgs(policy: SandboxPolicy): string[] {
54
+ const forms = ['(version 1)', '(allow default)', '(deny file-write*)', `(allow file-write* (literal ${sbplString('/dev/null')}))`]
55
+ const roots = writableRoots(policy)
56
+ if (roots.length > 0) {
57
+ forms.push(`(allow file-write* ${roots.map(root => `(subpath ${sbplString(root)})`).join(' ')})`)
58
+ }
59
+ return ['-p', forms.join(' ')]
60
+ }