@songtonyli/dsh-cli 0.1.67 → 0.1.68
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.md +1 -1
- package/bin/dsh.mjs +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox/lib/index.js +12 -11
- package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.i18n.yaml +6 -6
- package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.md +3 -3
- package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/README.zh.md +3 -3
- package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/lib/exec-shim.js +26 -34
- package/node_modules/@deepseek-ai/dsh-sandbox-apple-container/lib/index.js +118 -57
- package/node_modules/@deepseek-ai/dsh-tool-fs/lib/index.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ workspace and no build step. Native packages that ship one build per platform
|
|
|
26
26
|
ripgrep, the PTY backend's addons, sharp, koffi, and the Landlock launcher — are
|
|
27
27
|
ordinary optional dependencies, so npm resolves the right one for your machine.
|
|
28
28
|
|
|
29
|
-
Requires Node `^22.19.0 || >=24.0.0`. Version 0.1.
|
|
29
|
+
Requires Node `^22.19.0 || >=24.0.0`. Version 0.1.68; `dsh --version`
|
|
30
30
|
also reports the harness build the package was assembled from.
|
|
31
31
|
|
|
32
32
|
## License
|
package/bin/dsh.mjs
CHANGED
|
@@ -18,7 +18,7 @@ const argv = process.argv.slice(2)
|
|
|
18
18
|
// version this package publishes. Reporting only one of the two would make an
|
|
19
19
|
// ordinary `npm install @songtonyli/dsh-cli@x` look like it installed something else.
|
|
20
20
|
if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-V')) {
|
|
21
|
-
console.log('@songtonyli/dsh-cli 0.1.
|
|
21
|
+
console.log('@songtonyli/dsh-cli 0.1.68 (deepseek-harness 0.2.1-alpha.1)')
|
|
22
22
|
process.exit(0)
|
|
23
23
|
}
|
|
24
24
|
|
|
@@ -167,7 +167,7 @@ window.__ModuleLoader__.load({
|
|
|
167
167
|
const SCROLLBAR_LINGER_MS = 2e3;
|
|
168
168
|
/** Format complete-build metadata for the local brand badge. */
|
|
169
169
|
function localBuildVersion() {
|
|
170
|
-
return `0.2.1-alpha.1-
|
|
170
|
+
return `0.2.1-alpha.1-7d99acf` + ({}.DSH_CLIENT_GIT_DIRTY === "true" ? "-dirty" : "");
|
|
171
171
|
}
|
|
172
172
|
/** Each panel row subscribes only to its own selection state. */
|
|
173
173
|
function PanelRow({ id, label, wide, usePanelInfo, selectPanel, renderSlot }) {
|
|
@@ -187,15 +187,17 @@ function canonicalTarget(path) {
|
|
|
187
187
|
return parent === absolute ? absolute : join(canonicalTarget(parent), basename(absolute));
|
|
188
188
|
}
|
|
189
189
|
/**
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* @param
|
|
194
|
-
* @returns
|
|
190
|
+
* Compile file-name globs, where `*` matches any run of characters and
|
|
191
|
+
* matching ignores case, into one predicate. Compile once and reuse the
|
|
192
|
+
* predicate when testing many names.
|
|
193
|
+
* @param globs - patterns such as `.env.*` or `id_rsa*`.
|
|
194
|
+
* @returns whether a single path component matches any whole pattern; always false for no globs.
|
|
195
195
|
*/
|
|
196
|
-
function
|
|
197
|
-
|
|
198
|
-
|
|
196
|
+
function nameGlobMatcher(globs) {
|
|
197
|
+
if (globs.length === 0) return () => false;
|
|
198
|
+
const patterns = globs.map((glob) => glob.split("*").map((part) => part.replaceAll(/[.+?^${}()|[\]\\]/gu, String.raw`\$&`)).join(".*"));
|
|
199
|
+
const regex = new RegExp(`^(?:${patterns.join("|")})$`, "iu");
|
|
200
|
+
return (name) => regex.test(name);
|
|
199
201
|
}
|
|
200
202
|
/**
|
|
201
203
|
* Whether the canonical file name of `path` matches a hidden-name glob of
|
|
@@ -205,8 +207,7 @@ function matchesNameGlob(name, glob) {
|
|
|
205
207
|
* @returns true when the path is hidden regardless of its root.
|
|
206
208
|
*/
|
|
207
209
|
function isHiddenIn(path, scope) {
|
|
208
|
-
|
|
209
|
-
return scope.hiddenNames.some((glob) => matchesNameGlob(name, glob));
|
|
210
|
+
return nameGlobMatcher(scope.hiddenNames)(basename(canonicalTarget(path)));
|
|
210
211
|
}
|
|
211
212
|
/**
|
|
212
213
|
* Whether `path` is readable within `scope`: it lies inside a root after both
|
|
@@ -361,4 +362,4 @@ var SandboxProvider = class extends Service {
|
|
|
361
362
|
escalationNote(_policy, _target) {}
|
|
362
363
|
};
|
|
363
364
|
//#endregion
|
|
364
|
-
export { ESCALATION_TARGETS, SANDBOX_UNAVAILABLE, SandboxProvider, SandboxProvider as default, SandboxUnavailableError, WIDER_MODES, approveEscalation, canonicalPath, classifyRunnerFailure, escalationHintMarker, isHiddenIn, isReadableIn, isRunnerSpawnFailure,
|
|
365
|
+
export { ESCALATION_TARGETS, SANDBOX_UNAVAILABLE, SandboxProvider, SandboxProvider as default, SandboxUnavailableError, WIDER_MODES, approveEscalation, canonicalPath, classifyRunnerFailure, escalationHintMarker, isHiddenIn, isReadableIn, isRunnerSpawnFailure, matchesSignature, nameGlobMatcher, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs, writableRoots };
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
en: fe0f7d5ac6160763
|
|
28
28
|
zh: 4e1455a8559d46ca
|
|
29
29
|
/deepseek-ai-dsh-sandbox-apple-container/use-this-package/what-confinement-covers:
|
|
30
|
-
en:
|
|
31
|
-
zh:
|
|
30
|
+
en: 36ce4366173e0544
|
|
31
|
+
zh: 4f7537ee5c9c78c0
|
|
32
32
|
/deepseek-ai-dsh-sandbox-apple-container/use-this-package/failures-and-recovery:
|
|
33
33
|
en: 79782500f91b1f06
|
|
34
34
|
zh: a132d680acb85edc
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
en: 42b15ac6321706aa
|
|
37
37
|
zh: c8011788e17a2cd6
|
|
38
38
|
/deepseek-ai-dsh-sandbox-apple-container/understand-the-implementation/containers:
|
|
39
|
-
en:
|
|
40
|
-
zh:
|
|
39
|
+
en: 9d22cd4f279e3c98
|
|
40
|
+
zh: b401fea7af29a453
|
|
41
41
|
/deepseek-ai-dsh-sandbox-apple-container/understand-the-implementation/execution-shim:
|
|
42
|
-
en:
|
|
43
|
-
zh:
|
|
42
|
+
en: 98ef17c4b9975fa3
|
|
43
|
+
zh: 223994718947d592
|
|
44
44
|
/deepseek-ai-dsh-sandbox-apple-container/understand-the-implementation/source-map:
|
|
45
45
|
en: 866bf8dec1ab38ba
|
|
46
46
|
zh: af875a19b5ceb7b9
|
|
@@ -71,7 +71,7 @@ The fields of `@deepseek-ai/dsh-sandbox-local` also apply to the `local` backend
|
|
|
71
71
|
| A command or tool reads a secret file in the workspace | Masked to `/dev/null` in the guest; refused by file tools; excluded from `grep` |
|
|
72
72
|
| A credential reaches the guest environment | Denied names and URLs carrying `user:password@` are never forwarded |
|
|
73
73
|
| A command plants a Git hook or config the host later runs | `.git` is read-only under `workspace-write`; writes fail with `Read-only file system` and use the normal escalation |
|
|
74
|
-
| A command writes outside the workspace | The write lands in the container's own disk and never reaches the host |
|
|
74
|
+
| A command writes outside the workspace | The write lands in the container's own disk and never reaches the host, except under `/run/dsh`, the container's private run directory for start sentinels, which is deleted with the container |
|
|
75
75
|
|
|
76
76
|
`danger-full-access` bypasses `confine`, so it runs on the host under either backend. The approval prompt for an escalation to `danger-full-access` from a container session adds that the command runs directly on the Mac, outside the container. The Auto permission does not write it while a session runs on this backend: it writes `workspace-write`, and the reviewer, not a prompt, approves a one-shot escalation that leaves the container ([Auto review](../../experimental/auto-review/README.md)). On the `local` backend Auto still writes `danger-full-access`.
|
|
77
77
|
|
|
@@ -89,11 +89,11 @@ Missing CLI, a stopped API server that cannot start, or a failed `container run`
|
|
|
89
89
|
|
|
90
90
|
### Containers
|
|
91
91
|
|
|
92
|
-
The provider owns one container per canonical workspace root and confined mode, shared by every session and subagent in that workspace and mode. It starts with `container run --detach --init --rm`, labelled with the owning process id, bind-mounted with `--mount type=bind,…` (the `-v src:dst:ro` form is not used because `container` 1.5.0 misparses it), and idles on `sleep infinity`. A cached container is re-inspected at most once per `recheckMs` and restarted when gone; disposal deletes every owned container, and load deletes containers whose
|
|
92
|
+
The provider owns one container per canonical workspace root and confined mode, shared by every session and subagent in that workspace and mode. It starts with `container run --detach --init --rm`, labelled with the owning process id, bind-mounted with `--mount type=bind,…` (the `-v src:dst:ro` form is not used because `container` 1.5.0 misparses it), and idles on `sleep infinity`. Each container also mounts a private host run directory, `<os tmpdir>/dsh-container-run/<container name>`, writable at `/run/dsh` under every confined mode. A cached container is re-inspected with one `container inspect` at most once per `recheckMs` and restarted when it is gone or its run directory was deleted; disposal deletes every owned container and its run directory, and load deletes containers and run directories whose process has exited. When the default backend is `container` and the deployment default mode is confined, the default-mode container starts in the background at load.
|
|
93
93
|
|
|
94
94
|
### Execution shim
|
|
95
95
|
|
|
96
|
-
`confine` returns `[node, exec-shim.js, <executable>, <container>, <denylist>, '--', ...argv]`. The shim runs on the host with the caller's working directory and environment, writes the filtered environment to a private `--env-file`, and runs `container exec -i [-t] -w <cwd>` with the argv under `setsid -w` in the guest. Because `container exec` does not forward signals, the shim
|
|
96
|
+
`confine` returns `[node, exec-shim.js, <executable>, <container>, <run dir>, <denylist>, '--', ...argv]`. The shim runs on the host with the caller's working directory and environment, writes the filtered environment to a private `--env-file`, and runs `container exec -i [-t] -w <cwd>` with the argv under `setsid -w` in the guest. Before the argv starts, the guest wrapper writes its process-group id to `/run/dsh/<token>.pid`; when that write fails, the argv does not run. Because `container exec` does not forward signals, the shim signals that process group itself; a forwarded signal exits `128 + n`. The pid file doubles as the start sentinel: after `container exec` exits, the shim removes it from the host run directory, and a missing file marks a runtime failure, reported as `dsh-container-exec: …` with exit 125 and classified by the runner-failure rule, rather than a command that ran and failed. Each command therefore costs one `container exec`. The built `lib/exec-shim.js` depends only on Node built-ins and runs under plain Node in the npm-installed CLI; a source checkout launches `src/exec-shim.ts` through tsx.
|
|
97
97
|
|
|
98
98
|
### Source map
|
|
99
99
|
|
|
@@ -71,7 +71,7 @@ kind: "package-reference"
|
|
|
71
71
|
| 命令或工具读取工作区中的密钥文件 | 在客户机中被遮蔽为 `/dev/null`;被文件工具拒绝;从 `grep` 中排除 |
|
|
72
72
|
| 凭据进入客户机环境 | 被拒绝的名称以及带有 `user:password@` 的 URL 永不转发 |
|
|
73
73
|
| 命令植入宿主机之后会执行的 Git hook 或配置 | 在 `workspace-write` 下 `.git` 为只读;写入以 `Read-only file system` 失败,并走常规提权流程 |
|
|
74
|
-
| 命令写入工作区之外 |
|
|
74
|
+
| 命令写入工作区之外 | 写入落在容器自己的磁盘上,不会到达宿主机;唯一例外是 `/run/dsh`,即容器存放启动哨兵的私有运行目录,它随容器一起删除 |
|
|
75
75
|
|
|
76
76
|
`danger-full-access` 绕过 `confine`,因此在任一后端下都在宿主机上运行。从容器会话升权到 `danger-full-access` 时,审批提示会补充说明该命令将直接在 Mac 上运行,而不是在容器内。会话运行在此后端时,Auto 权限不会写入它:而是写入 `workspace-write`,并由 reviewer 而不是提示批准离开容器的一次性提权([Auto review](../../experimental/auto-review/README.zh.md))。在 `local` 后端上,Auto 仍写入 `danger-full-access`。
|
|
77
77
|
|
|
@@ -89,11 +89,11 @@ CLI 缺失、已停止且无法启动的 API 服务器,或 `container run` 失
|
|
|
89
89
|
|
|
90
90
|
### 容器
|
|
91
91
|
|
|
92
|
-
提供方为每个规范化的工作区根目录与受限模式各持有一个容器,由该工作区与模式下的所有会话和子智能体共享。容器以 `container run --detach --init --rm` 启动,带有所属进程 id 的标签,使用 `--mount type=bind,…` 绑定挂载(不使用 `-v src:dst:ro` 形式,因为 `container` 1.5.0 会错误解析它),并以 `sleep infinity`
|
|
92
|
+
提供方为每个规范化的工作区根目录与受限模式各持有一个容器,由该工作区与模式下的所有会话和子智能体共享。容器以 `container run --detach --init --rm` 启动,带有所属进程 id 的标签,使用 `--mount type=bind,…` 绑定挂载(不使用 `-v src:dst:ro` 形式,因为 `container` 1.5.0 会错误解析它),并以 `sleep infinity` 空转。每个容器还挂载一个私有的宿主机运行目录 `<os tmpdir>/dsh-container-run/<container name>`,在所有受限模式下都以可写方式挂载到 `/run/dsh`。缓存的容器每 `recheckMs` 至多以一次 `container inspect` 重新检查,在容器消失或其运行目录被删除时重新启动;销毁时删除所有自有容器及其运行目录,加载时删除所属进程已退出的容器与运行目录。当默认后端为 `container` 且部署默认模式为受限模式时,默认模式的容器会在加载时于后台启动。
|
|
93
93
|
|
|
94
94
|
### 执行 shim
|
|
95
95
|
|
|
96
|
-
`confine` 返回 `[node, exec-shim.js, <executable>, <container>, <denylist>, '--', ...argv]`。shim 以调用方的工作目录与环境在宿主机上运行,将过滤后的环境写入私有的 `--env-file`,并在客户机中通过 `setsid -w` 以 `container exec -i [-t] -w <cwd>` 运行 argv
|
|
96
|
+
`confine` 返回 `[node, exec-shim.js, <executable>, <container>, <run dir>, <denylist>, '--', ...argv]`。shim 以调用方的工作目录与环境在宿主机上运行,将过滤后的环境写入私有的 `--env-file`,并在客户机中通过 `setsid -w` 以 `container exec -i [-t] -w <cwd>` 运行 argv。argv 启动前,客户机包装脚本将其进程组 id 写入 `/run/dsh/<token>.pid`;写入失败时 argv 不会运行。由于 `container exec` 不转发信号,shim 自行向该进程组发送信号;被转发的信号以 `128 + n` 退出。该 pid 文件同时充当启动哨兵:`container exec` 退出后,shim 从宿主机运行目录中删除它,文件缺失即表示运行时失败(以 `dsh-container-exec: …` 报告、退出码 125,并由运行器失败规则分类),而非已运行但失败的命令。因此每条命令只需一次 `container exec`。构建后的 `lib/exec-shim.js` 只依赖 Node 内置模块,可在 npm 安装的 CLI 中以纯 Node 运行;源码检出则通过 tsx 启动 `src/exec-shim.ts`。
|
|
97
97
|
|
|
98
98
|
### 源码地图
|
|
99
99
|
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { execFile, spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { constants, tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
/** Prefix of the single stderr line the shim writes for {@link SHIM_FAILURE_EXIT}. */
|
|
7
7
|
const SHIM_FAILURE_PREFIX = "dsh-container-exec: ";
|
|
8
|
+
/** Guest path of each container's run directory, a writable bind mount of a host directory. */
|
|
9
|
+
const GUEST_RUN_DIR = "/run/dsh";
|
|
8
10
|
/**
|
|
9
11
|
* Decode the argument list produced by {@link encodeShimArgs}.
|
|
10
12
|
* @param args - the shim process arguments after the entry path.
|
|
@@ -12,11 +14,12 @@ const SHIM_FAILURE_PREFIX = "dsh-container-exec: ";
|
|
|
12
14
|
* @throws {Error} when the list is malformed or the argv is empty.
|
|
13
15
|
*/
|
|
14
16
|
function parseShimArgs(args) {
|
|
15
|
-
const [executable, container, denylist, separator, ...argv] = args;
|
|
16
|
-
if (executable === void 0 || container === void 0 || denylist === void 0 || separator !== "--" || argv.length === 0) throw new Error("usage: exec-shim <executable> <container> <denylist> -- <argv...>");
|
|
17
|
+
const [executable, container, runDir, denylist, separator, ...argv] = args;
|
|
18
|
+
if (executable === void 0 || container === void 0 || runDir === void 0 || denylist === void 0 || separator !== "--" || argv.length === 0) throw new Error("usage: exec-shim <executable> <container> <run-dir> <denylist> -- <argv...>");
|
|
17
19
|
return {
|
|
18
20
|
executable,
|
|
19
21
|
container,
|
|
22
|
+
runDir,
|
|
20
23
|
denylist: denylist === "" ? [] : denylist.split(","),
|
|
21
24
|
argv
|
|
22
25
|
};
|
|
@@ -50,22 +53,20 @@ function envFileText(env, denylist) {
|
|
|
50
53
|
}
|
|
51
54
|
return text;
|
|
52
55
|
}
|
|
53
|
-
/**
|
|
54
|
-
function
|
|
55
|
-
return {
|
|
56
|
-
pid: `/run/dsh-${token}.pid`,
|
|
57
|
-
started: `/run/dsh-${token}.started`
|
|
58
|
-
};
|
|
56
|
+
/** File name of one run's process-group-id file in the run directory. */
|
|
57
|
+
function pidFileName(token) {
|
|
58
|
+
return `${token}.pid`;
|
|
59
59
|
}
|
|
60
60
|
/**
|
|
61
|
-
* The guest `sh -c` wrapper: records its process-group id
|
|
62
|
-
* sentinel, runs the argv
|
|
61
|
+
* The guest `sh -c` wrapper: records its process-group id, which doubles as
|
|
62
|
+
* the start sentinel, then runs the argv and exits with its status. When the
|
|
63
|
+
* file cannot be written, the argv never runs and the wrapper exits
|
|
64
|
+
* {@link SHIM_FAILURE_EXIT}.
|
|
63
65
|
* @param token - the run's unique token.
|
|
64
66
|
* @returns the script text.
|
|
65
67
|
*/
|
|
66
68
|
function wrapperScript(token) {
|
|
67
|
-
|
|
68
|
-
return `echo $$ > ${pid}; : > ${started}; "$@"; s=$?; if [ $s -eq 0 ]; then rm -f ${pid} ${started}; fi; exit $s`;
|
|
69
|
+
return `echo $$ > ${GUEST_RUN_DIR}/${pidFileName(token)} || exit 125; "$@"`;
|
|
69
70
|
}
|
|
70
71
|
/**
|
|
71
72
|
* The `container exec` arguments that run the caller's argv in its own guest session.
|
|
@@ -105,24 +106,7 @@ function killArgs(container, token, signal) {
|
|
|
105
106
|
container,
|
|
106
107
|
"sh",
|
|
107
108
|
"-c",
|
|
108
|
-
`kill -${signal.slice(3)} -$(cat ${
|
|
109
|
-
];
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* The `container exec` arguments that remove the run's token files and exit
|
|
113
|
-
* zero only when the start sentinel existed.
|
|
114
|
-
* @param container - the container name.
|
|
115
|
-
* @param token - the run's token.
|
|
116
|
-
* @returns the arguments after the `container` executable.
|
|
117
|
-
*/
|
|
118
|
-
function settleArgs(container, token) {
|
|
119
|
-
const { pid, started } = tokenPaths(token);
|
|
120
|
-
return [
|
|
121
|
-
"exec",
|
|
122
|
-
container,
|
|
123
|
-
"sh",
|
|
124
|
-
"-c",
|
|
125
|
-
`test -e ${started}; s=$?; rm -f ${pid} ${started}; exit $s`
|
|
109
|
+
`kill -${signal.slice(3)} -$(cat ${GUEST_RUN_DIR}/${pidFileName(token)}) 2>/dev/null; true`
|
|
126
110
|
];
|
|
127
111
|
}
|
|
128
112
|
/** The exit status a shell reports for a process killed by `signal`. */
|
|
@@ -157,10 +141,9 @@ async function runShim(args, deps) {
|
|
|
157
141
|
resolve(code ?? signalExit(signal));
|
|
158
142
|
});
|
|
159
143
|
});
|
|
160
|
-
|
|
161
|
-
const started = await deps.run(args.executable, settleArgs(args.container, deps.token));
|
|
144
|
+
const started = deps.consumeFile(join(args.runDir, pidFileName(deps.token)));
|
|
162
145
|
if (forwarded !== void 0) return signalExit(forwarded);
|
|
163
|
-
if (
|
|
146
|
+
if (exit === 0 || started) return exit;
|
|
164
147
|
deps.stderr(`${SHIM_FAILURE_PREFIX}the container runtime failed before the command started (container exec exited ${exit})\n`);
|
|
165
148
|
return 125;
|
|
166
149
|
} catch (error) {
|
|
@@ -198,6 +181,15 @@ try {
|
|
|
198
181
|
resolve(error === null ? 0 : typeof error.code === "number" ? error.code : 125);
|
|
199
182
|
});
|
|
200
183
|
}),
|
|
184
|
+
consumeFile: (path) => {
|
|
185
|
+
try {
|
|
186
|
+
unlinkSync(path);
|
|
187
|
+
return true;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if (error.code === "ENOENT") return false;
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
},
|
|
201
193
|
writeEnvFile: (text) => {
|
|
202
194
|
const path = join(mkdtempSync(join(tmpdir(), "dsh-container-env-")), "env");
|
|
203
195
|
writeFileSync(path, text, { mode: 384 });
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import { accessSync, constants, existsSync,
|
|
1
|
+
import { accessSync, constants, existsSync, statSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
2
3
|
import { delimiter, isAbsolute, join } from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
4
5
|
import z from "@deepseek-ai/schemastery";
|
|
5
6
|
import { z as z$1 } from "zod";
|
|
6
7
|
import { CommandDefinitionId } from "@deepseek-ai/dsh-commands/brand";
|
|
7
|
-
import { SandboxUnavailableError, canonicalPath,
|
|
8
|
+
import { SandboxUnavailableError, canonicalPath, nameGlobMatcher } from "@deepseek-ai/dsh-sandbox";
|
|
8
9
|
import { LocalSandboxProvider } from "@deepseek-ai/dsh-sandbox-local";
|
|
9
10
|
import { createHash } from "node:crypto";
|
|
11
|
+
import { mkdir, readdir, rm } from "node:fs/promises";
|
|
10
12
|
import { execFile } from "node:child_process";
|
|
11
13
|
//#region lib/types/secrets.js
|
|
12
14
|
/**
|
|
@@ -18,29 +20,54 @@ import { execFile } from "node:child_process";
|
|
|
18
20
|
*/
|
|
19
21
|
/**
|
|
20
22
|
* Find files and symlinks under `root` whose name matches a hidden-name glob,
|
|
21
|
-
* without following symlinked directories.
|
|
23
|
+
* without following symlinked directories. Sibling directories are read
|
|
24
|
+
* concurrently, so the scan never blocks the event loop on a large workspace.
|
|
22
25
|
* @param root - the canonical workspace root.
|
|
23
26
|
* @param scan - names, depth, and skipped directory names.
|
|
24
|
-
* @returns absolute paths in
|
|
27
|
+
* @returns absolute paths in sorted order; unreadable directories are skipped.
|
|
25
28
|
*/
|
|
26
|
-
function findHiddenFiles(root, scan) {
|
|
29
|
+
async function findHiddenFiles(root, scan) {
|
|
30
|
+
const hidden = nameGlobMatcher(scan.names);
|
|
27
31
|
const found = [];
|
|
28
|
-
const walk = (dir, depth) => {
|
|
32
|
+
const walk = async (dir, depth) => {
|
|
29
33
|
let entries;
|
|
30
34
|
try {
|
|
31
|
-
entries =
|
|
35
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
32
36
|
} catch {
|
|
33
37
|
return;
|
|
34
38
|
}
|
|
39
|
+
const children = [];
|
|
35
40
|
for (const entry of entries) {
|
|
36
41
|
const path = join(dir, entry.name);
|
|
37
42
|
if (entry.isDirectory()) {
|
|
38
|
-
if (depth < scan.maxDepth && !scan.skipDirs.includes(entry.name)) walk(path, depth + 1);
|
|
39
|
-
} else if (
|
|
43
|
+
if (depth < scan.maxDepth && !scan.skipDirs.includes(entry.name)) children.push(walk(path, depth + 1));
|
|
44
|
+
} else if (hidden(entry.name)) found.push(path);
|
|
40
45
|
}
|
|
46
|
+
await Promise.all(children);
|
|
41
47
|
};
|
|
42
|
-
walk(root, 0);
|
|
43
|
-
return found;
|
|
48
|
+
await walk(root, 0);
|
|
49
|
+
return found.sort();
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region lib/types/shim.js
|
|
53
|
+
/** Prefix of the single stderr line the shim writes for {@link SHIM_FAILURE_EXIT}. */
|
|
54
|
+
const SHIM_FAILURE_PREFIX = "dsh-container-exec: ";
|
|
55
|
+
/** Guest path of each container's run directory, a writable bind mount of a host directory. */
|
|
56
|
+
const GUEST_RUN_DIR = "/run/dsh";
|
|
57
|
+
/**
|
|
58
|
+
* Encode a shim invocation as the argument list that follows the shim entry.
|
|
59
|
+
* @param args - the invocation; denylist entries are environment names and never contain commas.
|
|
60
|
+
* @returns `[executable, container, runDir, denylist, '--', ...argv]`.
|
|
61
|
+
*/
|
|
62
|
+
function encodeShimArgs(args) {
|
|
63
|
+
return [
|
|
64
|
+
args.executable,
|
|
65
|
+
args.container,
|
|
66
|
+
args.runDir,
|
|
67
|
+
args.denylist.join(","),
|
|
68
|
+
"--",
|
|
69
|
+
...args.argv
|
|
70
|
+
];
|
|
44
71
|
}
|
|
45
72
|
//#endregion
|
|
46
73
|
//#region lib/types/pool.js
|
|
@@ -51,12 +78,16 @@ function findHiddenFiles(root, scan) {
|
|
|
51
78
|
* that differs; `read-only` mounts it read-only, and `workspace-write` mounts
|
|
52
79
|
* its protected directories (such as `.git`) read-only. Extra read-only
|
|
53
80
|
* directories are mounted at their own paths, and hidden files found at start
|
|
54
|
-
* are masked.
|
|
55
|
-
*
|
|
81
|
+
* are masked. Each container also mounts a private host run directory, named
|
|
82
|
+
* after the container, writable at {@link GUEST_RUN_DIR} for the exec shim's
|
|
83
|
+
* start sentinels. A cached container is re-inspected at most once per
|
|
84
|
+
* `recheckMs` and restarted when gone or when its run directory is gone.
|
|
56
85
|
* @module @deepseek-ai/dsh-sandbox-apple-container/pool
|
|
57
86
|
*/
|
|
58
87
|
/** Label naming the owning DSH process id. */
|
|
59
88
|
const PID_LABEL = "dsh.pid";
|
|
89
|
+
/** Owned container names: a workspace-and-mode hash and the owning process id. */
|
|
90
|
+
const CONTAINER_NAME = /^dsh-[0-9a-f]{12}-(\d+)$/u;
|
|
60
91
|
/** Whether `path` is an existing directory. */
|
|
61
92
|
function isDirectory(path) {
|
|
62
93
|
return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
@@ -71,32 +102,37 @@ var ContainerPool = class {
|
|
|
71
102
|
this.options = options;
|
|
72
103
|
}
|
|
73
104
|
/**
|
|
74
|
-
* Return
|
|
75
|
-
*
|
|
105
|
+
* Return a running container for `policy`, starting one when none is cached
|
|
106
|
+
* or the cached one is gone. Concurrent callers share one start.
|
|
76
107
|
* @param policy - the confined mode and workspace root.
|
|
77
|
-
* @returns the container
|
|
78
|
-
* @throws {Error} when the root cannot be mounted or the runtime fails.
|
|
108
|
+
* @returns the container's entry.
|
|
109
|
+
* @throws {Error} when the root or run directory cannot be mounted or the runtime fails.
|
|
79
110
|
*/
|
|
80
111
|
async ensure(policy) {
|
|
81
112
|
const root = canonicalPath(policy.workspaceRoot);
|
|
82
113
|
if (root.includes(",") || policy.workspaceRoot.includes(",")) throw new Error(`workspace root ${JSON.stringify(policy.workspaceRoot)} contains a comma, which \`container --mount\` cannot express`);
|
|
114
|
+
if (this.options.runRoot.includes(",")) throw new Error(`container run directory ${JSON.stringify(this.options.runRoot)} contains a comma, which \`container --mount\` cannot express; set TMPDIR to a path without one`);
|
|
83
115
|
const key = `${policy.mode}\0${root}`;
|
|
84
116
|
const now = this.options.now();
|
|
85
117
|
let slot = this.slots.get(key);
|
|
86
118
|
if (slot === void 0) {
|
|
87
119
|
const name = `dsh-${createHash("sha256").update(key).digest("hex").slice(0, 12)}-${this.options.pid}`;
|
|
88
|
-
|
|
120
|
+
const entry = {
|
|
89
121
|
mode: policy.mode,
|
|
90
122
|
root,
|
|
91
123
|
name,
|
|
124
|
+
runDir: join(this.options.runRoot, name)
|
|
125
|
+
};
|
|
126
|
+
slot = {
|
|
127
|
+
...entry,
|
|
92
128
|
checkedAt: now,
|
|
93
|
-
ready: this.start(
|
|
129
|
+
ready: this.start(entry, policy.workspaceRoot)
|
|
94
130
|
};
|
|
95
131
|
this.slots.set(key, slot);
|
|
96
132
|
} else if (now - slot.checkedAt >= this.options.recheckMs) {
|
|
97
|
-
const
|
|
133
|
+
const entry = slot;
|
|
98
134
|
slot.checkedAt = now;
|
|
99
|
-
slot.ready = slot.ready.then(() => this.
|
|
135
|
+
slot.ready = slot.ready.then(() => this.recheck(entry, policy.workspaceRoot));
|
|
100
136
|
}
|
|
101
137
|
try {
|
|
102
138
|
await slot.ready;
|
|
@@ -104,42 +140,77 @@ var ContainerPool = class {
|
|
|
104
140
|
if (this.slots.get(key) === slot) this.slots.delete(key);
|
|
105
141
|
throw error;
|
|
106
142
|
}
|
|
107
|
-
return
|
|
143
|
+
return {
|
|
144
|
+
mode: slot.mode,
|
|
145
|
+
root: slot.root,
|
|
146
|
+
name: slot.name,
|
|
147
|
+
runDir: slot.runDir
|
|
148
|
+
};
|
|
108
149
|
}
|
|
109
150
|
/**
|
|
110
151
|
* Every owned container.
|
|
111
152
|
* @returns the entries in first-start order.
|
|
112
153
|
*/
|
|
113
154
|
entries() {
|
|
114
|
-
return [...this.slots.values()].map(({ mode, root, name }) => ({
|
|
155
|
+
return [...this.slots.values()].map(({ mode, root, name, runDir }) => ({
|
|
115
156
|
mode,
|
|
116
157
|
root,
|
|
117
|
-
name
|
|
158
|
+
name,
|
|
159
|
+
runDir
|
|
118
160
|
}));
|
|
119
161
|
}
|
|
120
162
|
/**
|
|
121
|
-
* Delete containers left by DSH processes that no longer exist.
|
|
163
|
+
* Delete containers and run directories left by DSH processes that no longer exist.
|
|
122
164
|
* @param isAlive - whether a process id names a live process.
|
|
123
165
|
*/
|
|
124
166
|
async sweep(isAlive) {
|
|
125
|
-
const stale = (
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
167
|
+
const stale = (pid) => Number.isSafeInteger(pid) && pid > 0 && pid !== this.options.pid && !isAlive(pid);
|
|
168
|
+
const containers = (await this.runtime.list()).filter((container) => stale(Number(container.labels[PID_LABEL])));
|
|
169
|
+
await Promise.all(containers.map((container) => this.runtime.remove(container.id)));
|
|
170
|
+
let runDirs;
|
|
171
|
+
try {
|
|
172
|
+
runDirs = await readdir(this.options.runRoot);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (error.code === "ENOENT") return;
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
const orphaned = runDirs.filter((name) => stale(Number(CONTAINER_NAME.exec(name)?.[1])));
|
|
178
|
+
await Promise.all(orphaned.map((name) => rm(join(this.options.runRoot, name), {
|
|
179
|
+
recursive: true,
|
|
180
|
+
force: true
|
|
181
|
+
})));
|
|
130
182
|
}
|
|
131
|
-
/** Delete every owned container, after any in-flight start settles. */
|
|
183
|
+
/** Delete every owned container and its run directory, after any in-flight start settles. */
|
|
132
184
|
async dispose() {
|
|
133
185
|
const slots = [...this.slots.values()];
|
|
134
186
|
this.slots.clear();
|
|
135
187
|
await Promise.allSettled(slots.map((slot) => slot.ready));
|
|
136
|
-
await Promise.all(slots.map((slot) =>
|
|
188
|
+
await Promise.all(slots.map(async (slot) => {
|
|
189
|
+
await this.runtime.remove(slot.name);
|
|
190
|
+
await rm(slot.runDir, {
|
|
191
|
+
recursive: true,
|
|
192
|
+
force: true
|
|
193
|
+
});
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Inspect a cached container on the command path; only one that stopped,
|
|
198
|
+
* vanished, or lost its run directory pays for a service check and start.
|
|
199
|
+
*/
|
|
200
|
+
async recheck(entry, lexical) {
|
|
201
|
+
if (isDirectory(entry.runDir) && await this.runtime.state(entry.name) === "running") return;
|
|
202
|
+
await this.start(entry, lexical);
|
|
137
203
|
}
|
|
138
|
-
async start(name, mode, root, lexical) {
|
|
204
|
+
async start({ name, mode, root, runDir }, lexical) {
|
|
205
|
+
const masks = findHiddenFiles(root, this.options.hidden);
|
|
139
206
|
await this.runtime.ensureService();
|
|
140
207
|
const state = await this.runtime.state(name);
|
|
141
|
-
if (state === "running") return;
|
|
142
|
-
if (state
|
|
208
|
+
if (state === "running" && isDirectory(runDir)) return;
|
|
209
|
+
if (state !== "missing") await this.runtime.remove(name);
|
|
210
|
+
await mkdir(runDir, {
|
|
211
|
+
recursive: true,
|
|
212
|
+
mode: 448
|
|
213
|
+
});
|
|
143
214
|
const spellings = (path) => lexical === root ? [path] : [path, join(lexical, path.slice(root.length))];
|
|
144
215
|
const bind = (source, readonly) => spellings(source).map((target) => ({
|
|
145
216
|
source,
|
|
@@ -164,9 +235,14 @@ var ContainerPool = class {
|
|
|
164
235
|
target,
|
|
165
236
|
readonly: true
|
|
166
237
|
})) : [];
|
|
167
|
-
})
|
|
238
|
+
}),
|
|
239
|
+
{
|
|
240
|
+
source: runDir,
|
|
241
|
+
target: GUEST_RUN_DIR,
|
|
242
|
+
readonly: false
|
|
243
|
+
}
|
|
168
244
|
],
|
|
169
|
-
maskedPaths:
|
|
245
|
+
maskedPaths: (await masks).flatMap(spellings)
|
|
170
246
|
});
|
|
171
247
|
}
|
|
172
248
|
};
|
|
@@ -366,24 +442,6 @@ function setSandboxBackend(session, backend) {
|
|
|
366
442
|
session.append("sandbox/backend", { backend });
|
|
367
443
|
}
|
|
368
444
|
//#endregion
|
|
369
|
-
//#region lib/types/shim.js
|
|
370
|
-
/** Prefix of the single stderr line the shim writes for {@link SHIM_FAILURE_EXIT}. */
|
|
371
|
-
const SHIM_FAILURE_PREFIX = "dsh-container-exec: ";
|
|
372
|
-
/**
|
|
373
|
-
* Encode a shim invocation as the argument list that follows the shim entry.
|
|
374
|
-
* @param args - the invocation; denylist entries are environment names and never contain commas.
|
|
375
|
-
* @returns `[executable, container, denylist, '--', ...argv]`.
|
|
376
|
-
*/
|
|
377
|
-
function encodeShimArgs(args) {
|
|
378
|
-
return [
|
|
379
|
-
args.executable,
|
|
380
|
-
args.container,
|
|
381
|
-
args.denylist.join(","),
|
|
382
|
-
"--",
|
|
383
|
-
...args.argv
|
|
384
|
-
];
|
|
385
|
-
}
|
|
386
|
-
//#endregion
|
|
387
445
|
//#region lib/types/index.js
|
|
388
446
|
/**
|
|
389
447
|
* Apple container sandbox backend. Registers as `ctx.sandbox` and routes each
|
|
@@ -562,7 +620,8 @@ var AppleContainerSandboxProvider = class extends LocalSandboxProvider {
|
|
|
562
620
|
names: this.hiddenFiles,
|
|
563
621
|
maxDepth: config.hiddenFilesMaxDepth,
|
|
564
622
|
skipDirs: config.hiddenFilesSkipDirs
|
|
565
|
-
}
|
|
623
|
+
},
|
|
624
|
+
runRoot: join(canonicalPath(tmpdir()), "dsh-container-run")
|
|
566
625
|
});
|
|
567
626
|
ctx.sessionProjections.register({
|
|
568
627
|
key: "sandboxBackend",
|
|
@@ -648,10 +707,12 @@ var AppleContainerSandboxProvider = class extends LocalSandboxProvider {
|
|
|
648
707
|
throw new SandboxUnavailableError(policy.mode, `${messageOf(error)}; run /sandbox local to confine commands on this host instead`);
|
|
649
708
|
}
|
|
650
709
|
signal?.throwIfAborted();
|
|
710
|
+
const { name, runDir } = container;
|
|
651
711
|
return {
|
|
652
712
|
argv: [...shimInvocation(import.meta.url), ...encodeShimArgs({
|
|
653
713
|
executable: this.executable,
|
|
654
|
-
container,
|
|
714
|
+
container: name,
|
|
715
|
+
runDir,
|
|
655
716
|
denylist: this.envDenylist,
|
|
656
717
|
argv
|
|
657
718
|
})],
|
|
@@ -3,7 +3,7 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
|
3
3
|
import { FsError } from "@deepseek-ai/dsh-fs";
|
|
4
4
|
import { readLangHintForPath as langFromPath } from "@deepseek-ai/dsh-util-code-language";
|
|
5
5
|
import { basename, extname, isAbsolute, relative, resolve } from "node:path";
|
|
6
|
-
import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, isHiddenIn, isReadableIn,
|
|
6
|
+
import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, isHiddenIn, isReadableIn, nameGlobMatcher, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
|
|
7
7
|
import { structuredPatch } from "diff";
|
|
8
8
|
import { AttachmentError, AttachmentId } from "@deepseek-ai/dsh-attachment";
|
|
9
9
|
//#region lib/types/read-render.js
|
|
@@ -295,7 +295,7 @@ async function resolveAuthorizedReadTarget(ctx, exec, requestedPath, toolName) {
|
|
|
295
295
|
const spelledInside = !requestedPath.split(/[\\/]/u).includes("..") && scope.roots.some((root) => isLexicallyUnder(spelled, root));
|
|
296
296
|
let approved = false;
|
|
297
297
|
if (!spelledInside) {
|
|
298
|
-
if (scope.hiddenNames
|
|
298
|
+
if (nameGlobMatcher(scope.hiddenNames)(basename(spelled))) throw new FsError(hiddenMessage(requestedPath), "FS_SANDBOX_DENIED");
|
|
299
299
|
await approveOutsideRead(ctx, exec, spelled, requestedPath, toolName);
|
|
300
300
|
approved = true;
|
|
301
301
|
}
|
package/package.json
CHANGED