pi-subagents-extend 0.0.0-stage → 0.1.2

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
  4. package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
  5. package/package.json +63 -4
  6. package/skills/pi-subagents-extend/SKILL.md +312 -0
  7. package/skills/pi-subagents-extend-context/SKILL.md +103 -0
  8. package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
  9. package/src/bash/env.ts +108 -0
  10. package/src/bash/index.ts +27 -0
  11. package/src/bash/network.ts +97 -0
  12. package/src/bash/programs.ts +367 -0
  13. package/src/bash/rules.ts +247 -0
  14. package/src/bash/tokens.ts +169 -0
  15. package/src/bash/unreachable.ts +429 -0
  16. package/src/budgets.ts +89 -0
  17. package/src/child-context.ts +24 -0
  18. package/src/context-scope.ts +93 -0
  19. package/src/deliverable.ts +216 -0
  20. package/src/dependencies.ts +320 -0
  21. package/src/handoff-hint.ts +69 -0
  22. package/src/index.ts +181 -0
  23. package/src/main-context.ts +30 -0
  24. package/src/main-skills.ts +77 -0
  25. package/src/notices.ts +299 -0
  26. package/src/paths/index.ts +165 -0
  27. package/src/policy/glob.ts +146 -0
  28. package/src/policy/index.ts +36 -0
  29. package/src/policy/payload.ts +312 -0
  30. package/src/probe.ts +495 -0
  31. package/src/role-config.ts +434 -0
  32. package/src/sandbox/grants.ts +339 -0
  33. package/src/sandbox/helper.ts +137 -0
  34. package/src/sandbox/index.ts +12 -0
  35. package/src/sandbox/spec.ts +285 -0
  36. package/src/sandbox-note.ts +194 -0
  37. package/src/wiring/agent-start.ts +371 -0
  38. package/src/wiring/context.ts +216 -0
  39. package/src/wiring/misc.ts +55 -0
  40. package/src/wiring/session-start.ts +69 -0
  41. package/src/wiring/tool-call/anchor.ts +138 -0
  42. package/src/wiring/tool-call/bash-path.ts +0 -0
  43. package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
  44. package/src/wiring/tool-call/judge.ts +585 -0
  45. package/src/wiring/tool-call/original-args.ts +64 -0
  46. package/src/wiring/tool-call/paths.ts +235 -0
  47. package/src/wiring/tool-result.ts +68 -0
  48. package/src/worktree-default.ts +27 -0
@@ -0,0 +1,339 @@
1
+ /**
2
+ * SANDBOX 层 · grants 模块:沙箱允许碰什么 —— 写范围派生的可写路径(子树 glob 给目录、
3
+ * 文件级 glob 展开成实际存在的文件)、git 需要的额外可写目录、产物目录、工具链缓存、
4
+ * 交付物目标路径,以及 spec 帮手 stateDir / toolchainCacheDir 与被剔授权的一次性上报。
5
+ *
6
+ * stateDir / toolchainCacheDir 放在本模块而不是它们多数调用方所在的 spec 模块:
7
+ * grants 侧的 sandboxWritableDirs 也消费它们,放在这里让 spec → grants 保持单向依赖、
8
+ * 不出现模块间的环。
9
+ */
10
+ import { execFileSync } from "node:child_process";
11
+ import { existsSync, mkdirSync, readdirSync, realpathSync, type Dirent } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { resolve } from "node:path";
14
+ import type { BashRule } from "../bash/index.ts";
15
+ import { DETECT_SKIP, detectScratchDirs } from "../dependencies.ts";
16
+ import { canonical, expandPath, insideTree } from "../paths/index.ts";
17
+ import { globToRegExp, normalizeGlob, type Policy } from "../policy/index.ts";
18
+
19
+ /**
20
+ * linked worktree 的 git 公共目录(主仓的 .git)。只有 .git 是文件(worktree)时才问 git,
21
+ * 普通仓库直接返回 undefined:那边 .git 在 cwd 之内,不需要额外授权,也省掉一次 spawn。
22
+ * 结果按 cwd 缓存:bash 白名单命令会反复拼 spec。
23
+ */
24
+ const gitDirsCache = new Map<string, { gitDir: string; common: string } | undefined>();
25
+ /**
26
+ * git 需要可写的路径。
27
+ *
28
+ * 索引、HEAD 与它们的锁文件(`index.lock`、`HEAD.lock`)建在本次 checkout 的 gitdir 根上,
29
+ * 所以那个目录必须整个授权 —— Landlock 只能正向授权,没有「授权目录但排除 hooks/」的写法。
30
+ *
31
+ * 区别在 gitdir 是谁:linked worktree 里它是 `<common>/worktrees/<id>`,里面只有 HEAD /
32
+ * index / logs / refs,没有 hooks 也没有 config;于是 hooks/config 留在 common dir 里,
33
+ * 那里只给 git 真正要写的三个子目录,不再整目录授权(否则子代理能植入 hook 或改
34
+ * core.hooksPath,之后以父代理身份执行)。四个路径全部实测过:少给哪一个都有具体命令
35
+ * 先失败(per-worktree gitdir → index.lock / HEAD.lock;objects → 对象库;refs → ref 锁;
36
+ * logs → reflog 追加)。
37
+ *
38
+ * 普通 checkout 里 gitdir 与 common 就是同一个目录,hooks、config 和索引挤在一起:只能整
39
+ * 目录授权。这是 Landlock 的能力边界,不是实现取舍 —— 只给 objects/refs/logs 加根级文件时,
40
+ * `git add` 第一个死在 `.git/index.lock` 上(实测)。
41
+ */
42
+ function gitWritablePaths(git: { gitDir: string; common: string }): string[] {
43
+ if (canonical(git.gitDir) === canonical(git.common)) return [git.gitDir];
44
+ const paths = [git.gitDir];
45
+ for (const name of ["objects", "refs", "logs"]) {
46
+ const abs = resolve(git.common, name);
47
+ // helper 会拒掉不存在的 spec 路径,所以这里先滤一遍。
48
+ if (existsSync(abs)) paths.push(abs);
49
+ }
50
+ return paths;
51
+ }
52
+
53
+ /**
54
+ * git 需要可写的两个目录:本次 checkout 的 gitdir,以及(linked worktree 时)主仓的
55
+ * 公共目录。索引与 ref 分别住在两处,所以两个都要问出来;具体授权哪几层见
56
+ * gitWritablePaths。
57
+ */
58
+ function gitDirs(cwd: string): { gitDir: string; common: string } | undefined {
59
+ const key = resolve(cwd);
60
+ if (gitDirsCache.has(key)) return gitDirsCache.get(key);
61
+ let found: { gitDir: string; common: string } | undefined;
62
+ try {
63
+ const out = execFileSync("git", ["rev-parse", "--absolute-git-dir", "--git-common-dir"], {
64
+ cwd: key,
65
+ encoding: "utf8",
66
+ stdio: ["ignore", "pipe", "ignore"],
67
+ timeout: 5000,
68
+ });
69
+ const [gitDirRaw, commonRaw] = out.trim().split("\n");
70
+ const gitDir = gitDirRaw?.trim();
71
+ const common = commonRaw ? resolve(key, commonRaw.trim()) : "";
72
+ if (gitDir && existsSync(gitDir)) {
73
+ found = { gitDir, common: common && existsSync(common) ? common : gitDir };
74
+ }
75
+ } catch {
76
+ found = undefined;
77
+ }
78
+ gitDirsCache.set(key, found);
79
+ return found;
80
+ }
81
+
82
+ /**
83
+ * 整棵子树写法 → 该子树根(相对路径,"" 表示 cwd)。`dir/**`、`**`,以及在 `dir/**`
84
+ * 后面再跟一层单层通配的写法都算;`dir/*.ts` 不算 —— 它只覆盖一部分,须按文件展开。
85
+ *
86
+ * 判据是「第一个通配符段起,剩下的段是否都是 `**`(可带一个收尾的单层 `*`)」:`**`
87
+ * 能吃任意层,所以 `**` 后面再跟一层单层通配仍然覆盖全部;而以单层通配开头只覆盖一层,
88
+ * 例如 `dir` 下一层的 `*` 摸不到子目录里的文件,两层倒过来的写法也摸不到 dir 的直接子文件。
89
+ */
90
+ function subtreeRoot(glob: string): string | undefined {
91
+ const segments = glob.split("/");
92
+ const first = segments.findIndex((segment) => /[*?]/.test(segment));
93
+ if (first === -1) return undefined;
94
+ const rest = segments.slice(first);
95
+ if (rest[0] !== "**" || rest.some((segment) => segment !== "**" && segment !== "*")) return undefined;
96
+ return segments.slice(0, first).join("/");
97
+ }
98
+
99
+ /** 展开文件级 glob 时的遍历上限:一条 glob 不该把大仓整个走一遍。 */
100
+ const GLOB_WALK_MAX_ENTRIES = 20000;
101
+
102
+ /**
103
+ * 文件级 glob 展开成实际存在的文件。
104
+ *
105
+ * spec.write 可以列文件,Landlock 对文件路径只授权那个 inode,所以 `src/auth/*.ts`
106
+ * 只打开它真正匹配到的文件,而不是整个 src/auth/。代价是「还没创建的新文件」不在
107
+ * 这里 —— 那需要一个目录级的 MAKE_REG,也就等于把整个目录打开。
108
+ *
109
+ * 走过的目录用 DETECT_SKIP 同一张跳过表:那是「依赖/产物不往里走」的判据,展开 glob
110
+ * 与探测清单是同一件事。软链指到树外的不收:Landlock 按目标 inode 授权,收了就等于
111
+ * 授权树外那个文件。
112
+ */
113
+ function expandFileGlob(cwd: string, glob: string): string[] {
114
+ const re = globToRegExp(glob);
115
+ const base = canonical(cwd);
116
+ const segments = glob.split("/");
117
+ const firstWild = segments.findIndex((segment) => /[*?]/.test(segment));
118
+ // 静态前缀:第一个通配符段之前的那些段。调用方只传带通配符的 glob,prefix 不会等于整条。
119
+ const prefix = firstWild === -1 ? "" : segments.slice(0, firstWild).join("/");
120
+ const found: string[] = [];
121
+ const stack = [resolve(cwd, prefix || ".")];
122
+ let seen = 0;
123
+ while (stack.length > 0) {
124
+ const dir = stack.pop() as string;
125
+ let entries: Dirent[];
126
+ try {
127
+ entries = readdirSync(dir, { withFileTypes: true });
128
+ } catch {
129
+ continue;
130
+ }
131
+ for (const entry of entries) {
132
+ seen += 1;
133
+ if (seen > GLOB_WALK_MAX_ENTRIES) return found.sort();
134
+ const abs = resolve(dir, entry.name);
135
+ const rel = insideTree(base, abs);
136
+ if (rel === undefined) continue;
137
+ if (entry.isDirectory()) {
138
+ if (!DETECT_SKIP.has(entry.name)) stack.push(abs);
139
+ } else if (entry.isFile() && (re.test(rel) || re.test(abs))) {
140
+ found.push(abs);
141
+ }
142
+ }
143
+ }
144
+ return found.sort();
145
+ }
146
+
147
+ /** Phase 3 output.deliverable: the real file in the main checkout, for write grants and refusals. */
148
+ let deliverableTargetPath: string | undefined;
149
+
150
+ /**
151
+ * wireDeliverable 登记交付物目标路径(state 在本层,因为唯一的读者是 sandboxWritableDirs)。
152
+ * index.ts 侧的赋值点全部走这一个入口,模块内可变状态只有这一份。
153
+ */
154
+ export function setDeliverableTargetPath(path: string | undefined): void {
155
+ deliverableTargetPath = path;
156
+ }
157
+
158
+ /**
159
+ * 写范围 → 沙箱可写路径。
160
+ *
161
+ * 只有覆盖整棵子树的写法(`dir`、`dir/**`)才授权目录本身:授权目录就是授权它下面
162
+ * 所有东西,而 Landlock 只能正向授权、无法从已授权的目录里再排除子目录,所以「目录
163
+ * 授权」必须恰好等于「这条 glob 覆盖到的范围」。文件级写法(`src/auth/*.ts`,以及通配符
164
+ * 在中间层的写法)因此展开成实际存在的文件 —— 旧做法是截到第一个通配符,于是
165
+ * `src/auth/*.ts` 把整个 src/auth/ 打开,中间层通配则把 src/ 整个打开。
166
+ */
167
+ function writablePaths(policy: Policy, cwd: string): string[] {
168
+ const paths = new Set<string>();
169
+ // 按写范围派生,不用读范围:bash 的可写面不该比 edit / write 更宽。
170
+ for (const raw of policy.writeGlobs) {
171
+ const glob = normalizeGlob(raw);
172
+ if (!glob) continue;
173
+ const root = subtreeRoot(glob);
174
+ if (root !== undefined) {
175
+ const abs = resolve(cwd, root || ".");
176
+ if (abs !== "/" && existsSync(abs)) paths.add(abs);
177
+ continue;
178
+ }
179
+ if (!/[*?]/.test(glob)) {
180
+ // 纯路径:是目录就授权整棵子树,是文件就授权该文件。
181
+ const abs = resolve(cwd, glob);
182
+ if (abs !== "/" && existsSync(abs)) paths.add(abs);
183
+ continue;
184
+ }
185
+ for (const file of expandFileGlob(cwd, glob)) paths.add(file);
186
+ }
187
+ return [...paths];
188
+ }
189
+
190
+ /**
191
+ * 产物目录:探测结果 + 显式追加。已存在的直接放行;探测到的主产物缺了就创建,
192
+ * 其余缺了不管(空目录本身没有意义);显式追加的缺了也创建 —— 那是父代理点名的。
193
+ */
194
+ function scratchDirs(cwd: string, rule: BashRule, options: { create: boolean }): string[] {
195
+ if (rule.scratchPaths === false) return [];
196
+ const dirs = new Set<string>();
197
+ const add = (abs: string, create: boolean) => {
198
+ if (existsSync(abs)) {
199
+ dirs.add(abs);
200
+ return;
201
+ }
202
+ // /permission 只报告「将要放行什么」:缺的也列出来,但不落盘。
203
+ if (!options.create) {
204
+ dirs.add(abs);
205
+ return;
206
+ }
207
+ // 建 spec 时:只有主产物和显式追加的才创建。创建失败就不放行 —— 把不存在的路径
208
+ // 写进 spec,helper 会拒绝整条命令,报错点离真正的原因太远。
209
+ if (!create) return;
210
+ try {
211
+ mkdirSync(abs, { recursive: true });
212
+ dirs.add(abs);
213
+ } catch {
214
+ // 只读树或权限不足:如实失败,别把它算成已授权。
215
+ }
216
+ };
217
+ for (const { dir, primary } of detectScratchDirs(cwd)) add(dir, primary);
218
+ for (const extra of rule.scratchPaths) add(resolve(cwd, extra), true);
219
+ return [...dirs];
220
+ }
221
+
222
+ /**
223
+ * 状态目录:spec 文件、`git-excludes` 与工具链缓存都放这里,默认 `~/.cache/pi-subagents-extend`。
224
+ *
225
+ * `PI_SUBAGENTS_EXTEND_STATE` 覆盖它,测试用它把套件的写入挪出真实 home。不给覆盖时改 HOME 也能达到
226
+ * 同样效果,但那太粗暴:CI 上的 cargo 是 rustup 的 shim,会去建 `$HOME/.rustup`,而包目录不在沙箱
227
+ * 写授权里,整条工具链用例就被 Landlock 拒掉。
228
+ */
229
+ export function stateDir(): string {
230
+ const override = process.env.PI_SUBAGENTS_EXTEND_STATE;
231
+ if (override) return resolve(override);
232
+ return resolve(homedir(), ".cache", "pi-subagents-extend");
233
+ }
234
+
235
+ /**
236
+ * 工具链缓存目录。放 ~/.cache 下持久保存:沙箱里的 /tmp 是每次调用私有的 tmpfs,
237
+ * 把 GOCACHE 放那里会让 `go test` 每次都全量重编译。
238
+ * 只设一条 XDG_CACHE_HOME,而不是逐个数 GOCACHE / MYPY_CACHE_DIR / RUFF_CACHE_DIR:
239
+ * 前者是约定(实测 go 的默认 cache 跟着它走),后者是一份要一直维护的工具名单。
240
+ */
241
+ let toolchainCacheDirMemo: string | undefined | null = null;
242
+
243
+ export function toolchainCacheDir(): string | undefined {
244
+ if (toolchainCacheDirMemo !== null) return toolchainCacheDirMemo;
245
+ let dir: string | undefined;
246
+ try {
247
+ dir = resolve(stateDir(), "xdg-cache");
248
+ mkdirSync(dir, { recursive: true });
249
+ } catch {
250
+ dir = undefined;
251
+ }
252
+ toolchainCacheDirMemo = dir;
253
+ return dir;
254
+ }
255
+
256
+ /**
257
+ * 沙箱里要绑成可写的路径集合:
258
+ * - 写范围覆盖到的路径(bash.writable 时):整棵子树的 glob 给目录,文件级 glob 给文件
259
+ * - git 真正要写的目录(见 gitWritablePaths):不给的话 add / commit / stash 全拼在 index.lock 上
260
+ * - `<cwd>/node_modules`:pnpm install 要写 .bin 里的 shim;worktree 里它是软链,给真实路径
261
+ * - 项目声明的产物目录 + 工具链缓存目录(XDG_CACHE_HOME)
262
+ * - bash.writablePaths 里的全局可写区(pnpm store、mise state 等;bash.writable 时)
263
+ *
264
+ * cwd 本身不在其中:整棵授权等于把整个 checkout 打开,读范围的宽窄不该自动变成写权限。
265
+ * 各项都以 bash.writable 为前提:false 是角色自己定下的上限,任何一层都不该把它放宽。
266
+ */
267
+ export function sandboxWritableDirs(
268
+ policy: Policy,
269
+ cwd: string,
270
+ rule: BashRule,
271
+ options: { create: boolean } = { create: true },
272
+ ): string[] {
273
+ const dirs = new Set<string>();
274
+ if (rule.writable) {
275
+ for (const dir of writablePaths(policy, cwd)) dirs.add(dir);
276
+ // git 的索引与 ref 必须可写,否则 add / commit / stash 全拼在 index.lock 上;但只给
277
+ // git 真正要写的部分,不因此把整个 checkout 打开。linked worktree 的索引在
278
+ // <common>/worktrees/<id> 里,ref 与对象在 common dir 的 refs / logs / objects 里,
279
+ // hooks 和 config 不在授权范围内。
280
+ const git = gitDirs(cwd);
281
+ if (git) {
282
+ for (const path of gitWritablePaths(git)) dirs.add(path);
283
+ }
284
+ // node_modules 也要可写:pnpm install 要写 .bin 里的 shim。它通常不在
285
+ // scope 里,但装依赖是任务的必要步骤。worktree 里它是符号链接,要给
286
+ // 解析后的真实路径:Landlock 规则落在 inode 上,符号链接自身不覆盖目标。
287
+ const nodeModules = resolve(cwd, "node_modules");
288
+ if (existsSync(nodeModules)) {
289
+ try {
290
+ dirs.add(realpathSync(nodeModules));
291
+ } catch {
292
+ dirs.add(nodeModules);
293
+ }
294
+ }
295
+ // 项目自己声明过的产物目录(git 忽略的):build/test 往这里写。
296
+ for (const dir of scratchDirs(cwd, rule, options)) dirs.add(dir);
297
+ const cache = toolchainCacheDir();
298
+ if (cache) dirs.add(cache);
299
+ for (const raw of rule.writablePaths) {
300
+ const abs = expandPath(cwd, raw);
301
+ if (abs && abs !== "/" && existsSync(abs)) dirs.add(abs);
302
+ }
303
+ // 交付物是文件级授权:只放真实文件,不打开它所在的目录。
304
+ if (deliverableTargetPath) dirs.add(deliverableTargetPath);
305
+ }
306
+ return [...dirs];
307
+ }
308
+
309
+ /**
310
+ * 沙箱里默认可写的设备。没有它们,`2>/dev/null` 这种写法会直接 EPERM。
311
+ */
312
+ export const SANDBOX_DEVICE_PATHS = [
313
+ "/dev/null",
314
+ "/dev/zero",
315
+ "/dev/full",
316
+ "/dev/random",
317
+ "/dev/urandom",
318
+ "/dev/tty",
319
+ "/dev/pts",
320
+ ];
321
+
322
+ /** 已提示过的被剔授权:每条命令一份 spec,不记下来就会每调一次重复提示一次。 */
323
+ export const reportedHiddenGrants = new Set<string>();
324
+
325
+ /**
326
+ * 把「授权落在私有 tmpfs 之下、已被剔掉」这件事告诉父代理一次。
327
+ *
328
+ * 不提示的话,子代理只会看到自己的写被 Landlock 拒掉,而真正的原因在配置里:那个目录每次调用都
329
+ * 被挂上一个空的 tmpfs。提示走 UI,不进模型上下文 —— 这是给父代理看的配置告警,不是给子代理的
330
+ * 行动指令(子代理那边已经有「拿报告代替写文件」的既定退路)。
331
+ */
332
+ export function reportHiddenGrants(dropped: string[], warn: ((message: string) => void) | undefined): void {
333
+ const fresh = dropped.filter((path) => !reportedHiddenGrants.has(path));
334
+ if (fresh.length === 0) return;
335
+ for (const path of fresh) reportedHiddenGrants.add(path);
336
+ warn?.(
337
+ `pi-subagents-extend: write grant(s) dropped: the sandbox mounts a private tmpfs over that path when it can, and a grant below a mount point is hidden inside it: ${fresh.join(", ")}. Write the file with the write tool, or point bash.env.TMPDIR outside /tmp.`
338
+ );
339
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * SANDBOX 层 · helper 模块:helper 二进制的定位(候选顺序)、能力探测(--describe)、
3
+ * 以及开场拦截文案(缺 helper / 内核 ABI 不足时 fail closed)。pnpm store 的探测与
4
+ * 描述也在这里:它是 /permission 与拒绝文案里「环境描述」的一部分,不参与授权推导。
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { existsSync } from "node:fs";
8
+ import { dirname, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ /** helper 的名字:找它、报它、文档里写它都用这一个常量。 */
12
+ const HELPER_NAME = "pi-subagents-extend-helper";
13
+
14
+ /**
15
+ * helper 候选路径。纯函数,便于直接钉住候选及其顺序:环境变量不是候选,
16
+ * 而是覆盖(设了但不存在就不往下找,否则「指错了」会静默用上另一个)。
17
+ *
18
+ * 包里只有一份按平台命名的二进制:helper 是 Linux 特有的(Landlock + userns),
19
+ * 而一个 npm 包同时带 x64 与 arm64 两份,靠文件名区分,安装后在自己的平台上找得到、
20
+ * 在别的平台上找不到也说得清。候选只有这一条;环境变量是覆盖(见 helperPath)。
21
+ */
22
+ export function helperCandidates(
23
+ here: string,
24
+ platform: string = process.platform,
25
+ arch: string = process.arch,
26
+ ): string[] {
27
+ return [resolve(here, "..", "bin", `${HELPER_NAME}-${platform}-${arch}`)];
28
+ }
29
+
30
+ export function helperPath(): string | undefined {
31
+ const fromEnv = process.env.PI_SUBAGENTS_EXTEND_HELPER_PATH?.trim();
32
+ if (fromEnv) return existsSync(fromEnv) ? fromEnv : undefined;
33
+ // 候选锚在包的 src/ 目录上;本文件在 src/sandbox/ 下,比拆分前深一层,向上补回。
34
+ const here = resolve(dirname(fileURLToPath(import.meta.url)), "..");
35
+ for (const candidate of helperCandidates(here)) {
36
+ if (existsSync(candidate)) return candidate;
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ /**
42
+ * bash 到底能不能跑。缺 helper 与内核对不上都是「每条命令都拒」,与其让子代理
43
+ * 撞墙几次再自己推断,不如开场就把它说出来。
44
+ */
45
+ export function bashBlocker(helper: string | undefined): string | undefined {
46
+ if (!helper) {
47
+ const platform = `${process.platform}-${process.arch}`;
48
+ return (
49
+ `no sandbox helper found for ${platform}, so every bash command will be refused. ` +
50
+ `The package carries bin/${HELPER_NAME}-<platform>-<arch> (the helper needs Landlock and ` +
51
+ "user namespaces, so it is Linux-only); set PI_SUBAGENTS_EXTEND_HELPER_PATH to use a binary you built yourself."
52
+ );
53
+ }
54
+ const caps = describeHelper(helper);
55
+ if (!caps?.landlock.supported) {
56
+ const reason = caps?.landlock.reason ?? "helper --describe returned nothing usable";
57
+ return `this kernel cannot enforce the sandbox (${reason}), so every bash command will be refused`;
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ /**
63
+ * 探测 pnpm 的 store 路径(只探测,不自动放行)。路径随 cwd 变,必须用子代理的
64
+ * cwd 跑。探测失败不影响其他功能,只是这一行显示不出来。
65
+ */
66
+ const pnpmStoreCache = new Map<string, { path?: string; error?: string }>();
67
+
68
+ export function detectPnpmStore(cwd: string): { path?: string; error?: string } {
69
+ const cached = pnpmStoreCache.get(cwd);
70
+ if (cached) return cached;
71
+ const found = probePnpmStore(cwd);
72
+ pnpmStoreCache.set(cwd, found);
73
+ return found;
74
+ }
75
+
76
+ function probePnpmStore(cwd: string): { path?: string; error?: string } {
77
+ try {
78
+ const out = execFileSync("pnpm", ["store", "path"], {
79
+ cwd,
80
+ encoding: "utf8",
81
+ timeout: 2000,
82
+ stdio: ["ignore", "pipe", "ignore"],
83
+ });
84
+ const line = out
85
+ .split("\n")
86
+ .map((l) => l.trim())
87
+ .filter(Boolean)
88
+ .pop();
89
+ return line ? { path: line } : { error: "pnpm store path printed nothing" };
90
+ } catch (error) {
91
+ return { error: error instanceof Error ? error.message : String(error) };
92
+ }
93
+ }
94
+
95
+ /** /permission 里显示 pnpm store:探测到的路径 + 一句「未放行」的提示。 */
96
+ export function describePnpmStore(cwd: string): string {
97
+ const found = detectPnpmStore(cwd);
98
+ if (found.path) return `${found.path} (not writable; add it to bash.writablePaths if the subagent must install dependencies)`;
99
+ return `detection failed (${found.error ?? "unknown cause"})`;
100
+ }
101
+
102
+ /**
103
+ * helper 的能力探测结果:`--describe` 只读,每个进程查一次。
104
+ */
105
+ export type HelperCapabilities = {
106
+ landlock: { kernel_abi: number; required_abi: number; supported: boolean; reason?: string | null };
107
+ network_namespace: boolean;
108
+ resolver_sockets: string[];
109
+ };
110
+
111
+ const helperCache = new Map<string, HelperCapabilities | undefined>();
112
+
113
+ /** 问 helper 能做到什么程度;拿不到就返回 undefined,调用方按不可用处理。 */
114
+ export function describeHelper(helper: string): HelperCapabilities | undefined {
115
+ if (helperCache.has(helper)) return helperCache.get(helper);
116
+ let caps: HelperCapabilities | undefined;
117
+ try {
118
+ // ABI 不够时 --describe 也会输出 JSON,只是退出码非 0;所以按输出解析。
119
+ const out = execFileSync(helper, ["--describe"], {
120
+ encoding: "utf8",
121
+ timeout: 5000,
122
+ stdio: ["ignore", "pipe", "ignore"],
123
+ });
124
+ caps = JSON.parse(out) as HelperCapabilities;
125
+ } catch (error) {
126
+ const stdout = (error as { stdout?: unknown })?.stdout;
127
+ if (typeof stdout === "string" && stdout.trim()) {
128
+ try {
129
+ caps = JSON.parse(stdout) as HelperCapabilities;
130
+ } catch {
131
+ caps = undefined;
132
+ }
133
+ }
134
+ }
135
+ helperCache.set(helper, caps);
136
+ return caps;
137
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * SANDBOX 层 · barrel:bash 沙箱按主题拆成三个模块,这里原样转出全部既有公开面,
3
+ * 调用方(index.ts、wiring/*)的 import 不变:
4
+ * - helper.ts:helper 定位与能力探测(--describe)、缺 helper / ABI 不足的开场拦截、pnpm store 描述
5
+ * - grants.ts:可写路径推导(写范围、git、产物目录、工具链缓存、交付物)与被剔授权上报
6
+ * - spec.ts:spec 的构建与落盘(生命周期)、沙箱内环境变量、命令包装
7
+ * 各模块除 memo(gitDirsCache、pnpmStoreCache、helperCache、toolchainCacheDirMemo、specSeq,
8
+ * 语义上仍是纯推导)外不持有会话状态;index.ts 只做接线。
9
+ */
10
+ export { bashBlocker, describeHelper, describePnpmStore, detectPnpmStore, helperCandidates, helperPath, type HelperCapabilities } from "./helper.ts";
11
+ export { reportHiddenGrants, reportedHiddenGrants, SANDBOX_DEVICE_PATHS, sandboxWritableDirs, setDeliverableTargetPath, stateDir, toolchainCacheDir } from "./grants.ts";
12
+ export { buildSpec, dropSpecFile, scratchDir, sweepStaleSpecFiles, wrapInSandbox, writeSpecFile } from "./spec.ts";