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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
- package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
- package/package.json +63 -4
- package/skills/pi-subagents-extend/SKILL.md +312 -0
- package/skills/pi-subagents-extend-context/SKILL.md +103 -0
- package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
- package/src/bash/env.ts +108 -0
- package/src/bash/index.ts +27 -0
- package/src/bash/network.ts +97 -0
- package/src/bash/programs.ts +367 -0
- package/src/bash/rules.ts +247 -0
- package/src/bash/tokens.ts +169 -0
- package/src/bash/unreachable.ts +429 -0
- package/src/budgets.ts +89 -0
- package/src/child-context.ts +24 -0
- package/src/context-scope.ts +93 -0
- package/src/deliverable.ts +216 -0
- package/src/dependencies.ts +320 -0
- package/src/handoff-hint.ts +69 -0
- package/src/index.ts +181 -0
- package/src/main-context.ts +30 -0
- package/src/main-skills.ts +77 -0
- package/src/notices.ts +299 -0
- package/src/paths/index.ts +165 -0
- package/src/policy/glob.ts +146 -0
- package/src/policy/index.ts +36 -0
- package/src/policy/payload.ts +312 -0
- package/src/probe.ts +495 -0
- package/src/role-config.ts +434 -0
- package/src/sandbox/grants.ts +339 -0
- package/src/sandbox/helper.ts +137 -0
- package/src/sandbox/index.ts +12 -0
- package/src/sandbox/spec.ts +285 -0
- package/src/sandbox-note.ts +194 -0
- package/src/wiring/agent-start.ts +371 -0
- package/src/wiring/context.ts +216 -0
- package/src/wiring/misc.ts +55 -0
- package/src/wiring/session-start.ts +69 -0
- package/src/wiring/tool-call/anchor.ts +138 -0
- package/src/wiring/tool-call/bash-path.ts +0 -0
- package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
- package/src/wiring/tool-call/judge.ts +585 -0
- package/src/wiring/tool-call/original-args.ts +64 -0
- package/src/wiring/tool-call/paths.ts +235 -0
- package/src/wiring/tool-result.ts +68 -0
- package/src/worktree-default.ts +27 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 子代理侧入口:只由 agent 定义的 `subagentOnlyExtensions` 声明,所以它一旦运行就
|
|
3
|
+
* 说明当前会话是子代理——不需要判断环境变量,前台子代理(同进程、没有
|
|
4
|
+
* PI_SUBAGENT_CHILD)也覆盖得到。
|
|
5
|
+
*
|
|
6
|
+
* 作用只有一件:把 AGENTS.md 里 `<!-- main-agent-only:start -->` … `<!-- main-agent-only:end -->` 圈出的
|
|
7
|
+
* 段落从本轮提示词里删掉。其余内容不动。
|
|
8
|
+
*
|
|
9
|
+
* agent 定义里和权限入口一起声明:
|
|
10
|
+
*
|
|
11
|
+
* subagentOnlyExtensions: ~/extensions/pi-subagents-extend/packages/pi-plugin/src/index.ts, ~/extensions/pi-subagents-extend/packages/pi-plugin/src/child-context.ts
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { stripMarkedSections, unbalancedWarning } from "./context-scope.ts";
|
|
16
|
+
|
|
17
|
+
export default function (pi: ExtensionAPI) {
|
|
18
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
19
|
+
const options = event.systemPromptOptions;
|
|
20
|
+
if (!options) return;
|
|
21
|
+
const warning = unbalancedWarning(stripMarkedSections(options.contextFiles));
|
|
22
|
+
if (warning) ctx.ui?.notify?.(`pi-subagents-extend: ${warning}`, "warning");
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 上下文隔离:把「只给主代理看」的内容挡在子代理之外。
|
|
3
|
+
*
|
|
4
|
+
* 两个方向,都由项目自己的文件驱动,不引入新配置项:
|
|
5
|
+
*
|
|
6
|
+
* - AGENTS.md 里用 `<!-- main-agent-only:start -->` … `<!-- main-agent-only:end -->` 圈出的段落,在子代理
|
|
7
|
+
* 的提示词里被删掉;主代理照常读整份文件。
|
|
8
|
+
* - `.pi/main-only.md` 只注入主代理的提示词,不进子代理。
|
|
9
|
+
*
|
|
10
|
+
* 哪一半生效取决于扩展「怎么被加载」,而不是它「猜自己是谁」:前台子代理没有
|
|
11
|
+
* PI_SUBAGENT_CHILD 环境变量,和主会话无法区分。所以两个入口各管一半——
|
|
12
|
+
* `main-context.ts` 走环境加载(主会话 + 后台子代理),`child-context.ts` 由 agent
|
|
13
|
+
* 的 subagentOnlyExtensions 声明(只会进子代理)。
|
|
14
|
+
*
|
|
15
|
+
* 判据是 pi 的 systemPromptOptions.contextFiles(每项 { path, content }),在
|
|
16
|
+
* before_agent_start 里改完再渲染,所以改 content 会真正影响本轮提示词。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readFileSync } from "node:fs";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
|
|
22
|
+
/** pi 传给 before_agent_start 的一份上下文文件。 */
|
|
23
|
+
export type ContextFile = { path: string; content: string };
|
|
24
|
+
|
|
25
|
+
/** 只注入主代理的文件,相对项目根。 */
|
|
26
|
+
export const MAIN_ONLY_FILE = ".pi/main-only.md";
|
|
27
|
+
|
|
28
|
+
/** 注入用的 section 名,同时是包住这段文字的 XML 标签。 */
|
|
29
|
+
const SECTION_TAG = "main_only_instructions";
|
|
30
|
+
|
|
31
|
+
/** 成对的标记块;整段连同前后空行一起删。 */
|
|
32
|
+
const MARKED_BLOCK = /<!--\s*main-agent-only:start\s*-->[\s\S]*?<!--\s*main-agent-only:end\s*-->\s*/g;
|
|
33
|
+
|
|
34
|
+
/** 剥完之后还剩标记,说明有一侧没闭合。 */
|
|
35
|
+
const ANY_MARKER = /<!--\s*\/?\s*main-agent-only:(start|end)\s*-->/i;
|
|
36
|
+
|
|
37
|
+
export type StripResult = {
|
|
38
|
+
/** 真正被改动过的文件数。 */
|
|
39
|
+
files: number;
|
|
40
|
+
/** 删掉的字符数,用来在测试和日志里确认删了东西。 */
|
|
41
|
+
removedChars: number;
|
|
42
|
+
/** 标记不闭合、因而没有被剥离的文件。 */
|
|
43
|
+
unbalanced: string[];
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 就地把标记段落从上下文文件里删掉。
|
|
48
|
+
*
|
|
49
|
+
* 标记不闭合时整段保留:宁可让子代理多看见一段,也不要因为它猜错边界而删掉
|
|
50
|
+
* 半个文件。
|
|
51
|
+
*/
|
|
52
|
+
export function stripMarkedSections(files: ContextFile[] | undefined): StripResult {
|
|
53
|
+
const result: StripResult = { files: 0, removedChars: 0, unbalanced: [] };
|
|
54
|
+
for (const file of files ?? []) {
|
|
55
|
+
const before = file.content.length;
|
|
56
|
+
file.content = file.content.replace(MARKED_BLOCK, "");
|
|
57
|
+
const changed = file.content.length !== before;
|
|
58
|
+
if (changed) {
|
|
59
|
+
result.files += 1;
|
|
60
|
+
result.removedChars += before - file.content.length;
|
|
61
|
+
}
|
|
62
|
+
if (ANY_MARKER.test(file.content)) result.unbalanced.push(file.path);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 把项目的主代理专属文件注入提示词,返回注入的字符数(0 表示没有这个文件)。
|
|
69
|
+
*
|
|
70
|
+
* 用 sections 而不是整段替换 systemPrompt:pi 会按 section 做差量,改动只补一条
|
|
71
|
+
* 系统消息,前面的提示词缓存仍然命中。
|
|
72
|
+
*/
|
|
73
|
+
export function injectMainOnly(options: { sections?: Record<string, string> }, cwd: string | undefined): number {
|
|
74
|
+
const path = join(cwd ?? process.cwd(), MAIN_ONLY_FILE);
|
|
75
|
+
let text: string;
|
|
76
|
+
try {
|
|
77
|
+
text = readFileSync(path, "utf8").trim();
|
|
78
|
+
} catch {
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
if (!text) return 0;
|
|
82
|
+
options.sections = { ...(options.sections ?? {}), [SECTION_TAG]: text };
|
|
83
|
+
return text.length;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 标记不闭合时给调用方一句人话(子代理和主代理的可见通道不同,由入口决定怎么报)。
|
|
88
|
+
* 返回 undefined 表示不该报。
|
|
89
|
+
*/
|
|
90
|
+
export function unbalancedWarning(result: StripResult): string | undefined {
|
|
91
|
+
if (!result.unbalanced.length) return undefined;
|
|
92
|
+
return `unclosed <!-- main-agent-only:start --> in ${result.unbalanced.join(", ")} — the section was kept`;
|
|
93
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 子工作树里的交付物:真实文件落在主仓库,子工作树侧只放一个指过去的符号链接。
|
|
3
|
+
* 主仓库锚点按四级依次尝试;都没有证据时退回会话 cwd,cwd 本身不可用才报 null。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, statSync, symlinkSync } from "node:fs";
|
|
8
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
9
|
+
|
|
10
|
+
export type MainRepoAnchor =
|
|
11
|
+
| { root: string; via: "common-dir" | "gitfile" | "worktree-list" | "cwd" }
|
|
12
|
+
| { root: null; tried: string[] };
|
|
13
|
+
|
|
14
|
+
/** 四级锚点,按这个顺序试;四级都失败时不猜。 */
|
|
15
|
+
export function mainRepoRoot(cwd: string): MainRepoAnchor {
|
|
16
|
+
const start = resolve(cwd);
|
|
17
|
+
const tried: string[] = [];
|
|
18
|
+
if (!isDirectory(start)) return { root: null, tried: [`${start}: not a directory`] };
|
|
19
|
+
|
|
20
|
+
const gitDir = gitDirFromFile(start, tried);
|
|
21
|
+
if (gitDir) {
|
|
22
|
+
// 链接工作树:<main>/.git/worktrees/<name>/commondir 指回 <main>/.git。
|
|
23
|
+
const commonFile = join(gitDir, "commondir");
|
|
24
|
+
if (existsSync(commonFile)) {
|
|
25
|
+
try {
|
|
26
|
+
const common = readFileSync(commonFile, "utf8").trim();
|
|
27
|
+
if (!common) tried.push(`${commonFile}: empty commondir`);
|
|
28
|
+
else {
|
|
29
|
+
const root = dirname(resolve(gitDir, common));
|
|
30
|
+
if (isDirectory(root)) return { root, via: "common-dir" };
|
|
31
|
+
tried.push(`${root}: commondir target is not a directory`);
|
|
32
|
+
}
|
|
33
|
+
} catch (error) {
|
|
34
|
+
tried.push(`${commonFile}: ${errorText(error)}`);
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
tried.push(`${commonFile}: missing`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 普通 gitfile(submodule / --separate-git-dir):gitdir 本身就是仓库的 .git。
|
|
41
|
+
if (existsSync(join(gitDir, "HEAD"))) return { root: dirname(gitDir), via: "gitfile" };
|
|
42
|
+
tried.push(`${gitDir}: no HEAD, not a standalone gitdir`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 在链接工作树的子目录里,cwd 没有 .git,但 git 自己知道主工作树在哪。
|
|
46
|
+
try {
|
|
47
|
+
const output = execFileSync("git", ["worktree", "list", "--porcelain"], {
|
|
48
|
+
cwd: start,
|
|
49
|
+
encoding: "utf8",
|
|
50
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
51
|
+
timeout: 5000,
|
|
52
|
+
});
|
|
53
|
+
const entries = output.split(/\r?\n/).filter((entry) => entry.startsWith("worktree "));
|
|
54
|
+
if (entries.length === 0) {
|
|
55
|
+
tried.push("git worktree list --porcelain: no worktree entry");
|
|
56
|
+
} else {
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
const candidate = entry.slice("worktree ".length).trim();
|
|
59
|
+
if (!candidate) continue;
|
|
60
|
+
const root = resolve(candidate);
|
|
61
|
+
// 只有主检出才有 .git 目录;链接工作树的 .git 是文件,不能当锚点。
|
|
62
|
+
if (!isDirectory(join(root, ".git"))) {
|
|
63
|
+
tried.push(`${root}: git worktree list entry is not the main checkout (no .git directory)`);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (isDirectory(root)) return { root, via: "worktree-list" };
|
|
67
|
+
tried.push(`${root}: git worktree list target is not a directory`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
} catch (error) {
|
|
71
|
+
tried.push(`git worktree list --porcelain: ${errorText(error)}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 没有 git 证据就是没有工作树:主仓库与当前目录同一处。
|
|
75
|
+
return { root: start, via: "cwd" };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const isDirectory = (path: string): boolean => {
|
|
79
|
+
try {
|
|
80
|
+
return statSync(path).isDirectory();
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const errorText = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
87
|
+
|
|
88
|
+
/** 读 cwd 的 .git 文件里的 gitdir;.git 是目录或读不出来时返回 undefined。 */
|
|
89
|
+
const gitDirFromFile = (cwd: string, tried: string[]): string | undefined => {
|
|
90
|
+
const dotGit = join(cwd, ".git");
|
|
91
|
+
if (isDirectory(dotGit)) {
|
|
92
|
+
tried.push(`${dotGit}: a directory, not a gitfile`);
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
let text: string;
|
|
96
|
+
try {
|
|
97
|
+
text = readFileSync(dotGit, "utf8");
|
|
98
|
+
} catch (error) {
|
|
99
|
+
tried.push(`${dotGit}: ${errorText(error)}`);
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
const match = /^gitdir:\s*(.+?)\s*$/m.exec(text);
|
|
103
|
+
if (!match?.[1]) {
|
|
104
|
+
tried.push(`${dotGit}: no gitdir entry`);
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
return resolve(cwd, match[1]);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const isSafeDeliverable = (deliverable: string): boolean =>
|
|
111
|
+
deliverable.length > 0 &&
|
|
112
|
+
!isAbsolute(deliverable) &&
|
|
113
|
+
!/^[a-zA-Z]:[\\/]/.test(deliverable) &&
|
|
114
|
+
!deliverable.split(/[\\/]/).includes("..") &&
|
|
115
|
+
!deliverable.includes("\0");
|
|
116
|
+
|
|
117
|
+
/** 配置里的交付物必须是工作树之内的相对路径。 */
|
|
118
|
+
const assertSafeDeliverable = (deliverable: string): void => {
|
|
119
|
+
if (!isSafeDeliverable(deliverable)) {
|
|
120
|
+
throw new Error(`invalid deliverable "${deliverable}": expected a relative path inside the worktree`);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
export type LinkResult =
|
|
125
|
+
| { action: "none"; reason: "same-directory"; linkPath: string; targetPath: string }
|
|
126
|
+
| { action: "created" | "reused"; linkPath: string; targetPath: string }
|
|
127
|
+
| { action: "retargeted"; linkPath: string; targetPath: string; warning: string }
|
|
128
|
+
| { action: "skipped"; linkPath: string; targetPath: string; reason: "real-file" | "link-failed"; warning: string };
|
|
129
|
+
|
|
130
|
+
/** Point <childCwd>/<deliverable> at <mainRoot>/<deliverable>, creating the parent dir on the main side. */
|
|
131
|
+
export function ensureDeliverableLink(childCwd: string, mainRoot: string, deliverable: string): LinkResult {
|
|
132
|
+
assertSafeDeliverable(deliverable);
|
|
133
|
+
const child = resolve(childCwd);
|
|
134
|
+
const main = resolve(mainRoot);
|
|
135
|
+
const targetPath = deliverableTarget(main, deliverable);
|
|
136
|
+
const linkPath = resolve(child, deliverable);
|
|
137
|
+
const skipped = (reason: "real-file" | "link-failed", warning: string, at = linkPath): LinkResult =>
|
|
138
|
+
({ action: "skipped", linkPath: at, targetPath, reason, warning });
|
|
139
|
+
|
|
140
|
+
if (child === main) return { action: "none", reason: "same-directory", linkPath, targetPath };
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
mkdirSync(dirname(targetPath), { recursive: true });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return skipped("link-failed", `unable to create ${dirname(targetPath)}: ${errorText(error)}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let existing: ReturnType<typeof lstatSync> | undefined;
|
|
149
|
+
try {
|
|
150
|
+
existing = lstatSync(linkPath);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (!existsSync(linkPath)) {
|
|
153
|
+
// ENOENT 是正常的新建路径;其它错误落到下面的 link-failed。
|
|
154
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
155
|
+
return skipped("link-failed", `unable to inspect ${linkPath}: ${errorText(error)}`);
|
|
156
|
+
}
|
|
157
|
+
} else {
|
|
158
|
+
return skipped("link-failed", `unable to inspect ${linkPath}: ${errorText(error)}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (existing?.isSymbolicLink()) {
|
|
163
|
+
let current: string;
|
|
164
|
+
try {
|
|
165
|
+
current = resolve(dirname(linkPath), readlinkSync(linkPath));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
return skipped("link-failed", `unable to read link ${linkPath}: ${errorText(error)}`);
|
|
168
|
+
}
|
|
169
|
+
if (current === targetPath) return { action: "reused", linkPath, targetPath };
|
|
170
|
+
|
|
171
|
+
const newPath = `${linkPath}.new`;
|
|
172
|
+
if (existsSync(newPath) || isSymlink(newPath)) {
|
|
173
|
+
return {
|
|
174
|
+
action: "retargeted",
|
|
175
|
+
linkPath: newPath,
|
|
176
|
+
targetPath,
|
|
177
|
+
warning: `${linkPath} points to ${current}; ${newPath} already exists and was left untouched`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
symlinkSync(targetPath, newPath, "file");
|
|
182
|
+
} catch (error) {
|
|
183
|
+
return skipped("link-failed", `unable to link ${newPath}: ${errorText(error)}`, newPath);
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
action: "retargeted",
|
|
187
|
+
linkPath: newPath,
|
|
188
|
+
targetPath,
|
|
189
|
+
warning: `${linkPath} points to ${current}; left it untouched and wrote ${newPath} instead`,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (existing) return skipped("real-file", `${linkPath} is a real file; left it untouched`);
|
|
194
|
+
|
|
195
|
+
try {
|
|
196
|
+
mkdirSync(dirname(linkPath), { recursive: true });
|
|
197
|
+
symlinkSync(targetPath, linkPath, "file");
|
|
198
|
+
} catch (error) {
|
|
199
|
+
return skipped("link-failed", `unable to link ${linkPath}: ${errorText(error)}`);
|
|
200
|
+
}
|
|
201
|
+
return { action: "created", linkPath, targetPath };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const isSymlink = (path: string): boolean => {
|
|
205
|
+
try {
|
|
206
|
+
return lstatSync(path).isSymbolicLink();
|
|
207
|
+
} catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
/** Absolute path of the real file, for the parent's write grant and for printing. */
|
|
213
|
+
export function deliverableTarget(mainRoot: string, deliverable: string): string {
|
|
214
|
+
assertSafeDeliverable(deliverable);
|
|
215
|
+
return resolve(mainRoot, deliverable);
|
|
216
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DEPENDENCY-ENVIRONMENT 层:依赖环境探测与闸门 —— 工具链产物目录探测(scratch dirs)、
|
|
3
|
+
* lockfile / 安装凭据检查、依赖闸门(dependency gate)的命令归类与最终判定。
|
|
4
|
+
* 除 `scratchDirsCache`(探测结果按 cwd 的 memo,语义上仍是纯函数)外不持有会话状态;
|
|
5
|
+
* index.ts 只做接线。
|
|
6
|
+
* 模块拆分第三步:以下声明从 index.ts 原样搬出,行为不变。
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readdirSync, type Dirent } from "node:fs";
|
|
9
|
+
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
10
|
+
/**
|
|
11
|
+
* 工具链 → 项目里会出现的产物目录。判据是仓库根(及其一层子目录,覆盖 monorepo 的
|
|
12
|
+
* packages/*)里的清单文件:有 Cargo.toml 就是 Rust 项目,有 package.json 就是 Node 项目。
|
|
13
|
+
* 只读文件,不 spawn 进程,也不猜「这个目录现在存不存在」。
|
|
14
|
+
*
|
|
15
|
+
* dirs 里的目录:存在就放行,不存在就不管(空目录没有意义,凭空造一堆更吵)。
|
|
16
|
+
* primary 里的目录:属于该工具链的主产物,缺了就创建 —— `cargo test` 一定会写 target/,
|
|
17
|
+
* 不放行也不创建的话,命令第一次跑就是 Permission denied。
|
|
18
|
+
*/
|
|
19
|
+
const TOOLCHAINS: { markers: string[]; dirs: string[]; primary: string[] }[] = [
|
|
20
|
+
{
|
|
21
|
+
markers: ["package.json"],
|
|
22
|
+
dirs: ["coverage", "dist", "build", ".next", ".nuxt", ".output", ".svelte-kit", ".turbo", ".vite", ".parcel-cache", ".cache", ".angular"],
|
|
23
|
+
primary: [],
|
|
24
|
+
},
|
|
25
|
+
{ markers: ["Cargo.toml"], dirs: ["target"], primary: ["target"] },
|
|
26
|
+
{
|
|
27
|
+
markers: ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"],
|
|
28
|
+
dirs: ["__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".venv"],
|
|
29
|
+
primary: ["__pycache__"],
|
|
30
|
+
},
|
|
31
|
+
{ markers: ["go.mod"], dirs: ["bin"], primary: [] },
|
|
32
|
+
{ markers: ["pom.xml"], dirs: ["target"], primary: ["target"] },
|
|
33
|
+
{ markers: ["build.gradle", "build.gradle.kts"], dirs: ["build", ".gradle"], primary: ["build"] },
|
|
34
|
+
{ markers: ["mix.exs"], dirs: ["_build", "deps"], primary: ["_build"] },
|
|
35
|
+
{ markers: ["pubspec.yaml"], dirs: [".dart_tool", "build"], primary: [".dart_tool"] },
|
|
36
|
+
{ markers: ["Gemfile"], dirs: ["tmp", "log", ".bundle"], primary: [] },
|
|
37
|
+
{ markers: ["Package.swift"], dirs: [".build"], primary: [".build"] },
|
|
38
|
+
{ markers: ["build.zig"], dirs: ["zig-out", "zig-cache", ".zig-cache"], primary: ["zig-out", "zig-cache"] },
|
|
39
|
+
{ markers: ["stack.yaml", "cabal.project"], dirs: ["dist-newstyle", ".stack-work"], primary: ["dist-newstyle"] },
|
|
40
|
+
{ markers: ["CMakeLists.txt"], dirs: ["build"], primary: ["build"] },
|
|
41
|
+
{ markers: ["*.csproj", "*.sln"], dirs: ["obj", "bin"], primary: [] },
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 清单也往子目录里找两层(`packages/web/package.json` 这种 monorepo 布局),
|
|
46
|
+
* 但不开销太大:跳过明显的产物/依赖目录,并给总量封顶。
|
|
47
|
+
*/
|
|
48
|
+
export const DETECT_SKIP = new Set(["node_modules", ".git", "dist", "build", "target", ".venv", "vendor", "__pycache__", "bin", "obj"]);
|
|
49
|
+
const DETECT_MAX_ROOTS = 200;
|
|
50
|
+
|
|
51
|
+
const scratchDirsCache = new Map<string, { dir: string; primary: boolean }[]>();
|
|
52
|
+
|
|
53
|
+
/** 探测结果按 cwd 缓存:bash 白名单命令会反复拼 spec。 */
|
|
54
|
+
/**
|
|
55
|
+
* 按名字排序(纯函数,供 `sortedEntries` 与测试使用)。用字典序而不是 localeCompare:
|
|
56
|
+
* 后者的结果依赖运行时的 locale,那正好是排序要消除的那类不确定性。
|
|
57
|
+
*/
|
|
58
|
+
export function sortByName<T extends { name: string }>(entries: T[]): T[] {
|
|
59
|
+
return entries.sort((a, b) => {
|
|
60
|
+
if (a.name === b.name) return 0;
|
|
61
|
+
return a.name < b.name ? -1 : 1;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 目录项按名字排序后返回;读不了就当作空目录。
|
|
67
|
+
*
|
|
68
|
+
* readdir 的顺序由文件系统决定:这台机器上 tmpfs 给的是排序结果,而 ext4 的 dir_index、
|
|
69
|
+
* XFS、NFS 给的是哈希序。扫描有 DETECT_MAX_ROOTS 的名额上限,顺序不定就意味着
|
|
70
|
+
* 「哪些目录被检查、被授权」随机器而变 —— 闸门可能在一台机器上放行、在另一台上拒绝。
|
|
71
|
+
* 排序把这个不确定性按死。
|
|
72
|
+
*/
|
|
73
|
+
export function sortedEntries(dir: string): Dirent[] {
|
|
74
|
+
try {
|
|
75
|
+
return sortByName(readdirSync(dir, { withFileTypes: true }));
|
|
76
|
+
} catch {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function detectScratchDirs(cwd: string): { dir: string; primary: boolean }[] {
|
|
82
|
+
const key = resolve(cwd);
|
|
83
|
+
const cached = scratchDirsCache.get(key);
|
|
84
|
+
if (cached) return cached;
|
|
85
|
+
|
|
86
|
+
const found: { dir: string; primary: boolean }[] = [];
|
|
87
|
+
const roots = [key];
|
|
88
|
+
// 广度优先往下两层,遇到产物/依赖目录不再深入。
|
|
89
|
+
let frontier = [key];
|
|
90
|
+
for (let depth = 0; depth < 2 && roots.length < DETECT_MAX_ROOTS; depth += 1) {
|
|
91
|
+
const next: string[] = [];
|
|
92
|
+
for (const dir of frontier) {
|
|
93
|
+
for (const entry of sortedEntries(dir)) {
|
|
94
|
+
if (!entry.isDirectory() || DETECT_SKIP.has(entry.name) || entry.name.startsWith(".")) continue;
|
|
95
|
+
const child = resolve(dir, entry.name);
|
|
96
|
+
roots.push(child);
|
|
97
|
+
next.push(child);
|
|
98
|
+
if (roots.length >= DETECT_MAX_ROOTS) break;
|
|
99
|
+
}
|
|
100
|
+
if (roots.length >= DETECT_MAX_ROOTS) break;
|
|
101
|
+
}
|
|
102
|
+
frontier = next;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const root of roots) {
|
|
106
|
+
let entries: string[] = [];
|
|
107
|
+
try {
|
|
108
|
+
entries = readdirSync(root);
|
|
109
|
+
} catch {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
for (const toolchain of TOOLCHAINS) {
|
|
113
|
+
const matched = toolchain.markers.some((marker) =>
|
|
114
|
+
marker.startsWith("*.")
|
|
115
|
+
? entries.some((name) => name.endsWith(marker.slice(1)))
|
|
116
|
+
: entries.includes(marker),
|
|
117
|
+
);
|
|
118
|
+
if (!matched) continue;
|
|
119
|
+
for (const name of toolchain.dirs) {
|
|
120
|
+
found.push({ dir: resolve(root, name), primary: toolchain.primary.includes(name) });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
scratchDirsCache.set(key, found);
|
|
126
|
+
return found;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 有依赖的项目以 lockfile 为准(只有 package.json 不算:那可能只是个配置包)。
|
|
131
|
+
* 判据:有 lockfile 的目录必须出现过安装结果 —— `node_modules/.bin`,或 Yarn PnP 的 `.pnp.cjs`。
|
|
132
|
+
*/
|
|
133
|
+
const LOCKFILES = new Set([
|
|
134
|
+
"pnpm-lock.yaml",
|
|
135
|
+
"package-lock.json",
|
|
136
|
+
"npm-shrinkwrap.json",
|
|
137
|
+
"yarn.lock",
|
|
138
|
+
"bun.lockb",
|
|
139
|
+
"bun.lock",
|
|
140
|
+
]);
|
|
141
|
+
|
|
142
|
+
/** Yarn 2+ 的 PnP 不建 node_modules,`.pnp.cjs` 才是「装好了」的凭据。 */
|
|
143
|
+
const PNP_MARKERS = [".pnp.cjs", ".pnp.js"];
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 依赖根:cwd 往下两层里有 lockfile 的目录。`ignored` 里的前缀不参与。
|
|
147
|
+
*
|
|
148
|
+
* 不缓存。会话中途 `git checkout` 一个新增了包的分支是很常见的动作,而闸门的 `git` 豁免
|
|
149
|
+
* 恰好让这个动作畅通无阻 —— 缓存会让闸门停在旧结论上。这个扫描只在闸门真正生效时跑,
|
|
150
|
+
* 代价是几个 readdir。
|
|
151
|
+
*/
|
|
152
|
+
function dependencyRoots(cwd: string, ignored: string[]): string[] {
|
|
153
|
+
return dependencyScope(cwd, ignored).filter(hasLockfile);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 要查的目录:cwd 与它往下两层的子目录(跳过依赖/产物目录与被忽略的目录)。
|
|
158
|
+
*
|
|
159
|
+
* 被忽略的目录在遍历时就剪掉,而不是收集完再筛:一棵 fixtures 树能占满
|
|
160
|
+
* DETECT_MAX_ROOTS 的名额,把真包挤出扫描范围,闸门于是无声失效。
|
|
161
|
+
*/
|
|
162
|
+
export function dependencyScope(cwd: string, ignored: string[]): string[] {
|
|
163
|
+
const key = resolve(cwd);
|
|
164
|
+
if (gateIgnores(cwd, ignored, key)) return [];
|
|
165
|
+
const roots = [key];
|
|
166
|
+
let frontier = [key];
|
|
167
|
+
// 与工具链探测同一个范围:cwd 往下两层,跳过依赖/产物目录。
|
|
168
|
+
for (let depth = 0; depth < 2 && roots.length < DETECT_MAX_ROOTS; depth += 1) {
|
|
169
|
+
const next: string[] = [];
|
|
170
|
+
for (const dir of frontier) {
|
|
171
|
+
for (const entry of sortedEntries(dir)) {
|
|
172
|
+
if (!entry.isDirectory() || DETECT_SKIP.has(entry.name) || entry.name.startsWith(".")) continue;
|
|
173
|
+
const child = resolve(dir, entry.name);
|
|
174
|
+
if (gateIgnores(cwd, ignored, child)) continue;
|
|
175
|
+
roots.push(child);
|
|
176
|
+
next.push(child);
|
|
177
|
+
if (roots.length >= DETECT_MAX_ROOTS) break;
|
|
178
|
+
}
|
|
179
|
+
// 外层也要断:内层 break 只退出当前目录,frontier 里剩下的每个目录还会各推一个
|
|
180
|
+
// 子目录进来,250 个目录的树能得 246 个 root,而文档说的是 200。
|
|
181
|
+
if (roots.length >= DETECT_MAX_ROOTS) break;
|
|
182
|
+
}
|
|
183
|
+
frontier = next;
|
|
184
|
+
}
|
|
185
|
+
return roots;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 目录里有没有 lockfile。软链的也算:workspace 常把它链到共享文件。 */
|
|
189
|
+
function hasLockfile(dir: string): boolean {
|
|
190
|
+
try {
|
|
191
|
+
return readdirSync(dir, { withFileTypes: true }).some(
|
|
192
|
+
(entry) => (entry.isFile() || entry.isSymbolicLink()) && LOCKFILES.has(entry.name),
|
|
193
|
+
);
|
|
194
|
+
} catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 依赖没装好的目录(相对 cwd,`.` 表示就是 cwd)。
|
|
201
|
+
*
|
|
202
|
+
* 沙箱里 store 多半不可写,pnpm 于是退回一个空 store 去装,那条 WARN 埋在几百行输出里,
|
|
203
|
+
* 构建则可能干脆卡在锁上 —— 与其让第一条命令莫名卡死,不如在它跑起来之前点名缺哪个目录。
|
|
204
|
+
*/
|
|
205
|
+
function missingDependencies(cwd: string, ignored: string[]): string[] {
|
|
206
|
+
return dependencyRoots(cwd, ignored)
|
|
207
|
+
.filter((dir) => !installed(dir))
|
|
208
|
+
.map((dir) => relative(cwd, dir) || ".");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* `dir` 是否落在某个被忽略的目录前缀里。
|
|
213
|
+
*
|
|
214
|
+
* 前缀按 cwd 解析,并且必须对齐目录边界:`fixtures` 忽略 fixtures 本身及其下全部,
|
|
215
|
+
* 不会连坐 `fixtures-old`。这与 scope 里写一个纯目录路径的含义一致(那也覆盖整棵子树),
|
|
216
|
+
* 但**不收 glob**:闸门的用途是「这个目录没人装依赖」,那是一处固定位置,
|
|
217
|
+
* 一条写死的路径就够;允许 `fixtures/*` 这类写法只会让「我明明忽略了它」变成调试题。
|
|
218
|
+
*/
|
|
219
|
+
function gateIgnores(cwd: string, ignored: string[], dir: string): boolean {
|
|
220
|
+
return ignored.some((prefix) => {
|
|
221
|
+
// resolve 对绝对路径本就返回它自己,所以绝对前缀天然可以指到 cwd 之上;相对前缀
|
|
222
|
+
// 则一定落在 cwd 之下,包含 cwd 的只有 "." / ".." 这类写法(等于关掉整道闸门)。
|
|
223
|
+
const rel = relative(resolve(cwd, prefix), dir);
|
|
224
|
+
return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel));
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** 装好的两个凭据:`node_modules/.bin`(普通安装)或 `.pnp.cjs`(Yarn PnP)。 */
|
|
229
|
+
function installed(dir: string): boolean {
|
|
230
|
+
if (existsSync(resolve(dir, "node_modules", ".bin"))) return true;
|
|
231
|
+
return PNP_MARKERS.some((marker) => existsSync(resolve(dir, marker)));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 闸门的拒绝文案;依赖齐了返回 undefined。 */
|
|
235
|
+
function dependencyGateReason(cwd: string, ignored: string[]): string | undefined {
|
|
236
|
+
const missing = missingDependencies(cwd, ignored);
|
|
237
|
+
if (missing.length === 0) return undefined;
|
|
238
|
+
const shown = missing.slice(0, 3).join(", ");
|
|
239
|
+
const rest = missing.length > 3 ? ` and ${missing.length - 3} more` : "";
|
|
240
|
+
// 忽略项是字面路径,不认 glob。写成 `fixtures/*` 或写错一个字母都会静默匹配不到任何目录,
|
|
241
|
+
// 于是「我明明忽略了它」变成调试题 —— 点名一句,省掉那一轮。
|
|
242
|
+
const globbed = ignored.filter((prefix) => /[*?]/.test(prefix));
|
|
243
|
+
const hint = globbed.length > 0
|
|
244
|
+
? ` Ignore entries are literal paths, not globs: ${globbed.join(", ")} matched nothing.`
|
|
245
|
+
: "";
|
|
246
|
+
return `pi-subagents-extend: ${shown}${rest} has a lockfile but no node_modules/.bin or .pnp.cjs, so this command would run against an unfinished install. File tools still work; use contact_supervisor so the parent finishes the install or grants the store.${hint}`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 命令的第一个词,跳过 `FOO=bar cmd` 这类前置赋值。 */
|
|
250
|
+
function commandHead(command: string): string {
|
|
251
|
+
for (const token of command.trim().split(/\s+/)) {
|
|
252
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) continue;
|
|
253
|
+
return basename(token);
|
|
254
|
+
}
|
|
255
|
+
return "";
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const PACKAGE_MANAGERS = new Set(["pnpm", "npm", "yarn", "bun", "npx", "pnpx", "bunx", "corepack"]);
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* 包在另一条命令外面的壳。`sh -c "pnpm test"`、`env pnpm test`、`exec pnpm test`
|
|
262
|
+
* 的第二个词才是真正要跑的命令,只看第一个词会把它们当成阅读类放过去。
|
|
263
|
+
*/
|
|
264
|
+
const COMMAND_WRAPPERS = new Set([
|
|
265
|
+
"sh", "bash", "zsh", "dash", "ash", "ksh", "env", "exec", "command",
|
|
266
|
+
"nohup", "setsid", "nice", "ionice", "stdbuf", "timeout", "xargs",
|
|
267
|
+
]);
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* 包装器后面真正要跑的那条命令的名字。
|
|
271
|
+
*
|
|
272
|
+
* 跳过包装器自己、它的选项、`NAME=value` 前置赋值和纯数值参数(`timeout 30 pnpm test`)。
|
|
273
|
+
* 只看头而不扫描全部词元:`sh -c "rg pnpm"` 是在搜这个字,不该被当成要装依赖。
|
|
274
|
+
*/
|
|
275
|
+
function payloadHead(command: string): string {
|
|
276
|
+
const words = command.split(/[\s'"]+/).filter(Boolean);
|
|
277
|
+
for (const word of words.slice(1)) {
|
|
278
|
+
if (word.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || /^[0-9]/.test(word)) continue;
|
|
279
|
+
if (COMMAND_WRAPPERS.has(basename(word))) continue;
|
|
280
|
+
return basename(word);
|
|
281
|
+
}
|
|
282
|
+
return "";
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* 闸门只管「会去装依赖」的那几类:写类命令(构建、测试)与包管理器本身。
|
|
287
|
+
*
|
|
288
|
+
* `git` 与只读命令不受影响。git 不需要 node_modules,而「先落任务日志再提交」这种保树
|
|
289
|
+
* 纪律恰恰在依赖缺失时最要用得上 —— 把 git 一起挡掉,拒绝就发生在最不该发生的时刻。
|
|
290
|
+
*
|
|
291
|
+
* 包装器要穿透到载荷的命令名上,否则 `sh -c "pnpm test"` 会从侧面跳过闸门;但只认载荷
|
|
292
|
+
* 的命令名,不认命令里出现的字,否则 `sh -c "rg pnpm"` 会被误拦。脚本文件
|
|
293
|
+
* (`node build.mjs`)里写的是什么从命令行看不出来,那是这条判据的边界。
|
|
294
|
+
*/
|
|
295
|
+
function dependencyGateApplies(command: string, access: "read" | "write"): boolean {
|
|
296
|
+
const head = commandHead(command);
|
|
297
|
+
if (head === "git") return false;
|
|
298
|
+
if (!COMMAND_WRAPPERS.has(head)) {
|
|
299
|
+
if (access === "write") return true;
|
|
300
|
+
return PACKAGE_MANAGERS.has(head);
|
|
301
|
+
}
|
|
302
|
+
// 包装器要穿透到载荷的命令名;`env git commit` 照样享 git 豁免。
|
|
303
|
+
// `command -v pnpm` 是问「这个工具在不在」,不是跑它。
|
|
304
|
+
if (head === "command" && /(^|\s)-[vV](\s|$)/.test(command)) return false;
|
|
305
|
+
const payload = payloadHead(command);
|
|
306
|
+
if (payload === "" || payload === "git") return false;
|
|
307
|
+
if (PACKAGE_MANAGERS.has(payload)) return true;
|
|
308
|
+
return access === "write";
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** 闸门的最终判定:关掉、不适用或依赖齐全时返回 undefined。 */
|
|
312
|
+
export function dependencyGateVerdict(
|
|
313
|
+
rule: { dependencyGate: string[] | false },
|
|
314
|
+
command: string,
|
|
315
|
+
access: "read" | "write",
|
|
316
|
+
cwd: string,
|
|
317
|
+
): string | undefined {
|
|
318
|
+
if (rule.dependencyGate === false || !dependencyGateApplies(command, access)) return undefined;
|
|
319
|
+
return dependencyGateReason(cwd, rule.dependencyGate);
|
|
320
|
+
}
|