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,434 @@
1
+ /**
2
+ * 角色 md 的配置源:从 agent 定义文件的 YAML frontmatter 里读出 extend 段,
3
+ * 转换成扩展已有的策略字段。这里只做解析与转换,不参与工具判定。
4
+ *
5
+ * 本阶段接 permissions 下的 scope / write / readOnly / allowTools / budgets / bash;
6
+ * worktree、setup、output 也各有类型化解析入口;各块的接线在 index.ts 里完成,
7
+ * policyFromBlock 只对真正不认识的块名报错。
8
+ */
9
+
10
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import { parse } from "yaml";
13
+
14
+ import { stringList as bashStringList } from "./bash/rules.ts";
15
+ export const BINDING_NAMESPACE = "pi-subagents-extend";
16
+ export const BINDING_VERSION = 1;
17
+
18
+ export const bindingKey = (): string => `${BINDING_NAMESPACE}/${BINDING_VERSION}`;
19
+
20
+ /** md 里的 bash 单列授权:只收新拼法,legacy 的 read / write 属于 bindings。 */
21
+ export interface RoleBashPolicy {
22
+ allow?: string[];
23
+ deny?: string[];
24
+ writable?: boolean;
25
+ network?: boolean;
26
+ dependencyGate?: string[] | false;
27
+ }
28
+
29
+ /** md 基线能提供的字段,名字与现有 bindings 的策略字段对齐。 */
30
+ export interface RolePolicy {
31
+ scope?: string[];
32
+ writeScope?: string[];
33
+ readOnly?: boolean;
34
+ allowTools?: string[];
35
+ maxDenies?: number;
36
+ maxWriteDenies?: number;
37
+ bash?: RoleBashPolicy;
38
+ }
39
+
40
+
41
+ /** md 里的工作树策略:块缺席表示不介入;块存在但没写 nodeModules 时默认 keep。 */
42
+ export interface RoleWorktreeConfig {
43
+ enabled?: boolean;
44
+ nodeModules?: "keep" | "remove";
45
+ }
46
+
47
+ /** md 里的执行前脚本。 */
48
+ export interface RoleSetupConfig {
49
+ preExec?: string;
50
+ }
51
+
52
+ /** md 里的交付物相对路径。 */
53
+ export interface RoleOutputConfig {
54
+ deliverable?: string;
55
+ }
56
+ const asRecord = (value: unknown): Record<string, unknown> | undefined =>
57
+ value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
58
+
59
+ const XML_ENTITIES: Record<string, string> = {
60
+ amp: "&",
61
+ lt: "<",
62
+ gt: ">",
63
+ quot: '"',
64
+ apos: "'",
65
+ };
66
+
67
+ /**
68
+ /**
69
+ * 子代理提示里的 `<active_agent name="…"/>` 跟在重写后的提示后面,不一定在第一行。
70
+ * 逐行找第一条「整行只有这个标签」的行:上下文里引用到的同类标签不能当成当前角色。
71
+ * 属性值做过 XML 转义,找到以后再解码。
72
+ */
73
+ export function parseRoleName(systemPrompt: string): string | null {
74
+ for (const line of systemPrompt.split(/\r?\n/)) {
75
+ const match = /^\s*<active_agent\s+name="([^"]*)"\s*\/>\s*$/.exec(line);
76
+ if (!match || !match[1]) continue;
77
+ const name = match[1].replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, (whole, code: string) => {
78
+ if (code.startsWith("#")) {
79
+ const hex = code[1] === "x";
80
+ const value = Number.parseInt(hex ? code.slice(2) : code.slice(1), hex ? 16 : 10);
81
+ return Number.isFinite(value) && value > 0 && value <= 0x10ffff ? String.fromCodePoint(value) : whole;
82
+ }
83
+ return XML_ENTITIES[code] ?? whole;
84
+ });
85
+ return name.trim() ? name : null;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ const MAX_MD_PARENT_LEVELS = 8;
91
+
92
+ /**
93
+ * md 的查找目录:从会话 cwd 起逐级向上,每级先看 .pi/agents 再看 .agents,
94
+ * 最后才是用户目录的两级。向上封顶 8 层,异常深的路径也不至于无限扫。
95
+ */
96
+ export function agentMdDirs(cwd: string, home: string): string[] {
97
+ const dirs: string[] = [];
98
+ let current = resolve(cwd);
99
+ for (let level = 0; level < MAX_MD_PARENT_LEVELS; level += 1) {
100
+ dirs.push(join(current, ".pi", "agents"), join(current, ".agents"));
101
+ const parent = dirname(current);
102
+ if (parent === current) break;
103
+ current = parent;
104
+ }
105
+ dirs.push(join(home, ".pi", "agent", "agents"), join(home, ".agents"));
106
+ return dirs;
107
+ }
108
+
109
+ /** agent md 的解析顺序:项目两级在用户两级之前,逐级向上,命中即停。 */
110
+ export function resolveAgentFile(role: string, cwd: string, home: string): string | null {
111
+ if (!role) return null;
112
+ for (const dir of agentMdDirs(cwd, home)) {
113
+ const file = join(dir, `${role}.md`);
114
+ if (existsSync(file)) return file;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /** 一次 md 扫描得到的候选:角色名、文件、正文探针,以及 frontmatter 是否声明了 extend。 */
120
+ interface RoleMdCandidate {
121
+ role: string;
122
+ file: string;
123
+ probe: string;
124
+ declaresExtend: boolean;
125
+ }
126
+
127
+ /** 探针长度:够长以避开「# reviewer」这类通用开头,够短以容忍宿主截掉正文尾部。 */
128
+ const BODY_PROBE_LENGTH = 120;
129
+ /** 一次扫描最多看多少个 md,异常目录不该把接线拖慢。 */
130
+ const MAX_ROLE_MD_FILES = 32;
131
+
132
+ const collapseWhitespace = (text: string): string => text.replace(/\s+/g, " ").trim();
133
+
134
+ /**
135
+ * 扫描角色 md 目录,取正文(去掉 frontmatter)归一化后的前 120 字符当探针。
136
+ * 读不到、frontmatter 没闭合、正文为空的文件都跳过;同一路径只算一次,否则重复目录会误报歧义。
137
+ */
138
+ function scanRoleMdCandidates(cwd: string, home: string): RoleMdCandidate[] {
139
+ const candidates: RoleMdCandidate[] = [];
140
+ const seen = new Set<string>();
141
+ for (const dir of agentMdDirs(cwd, home)) {
142
+ let names: string[];
143
+ try {
144
+ names = readdirSync(dir);
145
+ } catch {
146
+ continue; // 目录不存在或不可读:跳过
147
+ }
148
+ for (const name of names) {
149
+ if (!name.endsWith(".md") || candidates.length >= MAX_ROLE_MD_FILES) continue;
150
+ const file = join(dir, name);
151
+ const key = resolve(file);
152
+ if (seen.has(key)) continue;
153
+ seen.add(key);
154
+ let text: string;
155
+ try {
156
+ text = readFileSync(file, "utf8");
157
+ } catch {
158
+ continue; // 角色 md 可能不可读:静默跳过
159
+ }
160
+ const lines = text.split(/\r?\n/);
161
+ let body = text;
162
+ let frontmatter: string | undefined;
163
+ if (lines[0]?.trim() === "---") {
164
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
165
+ if (end < 0) continue; // frontmatter 没闭合:不拿它判身份
166
+ frontmatter = lines.slice(1, end).join("\n");
167
+ body = lines.slice(end + 1).join("\n");
168
+ }
169
+ const normalised = collapseWhitespace(body);
170
+ if (!normalised) continue; // 空正文不参与匹配,否则空探针会命中所有提示
171
+ let declaresExtend = false;
172
+ if (frontmatter !== undefined) {
173
+ try {
174
+ declaresExtend = asRecord(parse(frontmatter))?.extend !== undefined;
175
+ } catch {
176
+ // frontmatter 不是合法 YAML:不算声明了 extend
177
+ }
178
+ }
179
+ candidates.push({ role: name.slice(0, -3), file, probe: normalised.slice(0, BODY_PROBE_LENGTH), declaresExtend });
180
+ }
181
+ }
182
+ return candidates;
183
+ }
184
+
185
+ export interface RoleResolution {
186
+ role: string | null;
187
+ warnings: string[];
188
+ extendMdSeen: boolean;
189
+ }
190
+
191
+ /**
192
+ * 先找 <active_agent> 标签;找不到(如 systemPromptMode: replace 丢了标签)再用每个 md 的正文
193
+ * 探针匹配提示。唯一命中才认角色;零命中交回调用方按原样告警;多命中一律当没身份并点名候选,
194
+ * 绝不猜一个。标签优先保证原有宿主行为不变,也保证正文误命中时标签仍能定案。
195
+ */
196
+ export function resolveRoleFromPrompt(systemPrompt: string, cwd: string, home: string): RoleResolution {
197
+ const tag = parseRoleName(systemPrompt);
198
+ if (tag) return { role: tag, warnings: [], extendMdSeen: false };
199
+
200
+ const candidates = scanRoleMdCandidates(cwd, home);
201
+ const extendMdSeen = candidates.some((candidate) => candidate.declaresExtend);
202
+ const normalisedPrompt = collapseWhitespace(systemPrompt);
203
+ const matches = candidates.filter((candidate) => normalisedPrompt.includes(candidate.probe));
204
+ if (matches.length === 1) return { role: matches[0].role, warnings: [], extendMdSeen };
205
+ if (matches.length > 1) {
206
+ const names = matches.map((candidate) => `${candidate.role} (${candidate.file})`).join(", ");
207
+ return {
208
+ role: null,
209
+ warnings: [`pi-subagents-extend: the prompt body matches more than one role md, so no role was selected; candidates: ${names}. Add a <active_agent> tag to disambiguate.`],
210
+ extendMdSeen,
211
+ };
212
+ }
213
+ return { role: null, warnings: [], extendMdSeen };
214
+ }
215
+ /** 读 frontmatter 里的 extend 对象;没有 frontmatter 或没有 extend 都不算问题。 */
216
+ export function readExtendBlock(file: string): { block?: Record<string, unknown>; problems: string[] } {
217
+ const problems: string[] = [];
218
+ let text: string;
219
+ try {
220
+ text = readFileSync(file, "utf8");
221
+ } catch (error) {
222
+ problems.push(`unable to read ${file}: ${error instanceof Error ? error.message : String(error)}`);
223
+ return { problems };
224
+ }
225
+ const lines = text.split(/\r?\n/);
226
+ if (lines[0]?.trim() !== "---") return { problems };
227
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
228
+ if (end < 0) return { problems };
229
+ let parsed: unknown;
230
+ try {
231
+ parsed = parse(lines.slice(1, end).join("\n"));
232
+ } catch (error) {
233
+ problems.push(`invalid YAML in frontmatter: ${error instanceof Error ? error.message : String(error)}`);
234
+ return { problems };
235
+ }
236
+ const extend = asRecord(parsed)?.extend;
237
+ if (extend === undefined) return { problems };
238
+ const block = asRecord(extend);
239
+ if (!block) {
240
+ problems.push("extend must be an object");
241
+ return { problems };
242
+ }
243
+ return { block, problems };
244
+ }
245
+
246
+ const TOP_LEVEL_KEYS = new Set(["permissions", "worktree", "setup", "output"]);
247
+ const PERMISSION_KEYS = new Set(["scope", "write", "readOnly", "allowTools", "budgets", "bash"]);
248
+
249
+ /** permissions → 现有策略字段;写错的键报出来并省掉,不让坏值混进策略。 */
250
+ export function policyFromBlock(block: Record<string, unknown>): { policy?: RolePolicy; problems: string[] } {
251
+ const problems: string[] = [];
252
+ const policy: RolePolicy = {};
253
+
254
+ for (const key of Object.keys(block)) {
255
+ if (!TOP_LEVEL_KEYS.has(key)) problems.push(`${key}: unknown block`);
256
+ }
257
+
258
+ const permissions = asRecord(block.permissions);
259
+ if (block.permissions !== undefined && !permissions) {
260
+ problems.push("permissions must be an object");
261
+ return { policy, problems };
262
+ }
263
+ if (!permissions) return { policy, problems };
264
+
265
+ const stringList = (key: "scope" | "write" | "allowTools"): string[] | undefined => {
266
+ const value = permissions[key];
267
+ if (value === undefined) return undefined;
268
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
269
+ problems.push(`permissions.${key} must be an array of strings`);
270
+ return undefined;
271
+ }
272
+ return value as string[];
273
+ };
274
+ const scope = stringList("scope");
275
+ if (scope) policy.scope = scope;
276
+ const write = stringList("write");
277
+ if (write) policy.writeScope = write;
278
+ const allowTools = stringList("allowTools");
279
+ if (allowTools) policy.allowTools = allowTools;
280
+
281
+ if (permissions.readOnly !== undefined) {
282
+ if (typeof permissions.readOnly === "boolean") policy.readOnly = permissions.readOnly;
283
+ else problems.push("permissions.readOnly must be a boolean");
284
+ }
285
+ if (permissions.bash !== undefined) {
286
+ const bash = asRecord(permissions.bash);
287
+ if (!bash) {
288
+ problems.push("permissions.bash must be an object");
289
+ } else {
290
+ const converted: RoleBashPolicy = {};
291
+ const bashList = (key: "allow" | "deny"): string[] | undefined => {
292
+ const value = bash[key];
293
+ if (value === undefined) return undefined;
294
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
295
+ problems.push(`permissions.bash.${key} must be an array of strings`);
296
+ return undefined;
297
+ }
298
+ return value as string[];
299
+ };
300
+ const allow = bashList("allow");
301
+ if (allow) converted.allow = allow;
302
+ const deny = bashList("deny");
303
+ if (deny) converted.deny = deny;
304
+ const dependencyGate = (() => {
305
+ const value = bash.dependencyGate;
306
+ if (value === undefined) return undefined;
307
+ if (value === false) return false;
308
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
309
+ problems.push("permissions.bash.dependencyGate must be false or an array of strings");
310
+ return undefined;
311
+ }
312
+ return bashStringList(value);
313
+ })();
314
+ if (dependencyGate !== undefined) converted.dependencyGate = dependencyGate;
315
+ for (const key of ["writable", "network"] as const) {
316
+ const value = bash[key];
317
+ if (value === undefined) continue;
318
+ if (typeof value !== "boolean") {
319
+ problems.push(`permissions.bash.${key} must be a boolean`);
320
+ continue;
321
+ }
322
+ converted[key] = value;
323
+ }
324
+ for (const key of Object.keys(bash)) {
325
+ if (key === "read" || key === "write") {
326
+ // legacy 拼法属于 bindings,不属于 md:保留这句事实并指出现在新写法。
327
+ problems.push(`permissions.bash: the legacy read/write spelling belongs to bindings, not to the md; use "allow" instead`);
328
+ } else if (!["allow", "deny", "writable", "network", "dependencyGate"].includes(key)) {
329
+ problems.push(`permissions.bash.${key}: unknown key`);
330
+ }
331
+ }
332
+ if (Object.keys(converted).length > 0) policy.bash = converted;
333
+ }
334
+ }
335
+ for (const key of Object.keys(permissions)) {
336
+ if (!PERMISSION_KEYS.has(key)) problems.push(`permissions.${key}: unknown key`);
337
+ }
338
+
339
+ const budgets = asRecord(permissions.budgets);
340
+ if (permissions.budgets !== undefined && !budgets) {
341
+ problems.push("permissions.budgets must be an object");
342
+ } else if (budgets) {
343
+ const budgetNumber = (key: "deny" | "writeDeny"): number | undefined => {
344
+ const value = budgets[key];
345
+ if (value === undefined) return undefined;
346
+ if (typeof value !== "number" || !Number.isFinite(value)) {
347
+ problems.push(`permissions.budgets.${key} must be a number`);
348
+ return undefined;
349
+ }
350
+ return value;
351
+ };
352
+ const deny = budgetNumber("deny");
353
+ if (deny !== undefined) policy.maxDenies = deny;
354
+ const writeDeny = budgetNumber("writeDeny");
355
+ if (writeDeny !== undefined) policy.maxWriteDenies = writeDeny;
356
+ }
357
+
358
+ return { policy, problems };
359
+ }
360
+
361
+ /** 取 extend 下的一个子块;类型不对就报出来并当作缺席。 */
362
+ const subBlock = (
363
+ block: Record<string, unknown>,
364
+ key: "worktree" | "setup" | "output",
365
+ problems: string[],
366
+ ): Record<string, unknown> | undefined => {
367
+ const value = block[key];
368
+ if (value === undefined) return undefined;
369
+ const record = asRecord(value);
370
+ if (!record) problems.push(`${key} must be an object`);
371
+ return record;
372
+ };
373
+
374
+ /** extend.worktree → 工作树策略;缺席时不返回 worktree 字段。 */
375
+ export function worktreeFromBlock(block: Record<string, unknown>): { worktree?: RoleWorktreeConfig; problems: string[] } {
376
+ const problems: string[] = [];
377
+ const raw = subBlock(block, "worktree", problems);
378
+ if (!raw) return { problems };
379
+ const worktree: RoleWorktreeConfig = { nodeModules: "keep" };
380
+ if (raw.enabled !== undefined) {
381
+ if (typeof raw.enabled === "boolean") worktree.enabled = raw.enabled;
382
+ else problems.push("worktree.enabled must be a boolean");
383
+ }
384
+ if (raw.nodeModules !== undefined) {
385
+ if (raw.nodeModules === "keep" || raw.nodeModules === "remove") worktree.nodeModules = raw.nodeModules;
386
+ else problems.push('worktree.nodeModules must be "keep" or "remove"');
387
+ }
388
+ for (const key of Object.keys(raw)) {
389
+ if (key !== "enabled" && key !== "nodeModules") problems.push(`worktree.${key}: unknown key`);
390
+ }
391
+ return { worktree, problems };
392
+ }
393
+
394
+ /** extend.setup → 派单前要执行的命令。 */
395
+ export function setupFromBlock(block: Record<string, unknown>): { setup?: RoleSetupConfig; problems: string[] } {
396
+ const problems: string[] = [];
397
+ const raw = subBlock(block, "setup", problems);
398
+ if (!raw) return { problems };
399
+ const setup: RoleSetupConfig = {};
400
+ if (raw.preExec !== undefined) {
401
+ if (typeof raw.preExec === "string") setup.preExec = raw.preExec;
402
+ else problems.push("setup.preExec must be a string");
403
+ }
404
+ for (const key of Object.keys(raw)) {
405
+ if (key !== "preExec") problems.push(`setup.${key}: unknown key`);
406
+ }
407
+ return { setup, problems };
408
+ }
409
+
410
+ /** extend.output → 交付物;越界路径报出来并省掉,不让配置变成一个越权的链接。 */
411
+ export function outputFromBlock(block: Record<string, unknown>): { output?: RoleOutputConfig; problems: string[] } {
412
+ const problems: string[] = [];
413
+ const raw = subBlock(block, "output", problems);
414
+ if (!raw) return { problems };
415
+ const output: RoleOutputConfig = {};
416
+ if (raw.deliverable !== undefined) {
417
+ if (typeof raw.deliverable !== "string") {
418
+ problems.push("output.deliverable must be a string");
419
+ } else if (
420
+ raw.deliverable.length === 0 ||
421
+ raw.deliverable.startsWith("/") ||
422
+ /^[a-zA-Z]:[\\/]/.test(raw.deliverable) ||
423
+ raw.deliverable.split(/[\\/]/).includes("..")
424
+ ) {
425
+ problems.push("output.deliverable must be a relative path inside the worktree");
426
+ } else {
427
+ output.deliverable = raw.deliverable;
428
+ }
429
+ }
430
+ for (const key of Object.keys(raw)) {
431
+ if (key !== "deliverable") problems.push(`output.${key}: unknown key`);
432
+ }
433
+ return { output, problems };
434
+ }