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,585 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { parse } from "yaml";
|
|
5
|
+
import { allEntries, classifyCommand, commandAccess, commandMatches, deniedEntry, deniedEnvAssignment, pathCandidates, requiresNetwork, type BashRule } from "../../bash/index.ts";
|
|
6
|
+
import { dispatchToolFaceRefusal, headEntriesHint, warnUnresolvedAgentName, warnUntrackedWorktreeProfile } from "../../notices.ts";
|
|
7
|
+
import { STOP_NOTICE } from "../../probe.ts";
|
|
8
|
+
import { shouldDefaultWorktree, WORKTREE_TOOLS } from "../../worktree-default.ts";
|
|
9
|
+
import { agentMdDirs, BINDING_NAMESPACE, bindingKey, readExtendBlock, resolveAgentFile, worktreeFromBlock } from "../../role-config.ts";
|
|
10
|
+
import { asObject, matches, type Policy } from "../../policy/index.ts";
|
|
11
|
+
import { dependencyGateVerdict } from "../../dependencies.ts";
|
|
12
|
+
import { expandPath, privatisedDirs, resolveComparable, underRoot } from "../../paths/index.ts";
|
|
13
|
+
import { buildSpec, detectPnpmStore, describeHelper, dropSpecFile, helperPath, SANDBOX_DEVICE_PATHS, scratchDir, wrapInSandbox, writeSpecFile } from "../../sandbox/index.ts";
|
|
14
|
+
import type { Wiring } from "../context.ts";
|
|
15
|
+
import { originalCommand } from "./original-args.ts";
|
|
16
|
+
import { bail, deny, pathToolVerdict, preview, writeBail } from "./paths.ts";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* tool_call 的总判定(judgeToolCall)从 index.ts 的 activate() 闭包整体移入。
|
|
20
|
+
* 判定函数不持有会话状态:会话状态都在 Wiring 上,由调用方传入;per-activation 的
|
|
21
|
+
* schema 缓存(schemaPathArgs)、pi 与 ctx 也经入参对象由 activate 传入 —— 与 paths.ts
|
|
22
|
+
* 同一形状(imports 只来自 node:* 与叶子模块,不来自 index.ts)。
|
|
23
|
+
*
|
|
24
|
+
* 闸门顺序是有意为之,别打乱(自上而下):
|
|
25
|
+
* 1. 派单预检(工具面冲突的拒绝、解析不到角色 md 的告警)、派单默认值补值与版本
|
|
26
|
+
* 告警先于范围判定 —— 预检判的是 pi-subagents 自己的解析与宿主工具面,与本层
|
|
27
|
+
* 策略激活无关;补值不是拒绝,预检的拒绝是配置冲突,只拒不计入预算;
|
|
28
|
+
* 2. 策略未激活直接放行;
|
|
29
|
+
* 3. SAFE_TOOLS(求援通道)最先放行,不受任何停机影响;
|
|
30
|
+
* 4. 已停机的会话挡住其后的一切(terminate);
|
|
31
|
+
* 5. 探针边界先于本工具的判定;
|
|
32
|
+
* 6. RUNTIME_TOOLS(todo 这类会话运行时工具)在停机闸门与探针边界之后放行:
|
|
33
|
+
* 活着的会话永远有它,停机的会话一个也没有;排在探针边界之后,纯 todo
|
|
34
|
+
* 空转的会话仍会被探针判据停掉;
|
|
35
|
+
* 7. bash → 其他执行器 → 路径类工具 → allowTools → 其余一律拒(fail closed)。
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 已知路径类工具的访问类别:读认读范围,写认写范围。
|
|
40
|
+
*
|
|
41
|
+
* 名字只是**默认值**,不是判据的全部。目标路径从工具自己的入参 schema 里取(见
|
|
42
|
+
* `pathArgOf`),父代理还能用 bindings.tools 覆盖。名字表之所以省不掉,是因为
|
|
43
|
+
* 「这个工具会不会改文件」推不出来,必须有人声明。
|
|
44
|
+
*
|
|
45
|
+
* 为什么必须收录 hashline 那一套:pi-hashline-edit-pro 把内置 `edit` 从活动工具集里
|
|
46
|
+
* 删掉(它自己 `setActiveTools(active.filter(t => t !== "edit"))`),换上一组以行锚点
|
|
47
|
+
* 定位的编辑工具。只认 `edit` / `write` 的名单在这种宿主上会把整套编辑能力判成
|
|
48
|
+
* 「未知工具」而拒绝——子代理一个改文件的工具都拿不到。
|
|
49
|
+
*/
|
|
50
|
+
const DEFAULT_TOOL_ACCESS: Record<string, "read" | "write"> = {
|
|
51
|
+
read: "read",
|
|
52
|
+
grep: "read",
|
|
53
|
+
find: "read",
|
|
54
|
+
ls: "read",
|
|
55
|
+
outline: "read",
|
|
56
|
+
edit: "write",
|
|
57
|
+
write: "write",
|
|
58
|
+
replace: "write",
|
|
59
|
+
replace_match: "write",
|
|
60
|
+
insert: "write",
|
|
61
|
+
copy: "write",
|
|
62
|
+
move: "write",
|
|
63
|
+
undo_last_change: "write",
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const EXEC_TOOLS = ["bash", "powershell", "codemode"];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 不碰文件系统的会话级运行时工具,范围生效时照常放行。
|
|
70
|
+
* contact_supervisor / intercom 是子代理向父代理(监督者)转告的正当通道——探针的
|
|
71
|
+
* 停机判据本来就要它立刻上报,封锁它只会把信息憋在死掉的会话里。
|
|
72
|
+
*/
|
|
73
|
+
export const SAFE_TOOLS = ["structured_output", "contact_supervisor", "intercom"];
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 会话级运行时工具:不碰文件系统、不与外界通信,只维护会话自己的任务清单。
|
|
77
|
+
* 与 SAFE_TOOLS 的差别有两条,都是刻意的:
|
|
78
|
+
* - 判定位置在停机闸门**之后**(SAFE_TOOLS 在之前):停机的会话不该再改任何东西,
|
|
79
|
+
* 任务清单也不例外;
|
|
80
|
+
* - 不豁免 index.ts 的计数归零:放行的 todo 不得清空拒绝预算,否则子代理可以在
|
|
81
|
+
* 两次拒之间插一句 todo 把连续计数洗掉,永远到不了硬停 —— 与求援通道被排除在
|
|
82
|
+
* 归零之外是同一个道理,所以这里开第三个名单而不是往 SAFE_TOOLS 里加一员。
|
|
83
|
+
*/
|
|
84
|
+
export const RUNTIME_TOOLS = ["todo"];
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 命令里是否有**未加引号**的 shell 控制字符。
|
|
88
|
+
*
|
|
89
|
+
* 命令最终以 `bash -lc <command>` 执行,所以引号语义就是 bash 的语义:
|
|
90
|
+
* 单引号内一切惰性;双引号内只有 `$`、反引号、反斜杠仍会展开,`; & | < > ( )`
|
|
91
|
+
* 都是普通字符。之前是纯文本正则匹配,于是 `python3 -c "print(1)"` 这种引号内的
|
|
92
|
+
* 括号也被拒——dogfooding 时一个子代理因此无法自验 YAML。
|
|
93
|
+
*
|
|
94
|
+
* 不进引号的正斜杠也一律拒;引号闭合不对(子代理手写错)也拒,交给它重写。
|
|
95
|
+
*/
|
|
96
|
+
export function hasUnquotedShellControl(command: string): boolean {
|
|
97
|
+
let quote: '"' | "'" | undefined;
|
|
98
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
99
|
+
const ch = command[i];
|
|
100
|
+
if (quote === "'") {
|
|
101
|
+
if (ch === "'") quote = undefined;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (quote === '"') {
|
|
105
|
+
// 双引号内反斜杠仍会转义,跳过后一个字符(保守:当成惰性)
|
|
106
|
+
if (ch === "\\") {
|
|
107
|
+
i += 1;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (ch === '"') {
|
|
111
|
+
quote = undefined;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (ch === "$" || ch === "`") return true;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (ch === "'") {
|
|
118
|
+
quote = "'";
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (ch === '"') {
|
|
122
|
+
quote = '"';
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (ch === "\\" || ch === "\n" || ch === "\r") return true;
|
|
126
|
+
if (";&|<>()`$".includes(ch)) return true;
|
|
127
|
+
}
|
|
128
|
+
// 引号没闭合:命令本身是坏的,直接拒
|
|
129
|
+
return quote !== undefined;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 只读类 bash 命令的参数路径可以指向、且无需再解释的系统目录:设备与系统信息,不是工具。
|
|
134
|
+
*
|
|
135
|
+
* 沙箱的读面仍是 `/`:node、rg、cargo 全在 /nix/store,收窄读根会一次打死所有命令。所以这一层
|
|
136
|
+
* 不判「能不能读」,只在插件层把参数里的路径引到任务范围上 —— 引导,不是墙。
|
|
137
|
+
*
|
|
138
|
+
* 刻意**不**含 /nix/store、/usr、/bin、/sbin、/lib、/lib64:工具住在这些目录里,不代表命令的参数
|
|
139
|
+
* 会包含它们 —— 程序位由 bash 经 PATH 解析,根本不进参数表(见 bash/index.ts 的 `pathCandidates`)。
|
|
140
|
+
* 参数里真的出现 store 或系统二进制目录,就是子代理在工具链里翻东西,正是要把路径引回范围的场景
|
|
141
|
+
* (实测:一个子代理在 258MB 的包体里 rg 了 140 次,全部为空)。
|
|
142
|
+
*/
|
|
143
|
+
const BASH_READ_EXEMPT_ROOTS = ["/etc", "/proc", "/dev", "/sys"];
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 一条只读类命令的参数路径是否可放行。任一条成立即放行:在工作树内 / 在设备与系统信息豁免集内 /
|
|
147
|
+
* 在 cwd 或私有 scratch 之下 / 是沙箱默认可写的设备。
|
|
148
|
+
*
|
|
149
|
+
* 方向是宁可漏放:漏放只是少一次引导,误拒会让一条本来能跑的命令死在插件层,而子代理多半把它读成
|
|
150
|
+
* 「这台机器坏了」,然后换一百个写法再试。
|
|
151
|
+
*
|
|
152
|
+
* 下面 `expandPath` 那道守卫(返回 undefined 即放行)是防御性代码,当前**不可达**:候选由
|
|
153
|
+
* `pathCandidates` 产出,必含斜杠因而非空,而 `expandPath` 只在空串时返回 undefined。
|
|
154
|
+
*/
|
|
155
|
+
function bashPathArgAllowed(token: string, cwd: string, rule: BashRule, policy: Policy): boolean {
|
|
156
|
+
const expanded = expandPath(cwd, token);
|
|
157
|
+
if (!expanded) return true;
|
|
158
|
+
// 范围判定内部已经按真实路径比过软链,传绝对路径进去不影响它的语义。
|
|
159
|
+
if (matches(policy.regexps, cwd, expanded)) return true;
|
|
160
|
+
// 豁免集要按字面与真实两种形态各比一次:有些系统上 /etc 自己就是软链(macOS 上是 /private/etc),
|
|
161
|
+
// 只比一种会让同一个路径有时豁免、有时不豁免。
|
|
162
|
+
//
|
|
163
|
+
// 真实路径用 `resolveComparable` 而不是 `canonical`:前者是与 helper 的 `fs::canonicalize` 对齐的
|
|
164
|
+
// 实现(OS 的 realpath + 字面拼尾),后者是 Node 的自实现版,两边在部分输入上结果不同。
|
|
165
|
+
const real = resolveComparable(expanded);
|
|
166
|
+
if (BASH_READ_EXEMPT_ROOTS.some((root) => underRoot(root, expanded) || underRoot(root, real))) return true;
|
|
167
|
+
if (underRoot(resolveComparable(cwd), real)) return true;
|
|
168
|
+
// scratch 用 privatisedDirs:cwd 落在 /tmp 之下时 helper 并不挂那个 tmpfs,那就不算
|
|
169
|
+
// 「命令自己的临时目录」,免得 /tmp 顺带把整片宿主机路径放进来。
|
|
170
|
+
for (const dir of privatisedDirs(cwd, scratchDir(cwd, rule))) {
|
|
171
|
+
if (underRoot(resolveComparable(dir), real)) return true;
|
|
172
|
+
}
|
|
173
|
+
return SANDBOX_DEVICE_PATHS.some((device) => underRoot(device, real));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 只读类命令里第一个指向范围之外的路径参数;没有就返回 undefined。
|
|
178
|
+
*
|
|
179
|
+
* 只看读类命令:写类命令的文件面由 Landlock 与写范围管,而这里判的是「它在读什么」。候选的抽取
|
|
180
|
+
* 在 bash/index.ts 里(纯字符串),放行判定留在这里,因为豁免集、scratch 与 `resolveComparable` 都在这边。
|
|
181
|
+
*/
|
|
182
|
+
function foreignBashPath(command: string, cwd: string, rule: BashRule, policy: Policy): string | undefined {
|
|
183
|
+
return pathCandidates(command).find((token) => !bashPathArgAllowed(token, cwd, rule, policy));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 派单版本号写错的提示整进程只说一次;不在 session_start 清空。 */
|
|
187
|
+
let warnedDispatchVersion = false;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 派单目标角色的 worktree 默认值。按 input.agent 解析角色 md(与子代理侧同一套
|
|
191
|
+
* resolveAgentFile / readExtendBlock,父子不会对「md 在哪」各说各话),取
|
|
192
|
+
* extend.worktree.enabled。enabled: true 且派单没带 worktree(undefined / null,
|
|
193
|
+
* `??=` 语义)时补一个 true;显式 false 或其它值一律不动。md 缺席、没有 extend 块、
|
|
194
|
+
* 块写坏、enabled: false 都按「没配置」处理:不拒绝、不计数、不告警(fail open)。
|
|
195
|
+
*
|
|
196
|
+
* `fromMd` 标记这个值是否来自角色 md:派单自带 bindings 走的不是 md,补值时
|
|
197
|
+
* 不需要提示「worktree 副本里没有那份 md」。mdFile 只在 fromMd 时有意义,
|
|
198
|
+
* 未跟踪告警要用它点名文件。
|
|
199
|
+
*/
|
|
200
|
+
interface WorktreeStrategy {
|
|
201
|
+
worktree?: unknown;
|
|
202
|
+
fromMd: boolean;
|
|
203
|
+
mdFile?: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function worktreePolicyFor(
|
|
207
|
+
cwd: string,
|
|
208
|
+
call: Record<string, unknown> | undefined,
|
|
209
|
+
agent: string,
|
|
210
|
+
/** 调用方(预检)已解析过的 md 文件;缺省时按 agent 现场解析,目录序与 resolveAgentFile 相同。 */
|
|
211
|
+
resolvedMdFile?: string,
|
|
212
|
+
): WorktreeStrategy {
|
|
213
|
+
const mdFile = resolvedMdFile ?? (resolveAgentFile(agent, cwd, homedir()) ?? undefined);
|
|
214
|
+
const block = mdFile ? readExtendBlock(mdFile).block : undefined;
|
|
215
|
+
const enabled = worktreeFromBlock(block ?? {}).worktree?.enabled === true;
|
|
216
|
+
if (enabled && (call?.worktree === undefined || call?.worktree === null)) {
|
|
217
|
+
return { worktree: true, fromMd: true, mdFile };
|
|
218
|
+
}
|
|
219
|
+
return call?.worktree === true ? { worktree: true, fromMd: false } : { fromMd: false };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 角色 md frontmatter 顶层的 `tools:` 列表 —— pi-subagents 检查子代理工具面用的
|
|
224
|
+
* 就是这份声明,预检读同一份事实,不自己发明检查。
|
|
225
|
+
*
|
|
226
|
+
* 没有读得到文件、没有 frontmatter、没有 `tools:`、不是非空字符串数组、YAML 解不开
|
|
227
|
+
* —— 一律 undefined(fail open):预检漏报只是少一次提前拒绝,误报会把一条本来能跑
|
|
228
|
+
* 的派单打死在插件层。文件切片这一段与 readExtendBlock 的 frontmatter 外壳重复,
|
|
229
|
+
* 但那份代码在 role-config.ts 里只返回 extend 块,而本文件被授权改动的清单里没有
|
|
230
|
+
* role-config.ts —— 能把外壳提进共享层时再合,先不为此越权。
|
|
231
|
+
*/
|
|
232
|
+
const declaredToolsOf = (mdFile: string): string[] | undefined => {
|
|
233
|
+
let text: string;
|
|
234
|
+
try {
|
|
235
|
+
text = readFileSync(mdFile, "utf8");
|
|
236
|
+
} catch {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
const lines = text.split(/\r?\n/);
|
|
240
|
+
if (lines[0]?.trim() !== "---") return undefined;
|
|
241
|
+
const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
|
|
242
|
+
if (end < 0) return undefined;
|
|
243
|
+
let parsed: unknown;
|
|
244
|
+
try {
|
|
245
|
+
parsed = parse(lines.slice(1, end).join("\n"));
|
|
246
|
+
} catch {
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
const frontmatter =
|
|
250
|
+
parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : undefined;
|
|
251
|
+
const tools = frontmatter?.tools;
|
|
252
|
+
if (!Array.isArray(tools) || tools.length === 0 || tools.some((tool) => typeof tool !== "string")) return undefined;
|
|
253
|
+
return tools as string[];
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/** 工具名 → schema 里的路径入参名;一处缓存,避免每次调用都问一遍注册表。缓存由 activate 持有并传入。 */
|
|
257
|
+
const pathArgFromSchema = (
|
|
258
|
+
pi: ExtensionAPI,
|
|
259
|
+
schemaPathArgs: Map<string, string | undefined>,
|
|
260
|
+
toolName: string,
|
|
261
|
+
): string | undefined => {
|
|
262
|
+
if (schemaPathArgs.has(toolName)) return schemaPathArgs.get(toolName);
|
|
263
|
+
let found: string | undefined;
|
|
264
|
+
try {
|
|
265
|
+
const registered = (
|
|
266
|
+
pi as { getAllTools?: () => { name: string; parameters?: unknown }[] }
|
|
267
|
+
).getAllTools?.();
|
|
268
|
+
const tool = registered?.find((entry) => entry.name === toolName);
|
|
269
|
+
const properties = (tool?.parameters as { properties?: Record<string, { type?: string }> } | undefined)
|
|
270
|
+
?.properties;
|
|
271
|
+
if (properties?.path?.type === "string") found = "path";
|
|
272
|
+
else if (properties?.file_path?.type === "string") found = "file_path";
|
|
273
|
+
} catch {
|
|
274
|
+
// 宿主没暴露 getAllTools(老版本、测试桩):退回缺省的 "path"。
|
|
275
|
+
}
|
|
276
|
+
schemaPathArgs.set(toolName, found);
|
|
277
|
+
return found;
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 名字 → 类别。undefined 表示它不是路径类工具,交给 allowTools 那条路。
|
|
282
|
+
*
|
|
283
|
+
* 路径入参名的取值顺序:父代理显式声明 → 工具自己的 schema → "path"。中间那层是为了
|
|
284
|
+
* 不靠猜:hashline 那套工具的 schema 里就有 `path`,而换个宿主可能叫 `file_path`。
|
|
285
|
+
*/
|
|
286
|
+
const toolKindOf = (
|
|
287
|
+
w: Wiring,
|
|
288
|
+
pi: ExtensionAPI,
|
|
289
|
+
schemaPathArgs: Map<string, string | undefined>,
|
|
290
|
+
toolName: string,
|
|
291
|
+
): { access: "read" | "write"; pathArg: string | false; transferSource?: "read" | "write" } | undefined => {
|
|
292
|
+
const declared = Object.hasOwn(w.policy.tools, toolName) ? w.policy.tools[toolName] : undefined;
|
|
293
|
+
const fallback = Object.hasOwn(DEFAULT_TOOL_ACCESS, toolName) ? DEFAULT_TOOL_ACCESS[toolName] : undefined;
|
|
294
|
+
const access = declared?.access ?? fallback;
|
|
295
|
+
if (!access) return undefined;
|
|
296
|
+
return {
|
|
297
|
+
access,
|
|
298
|
+
pathArg: declared?.path ?? pathArgFromSchema(pi, schemaPathArgs, toolName) ?? "path",
|
|
299
|
+
...(declared?.transferSource === undefined ? {} : { transferSource: declared.transferSource }),
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* judgeToolCall 的入参对象。原先六个位置参数(pi、w、options、schemaPathArgs、
|
|
305
|
+
* event、ctx)只有 index.ts 的 tool_call 处理器一个调用方,位置序已经到了读不动的
|
|
306
|
+
* 边界;options 字段从来没人读,收对象时一并去掉。
|
|
307
|
+
*/
|
|
308
|
+
export interface JudgeToolCallOptions {
|
|
309
|
+
pi: ExtensionAPI;
|
|
310
|
+
w: Wiring;
|
|
311
|
+
/** activate 持有的 schema 路径入参缓存(见 pathArgFromSchema)。 */
|
|
312
|
+
schemaPathArgs: Map<string, string | undefined>;
|
|
313
|
+
event: ToolCallEvent;
|
|
314
|
+
ctx: ExtensionContext;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export const judgeToolCall = async ({
|
|
318
|
+
pi,
|
|
319
|
+
w,
|
|
320
|
+
schemaPathArgs,
|
|
321
|
+
event,
|
|
322
|
+
ctx,
|
|
323
|
+
}: JudgeToolCallOptions): Promise<ToolCallEventResult | undefined | void> => {
|
|
324
|
+
w.currentCtx = ctx;
|
|
325
|
+
w.uiWarning = (message) => {
|
|
326
|
+
const ui = ctx.ui as { notify?: (m: string, t?: string) => void } | undefined;
|
|
327
|
+
ui?.notify?.(message, "warning");
|
|
328
|
+
};
|
|
329
|
+
// 派单预检与默认值补值先于范围判定:父会话常常根本没有 bindings(本层策略不激活),
|
|
330
|
+
// 而这两条判的是 pi-subagents 自己的解析与宿主工具面,跟本层策略激活与否无关。
|
|
331
|
+
// 补值不是拒绝,不进 deny 预算;预检的拒绝是配置冲突,只拒不计(放宽授权治不了它)。
|
|
332
|
+
if (WORKTREE_TOOLS.has(event.toolName)) {
|
|
333
|
+
const candidate = event.input as { agent?: unknown; worktree?: unknown; extensionBindings?: unknown } | undefined;
|
|
334
|
+
const agent = candidate?.agent;
|
|
335
|
+
if (candidate && typeof agent === "string" && agent.trim()) {
|
|
336
|
+
const cwd = ctx.cwd ?? process.cwd();
|
|
337
|
+
const name = agent.trim();
|
|
338
|
+
// check 1 / check 2:md 解析得到就比工具面,解析不到就告警一次。都在 spawn 之前
|
|
339
|
+
// 发生 —— 派单失败得快,是因为 pi-subagents 在子会话起来之后才检查这些,报出来的
|
|
340
|
+
// 话没人能照着改;这里把同一件事提前到 tool_call,且带上因果。
|
|
341
|
+
const mdFile = resolveAgentFile(name, cwd, homedir()) ?? undefined;
|
|
342
|
+
if (!mdFile) {
|
|
343
|
+
// check 2 只告警不拒:builtin 代理(worker、scout、delegate…)本来就没有
|
|
344
|
+
// md,拒了会打死最常见的用法。告警让「名字其实落在了 builtin 别名上、
|
|
345
|
+
// 角色 md 的策略根本没生效」这件事在派单前可见。
|
|
346
|
+
warnUnresolvedAgentName(name, cwd, agentMdDirs(cwd, homedir()), w.uiWarning);
|
|
347
|
+
} else {
|
|
348
|
+
// check 1 只在 md 自己声明了 tools: 时才比:那是 pi-subagents 检查子代理
|
|
349
|
+
// 工具面用的同一份声明,本层不替 pi-subagents 发明检查。声明缺失、类型
|
|
350
|
+
// 不对、宿主没暴露活动面(测试桩)一律放行 —— 漏报只是少一次提前拒绝。
|
|
351
|
+
const declared = declaredToolsOf(mdFile);
|
|
352
|
+
const active = declared ? (pi as { getActiveTools?: () => string[] }).getActiveTools?.() : undefined;
|
|
353
|
+
if (declared && active) {
|
|
354
|
+
const missing = declared.filter((tool) => !active.includes(tool));
|
|
355
|
+
if (missing.length > 0) {
|
|
356
|
+
return deny(dispatchToolFaceRefusal(name, mdFile, missing));
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
// 只有 worktree 这一个决策把本次派单自带的 bindings 叠在会话 bindings 之上;
|
|
361
|
+
// 其余策略解析仍用会话启动时定格的那一份,范围不因单次派单而变。
|
|
362
|
+
const own = asObject(candidate.extensionBindings)?.[bindingKey()];
|
|
363
|
+
const strategy = worktreePolicyFor(cwd, { ...w.call.config, ...w.call.blocks, ...asObject(own) }, name, mdFile);
|
|
364
|
+
if (shouldDefaultWorktree(strategy, event.toolName, event.input)) {
|
|
365
|
+
candidate.worktree = true;
|
|
366
|
+
if (strategy.fromMd && strategy.mdFile) warnUntrackedWorktreeProfile(cwd, strategy.mdFile, w.uiWarning);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
// 只有这个扩展被装进主会话时才看得到派单载荷(默认并非如此):子会话在 session_start
|
|
371
|
+
// 就消费掉 bindings,tool_call 里根本没有。别把「这里没告警」当成坏掉来报。
|
|
372
|
+
if (!warnedDispatchVersion && (event.toolName === "subagent" || event.toolName === "subagent_launch")) {
|
|
373
|
+
const candidate = event.input as { extensionBindings?: unknown } | undefined;
|
|
374
|
+
const incoming = asObject(candidate?.extensionBindings);
|
|
375
|
+
const wrongKey = incoming && Object.keys(incoming).find(
|
|
376
|
+
(key) => key.startsWith(`${BINDING_NAMESPACE}/`) && key !== bindingKey(),
|
|
377
|
+
);
|
|
378
|
+
if (wrongKey) {
|
|
379
|
+
warnedDispatchVersion = true;
|
|
380
|
+
w.uiWarning?.(
|
|
381
|
+
`pi-subagents-extend: a ${event.toolName} dispatch declares binding "${wrongKey}", but this build supports "${bindingKey()}"; use the matching key or the dispatch will be refused.`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (!w.policy.active) return;
|
|
386
|
+
const cwd = ctx.cwd ?? process.cwd();
|
|
387
|
+
// 求援通道不受任何停机影响:被停住的子代理最需要的就是「报告我卡在哪」。
|
|
388
|
+
if (SAFE_TOOLS.includes(event.toolName)) return undefined;
|
|
389
|
+
if (w.stopped) return { block: true, reason: STOP_NOTICE, terminate: true };
|
|
390
|
+
// 探针在边界上的 warn / 到期停机,先于本工具的判定。
|
|
391
|
+
const boundary = w.probe?.atToolBoundary();
|
|
392
|
+
if (boundary) {
|
|
393
|
+
if (boundary.stop) return w.stop(boundary.reason);
|
|
394
|
+
return { block: true, reason: boundary.reason, terminate: false };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// 会话运行时工具(todo):不碰文件,活着的会话照常放行。位置在停机闸门与探针
|
|
398
|
+
// 边界**之后**:停机后不再放行(停了的会话不该再改任何东西,任务清单也不例外),
|
|
399
|
+
// 探针判据对纯 todo 空转的会话也照常生效。
|
|
400
|
+
if (RUNTIME_TOOLS.includes(event.toolName)) return undefined;
|
|
401
|
+
// 拒绝分三类,分类标准只有一条:**父代理放宽授权能不能解决**。
|
|
402
|
+
// 能 → 撞权限计数(bail):范围外路径、命令不在白名单、read 预算、
|
|
403
|
+
// 工具不在 allowTools、整个 bash 被关。这些是「授权与任务不匹配」的信号。
|
|
404
|
+
// 写不了 → 写预算(writeBail):写范围外、readOnly 会话里的写。放宽授权也解决不了,
|
|
405
|
+
// 正解是改成交报告,所以计数与文案都跟授权那类分开。
|
|
406
|
+
// 不能 → 只拒不计(deny):用法错误(缺 path、空命令、shell 元字符)、
|
|
407
|
+
// bash deny 的硬禁令、永远不开放的工具、环境/内核缺能力。
|
|
408
|
+
// 把后一类算进预算,会让一次参数写错就提前判死长任务。
|
|
409
|
+
|
|
410
|
+
if (event.toolName === "bash") {
|
|
411
|
+
// pi 的 tool_call 处理器共用可变的 event.input:先注册的处理器改了它,后面的看到的是改过的
|
|
412
|
+
// 值,顺序由加载顺序决定。实测 rtk 把命令换成 `rtk <cmd>`,白名单记的是模型原本那条,于是
|
|
413
|
+
// 整个会话的 bash 全被拒。判定因此用 transcript 里模型原本那条命令(见 original-args.ts),
|
|
414
|
+
// 执行用当前值:同伴的改写留在沙箱内层照常生效。
|
|
415
|
+
const rewritten = String((event.input as { command?: unknown })?.command ?? "").trim();
|
|
416
|
+
const command = originalCommand(ctx, event.toolCallId) ?? rewritten;
|
|
417
|
+
const rule = w.policy.bash;
|
|
418
|
+
if (!rule) {
|
|
419
|
+
return bail(
|
|
420
|
+
w,
|
|
421
|
+
`pi-subagents-extend: bash is not allowed here (source: ${w.policy.source}). For tests or a typecheck the parent must list the commands in bash.allow.`,
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
if (!command) return deny("pi-subagents-extend: empty bash command");
|
|
425
|
+
// 禁止列表先于一切判定:deny 是硬底线(两层并集,任何一层都拆不掉),
|
|
426
|
+
// 调用方的白名单不能放宽它。它不属于哪一层配置文件,来源只在 (source: …) 里。
|
|
427
|
+
const forbidden = deniedEntry(rule, command);
|
|
428
|
+
if (forbidden) {
|
|
429
|
+
return deny(
|
|
430
|
+
`pi-subagents-extend: command blocked by a deny entry: "${forbidden}" (source: ${w.policy.source}). A deny entry is a restriction; no layer can remove it.`,
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
if (hasUnquotedShellControl(command)) {
|
|
434
|
+
return deny(
|
|
435
|
+
`pi-subagents-extend: shell metacharacters are not allowed (; & | < > \` $ …): run one allowlisted command. Refused: ${preview([command])} — allowed: ${preview(allEntries(rule))}`,
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
// 前置赋值能把「被允许的命令」变成「跑我自己的代码」:`NODE_OPTIONS=--require=/tmp/x.js node`
|
|
439
|
+
// 实测直接执行 /tmp/x.js,`GIT_EXTERNAL_DIFF` 对 git 同理。已知入口一律拒并点名;
|
|
440
|
+
// 其余名字照常剥离放行(这一层是辅助上轨道,不是严格沙箱 —— 放行多了可以事后补)。
|
|
441
|
+
const deniedEnv = deniedEnvAssignment(command);
|
|
442
|
+
if (deniedEnv) {
|
|
443
|
+
return deny(
|
|
444
|
+
`pi-subagents-extend: bash refused: the leading assignment "${deniedEnv}=…" can change which program runs or load code into it, which would let an allowlisted command run arbitrary code. Drop it, or have the parent set it in bash.env. Refused: ${preview([command])}`,
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
const match = classifyCommand(rule, command);
|
|
448
|
+
if (!match) {
|
|
449
|
+
// 模型能看见这段文案,所以把它需要的路径直接写进去,省得它再猜。
|
|
450
|
+
const store = detectPnpmStore(cwd);
|
|
451
|
+
const storeHint = store.path
|
|
452
|
+
? ` (pnpm store at ${store.path}, not writable; the parent can add it to bash.writablePaths)`
|
|
453
|
+
: "";
|
|
454
|
+
// 点名被拒的**命令**,再列允许项。只印允许列表时,读起来像「列表里那条命令不被接受」:
|
|
455
|
+
// 实测真有人把 `command not in the allowlist: ls` 读成「ls 被拒」,而实际拒的是别的命令。
|
|
456
|
+
// 同首 token 的条目:让子代理知道**为什么**没匹配上、该改哪里。
|
|
457
|
+
const headHint = headEntriesHint(rule, command, cwd);
|
|
458
|
+
return bail(
|
|
459
|
+
w,
|
|
460
|
+
`pi-subagents-extend: command not in the allowlist: "${preview([command])}" — allowed: ${preview(allEntries(rule))} (source: ${w.policy.source})${storeHint}${headHint}`,
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
// allow 列放行的写类命令,role 却没给写权限:这是写拒,计入写预算而非撞权限预算。
|
|
464
|
+
// 判据是「确实有一条 allow 授权」+ 命令本身会写 + writable:false,不看 classifyCommand 报的列:
|
|
465
|
+
// 同一条命令也命中 legacy 列时那列会先被报出来,但 legacy 不授予写权限。
|
|
466
|
+
// classifyCommand 在 writable=false 时已把 access 压成 read,这里用固有判定(传 true)
|
|
467
|
+
// 认出「这条命令本来会写」,否则它会以只读的名义被放行去写。
|
|
468
|
+
if (rule.allow.some((entry) => commandMatches(entry, command)) && rule.writable === false && commandAccess(command, true) === "write") {
|
|
469
|
+
return writeBail(
|
|
470
|
+
w,
|
|
471
|
+
`pi-subagents-extend: the role may run this command (it is in bash.allow)${match.column === "allow" ? "" : ` (matched the legacy ${match.column} column, which does not grant writes)`}, but bash.writable: false gives no write access: "${preview([command])}". This is a write refusal, not a grant error — deliver the result as a report, or have the parent set bash.writable: true.`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
// 只读类命令的参数路径:沙箱读面是 `/`(工具链要读 /nix/store),所以路径引导放在插件层。
|
|
475
|
+
// 位置在元字符与注入型赋值之后、依赖闸门之前:前两条决定「这条命令能不能跑」,
|
|
476
|
+
// 闸门判的是环境,这一条只是把参数里的路径引回范围,三者互不重叠。
|
|
477
|
+
if (match.access === "read") {
|
|
478
|
+
const foreign = foreignBashPath(command, cwd, rule, w.policy);
|
|
479
|
+
if (foreign) {
|
|
480
|
+
// 计入撞权限预算(bail):父代理放宽范围就能解决,正是这一类。
|
|
481
|
+
return bail(
|
|
482
|
+
w,
|
|
483
|
+
`pi-subagents-extend: "${foreign}" is outside the working tree (source: ${w.policy.source}). This is a path nudge, not a wall: the command runs in ${cwd}, and a file outside it is not yours to read — say what you need from it instead.\nWorking tree: ${cwd}`,
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
// 离线时网络是裸 netns:包被丢弃而不是被拒绝,curl 这类命令没有输出也没有错误,
|
|
488
|
+
// 事后注解等不到触发文本,只能挂到超时。所以在 spawn 之前按名单拒掉确定要往返的
|
|
489
|
+
// 工具;名单只收确定项,拿不准的一律放行(引导,不是沙箱边界)。
|
|
490
|
+
if (rule.network !== true) {
|
|
491
|
+
const networkTool = requiresNetwork(command);
|
|
492
|
+
if (networkTool) {
|
|
493
|
+
return bail(
|
|
494
|
+
w,
|
|
495
|
+
`pi-subagents-extend: the network is off per the parent's bindings — a permission, not a broken machine. \`${networkTool}\` would hang here rather than fail (packets are dropped, not refused). Ask the parent via contact_supervisor for "network": true.\n(source: ${w.policy.source})`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
// 依赖完整性闸门判的是环境,不是授权,子代理重试也不会变好,所以只拒不计。
|
|
500
|
+
// 它已不再是「先于一切」的那一条:上面的路径 nudge 排在它之前,而且计入撞权限预算 ——
|
|
501
|
+
// 路径出了工作树属于「授权与任务不匹配」,父代理放宽范围能解决。
|
|
502
|
+
const gate = dependencyGateVerdict(rule, command, match.access, cwd);
|
|
503
|
+
if (gate) return deny(gate);
|
|
504
|
+
const repeatEvent = w.probe?.noteBashStart(command, match.access, event.toolCallId);
|
|
505
|
+
if (repeatEvent) {
|
|
506
|
+
return repeatEvent.stop
|
|
507
|
+
? w.stop(repeatEvent.reason)
|
|
508
|
+
: { block: true, reason: repeatEvent.reason, terminate: false };
|
|
509
|
+
}
|
|
510
|
+
const helper = helperPath();
|
|
511
|
+
if (!helper) {
|
|
512
|
+
return deny(
|
|
513
|
+
"pi-subagents-extend: the sandbox helper (pi-subagents-extend-helper) was not found; run `pnpm run build:helper` in pi-plugin, or set PI_SUBAGENTS_EXTEND_HELPER_PATH.",
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
const caps = describeHelper(helper);
|
|
517
|
+
if (!caps?.landlock.supported) {
|
|
518
|
+
const reason = caps?.landlock.reason ?? "helper --describe returned no usable information";
|
|
519
|
+
return deny(`pi-subagents-extend: this kernel cannot enforce the task scope: ${reason}`);
|
|
520
|
+
}
|
|
521
|
+
const spec = buildSpec(cwd, rule, w.policy, w.uiWarning);
|
|
522
|
+
const specFile = writeSpecFile(spec, event.toolCallId);
|
|
523
|
+
if (!specFile) {
|
|
524
|
+
return deny("pi-subagents-extend: cannot write the sandbox spec; check that ~/.cache/pi-subagents-extend is writable");
|
|
525
|
+
}
|
|
526
|
+
// 记下这条命令的写权限清单:tool_result 判「写越界」时要用它当事实依据,
|
|
527
|
+
// 不靠文案猜。
|
|
528
|
+
// 挡住条数上限,避免结果永远不回来的调用把表撑大。被挤出表的条目,结果按定义
|
|
529
|
+
// 不会再回来,所以它的 spec 文件也得删 —— 只 delete 不删文件,「一次调用一份
|
|
530
|
+
// 文件」就会变成永远堆在 ~/.cache 里的垃圾。
|
|
531
|
+
if (w.sandboxSpecs.size >= 64) {
|
|
532
|
+
const oldest = w.sandboxSpecs.keys().next().value as string | undefined;
|
|
533
|
+
if (oldest !== undefined) {
|
|
534
|
+
dropSpecFile(w.sandboxSpecs.get(oldest));
|
|
535
|
+
w.sandboxSpecs.delete(oldest);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
// 同一个 toolCallId 又来一次(模型输出了重复 id)时,只覆盖条目、**不**删旧文件:
|
|
539
|
+
// 重复 id 在真 pi 里只可能是畸形响应,我们无法判断先那次是否已经启动,删掉它就会让
|
|
540
|
+
// 一个还在途的 helper 以 exit 77 死在「读不到 spec」上。留下的孤儿由 shutdown 清扫
|
|
541
|
+
// 按年龄回收 —— 代价是多一份文件,和打死一条命令完全不对称。
|
|
542
|
+
w.sandboxSpecs.set(event.toolCallId, {
|
|
543
|
+
write: spec.write,
|
|
544
|
+
cwd,
|
|
545
|
+
command,
|
|
546
|
+
offline: spec.offline,
|
|
547
|
+
specFile,
|
|
548
|
+
});
|
|
549
|
+
(event.input as { command?: string }).command = wrapInSandbox(
|
|
550
|
+
rewritten,
|
|
551
|
+
specFile,
|
|
552
|
+
helper,
|
|
553
|
+
// helper 的「网络已隔离」提示每会话只值一次:本会话还没播报过就照常播报;
|
|
554
|
+
// 播报过之后(见下)的离线命令加 quiet 前缀让它安静。
|
|
555
|
+
!w.sandboxNetworkNoticeAnnounced,
|
|
556
|
+
);
|
|
557
|
+
// 只有离线命令会让 helper 播报,所以只在这里翻牌:会话先跑了在线命令时,
|
|
558
|
+
// 第一条离线命令仍然是全会话的第一次播报。
|
|
559
|
+
if (spec.offline) w.sandboxNetworkNoticeAnnounced = true;
|
|
560
|
+
return undefined;
|
|
561
|
+
}
|
|
562
|
+
if (EXEC_TOOLS.includes(event.toolName)) {
|
|
563
|
+
// 从来不可用:给多宽的范围、多长的命令白名单都不会打开,所以不计入撞权限。
|
|
564
|
+
return deny(
|
|
565
|
+
`pi-subagents-extend: ${event.toolName} is never available in a scoped session; no grant can widen it. Use a path tool (read / write / the host's edit family) or an allowlisted bash command.`,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
// 路径类工具先判:它们的授权来自范围,不来自 allowTools。顺序反过来就意味着父代理
|
|
569
|
+
// 一旦把名字写进 allowTools,路径判定整个被跳过——写范围在那种宿主上等于失效
|
|
570
|
+
// (实测:allowTools 里写 replace 时,树外路径照写不误)。
|
|
571
|
+
const kind = toolKindOf(w, pi, schemaPathArgs, event.toolName);
|
|
572
|
+
if (kind) {
|
|
573
|
+
const sessionFile =
|
|
574
|
+
ctx?.sessionManager?.getSessionFile?.() ?? process.env.PI_SESSION_FILE ?? undefined;
|
|
575
|
+
return pathToolVerdict(w, event as { toolName: string; input?: unknown }, cwd, kind, sessionFile);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// SAFE_TOOLS 与 RUNTIME_TOOLS 已经在前面处理过,这里只管调用方显式放行的工具。
|
|
579
|
+
if (w.policy.allowTools.includes(event.toolName)) return undefined;
|
|
580
|
+
|
|
581
|
+
return bail(
|
|
582
|
+
w,
|
|
583
|
+
`pi-subagents-extend: tool ${event.toolName} is not on the allow list (fail closed; the parent can add it to allowTools). Tools this layer already judges by scope: ${preview(Object.keys(DEFAULT_TOOL_ACCESS))}.`,
|
|
584
|
+
);
|
|
585
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型**原始**工具参数:按 toolCallId 从会话 transcript 里取回。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:pi 的 tool_call 处理器共用同一个可变的 `event.input`,先注册的处理器改了它,
|
|
5
|
+
* 后面的处理器看到的就是改过的值(pi 文档 extensions.md 的 In-place mutation),而处理器顺序
|
|
6
|
+
* 由扩展的加载顺序决定,不在本扩展手里。实测 rtk(把命令改写成 `rtk <cmd>` 省 token)先跑,
|
|
7
|
+
* 于是判定读到 `rtk git status`,与我们记的 bash.allow 里的 `git status` 永远匹配不上 ——
|
|
8
|
+
* 整个会话的 bash 全被拒,而模型根本没那么写过。
|
|
9
|
+
*
|
|
10
|
+
* transcript 里存的是模型实际输出的 arguments,不受处理器链改写影响,所以判定以它为准;
|
|
11
|
+
* 处理器链上的改写仍然保留,作为被沙箱包住的内层命令执行,两边的意图都不丢。
|
|
12
|
+
*/
|
|
13
|
+
interface ToolCallBlock {
|
|
14
|
+
type?: string;
|
|
15
|
+
id?: string;
|
|
16
|
+
arguments?: unknown;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const asArguments = (block: ToolCallBlock): Record<string, unknown> | undefined => {
|
|
20
|
+
const raw = block.arguments;
|
|
21
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw as Record<string, unknown>;
|
|
22
|
+
// 某些宿主把 arguments 存成 JSON 字符串;解析不出来就当没有,绝不让它变成判定失败。
|
|
23
|
+
if (typeof raw === "string") {
|
|
24
|
+
try {
|
|
25
|
+
const parsed: unknown = JSON.parse(raw);
|
|
26
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : undefined;
|
|
27
|
+
} catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 在 transcript 条目里找 toolCallId 对应的工具调用参数。找不到返回 undefined ——
|
|
36
|
+
* 嵌套调用(`<parent>/<n>`)按定义不落在 transcript 里,调用方要退回 `event.input`。
|
|
37
|
+
*/
|
|
38
|
+
export function originalToolArguments(entries: readonly unknown[], toolCallId: string): Record<string, unknown> | undefined {
|
|
39
|
+
if (!toolCallId) return undefined;
|
|
40
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
41
|
+
const entry = entries[i] as { message?: { content?: unknown } } | undefined;
|
|
42
|
+
const content = entry?.message?.content;
|
|
43
|
+
if (!Array.isArray(content)) continue;
|
|
44
|
+
for (const block of content as ToolCallBlock[]) {
|
|
45
|
+
if (block?.type !== "toolCall" || block.id !== toolCallId) continue;
|
|
46
|
+
const args = asArguments(block);
|
|
47
|
+
if (args) return args;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 取原始命令字符串:判定 bash 时的入口。宿主没给 sessionManager(测试替身、旧宿主)、
|
|
55
|
+
* transcript 里没有这一条、或者参数里没有 command 时都返回 undefined,调用方退回 event.input。
|
|
56
|
+
*/
|
|
57
|
+
export function originalCommand(ctx: unknown, toolCallId: string): string | undefined {
|
|
58
|
+
const sessionManager = (ctx as { sessionManager?: { getBranch?: () => unknown } } | undefined)?.sessionManager;
|
|
59
|
+
const entries = sessionManager?.getBranch?.();
|
|
60
|
+
if (!Array.isArray(entries)) return undefined;
|
|
61
|
+
const args = originalToolArguments(entries, toolCallId);
|
|
62
|
+
const command = args?.command;
|
|
63
|
+
return typeof command === "string" && command.trim() ? command.trim() : undefined;
|
|
64
|
+
}
|