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,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PATH 层:路径解析与比对的原语(realpath 归一、~ 展开、树内判定、前缀比对、
|
|
3
|
+
* 私有 tmpfs 下的授权剔除)。
|
|
4
|
+
* 这一层是纯函数,不持有会话状态;index.ts 只做接线。
|
|
5
|
+
* 模块拆分第二步:以下声明从 index.ts / policy.ts 原样搬出,行为不变。
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 真实路径。目标可能还不存在(写新文件),所以取最深的已存在祖先做 realpath,再把剩下的段拼回去。
|
|
13
|
+
*
|
|
14
|
+
* 为什么必须 realpath:词法比较只看路径字符串,软链是唯一能绕过它的向量 —— `src/link` 指到树外时,
|
|
15
|
+
* `write src/link/evil` 在词法上仍是 `src/` 之下。bash 那条路有 Landlock 按 inode 兜底,edit/write
|
|
16
|
+
* 工具在父进程里跑,没有第二层。
|
|
17
|
+
*/
|
|
18
|
+
export function canonical(path: string): string {
|
|
19
|
+
let head = path;
|
|
20
|
+
const rest: string[] = [];
|
|
21
|
+
for (;;) {
|
|
22
|
+
try {
|
|
23
|
+
const real = realpathSync(head);
|
|
24
|
+
return rest.length === 0 ? real : join(real, ...rest.slice().reverse());
|
|
25
|
+
} catch {
|
|
26
|
+
const parent = dirname(head);
|
|
27
|
+
if (parent === head) return path;
|
|
28
|
+
rest.push(basename(head));
|
|
29
|
+
head = parent;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 把路径解析到「可比形态」,与 helper 的 `resolve_comparable` 对齐:对最深的**已存在**祖先做
|
|
36
|
+
* realpath,再把不存在的尾巴原样接回去。两边都用 OS 的 realpath(Node 用 `.native`)并原样拼尾巴,
|
|
37
|
+
* 因此对存在的路径与「祖先软链 + 缺失尾巴」两类结果逐字节一致。
|
|
38
|
+
*
|
|
39
|
+
* 整体 realpath 在这里用不了:授权指向的路径可能还不存在(命令本来就要创建它),而挂载之后它更
|
|
40
|
+
* 是不存在。软链必须先解析,否则「经软链指向 /tmp/x 的授权」在插件侧看着不在 /tmp 之下,helper 却
|
|
41
|
+
* 解析成 /tmp/x 把整份 spec 拒掉 —— 那正是这套逻辑要避免的「一条命令都跑不了」。
|
|
42
|
+
*/
|
|
43
|
+
export function resolveComparable(path: string): string {
|
|
44
|
+
const tail: string[] = [];
|
|
45
|
+
let current = path;
|
|
46
|
+
for (;;) {
|
|
47
|
+
try {
|
|
48
|
+
// `realpathSync.native` 而不是 `realpathSync`:helper 用的是 Rust 的 `fs::canonicalize`,
|
|
49
|
+
// 它落到 OS 的 realpath(3),而 Node 的 `realpathSync` 是自实现版本,两者在部分输入上结果不同。
|
|
50
|
+
// 尾巴用字面拼接而不是 `resolve`:`resolve` 会把 `..` 归一化,Rust 那边是原样 push 进去的,
|
|
51
|
+
// 归一化会让「授权路径还没创建」这一类判断与 helper 不一致。
|
|
52
|
+
const base = realpathSync.native(current);
|
|
53
|
+
return tail.length === 0 ? base : `${base.replace(/\/+$/, "")}/${tail.join("/")}`;
|
|
54
|
+
} catch {
|
|
55
|
+
const parent = dirname(current);
|
|
56
|
+
if (parent === current) return path;
|
|
57
|
+
tail.unshift(basename(current));
|
|
58
|
+
current = parent;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 展开 ~ 与相对路径;返回 undefined 表示不是可用路径。 */
|
|
64
|
+
export function expandPath(cwd: string, raw: string): string | undefined {
|
|
65
|
+
const value = raw.trim();
|
|
66
|
+
if (!value) return undefined;
|
|
67
|
+
if (value.startsWith("~/")) return resolve(homedir(), value.slice(2));
|
|
68
|
+
if (value === "~") return homedir();
|
|
69
|
+
if (value.startsWith("/")) return value;
|
|
70
|
+
return resolve(cwd, value);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 目标落在 base 树内就返回它的相对路径,否则 undefined。软链按真实路径判:Landlock
|
|
75
|
+
* 只授权目标 inode,收了指到树外的软链等于把树外那个文件也开了。
|
|
76
|
+
*/
|
|
77
|
+
export function insideTree(base: string, abs: string): string | undefined {
|
|
78
|
+
const rel = relative(base, canonical(abs));
|
|
79
|
+
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return undefined;
|
|
80
|
+
return rel;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `path` 是否在 `root` 之下。按路径边界比,`/etc` 不覆盖 `/etc-other`。 */
|
|
84
|
+
export function underRoot(root: string, path: string): boolean {
|
|
85
|
+
if (path === root) return true;
|
|
86
|
+
return path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* "." / "./" / 仓库根 / "/":目标不是某个文件,而是「整棵树」。单独区分出来,
|
|
91
|
+
* 这样拒绝文案能直说「这是仓库根」,而不是让人以为 scope 写法有错。
|
|
92
|
+
*/
|
|
93
|
+
export function isRootish(raw: string, cwd: string): boolean {
|
|
94
|
+
const abs = resolve(cwd, raw);
|
|
95
|
+
return abs === cwd || abs === "/";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* helper 里的 `PRIVATE_TMP`:spec 不写 `tmp` 时它把私有 tmpfs 挂在这里。
|
|
100
|
+
* 扩展的 XDG_RUNTIME_DIR / MISE_STATE_DIR 也指在它下面,所以这个路径两边必须同一个。
|
|
101
|
+
*/
|
|
102
|
+
export const CONVENTIONAL_TMP = "/tmp";
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 会被私有 tmpfs 盖住的目录,与 helper 的 `privatised_dirs` 同一定义:约定 `/tmp` 恒在内,
|
|
106
|
+
* 外加 spec 的 `tmp`(scratch);但 cwd 落在其中时 helper 不挂(否则会盖掉工作目录)。
|
|
107
|
+
*/
|
|
108
|
+
export function privatisedDirs(cwd: string, scratch: string): string[] {
|
|
109
|
+
return [...new Set([CONVENTIONAL_TMP, scratch])]
|
|
110
|
+
.map((dir) => dir.replace(/\/+$/, "") || "/")
|
|
111
|
+
.filter((dir) => dir !== "/" && dir !== "." && !(cwd === dir || cwd.startsWith(`${dir}/`)));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 剔掉「拿到手也用不上」的写授权。
|
|
116
|
+
*
|
|
117
|
+
* helper 在私有化的目录上挂 tmpfs 之后,落在其**下**的授权路径从它的视图里消失,于是它拒掉整份
|
|
118
|
+
* spec(exit 77),bash 全灭。授权那个目录**本身**仍然有效(挂载点还在),所以只剔严格在下的。
|
|
119
|
+
*
|
|
120
|
+
* 两边都按 `resolveComparable` 解析,否则软链会造成两种错判:插件保留而 helper 拒(bash 全灭),
|
|
121
|
+
* 或插件剔掉而 helper 本来会接受(白白丢掉一条能用的授权)。
|
|
122
|
+
*
|
|
123
|
+
* 同时也把剔掉的交回去:静默丢弃会让子代理反复撞「写不进去」而不知道为什么。
|
|
124
|
+
*/
|
|
125
|
+
export function dropHiddenGrants(
|
|
126
|
+
write: string[],
|
|
127
|
+
cwd: string,
|
|
128
|
+
scratch: string,
|
|
129
|
+
): { kept: string[]; dropped: string[] } {
|
|
130
|
+
const dirs = privatisedDirs(cwd, scratch).map(resolveComparable);
|
|
131
|
+
const kept: string[] = [];
|
|
132
|
+
const dropped: string[] = [];
|
|
133
|
+
for (const path of write) {
|
|
134
|
+
const resolved = resolveComparable(path);
|
|
135
|
+
if (dirs.some((dir) => resolved !== dir && resolved.startsWith(`${dir}/`))) dropped.push(path);
|
|
136
|
+
else kept.push(path);
|
|
137
|
+
}
|
|
138
|
+
return { kept, dropped };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 找 git worktree 的根:从 cwd 往上找第一个「.git 是文件」的目录。
|
|
143
|
+
* worktree 里 .git 是指向主仓 gitdir 的文件;主仓 checkout 里 .git 是目录。
|
|
144
|
+
* 返回 undefined 表示不在 worktree 里。
|
|
145
|
+
*/
|
|
146
|
+
export function findWorktreeRoot(cwd: string): string | undefined {
|
|
147
|
+
let dir = resolve(cwd);
|
|
148
|
+
for (let i = 0; i < 64; i += 1) {
|
|
149
|
+
const dotGit = resolve(dir, ".git");
|
|
150
|
+
if (existsSync(dotGit)) {
|
|
151
|
+
try {
|
|
152
|
+
const st = statSync(dotGit);
|
|
153
|
+
// worktree:.git 是文件
|
|
154
|
+
if (!st.isDirectory()) return dir;
|
|
155
|
+
return undefined;
|
|
156
|
+
} catch {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const parent = dirname(dir);
|
|
161
|
+
if (parent === dir) return undefined;
|
|
162
|
+
dir = parent;
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POLICY / GLOB:范围匹配的原语(glob 编译、realpath 比对、绝对授权前缀匹配),
|
|
3
|
+
* 以及 `Policy` / `ToolDeclaration` 这两个各主题模块共用的类型。
|
|
4
|
+
* 这一层是纯函数,不持有会话状态;policy.ts 只做桶装再导出。
|
|
5
|
+
*/
|
|
6
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { type BashRule } from "../bash/index.ts";
|
|
8
|
+
import { canonical } from "../paths/index.ts";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 一个工具的类别声明。
|
|
12
|
+
*
|
|
13
|
+
* `access` 缺省时沿用 `DEFAULT_TOOL_ACCESS` 里按名字给的值;`path` 缺省时从工具自己的
|
|
14
|
+
* 入参 schema 里找(`pathArgFromSchema`),找不到就当 `path`。
|
|
15
|
+
*/
|
|
16
|
+
export interface ToolDeclaration {
|
|
17
|
+
access?: "read" | "write";
|
|
18
|
+
path?: string | false;
|
|
19
|
+
/** 双文件工具(copy/move)的源文件按读还是按写判;缺省见 `DEFAULT_TRANSFER_SOURCE`。 */
|
|
20
|
+
transferSource?: "read" | "write";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Policy {
|
|
24
|
+
globs: string[];
|
|
25
|
+
regexps: RegExp[];
|
|
26
|
+
/** 写范围(edit / write 工具)。没配 writeScope 时等于读范围;readOnly 时为空。 */
|
|
27
|
+
writeGlobs: string[];
|
|
28
|
+
/**
|
|
29
|
+
* writeScope 里写绝对路径的那几条,已 realpath,按前缀比对。
|
|
30
|
+
*
|
|
31
|
+
* 相对授权绑在项目树上(`matches` 里「落在工作树之外一律不认」是软链逃逸的唯一防线),
|
|
32
|
+
* 但「把报告写到某个文件」本来就是树外的事。绝对路径是父代理明确点名的授权,不是子代理
|
|
33
|
+
* 能自己构造的逃逸,所以单独放行;相对授权的老规则一点不动。
|
|
34
|
+
*/
|
|
35
|
+
absoluteWrite: string[];
|
|
36
|
+
writeRegexps: RegExp[];
|
|
37
|
+
source: string;
|
|
38
|
+
readOnly: boolean;
|
|
39
|
+
maxReads: number;
|
|
40
|
+
allowTools: string[];
|
|
41
|
+
/**
|
|
42
|
+
* 父代理对工具类别的显式声明,覆盖 `DEFAULT_TOOL_ACCESS`。
|
|
43
|
+
*
|
|
44
|
+
* `path: false` 表示这个工具没有可判的路径入参——写类工具这样声明等于「永远拒绝」,
|
|
45
|
+
* 因为拿不到目标就没有任何授权能覆盖它。
|
|
46
|
+
*/
|
|
47
|
+
tools: Record<string, ToolDeclaration>;
|
|
48
|
+
bash?: BashRule;
|
|
49
|
+
/** 探针配置;undefined = 关闭。 */
|
|
50
|
+
probe: unknown;
|
|
51
|
+
/** 连续被拒多少次算「撞权限」;0 = 关闭。 */
|
|
52
|
+
maxDenies: number;
|
|
53
|
+
/** 写拒的独立预算:写拒是用法错,换个交付方式就能解决,不该跟读拒共用额度。 */
|
|
54
|
+
maxWriteDenies: number;
|
|
55
|
+
active: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* glob → 正则,单趟扫描。不能串 replace:`**` 先变成 `.*` 后,后一步的 `*` 规则会
|
|
60
|
+
* 把新生成的 `*` 再改写一遍("**" 曾变成 ".[^/]*")。
|
|
61
|
+
*/
|
|
62
|
+
export function globToRegExp(glob: string): RegExp {
|
|
63
|
+
let re = "";
|
|
64
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
65
|
+
const ch = glob[i];
|
|
66
|
+
if (ch === "*") {
|
|
67
|
+
if (glob[i + 1] === "*") {
|
|
68
|
+
// `**/` 吃掉整段目录(含零段),`**` 吃掉任意层任意字符。
|
|
69
|
+
if (glob[i + 2] === "/") {
|
|
70
|
+
re += "(?:.*/)?";
|
|
71
|
+
i += 2;
|
|
72
|
+
} else {
|
|
73
|
+
re += ".*";
|
|
74
|
+
i += 1;
|
|
75
|
+
}
|
|
76
|
+
} else {
|
|
77
|
+
re += "[^/]*";
|
|
78
|
+
}
|
|
79
|
+
} else if (ch === "?") {
|
|
80
|
+
re += "[^/]";
|
|
81
|
+
} else {
|
|
82
|
+
re += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return new RegExp(`^${re}$`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* scope 写法归一,`compile` 与沙箱可写面共用一份,免得两处对同一个 glob 的理解
|
|
90
|
+
* 慢慢分叉。两件事:
|
|
91
|
+
* - 尾斜杠只是目录写法,去掉后再展开,否则 "dir/" 会变成 "dir//**"。
|
|
92
|
+
* - "." 和 "./" 表示整棵树。不归一的话会编译成 ^\.$ / ^\./.*$,而 matches 比的是
|
|
93
|
+
* 相对路径 —— 仓库根的相对路径是空串、子文件是 "src/a.ts",两条都命中不了,
|
|
94
|
+
* 于是 scope: ["."](文档里的「读全仓」写法)什么也授权不了。开头的 "./" 同理
|
|
95
|
+
* 要去掉:"." 归一成 "**"(整棵树),"./src" 归一成 "src"。
|
|
96
|
+
*/
|
|
97
|
+
export function normalizeGlob(glob: string): string {
|
|
98
|
+
const raw = glob.length > 1 ? glob.replace(/\/+$/, "") || "/" : glob;
|
|
99
|
+
return raw === "." ? "**" : raw.replace(/^\.\//, "");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 展开目录语义后编译。"dir/**" 额外匹配 "dir" 本身;不含通配符的纯路径额外
|
|
104
|
+
* 匹配 "dir/**",所以范围写 "src" 就覆盖 src 及其下所有内容。
|
|
105
|
+
*/
|
|
106
|
+
export function compile(globs: string[]): RegExp[] {
|
|
107
|
+
const expanded = new Set<string>();
|
|
108
|
+
for (const glob of globs) {
|
|
109
|
+
const g = normalizeGlob(glob);
|
|
110
|
+
expanded.add(g);
|
|
111
|
+
if (g.endsWith("/**")) expanded.add(g.slice(0, -3) || "/");
|
|
112
|
+
else if (!/[*?]/.test(g)) expanded.add(`${g}/**`);
|
|
113
|
+
}
|
|
114
|
+
return [...expanded].map(globToRegExp);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 目标是否落在某个范围里:相对路径与绝对路径都试,scope 写哪种都认。 */
|
|
118
|
+
export function matches(regexps: RegExp[], cwd: string, target: string): boolean {
|
|
119
|
+
if (regexps.length === 0) return false;
|
|
120
|
+
const base = canonical(cwd);
|
|
121
|
+
const abs = canonical(resolve(cwd, target));
|
|
122
|
+
const rel = relative(base, abs);
|
|
123
|
+
// 落在工作树之外的一律不认。范围是相对项目写的,项目就是这棵树;软链指到树外时真实路径
|
|
124
|
+
// 会带 "..",整棵树的范围("." / "**")也不该把它放进来。
|
|
125
|
+
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false;
|
|
126
|
+
for (const re of regexps) {
|
|
127
|
+
if (re.test(rel) || re.test(abs)) return true;
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 绝对授权(writeScope 里的绝对路径)按前缀比对,允许落在树外。
|
|
134
|
+
*
|
|
135
|
+
* 只给写用:读范围继续绑定在项目树上。绝对路径是父代理点名的,子代理无法自己构造,
|
|
136
|
+
* 所以它不破坏「相对授权不能出树」那条防线。
|
|
137
|
+
*/
|
|
138
|
+
export function underAny(grants: string[], cwd: string, target: string): boolean {
|
|
139
|
+
if (grants.length === 0) return false;
|
|
140
|
+
const abs = canonical(resolve(cwd, target));
|
|
141
|
+
for (const grant of grants) {
|
|
142
|
+
if (abs === grant) return true;
|
|
143
|
+
if (abs.startsWith(grant.endsWith(sep) ? grant : `${grant}${sep}`)) return true;
|
|
144
|
+
}
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POLICY / PARSE 层:把派单载荷与角色 md 基线解析成 `Policy`。两层的合并不在这里:
|
|
3
|
+
* wiring/context.ts 的 applyRoleBaseline 逐字段把基线补进载荷缺失的字段,
|
|
4
|
+
* bash.deny 取并集作硬底线。实现按主题住在 `policy/` 下的两个模块里,本文件只做
|
|
5
|
+
* 桶装再导出,调用方的 `from "./index.ts"` 全部原样可用,行为不变。
|
|
6
|
+
* - `policy/payload.ts`:读派单载荷交给我们的配置对象(键白名单、fail closed)。
|
|
7
|
+
* - `policy/glob.ts`:glob 编译与范围比对原语,以及共享类型 `Policy` / `ToolDeclaration`。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
BINDINGS_ENV,
|
|
12
|
+
PAYLOAD_IGNORED_KEYS,
|
|
13
|
+
NAMESPACE_BLOCK_KEYS,
|
|
14
|
+
NAMESPACE_KEYS,
|
|
15
|
+
POLICY_CONFIG_KEYS,
|
|
16
|
+
asObject,
|
|
17
|
+
denyAll,
|
|
18
|
+
extractCallConfig,
|
|
19
|
+
parsePolicyObject,
|
|
20
|
+
parseToolDeclarations,
|
|
21
|
+
parseWriteScope,
|
|
22
|
+
positiveInt,
|
|
23
|
+
unknownNamespaceKeysError,
|
|
24
|
+
unknownPayloadKeysError,
|
|
25
|
+
} from "./payload.ts";
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
compile,
|
|
30
|
+
globToRegExp,
|
|
31
|
+
matches,
|
|
32
|
+
normalizeGlob,
|
|
33
|
+
underAny,
|
|
34
|
+
} from "./glob.ts";
|
|
35
|
+
|
|
36
|
+
export type { Policy, ToolDeclaration } from "./glob.ts";
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POLICY / PAYLOAD:读派单载荷(extractCallConfig)并把它落成 `Policy`
|
|
3
|
+
* (parsePolicyObject)——键白名单、fail closed 的解析。角色 md 是基线层,
|
|
4
|
+
* 其 extend.permissions 由 wiring/context.ts 的 applyRoleBaseline 逐字段补进
|
|
5
|
+
* 载荷缺失的字段,bash.deny 与载荷的并集在那里是硬底线。本层是纯函数,
|
|
6
|
+
* 不持有会话状态;policy.ts 只做桶装再导出。
|
|
7
|
+
*/
|
|
8
|
+
import { isAbsolute } from "node:path";
|
|
9
|
+
import { parseBashRule } from "../bash/index.ts";
|
|
10
|
+
import { DEFAULT_MAX_DENIES, DEFAULT_MAX_WRITE_DENIES } from "../budgets.ts";
|
|
11
|
+
import { BINDING_NAMESPACE, bindingKey } from "../role-config.ts";
|
|
12
|
+
import { canonical } from "../paths/index.ts";
|
|
13
|
+
import { compile, type Policy, type ToolDeclaration } from "./glob.ts";
|
|
14
|
+
|
|
15
|
+
export const BINDINGS_ENV = "PI_SUBAGENT_EXTENSION_BINDINGS";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 解析 bindings.tools:名字 → 类别覆盖。
|
|
19
|
+
*
|
|
20
|
+
* 写坏就整份绑定作废(fail closed),与 scope / writeScope 的处理一致:一个说不清工具
|
|
21
|
+
* 类别的会话没办法安全地放行任何工具。
|
|
22
|
+
*/
|
|
23
|
+
export function parseToolDeclarations(value: unknown): {
|
|
24
|
+
declarations: Record<string, ToolDeclaration>;
|
|
25
|
+
error?: string;
|
|
26
|
+
} {
|
|
27
|
+
// 工具名来自外部输入:用无原型对象,避免 "__proto__" 这类键改写原型链。
|
|
28
|
+
const declarations: Record<string, ToolDeclaration> = Object.create(null);
|
|
29
|
+
if (value === undefined) return { declarations };
|
|
30
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
31
|
+
return { declarations, error: "tools must be an object of { toolName: { access, path } }" };
|
|
32
|
+
}
|
|
33
|
+
for (const [name, raw] of Object.entries(value as Record<string, unknown>)) {
|
|
34
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
35
|
+
return { declarations, error: `tools.${name} must be an object` };
|
|
36
|
+
}
|
|
37
|
+
const entry = raw as { access?: unknown; path?: unknown; transferSource?: unknown };
|
|
38
|
+
if (entry.access !== undefined && entry.access !== "read" && entry.access !== "write") {
|
|
39
|
+
return { declarations, error: `tools.${name}.access must be "read" or "write"` };
|
|
40
|
+
}
|
|
41
|
+
if (
|
|
42
|
+
entry.path !== undefined &&
|
|
43
|
+
entry.path !== false &&
|
|
44
|
+
(typeof entry.path !== "string" || entry.path.trim() === "")
|
|
45
|
+
) {
|
|
46
|
+
return { declarations, error: `tools.${name}.path must be a non-empty string or false` };
|
|
47
|
+
}
|
|
48
|
+
if (
|
|
49
|
+
entry.transferSource !== undefined &&
|
|
50
|
+
entry.transferSource !== "read" &&
|
|
51
|
+
entry.transferSource !== "write"
|
|
52
|
+
) {
|
|
53
|
+
return { declarations, error: `tools.${name}.transferSource must be "read" or "write"` };
|
|
54
|
+
}
|
|
55
|
+
const declaration: ToolDeclaration = {};
|
|
56
|
+
if (entry.access !== undefined) declaration.access = entry.access;
|
|
57
|
+
if (entry.path !== undefined) {
|
|
58
|
+
declaration.path = entry.path === false ? false : (entry.path as string).trim();
|
|
59
|
+
}
|
|
60
|
+
if (entry.transferSource !== undefined) declaration.transferSource = entry.transferSource;
|
|
61
|
+
declarations[name] = declaration;
|
|
62
|
+
}
|
|
63
|
+
return { declarations };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* bindings 存在但无法使用时的策略:会话保持活跃,但什么都拿不到。
|
|
68
|
+
*
|
|
69
|
+
* 预算用缺省值而不是 0:0 表示「永不计数」,那会让一次写坏的绑定变成无限重试的会话 ——
|
|
70
|
+
* 每个调用都被拒、却永远不会停,正是这条判据要避免的状态。拒几次就硬停,父代理能从拒绝
|
|
71
|
+
* 文案里看到真实原因(哪一份绑定、哪里写错)。
|
|
72
|
+
*/
|
|
73
|
+
export function denyAll(source: string): Policy {
|
|
74
|
+
return {
|
|
75
|
+
globs: [],
|
|
76
|
+
regexps: [],
|
|
77
|
+
writeGlobs: [],
|
|
78
|
+
absoluteWrite: [],
|
|
79
|
+
writeRegexps: [],
|
|
80
|
+
source,
|
|
81
|
+
readOnly: true,
|
|
82
|
+
maxReads: 0,
|
|
83
|
+
allowTools: [],
|
|
84
|
+
tools: {},
|
|
85
|
+
probe: undefined,
|
|
86
|
+
maxDenies: DEFAULT_MAX_DENIES,
|
|
87
|
+
maxWriteDenies: DEFAULT_MAX_WRITE_DENIES,
|
|
88
|
+
active: true,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function positiveInt(value: unknown): number {
|
|
93
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
94
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `extensionBindings` 里的这两个键属于角色 md,不该影响本次派单的策略。 */
|
|
98
|
+
export const PAYLOAD_IGNORED_KEYS = ["setup", "output"] as const;
|
|
99
|
+
|
|
100
|
+
/** 命名空间层站在 permissions 旁边的块级键;不进策略,交给 worktree 决策。 */
|
|
101
|
+
export const NAMESPACE_BLOCK_KEYS = ["worktree"] as const;
|
|
102
|
+
/** 命名空间层能识别的全部键;其余键一律拒绝,免得拼写错误被静默忽略。 */
|
|
103
|
+
export const NAMESPACE_KEYS = ["permissions", ...NAMESPACE_BLOCK_KEYS, ...PAYLOAD_IGNORED_KEYS] as const;
|
|
104
|
+
/** 从 PI_SUBAGENT_EXTENSION_BINDINGS 里取本扩展的 namespace 配置对象;版本不匹配一律拒绝。 */
|
|
105
|
+
interface CallConfigResult {
|
|
106
|
+
config?: Record<string, unknown>;
|
|
107
|
+
/** 命名空间层的块级键(如 worktree),不属于 permissions 策略。 */
|
|
108
|
+
blocks?: Record<string, unknown>;
|
|
109
|
+
error?: string;
|
|
110
|
+
/** 命名空间层或 permissions 层出现的、必须只告警一次的键。 */
|
|
111
|
+
ignored?: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 派单载荷 permissions 里出现 parsePolicyObject 不认识的键时的拒绝文案。
|
|
116
|
+
* `write` / `budgets` 是角色 md 的拼法,这里点名正确的派单拼法,避免用户照 md 抄过来被静默丢弃。
|
|
117
|
+
*/
|
|
118
|
+
export function unknownPayloadKeysError(keys: readonly string[], prefix: string): string {
|
|
119
|
+
const hints: Record<string, string> = {
|
|
120
|
+
write: 'the dispatch spelling is "writeScope"',
|
|
121
|
+
budgets: 'the dispatch spelling is "maxReads" / "maxDenies"',
|
|
122
|
+
};
|
|
123
|
+
const listed = keys
|
|
124
|
+
.map((key) => (hints[key] ? `"${key}" (${hints[key]})` : `"${key}"`))
|
|
125
|
+
.join(", ");
|
|
126
|
+
return `${prefix}.permissions: unknown key(s) ${listed}; everything is refused`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function unknownNamespaceKeysError(keys: readonly string[], prefix: string): string {
|
|
130
|
+
const listed = keys.map((key) => `"${key}"`).join(", ");
|
|
131
|
+
const accepted = NAMESPACE_KEYS.map((key) => `"${key}"`).join(", ");
|
|
132
|
+
return `${prefix}: unknown namespace key(s) ${listed}; accepted namespace keys are ${accepted}; everything is refused`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function extractCallConfig(raw: string | undefined): CallConfigResult {
|
|
136
|
+
if (!raw?.trim()) return {};
|
|
137
|
+
let parsed: unknown;
|
|
138
|
+
try {
|
|
139
|
+
parsed = JSON.parse(raw);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return {
|
|
142
|
+
error: `${BINDINGS_ENV} is not valid JSON (${error instanceof Error ? error.message : String(error)}); everything is refused`,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
146
|
+
return { error: `${BINDINGS_ENV} is not a JSON object; everything is refused` };
|
|
147
|
+
}
|
|
148
|
+
const record = parsed as Record<string, unknown>;
|
|
149
|
+
const prefix = `${BINDING_NAMESPACE}/`;
|
|
150
|
+
const keys = Object.keys(record).filter((key) => key.startsWith(prefix));
|
|
151
|
+
// 绑定是给别的扩展的,本扩展不参与。
|
|
152
|
+
if (keys.length === 0) return {};
|
|
153
|
+
if (keys.length > 1) {
|
|
154
|
+
return { error: `ambiguous: more than one ${BINDING_NAMESPACE}/* namespace; everything is refused` };
|
|
155
|
+
}
|
|
156
|
+
const key = keys[0];
|
|
157
|
+
if (key !== bindingKey()) {
|
|
158
|
+
return { error: `this build supports ${bindingKey()}, got ${key}; everything is refused` };
|
|
159
|
+
}
|
|
160
|
+
const cfg = record[key];
|
|
161
|
+
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) {
|
|
162
|
+
return { error: `extensionBindings ${key}: the configuration is not an object; everything is refused` };
|
|
163
|
+
}
|
|
164
|
+
const namespace = cfg as Record<string, unknown>;
|
|
165
|
+
const expected = `{"extensionBindings":{"${key}":{"permissions":{"scope":["src/**"]}}}}`;
|
|
166
|
+
// 派单载荷和角色 md 的 extend.permissions 是同一个对象;扁平写法不是「少一层语法糖」,
|
|
167
|
+
// 而是另一份契约。放过它会在用户照文档写对时反而拒绝,所以这里只认一层 permissions。
|
|
168
|
+
if (!Object.hasOwn(namespace, "permissions")) {
|
|
169
|
+
return {
|
|
170
|
+
error: `extensionBindings ${key}: missing "permissions" object; the namespace key must contain a permissions object; expected ${expected}; everything is refused`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const perms = asObject(namespace.permissions);
|
|
174
|
+
if (!perms) {
|
|
175
|
+
return {
|
|
176
|
+
error: `extensionBindings ${key}.permissions must be an object; expected ${expected}; everything is refused`,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
// 命名空间层只认 permissions / 块级键 / 忽略对;多出来的键直接拒绝,不让拼写错误藏在这里。
|
|
180
|
+
const unknownNamespace = Object.keys(namespace).filter(
|
|
181
|
+
(name) => !(NAMESPACE_KEYS as readonly string[]).includes(name),
|
|
182
|
+
);
|
|
183
|
+
if (unknownNamespace.length > 0) {
|
|
184
|
+
return { error: unknownNamespaceKeysError(unknownNamespace, `extensionBindings ${key}`) };
|
|
185
|
+
}
|
|
186
|
+
const config: Record<string, unknown> = Object.create(null);
|
|
187
|
+
const unknown: string[] = [];
|
|
188
|
+
for (const [name, value] of Object.entries(perms)) {
|
|
189
|
+
// setup / output 是给别的扩展的,本扩展不参与,只告警一次。
|
|
190
|
+
if ((PAYLOAD_IGNORED_KEYS as readonly string[]).includes(name)) continue;
|
|
191
|
+
// 原型键不是声明:Object.create(null) 让它成为普通键,这里直接跳过,不进 config 也不报错。
|
|
192
|
+
if (name === "__proto__") continue;
|
|
193
|
+
if ((POLICY_CONFIG_KEYS as readonly string[]).includes(name)) {
|
|
194
|
+
config[name] = value;
|
|
195
|
+
} else {
|
|
196
|
+
unknown.push(name);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (unknown.length > 0) {
|
|
200
|
+
return { error: unknownPayloadKeysError(unknown, `extensionBindings ${key}`) };
|
|
201
|
+
}
|
|
202
|
+
const blocks: Record<string, unknown> = Object.create(null);
|
|
203
|
+
for (const name of NAMESPACE_BLOCK_KEYS) {
|
|
204
|
+
if (Object.hasOwn(namespace, name)) blocks[name] = namespace[name];
|
|
205
|
+
}
|
|
206
|
+
const ignored = PAYLOAD_IGNORED_KEYS.filter(
|
|
207
|
+
(name) => Object.hasOwn(namespace, name) || Object.hasOwn(perms, name),
|
|
208
|
+
);
|
|
209
|
+
return { config, blocks, ignored: [...ignored] };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
213
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
214
|
+
return value as Record<string, unknown>;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 配置对象 → 策略。
|
|
219
|
+
*
|
|
220
|
+
* `requireScope` 为 true 时(本次调用的 bindings)scope 必须写成字符串数组,写错
|
|
221
|
+
* 就全拒;为 false 时(agent profile 的默认值)允许不写 scope:角色的默认值不知道
|
|
222
|
+
* 本次任务管哪些路径,此时文件访问全拒但 bash 白名单照常可用——漏传 bindings 是
|
|
223
|
+
* 「响的」失败,不是「什么限制都没有」。
|
|
224
|
+
*/
|
|
225
|
+
/**
|
|
226
|
+
* 写范围(edit / write 工具),与 bash.writablePaths(进程层)分开:
|
|
227
|
+
* 不写 writeScope → 等于读范围,现有派单行为不变;
|
|
228
|
+
* readOnly → 默认等价于空写范围;但**同一层写的 writeScope 优先**,这样「只读会话 + 一个
|
|
229
|
+
* 报告文件」是能表达的,而不是非黑即白。派单只写 readOnly 时不写 writeScope,
|
|
230
|
+
* applyRoleBaseline(wiring/context.ts)会跳过 md 基线的 writeScope,那份压不过它;
|
|
231
|
+
* 写了 → 只认这一份,写超出即拒,读不受影响。
|
|
232
|
+
*/
|
|
233
|
+
export function parseWriteScope(
|
|
234
|
+
config: Record<string, unknown>,
|
|
235
|
+
globs: string[],
|
|
236
|
+
readOnly: boolean,
|
|
237
|
+
source: string,
|
|
238
|
+
): { writeGlobs?: string[]; error?: string } {
|
|
239
|
+
if (readOnly && config.writeScope === undefined) return { writeGlobs: [] };
|
|
240
|
+
if (config.writeScope === undefined) return { writeGlobs: globs };
|
|
241
|
+
const ws = config.writeScope;
|
|
242
|
+
if (!Array.isArray(ws) || ws.some((g) => typeof g !== "string" || !g.trim())) {
|
|
243
|
+
return { error: `${source}.writeScope must be an array of strings; everything is refused` };
|
|
244
|
+
}
|
|
245
|
+
return { writeGlobs: (ws as string[]).map((g) => g.trim()).filter(Boolean) };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* parsePolicyObject 认识的配置键。派单载荷的 permissions 对象只认这些键,
|
|
250
|
+
* 其余键由 extractCallConfig 在入口拒绝(见 unknownPayloadKeysError),避免
|
|
251
|
+
* 「拼错的收窄字段被静默丢弃」——丢弃一个写范围收窄会把写授权放大到整个读范围。
|
|
252
|
+
*/
|
|
253
|
+
export const POLICY_CONFIG_KEYS = [
|
|
254
|
+
"scope",
|
|
255
|
+
"writeScope",
|
|
256
|
+
"readOnly",
|
|
257
|
+
"tools",
|
|
258
|
+
"allowTools",
|
|
259
|
+
"bash",
|
|
260
|
+
"probe",
|
|
261
|
+
"maxReads",
|
|
262
|
+
"maxDenies",
|
|
263
|
+
"maxWriteDenies",
|
|
264
|
+
] as const;
|
|
265
|
+
|
|
266
|
+
export function parsePolicyObject(
|
|
267
|
+
config: Record<string, unknown>,
|
|
268
|
+
source: string,
|
|
269
|
+
options: { requireScope: boolean },
|
|
270
|
+
): Policy {
|
|
271
|
+
const scope = config.scope;
|
|
272
|
+
const scopeGiven = scope !== undefined;
|
|
273
|
+
if (scopeGiven && (!Array.isArray(scope) || scope.some((g) => typeof g !== "string" || !g.trim()))) {
|
|
274
|
+
return denyAll(`${source}.scope must be an array of strings; everything is refused`);
|
|
275
|
+
}
|
|
276
|
+
if (!scopeGiven && options.requireScope) {
|
|
277
|
+
return denyAll(`${source}.scope is missing; everything is refused`);
|
|
278
|
+
}
|
|
279
|
+
const globs = scopeGiven ? (scope as string[]).map((g) => g.trim()).filter(Boolean) : [];
|
|
280
|
+
const readOnly = config.readOnly === true;
|
|
281
|
+
const write = parseWriteScope(config, globs, readOnly, source);
|
|
282
|
+
if (write.error) return denyAll(write.error);
|
|
283
|
+
const toolDeclarations = parseToolDeclarations(config.tools);
|
|
284
|
+
if (toolDeclarations.error)
|
|
285
|
+
return denyAll(`${source}.${toolDeclarations.error}; everything is refused`);
|
|
286
|
+
const allWrite = write.writeGlobs as string[];
|
|
287
|
+
const absoluteWrite = allWrite.filter((g) => isAbsolute(g)).map((g) => canonical(g));
|
|
288
|
+
const writeGlobs = allWrite.filter((g) => !isAbsolute(g));
|
|
289
|
+
const allowTools = Array.isArray(config.allowTools)
|
|
290
|
+
? (config.allowTools as unknown[]).filter((t): t is string => typeof t === "string" && t.trim() !== "")
|
|
291
|
+
: [];
|
|
292
|
+
return {
|
|
293
|
+
globs,
|
|
294
|
+
regexps: compile(globs),
|
|
295
|
+
writeGlobs,
|
|
296
|
+
absoluteWrite,
|
|
297
|
+
writeRegexps: compile(writeGlobs),
|
|
298
|
+
source,
|
|
299
|
+
readOnly,
|
|
300
|
+
maxReads: positiveInt(config.maxReads),
|
|
301
|
+
allowTools,
|
|
302
|
+
tools: toolDeclarations.declarations,
|
|
303
|
+
bash: parseBashRule(config.bash),
|
|
304
|
+
probe: config.probe,
|
|
305
|
+
// 撞权限是纯错误信号:不配也开,父代理可以显式写 0 关掉。
|
|
306
|
+
// 缺省 5:停机是硬停,判早一次就丢掉整轮任务,而多给几次只浪费几个调用。
|
|
307
|
+
maxDenies: config.maxDenies === 0 ? 0 : positiveInt(config.maxDenies) || DEFAULT_MAX_DENIES,
|
|
308
|
+
// 缺省 2:写拒是用法错(该回报告而不是落盘),给两次机会换做法就够。
|
|
309
|
+
maxWriteDenies: config.maxWriteDenies === 0 ? 0 : positiveInt(config.maxWriteDenies) || DEFAULT_MAX_WRITE_DENIES,
|
|
310
|
+
active: true,
|
|
311
|
+
};
|
|
312
|
+
}
|