@mozhi0012/pi-terminal-worker 0.2.0 → 0.3.0

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.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * team.yaml:把角色的模型、权限和数量上限从 skill 提示词中分离,由插件校验并强制执行。
3
+ *
4
+ * 每次 worker_start 都重新读取文件,修改后下一次启动立即生效,不做缓存。
5
+ *
6
+ * 只读取用户级 skill 目录,不读取工作目录下的 .pi:主控启动 Worker 时目标目录可能尚未被信任,
7
+ * 项目文件不能决定模型和写权限。
8
+ */
9
+
10
+ import * as fs from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import * as path from "node:path";
13
+ import { parse as parseYaml } from "yaml";
14
+ import { THINKING_LEVELS, type WorkerRole } from "./protocol.js";
15
+ import { encodeToolPolicy, type ToolPolicy, type WriteMode } from "./tool-policy.js";
16
+
17
+ export const TEAM_CONFIG_FILE = "team.yaml";
18
+ const TEAM_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
19
+ const ROLE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
20
+ const WRITE_MODES: readonly WriteMode[] = ["none", "scoped", "any"];
21
+
22
+ export interface TeamRoleConfig {
23
+ tier: WorkerRole;
24
+ provider: string;
25
+ model: string;
26
+ thinking: string;
27
+ write: WriteMode;
28
+ /** 本角色同时存活的实例上限 */
29
+ max?: number;
30
+ denyTools: string[];
31
+ }
32
+
33
+ export interface TeamConfig {
34
+ /** 本 team 在当前主控会话内同时存活的实例上限 */
35
+ maxConcurrent?: number;
36
+ roles: Map<string, TeamRoleConfig>;
37
+ }
38
+
39
+ /** worker_start 中与 team 相关的入参 */
40
+ export interface TeamStartParams {
41
+ team?: string;
42
+ teamRole?: string;
43
+ role?: WorkerRole;
44
+ cwd: string;
45
+ provider?: string;
46
+ model?: string;
47
+ thinkingLevel?: string;
48
+ allowedPaths?: string[];
49
+ }
50
+
51
+ export interface ResolvedTeamStart {
52
+ team: string;
53
+ teamRole: string;
54
+ configPath: string;
55
+ tier: WorkerRole;
56
+ provider: string;
57
+ model: string;
58
+ thinkingLevel: string;
59
+ write: WriteMode;
60
+ maxConcurrent?: number;
61
+ maxForRole?: number;
62
+ policy: ToolPolicy;
63
+ }
64
+
65
+ function configError(message: string): Error {
66
+ return new Error(`[TEAM_CONFIG_ERROR] ${message}`);
67
+ }
68
+
69
+ function requirePlainObject(value: unknown, label: string): Record<string, unknown> {
70
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
71
+ throw configError(`${label} 必须是对象`);
72
+ }
73
+ return value as Record<string, unknown>;
74
+ }
75
+
76
+ function rejectUnknownKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {
77
+ for (const key of Object.keys(value)) {
78
+ if (!allowed.includes(key)) {
79
+ throw configError(`${label} 含未知字段 "${key}",可用字段:${allowed.join(", ")}`);
80
+ }
81
+ }
82
+ }
83
+
84
+ function requireNonEmptyString(value: unknown, label: string): string {
85
+ if (typeof value !== "string" || value.trim() === "") {
86
+ throw configError(`${label} 必须是非空字符串`);
87
+ }
88
+ return value;
89
+ }
90
+
91
+ function optionalPositiveInteger(value: unknown, label: string): number | undefined {
92
+ if (value === undefined) return undefined;
93
+ if (!Number.isSafeInteger(value) || (value as number) <= 0) {
94
+ throw configError(`${label} 必须是正整数`);
95
+ }
96
+ return value as number;
97
+ }
98
+
99
+ function parseRole(value: unknown, label: string): TeamRoleConfig {
100
+ const raw = requirePlainObject(value, label);
101
+ rejectUnknownKeys(raw, ["tier", "provider", "model", "thinking", "write", "max", "denyTools"], label);
102
+
103
+ const tier = raw.tier ?? "worker";
104
+ if (tier !== "worker" && tier !== "lead") {
105
+ throw configError(`${label}.tier 必须是 worker 或 lead`);
106
+ }
107
+ const thinking = requireNonEmptyString(raw.thinking, `${label}.thinking`);
108
+ if (!(THINKING_LEVELS as readonly string[]).includes(thinking)) {
109
+ throw configError(`${label}.thinking 必须是以下之一:${THINKING_LEVELS.join(" | ")}`);
110
+ }
111
+ if (!WRITE_MODES.includes(raw.write as WriteMode)) {
112
+ throw configError(`${label}.write 必须是以下之一:${WRITE_MODES.join(" | ")}`);
113
+ }
114
+ const denyTools = raw.denyTools ?? [];
115
+ if (!Array.isArray(denyTools) || !denyTools.every((item) => typeof item === "string" && item !== "")) {
116
+ throw configError(`${label}.denyTools 必须是非空字符串数组`);
117
+ }
118
+ return {
119
+ tier,
120
+ provider: requireNonEmptyString(raw.provider, `${label}.provider`),
121
+ model: requireNonEmptyString(raw.model, `${label}.model`),
122
+ thinking,
123
+ write: raw.write as WriteMode,
124
+ max: optionalPositiveInteger(raw.max, `${label}.max`),
125
+ denyTools: denyTools as string[],
126
+ };
127
+ }
128
+
129
+ /** 严格解析:未知字段一律报错,防止拼错的限制项被静默忽略 */
130
+ export function parseTeamConfig(text: string, source: string): TeamConfig {
131
+ let parsed: unknown;
132
+ try {
133
+ parsed = parseYaml(text);
134
+ } catch (err: unknown) {
135
+ throw configError(`${source} 不是合法的 YAML:${err instanceof Error ? err.message : String(err)}`);
136
+ }
137
+ const raw = requirePlainObject(parsed, source);
138
+ rejectUnknownKeys(raw, ["version", "limits", "roles"], source);
139
+ if (raw.version !== 1) {
140
+ throw configError(`${source} 的 version 必须是 1`);
141
+ }
142
+
143
+ let maxConcurrent: number | undefined;
144
+ if (raw.limits !== undefined) {
145
+ const limits = requirePlainObject(raw.limits, `${source} 的 limits`);
146
+ rejectUnknownKeys(limits, ["maxConcurrent"], `${source} 的 limits`);
147
+ maxConcurrent = optionalPositiveInteger(limits.maxConcurrent, `${source} 的 limits.maxConcurrent`);
148
+ }
149
+
150
+ const rawRoles = requirePlainObject(raw.roles, `${source} 的 roles`);
151
+ const roles = new Map<string, TeamRoleConfig>();
152
+ for (const [name, value] of Object.entries(rawRoles)) {
153
+ if (!ROLE_NAME_PATTERN.test(name)) {
154
+ throw configError(`${source} 的角色名 "${name}" 非法,只能用小写字母、数字、- 和 _,且以字母开头`);
155
+ }
156
+ roles.set(name, parseRole(value, `${source} 的 roles.${name}`));
157
+ }
158
+ if (roles.size === 0) {
159
+ throw configError(`${source} 至少要定义一个角色`);
160
+ }
161
+ return { maxConcurrent, roles };
162
+ }
163
+
164
+ function agentDir(env: NodeJS.ProcessEnv): string {
165
+ const configured = env.PI_CODING_AGENT_DIR?.trim();
166
+ if (!configured) return path.join(homedir(), ".pi", "agent");
167
+ if (configured === "~") return homedir();
168
+ return configured.startsWith("~/") || configured.startsWith("~\\")
169
+ ? path.join(homedir(), configured.slice(2))
170
+ : path.resolve(configured);
171
+ }
172
+
173
+ export function teamConfigPath(team: string, env: NodeJS.ProcessEnv = process.env): string {
174
+ return path.join(agentDir(env), "skills", team, TEAM_CONFIG_FILE);
175
+ }
176
+
177
+ /** 允许目录写法 dir、dir/、dir/*、dir/**;其他通配符无法精确校验,直接拒绝 */
178
+ export function normalizeAllowedPaths(paths: readonly string[], cwd: string): string[] {
179
+ return paths.map((raw) => {
180
+ const stripped = raw.trim().replace(/[\\/]\*{1,2}$/, "");
181
+ if (stripped === "" || /[*?[\]{}]/.test(stripped)) {
182
+ throw configError(`allowedPaths 项 "${raw}" 无法精确校验,请使用文件或目录路径(可带 /** 后缀)`);
183
+ }
184
+ return path.resolve(cwd, stripped);
185
+ });
186
+ }
187
+
188
+ /**
189
+ * 解析 worker_start 的 team 参数。未使用 team 时返回 null,保持原有行为。
190
+ * 文件读取是同步的:调用方可以在同一轮事件循环内完成名额检查与登记,避免并发超限。
191
+ */
192
+ export function resolveTeamStart(
193
+ params: TeamStartParams,
194
+ env: NodeJS.ProcessEnv = process.env,
195
+ ): ResolvedTeamStart | null {
196
+ const { team, teamRole } = params;
197
+ if (team === undefined && teamRole === undefined) return null;
198
+ if (!path.isAbsolute(params.cwd)) {
199
+ throw configError(`cwd 必须是绝对路径: "${params.cwd}"`);
200
+ }
201
+ if (team === undefined || teamRole === undefined) {
202
+ throw configError("team 和 teamRole 必须同时提供");
203
+ }
204
+ if (!TEAM_NAME_PATTERN.test(team)) {
205
+ throw configError(`team 名称 "${team}" 非法,应为 skill 目录名`);
206
+ }
207
+ // 模型和层级以 team.yaml 为唯一来源,调用方不能在单次调用里覆盖
208
+ for (const field of ["role", "provider", "model", "thinkingLevel"] as const) {
209
+ if (params[field] !== undefined) {
210
+ throw configError(`使用 team 时不能同时传 ${field},请修改 team.yaml`);
211
+ }
212
+ }
213
+
214
+ const configPath = teamConfigPath(team, env);
215
+ if (!fs.existsSync(configPath)) {
216
+ throw configError(`找不到 team "${team}" 的配置:${configPath}`);
217
+ }
218
+ const config = parseTeamConfig(fs.readFileSync(configPath, "utf8"), configPath);
219
+ const role = config.roles.get(teamRole);
220
+ if (!role) {
221
+ throw configError(`${configPath} 没有角色 "${teamRole}",可用角色:${[...config.roles.keys()].join(", ")}`);
222
+ }
223
+
224
+ const allowedPaths = normalizeAllowedPaths(params.allowedPaths ?? [], params.cwd);
225
+ if (role.write === "scoped" && allowedPaths.length === 0) {
226
+ throw configError(`角色 ${team}/${teamRole} 是 write: scoped,必须提供非空的 allowedPaths`);
227
+ }
228
+ if (role.write === "none" && allowedPaths.length > 0) {
229
+ throw configError(`角色 ${team}/${teamRole} 是只读角色 (write: none),不能提供 allowedPaths`);
230
+ }
231
+
232
+ const policy: ToolPolicy = {
233
+ label: `${team}/${teamRole}`,
234
+ write: role.write,
235
+ cwd: params.cwd,
236
+ allowedPaths,
237
+ denyTools: role.denyTools,
238
+ };
239
+ // 在开窗之前发现超限,而不是启动到一半才失败
240
+ encodeToolPolicy(policy);
241
+
242
+ return {
243
+ team,
244
+ teamRole,
245
+ configPath,
246
+ tier: role.tier,
247
+ provider: role.provider,
248
+ model: role.model,
249
+ thinkingLevel: role.thinking,
250
+ write: role.write,
251
+ maxConcurrent: config.maxConcurrent,
252
+ maxForRole: role.max,
253
+ policy,
254
+ };
255
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Worker 侧工具策略:由主控在启动时写入环境变量,在 tool_call 钩子里强制执行。
3
+ *
4
+ * 这是防止模型误操作的护栏,不是安全沙箱:write / edit / code_rewrite 按路径精确判断,
5
+ * bash 只能用启发式识别常见写命令,python -c、node -e 等解释器内的写入无法识别。
6
+ */
7
+
8
+ import { realpathSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import * as path from "node:path";
11
+
12
+ export const TOOL_POLICY_ENV = "PI_TERMINAL_WORKER_TOOL_POLICY";
13
+ /** Windows 单个环境变量上限约 32K 字符,这里留足余量 */
14
+ export const MAX_TOOL_POLICY_SIZE = 16 * 1024;
15
+
16
+ export type WriteMode = "none" | "scoped" | "any";
17
+
18
+ export interface ToolPolicy {
19
+ /** 错误提示中展示的来源,如 dev-small/reviewer */
20
+ label: string;
21
+ write: WriteMode;
22
+ /** Worker 工作目录,用于解析相对路径 */
23
+ cwd: string;
24
+ /** write=scoped 时允许写入的绝对路径 */
25
+ allowedPaths: string[];
26
+ /** 额外禁用的工具名,支持 * 通配 */
27
+ denyTools: string[];
28
+ }
29
+
30
+ export function encodeToolPolicy(policy: ToolPolicy): string {
31
+ const encoded = JSON.stringify(policy);
32
+ if (encoded.length > MAX_TOOL_POLICY_SIZE) {
33
+ throw new Error(`工具策略超过 ${MAX_TOOL_POLICY_SIZE} 字符上限,请减少 allowedPaths 或 denyTools`);
34
+ }
35
+ return encoded;
36
+ }
37
+
38
+ function isStringArray(value: unknown): value is string[] {
39
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
40
+ }
41
+
42
+ export function decodeToolPolicy(raw: string): ToolPolicy {
43
+ const value = JSON.parse(raw) as Partial<ToolPolicy> | null;
44
+ if (
45
+ !value ||
46
+ typeof value.label !== "string" ||
47
+ !["none", "scoped", "any"].includes(value.write as string) ||
48
+ typeof value.cwd !== "string" ||
49
+ !isStringArray(value.allowedPaths) ||
50
+ !isStringArray(value.denyTools)
51
+ ) {
52
+ throw new Error("工具策略字段非法");
53
+ }
54
+ return value as ToolPolicy;
55
+ }
56
+
57
+ /** 策略环境变量损坏时按只读处理,绝不退化成不受限 */
58
+ export function loadToolPolicyFromEnv(env: NodeJS.ProcessEnv = process.env): ToolPolicy | null {
59
+ const raw = env[TOOL_POLICY_ENV];
60
+ if (!raw) return null;
61
+ try {
62
+ return decodeToolPolicy(raw);
63
+ } catch (err: unknown) {
64
+ console.error("[Worker] 工具策略解析失败,按只读处理:", err);
65
+ return { label: "invalid-policy", write: "none", cwd: process.cwd(), allowedPaths: [], denyTools: [] };
66
+ }
67
+ }
68
+
69
+ export function toolNameMatches(pattern: string, toolName: string): boolean {
70
+ const source = pattern
71
+ .split("*")
72
+ .map((part) => part.replace(/[\\^$.+?()[\]{}|]/g, "\\$&"))
73
+ .join(".*");
74
+ return new RegExp(`^${source}$`).test(toolName);
75
+ }
76
+
77
+ /** 解析为绝对路径,并沿最近的已存在祖先目录解开符号链接,防止经链接写到范围外 */
78
+ export function physicalPath(raw: string, cwd: string): string {
79
+ // 与 pi 内置文件工具的路径约定保持一致:@ 前缀与 ~ 展开
80
+ const unprefixed = raw.startsWith("@") ? raw.slice(1) : raw;
81
+ const expanded =
82
+ unprefixed === "~" || unprefixed.startsWith("~/") || unprefixed.startsWith("~\\")
83
+ ? path.join(homedir(), unprefixed.slice(1))
84
+ : unprefixed;
85
+ const absolute = path.resolve(cwd, expanded);
86
+ const tail: string[] = [];
87
+ let current = absolute;
88
+ for (;;) {
89
+ try {
90
+ return path.join(realpathSync.native(current), ...tail);
91
+ } catch {
92
+ const parent = path.dirname(current);
93
+ if (parent === current) return absolute;
94
+ tail.unshift(path.basename(current));
95
+ current = parent;
96
+ }
97
+ }
98
+ }
99
+
100
+ export function isPathWithin(target: string, root: string, platform = process.platform): boolean {
101
+ const fold = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
102
+ const relative = path.relative(fold(root), fold(target));
103
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
104
+ }
105
+
106
+ const BASH_WRITE_COMMANDS = new Set([
107
+ "rm", "rmdir", "mv", "cp", "mkdir", "touch", "chmod", "chown", "chgrp", "ln",
108
+ "tee", "dd", "truncate", "shred", "install", "unlink", "rsync", "patch",
109
+ ]);
110
+ const GIT_WRITE_SUBCOMMANDS = new Set([
111
+ "commit", "push", "pull", "add", "rm", "mv", "reset", "checkout", "switch", "restore",
112
+ "merge", "rebase", "cherry-pick", "revert", "clean", "apply", "am",
113
+ ]);
114
+
115
+ function commandName(word: string): string {
116
+ return (word.split(/[\\/]/).pop() ?? word).replace(/\.(exe|cmd|bat)$/i, "").toLowerCase();
117
+ }
118
+
119
+ function gitWriteSubcommand(words: string[]): string | undefined {
120
+ let index = 1;
121
+ while (index < words.length && words[index].startsWith("-")) {
122
+ // -C <path>、-c <key=value> 带独立参数,其余全局选项不带
123
+ index += words[index] === "-C" || words[index] === "-c" ? 2 : 1;
124
+ }
125
+ const sub = words[index];
126
+ if (sub === undefined) return undefined;
127
+ if (GIT_WRITE_SUBCOMMANDS.has(sub)) return `git ${sub}`;
128
+ if (sub === "stash" && !["list", "show"].includes(words[index + 1] ?? "")) return "git stash";
129
+ if (sub === "worktree" && ["add", "remove", "move"].includes(words[index + 1] ?? "")) return `git worktree ${words[index + 1]}`;
130
+ return undefined;
131
+ }
132
+
133
+ /** 单条简单命令是否为写操作;返回命中的命令名 */
134
+ function segmentWriteCommand(segment: string): string | undefined {
135
+ let words = segment.trim().split(/\s+/).filter(Boolean);
136
+ // 跳过前导环境变量赋值,以及只负责转发命令的 sudo / env / xargs
137
+ for (;;) {
138
+ while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) words = words.slice(1);
139
+ const head = commandName(words[0] ?? "");
140
+ if (head !== "sudo" && head !== "env" && head !== "xargs") break;
141
+ words = words.slice(1);
142
+ while (words.length > 0 && words[0].startsWith("-")) words = words.slice(1);
143
+ }
144
+ if (words.length === 0) return undefined;
145
+
146
+ const name = commandName(words[0]);
147
+ if (BASH_WRITE_COMMANDS.has(name)) return name;
148
+ if (name === "git") return gitWriteSubcommand(words);
149
+ if ((name === "sed" || name === "perl") && words.some((w) => /^-[a-zA-Z]*i|^--in-place/.test(w))) return `${name} -i`;
150
+ if (name === "find") {
151
+ if (words.includes("-delete")) return "find -delete";
152
+ const exec = words.findIndex((w) => w === "-exec" || w === "-execdir");
153
+ if (exec >= 0 && BASH_WRITE_COMMANDS.has(commandName(words[exec + 1] ?? ""))) return `find -exec ${commandName(words[exec + 1])}`;
154
+ }
155
+ return undefined;
156
+ }
157
+
158
+ /** 启发式识别 bash 写操作:引号内容先剥离,避免 rg "a > b" 这类只读命令误报 */
159
+ export function bashWriteReason(command: string): string | undefined {
160
+ const unquoted = command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, '""');
161
+
162
+ for (const match of unquoted.matchAll(/(?:\d|&)?>>?\|?\s*(&\d+|[^\s;&|()<>]+)?/g)) {
163
+ const target = match[1];
164
+ const harmless = target !== undefined && (target.startsWith("&") || /^(\/dev\/null|nul)$/i.test(target));
165
+ if (!harmless) return `输出重定向 ${match[0].trim()}`;
166
+ }
167
+ for (const segment of unquoted.split(/&&|\|\||[;&|\n(]|\$\(|`/)) {
168
+ const hit = segmentWriteCommand(segment);
169
+ if (hit) return hit;
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ /** 返回拦截原因;放行时返回 undefined */
175
+ export function evaluateToolCall(policy: ToolPolicy, toolName: string, input: unknown): string | undefined {
176
+ const prefix = `team.yaml 角色 ${policy.label}`;
177
+ if (policy.denyTools.some((pattern) => toolNameMatches(pattern, toolName))) {
178
+ return `${prefix} 禁用了工具 ${toolName}。如果任务确实需要,请用 worker_report 报告 blocked。`;
179
+ }
180
+ if (policy.write === "any") return undefined;
181
+
182
+ const args = (input ?? {}) as Record<string, unknown>;
183
+ const isFileWrite = toolName === "write" || toolName === "edit";
184
+ const isRewrite = toolName === "code_rewrite" && args.dry_run === false;
185
+
186
+ if (policy.write === "none") {
187
+ if (isFileWrite || isRewrite) {
188
+ return `${prefix} 是只读角色 (write: none),不能调用 ${toolName}。如果任务确实需要改动,请用 worker_report 报告 blocked。`;
189
+ }
190
+ if (toolName === "bash" && typeof args.command === "string") {
191
+ const reason = bashWriteReason(args.command);
192
+ if (reason) {
193
+ return `${prefix} 是只读角色 (write: none),已拦截写操作:${reason}。只读命令可以继续;如果任务确实需要改动,请用 worker_report 报告 blocked。`;
194
+ }
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ // write=scoped:只有文件类工具能精确判断路径;bash 不做路径判断
200
+ if (!isFileWrite && !isRewrite) return undefined;
201
+ if (typeof args.path !== "string" || args.path === "") {
202
+ return `${prefix} 只能写入 allowedPaths 范围内的路径,${toolName} 必须明确给出 path。`;
203
+ }
204
+ const target = physicalPath(args.path, policy.cwd);
205
+ if (policy.allowedPaths.some((root) => isPathWithin(target, physicalPath(root, policy.cwd)))) return undefined;
206
+ return `${prefix} 不允许写入 ${args.path}。允许范围:${policy.allowedPaths.join("、")}。如果确实需要扩大范围,请用 worker_report 报告 blocked。`;
207
+ }
208
+
209
+ /** 启动时从工具列表中隐藏的工具,让模型一开始就看不到不能用的写工具 */
210
+ export function isToolHidden(policy: ToolPolicy, toolName: string): boolean {
211
+ if (policy.denyTools.some((pattern) => toolNameMatches(pattern, toolName))) return true;
212
+ return policy.write === "none" && (toolName === "write" || toolName === "edit");
213
+ }
package/src/worker.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  } from "./protocol.js";
37
37
  import { JsonlConnection } from "./transport.js";
38
38
  import { SessionGenerationManager } from "./lifecycle.js";
39
+ import { evaluateToolCall, isToolHidden, loadToolPolicyFromEnv, type ToolPolicy } from "./tool-policy.js";
39
40
 
40
41
  const FORBIDDEN_WORKER_TOOLS = new Set([
41
42
  "subagent",
@@ -95,6 +96,7 @@ export class WorkerManager {
95
96
 
96
97
  private readonly role: WorkerRole;
97
98
  private readonly getActiveChildCount: () => number;
99
+ private readonly toolPolicy: ToolPolicy | null = loadToolPolicyFromEnv();
98
100
 
99
101
  constructor(private pi: ExtensionAPI, strictProtocol = false, options: WorkerManagerOptions = {}) {
100
102
  this.strictProtocol = strictProtocol;
@@ -653,7 +655,8 @@ export class WorkerManager {
653
655
  }
654
656
 
655
657
  this.pi.setActiveTools(
656
- this.pi.getActiveTools().filter((name) => !FORBIDDEN_WORKER_TOOLS.has(name)),
658
+ this.pi.getActiveTools().filter((name) =>
659
+ !FORBIDDEN_WORKER_TOOLS.has(name) && !(this.toolPolicy && isToolHidden(this.toolPolicy, name))),
657
660
  );
658
661
  // hello_ok 可能尚未到达或已到达;两种时序下均由双条件门控发送 worker_ready
659
662
  this.trySendWorkerReady();
@@ -716,6 +719,11 @@ export class WorkerManager {
716
719
  });
717
720
 
718
721
  this.pi.on("tool_call", async (event) => {
722
+ // 工具策略先于会话代际判断:任何时序下都不能绕过角色权限
723
+ if (this.toolPolicy) {
724
+ const reason = evaluateToolCall(this.toolPolicy, event.toolName, event.input);
725
+ if (reason) return { block: true, reason };
726
+ }
719
727
  const gen = this.activeGeneration;
720
728
  if (!this.isCurrentGeneration(gen) || !this.currentContext) {
721
729
  this.staleCallbacksIgnored++;