@mozhi0012/pi-terminal-worker 0.2.0 → 0.4.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.
Files changed (50) hide show
  1. package/README.md +220 -169
  2. package/dist/controller.d.ts +9 -0
  3. package/dist/controller.d.ts.map +1 -1
  4. package/dist/controller.js +106 -53
  5. package/dist/controller.js.map +1 -1
  6. package/dist/launcher.d.ts +9 -1
  7. package/dist/launcher.d.ts.map +1 -1
  8. package/dist/launcher.js +95 -22
  9. package/dist/launcher.js.map +1 -1
  10. package/dist/lifecycle.d.ts +7 -0
  11. package/dist/lifecycle.d.ts.map +1 -1
  12. package/dist/lifecycle.js +4 -0
  13. package/dist/lifecycle.js.map +1 -1
  14. package/dist/multi-worker.d.ts +20 -0
  15. package/dist/multi-worker.d.ts.map +1 -1
  16. package/dist/multi-worker.js +53 -10
  17. package/dist/multi-worker.js.map +1 -1
  18. package/dist/protocol.d.ts +2 -0
  19. package/dist/protocol.d.ts.map +1 -1
  20. package/dist/protocol.js +2 -0
  21. package/dist/protocol.js.map +1 -1
  22. package/dist/team-config.d.ts +61 -0
  23. package/dist/team-config.d.ts.map +1 -0
  24. package/dist/team-config.js +195 -0
  25. package/dist/team-config.js.map +1 -0
  26. package/dist/terminal-multiplexer.d.ts +25 -0
  27. package/dist/terminal-multiplexer.d.ts.map +1 -0
  28. package/dist/terminal-multiplexer.js +102 -0
  29. package/dist/terminal-multiplexer.js.map +1 -0
  30. package/dist/tool-policy.d.ts +36 -0
  31. package/dist/tool-policy.d.ts.map +1 -0
  32. package/dist/tool-policy.js +199 -0
  33. package/dist/tool-policy.js.map +1 -0
  34. package/dist/worker.d.ts +1 -0
  35. package/dist/worker.d.ts.map +1 -1
  36. package/dist/worker.js +9 -1
  37. package/dist/worker.js.map +1 -1
  38. package/package.json +78 -72
  39. package/runtime/bootstrap-support.mjs +68 -49
  40. package/runtime/bootstrap.mjs +328 -304
  41. package/runtime/terminal-support.mjs +63 -0
  42. package/src/controller.ts +2761 -2724
  43. package/src/launcher.ts +592 -517
  44. package/src/lifecycle.ts +289 -284
  45. package/src/multi-worker.ts +69 -9
  46. package/src/protocol.ts +5 -0
  47. package/src/team-config.ts +255 -0
  48. package/src/terminal-multiplexer.ts +108 -0
  49. package/src/tool-policy.ts +213 -0
  50. package/src/worker.ts +9 -1
@@ -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++;