@mozhi0012/pi-terminal-worker 0.1.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.
- package/README.md +71 -3
- package/dist/controller.d.ts +5 -1
- package/dist/controller.d.ts.map +1 -1
- package/dist/controller.js +9 -2
- package/dist/controller.js.map +1 -1
- package/dist/extension.d.ts +8 -3
- package/dist/extension.d.ts.map +1 -1
- package/dist/extension.js +26 -5
- package/dist/extension.js.map +1 -1
- package/dist/launcher.d.ts +5 -0
- package/dist/launcher.d.ts.map +1 -1
- package/dist/launcher.js +3 -1
- package/dist/launcher.js.map +1 -1
- package/dist/lifecycle.d.ts +4 -2
- package/dist/lifecycle.d.ts.map +1 -1
- package/dist/lifecycle.js +2 -1
- package/dist/lifecycle.js.map +1 -1
- package/dist/multi-worker.d.ts +26 -0
- package/dist/multi-worker.d.ts.map +1 -1
- package/dist/multi-worker.js +67 -4
- package/dist/multi-worker.js.map +1 -1
- package/dist/protocol.d.ts +6 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +14 -1
- package/dist/protocol.js.map +1 -1
- package/dist/team-config.d.ts +61 -0
- package/dist/team-config.d.ts.map +1 -0
- package/dist/team-config.js +195 -0
- package/dist/team-config.js.map +1 -0
- package/dist/tool-policy.d.ts +36 -0
- package/dist/tool-policy.d.ts.map +1 -0
- package/dist/tool-policy.js +199 -0
- package/dist/tool-policy.js.map +1 -0
- package/dist/worker.d.ts +13 -1
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +46 -23
- package/dist/worker.js.map +1 -1
- package/package.json +5 -2
- package/runtime/bootstrap-support.mjs +67 -0
- package/runtime/bootstrap.mjs +41 -15
- package/src/controller.ts +13 -0
- package/src/extension.ts +26 -6
- package/src/launcher.ts +8 -1
- package/src/lifecycle.ts +5 -2
- package/src/multi-worker.ts +86 -4
- package/src/protocol.ts +21 -2
- package/src/team-config.ts +255 -0
- package/src/tool-policy.ts +213 -0
- package/src/worker.ts +57 -25
|
@@ -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
|
@@ -32,9 +32,11 @@ import {
|
|
|
32
32
|
type WorkerReportPayload,
|
|
33
33
|
type WorkerReadyPayload,
|
|
34
34
|
type ModelChangedPayload,
|
|
35
|
+
type WorkerRole,
|
|
35
36
|
} from "./protocol.js";
|
|
36
37
|
import { JsonlConnection } from "./transport.js";
|
|
37
38
|
import { SessionGenerationManager } from "./lifecycle.js";
|
|
39
|
+
import { evaluateToolCall, isToolHidden, loadToolPolicyFromEnv, type ToolPolicy } from "./tool-policy.js";
|
|
38
40
|
|
|
39
41
|
const FORBIDDEN_WORKER_TOOLS = new Set([
|
|
40
42
|
"subagent",
|
|
@@ -51,6 +53,12 @@ interface FollowupQueueItem {
|
|
|
51
53
|
sessionGeneration: number;
|
|
52
54
|
}
|
|
53
55
|
|
|
56
|
+
export interface WorkerManagerOptions {
|
|
57
|
+
role?: WorkerRole;
|
|
58
|
+
/** lead 的协调器提供查询;普通 worker 始终沿用无子实例语义。 */
|
|
59
|
+
getActiveChildCount?: () => number;
|
|
60
|
+
}
|
|
61
|
+
|
|
54
62
|
export class WorkerManager {
|
|
55
63
|
private conn: JsonlConnection | null = null;
|
|
56
64
|
private isDetached = false;
|
|
@@ -86,8 +94,14 @@ export class WorkerManager {
|
|
|
86
94
|
|
|
87
95
|
private readonly strictProtocol: boolean;
|
|
88
96
|
|
|
89
|
-
|
|
97
|
+
private readonly role: WorkerRole;
|
|
98
|
+
private readonly getActiveChildCount: () => number;
|
|
99
|
+
private readonly toolPolicy: ToolPolicy | null = loadToolPolicyFromEnv();
|
|
100
|
+
|
|
101
|
+
constructor(private pi: ExtensionAPI, strictProtocol = false, options: WorkerManagerOptions = {}) {
|
|
90
102
|
this.strictProtocol = strictProtocol;
|
|
103
|
+
this.role = options.role ?? (process.env.PI_TERMINAL_WORKER_ROLE === "lead" ? "lead" : "worker");
|
|
104
|
+
this.getActiveChildCount = options.getActiveChildCount ?? (() => 0);
|
|
91
105
|
this.controllerId = process.env.PI_TERMINAL_WORKER_CONTROLLER_ID || "";
|
|
92
106
|
this.workerId = process.env.PI_TERMINAL_WORKER_WORKER_ID || "";
|
|
93
107
|
this.pipePath = process.env.PI_TERMINAL_WORKER_PIPE_PATH || "";
|
|
@@ -512,8 +526,12 @@ export class WorkerManager {
|
|
|
512
526
|
parts.push(
|
|
513
527
|
`执行与回执要求:`,
|
|
514
528
|
`1. 按照方案在指定工作目录内修改代码并进行本地验证。`,
|
|
515
|
-
|
|
516
|
-
|
|
529
|
+
this.role === "lead"
|
|
530
|
+
? `2. 你是阶段主代理,可用 worker_* 派发执行 Worker(只能 worker 角色,不能嵌套 lead)。负责划分范围、审查交付与测试,完成验收后关闭子 Worker。超出允许范围或需要改变设计时,调用 worker_report(kind="blocked") 说明原因。`
|
|
531
|
+
: `2. 不得再派发子代理或启动新终端;超出允许范围或需要改变设计时,调用 worker_report(kind="blocked") 说明原因。`,
|
|
532
|
+
this.role === "lead"
|
|
533
|
+
? `3. 完成验收、遇到提问或出现阻碍时,必须调用 worker_report 向上级主控汇报;worker_report 应是本轮最后一个工具调用。`
|
|
534
|
+
: `3. 任务完成、遇到提问或出现阻碍时,必须调用 worker_report 工具提交回执。`,
|
|
517
535
|
);
|
|
518
536
|
|
|
519
537
|
return parts.join("\n\n");
|
|
@@ -541,7 +559,7 @@ export class WorkerManager {
|
|
|
541
559
|
item.sessionGeneration = gen;
|
|
542
560
|
const queueItem = item as FollowupQueueItem;
|
|
543
561
|
|
|
544
|
-
if (ctx && ctx.isIdle() && !ctx.hasPendingMessages()) {
|
|
562
|
+
if ((this.role !== "lead" || this.followupQueue.length === 0) && ctx && ctx.isIdle() && !ctx.hasPendingMessages()) {
|
|
545
563
|
// 立即派发分支同样校验代际:绝不把消息交给已失效的会话
|
|
546
564
|
if (!this.isCurrentGeneration(queueItem.sessionGeneration)) {
|
|
547
565
|
this.staleCallbacksIgnored++;
|
|
@@ -599,8 +617,13 @@ export class WorkerManager {
|
|
|
599
617
|
this.staleCallbacksIgnored++;
|
|
600
618
|
return false;
|
|
601
619
|
}
|
|
620
|
+
// deliverAs: "followUp" 针对 pi 1.2.0 的竞态加固:isIdle() 检查与 prompt() 内部
|
|
621
|
+
// 异步间隙之间若有其他 run 启动(会话即算 busy),无 deliverAs 的 sendUserMessage
|
|
622
|
+
// 会抛 "Agent is already processing",且被 pi 扩展 API 层 catch 成扩展错误事件、
|
|
623
|
+
// 消息静默丢失;传 followUp 后改为排队。空闲时该选项被忽略,行为不变。
|
|
602
624
|
this.pi.sendUserMessage(text, {
|
|
603
625
|
expandPromptTemplates: false,
|
|
626
|
+
deliverAs: "followUp",
|
|
604
627
|
});
|
|
605
628
|
return true;
|
|
606
629
|
}
|
|
@@ -632,7 +655,8 @@ export class WorkerManager {
|
|
|
632
655
|
}
|
|
633
656
|
|
|
634
657
|
this.pi.setActiveTools(
|
|
635
|
-
this.pi.getActiveTools().filter((name) =>
|
|
658
|
+
this.pi.getActiveTools().filter((name) =>
|
|
659
|
+
!FORBIDDEN_WORKER_TOOLS.has(name) && !(this.toolPolicy && isToolHidden(this.toolPolicy, name))),
|
|
636
660
|
);
|
|
637
661
|
// hello_ok 可能尚未到达或已到达;两种时序下均由双条件门控发送 worker_ready
|
|
638
662
|
this.trySendWorkerReady();
|
|
@@ -650,23 +674,8 @@ export class WorkerManager {
|
|
|
650
674
|
}
|
|
651
675
|
});
|
|
652
676
|
|
|
653
|
-
// 监听 session_shutdown
|
|
654
|
-
this.pi.on("session_shutdown", async () =>
|
|
655
|
-
// 幂等:重复触发不得再次 destroy / 抛错;先推进代际使所有旧回调立即失效,
|
|
656
|
-
// 之后旧回调不得再调用 sendUserMessage / abort / shutdown / setActiveTools
|
|
657
|
-
this.sessionGen.nextGeneration();
|
|
658
|
-
this.activeGeneration = this.sessionGen.generation;
|
|
659
|
-
this.currentContext = null;
|
|
660
|
-
this.clearQueue();
|
|
661
|
-
this.currentCandidate = null;
|
|
662
|
-
this.candidateInvalidated = true;
|
|
663
|
-
|
|
664
|
-
const conn = this.conn;
|
|
665
|
-
if (conn) {
|
|
666
|
-
this.conn = null;
|
|
667
|
-
conn.destroy();
|
|
668
|
-
}
|
|
669
|
-
});
|
|
677
|
+
// 监听 session_shutdown;lead 也会在下级异步清理前主动执行此幂等入口。
|
|
678
|
+
this.pi.on("session_shutdown", async () => this.dispose());
|
|
670
679
|
|
|
671
680
|
// 监听 input 事件:识别本地用户在终端窗口键盘输入干预
|
|
672
681
|
this.pi.on("input", async (event: InputEvent) => {
|
|
@@ -710,6 +719,11 @@ export class WorkerManager {
|
|
|
710
719
|
});
|
|
711
720
|
|
|
712
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
|
+
}
|
|
713
727
|
const gen = this.activeGeneration;
|
|
714
728
|
if (!this.isCurrentGeneration(gen) || !this.currentContext) {
|
|
715
729
|
this.staleCallbacksIgnored++;
|
|
@@ -786,7 +800,8 @@ export class WorkerManager {
|
|
|
786
800
|
}).catch(() => {});
|
|
787
801
|
}
|
|
788
802
|
this.currentCandidate = null;
|
|
789
|
-
} else if (!this.taskHasReported && this.currentTaskId)
|
|
803
|
+
} else if (!this.taskHasReported && this.currentTaskId && !this.isWaitingForChildren() &&
|
|
804
|
+
!(this.role === "lead" && (this.followupQueue.length > 0 || ctx.hasPendingMessages()))) {
|
|
790
805
|
// 模型结束了但没有提交过回执
|
|
791
806
|
if (this.conn && !this.conn.socket.destroyed) {
|
|
792
807
|
this.conn.sendEnvelope({
|
|
@@ -840,13 +855,29 @@ export class WorkerManager {
|
|
|
840
855
|
id: crypto.randomUUID(),
|
|
841
856
|
seq: this.conn.nextSeq,
|
|
842
857
|
type: "activity",
|
|
843
|
-
payload: { state: "idle" },
|
|
858
|
+
payload: { state: this.isWaitingForChildren() ? "waiting_children" : "idle" },
|
|
844
859
|
}).catch(() => {});
|
|
845
860
|
}
|
|
846
861
|
});
|
|
847
862
|
});
|
|
848
863
|
}
|
|
849
864
|
|
|
865
|
+
/** 先同步失效上行回调,再允许 lead 等待下级协调器的异步清理。 */
|
|
866
|
+
public dispose(): void {
|
|
867
|
+
this.activeGeneration = this.sessionGen.nextGeneration();
|
|
868
|
+
this.currentContext = null;
|
|
869
|
+
this.clearQueue();
|
|
870
|
+
this.currentCandidate = null;
|
|
871
|
+
this.candidateInvalidated = true;
|
|
872
|
+
const conn = this.conn;
|
|
873
|
+
this.conn = null;
|
|
874
|
+
conn?.destroy();
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
private isWaitingForChildren(): boolean {
|
|
878
|
+
return this.role === "lead" && this.getActiveChildCount() > 0;
|
|
879
|
+
}
|
|
880
|
+
|
|
850
881
|
private registerWorkerReportTool(): void {
|
|
851
882
|
this.pi.registerTool({
|
|
852
883
|
name: "worker_report",
|
|
@@ -964,7 +995,8 @@ export class WorkerManager {
|
|
|
964
995
|
}
|
|
965
996
|
|
|
966
997
|
private registerWorkerCommands(): void {
|
|
967
|
-
|
|
998
|
+
// lead 的 /worker-status 保留给下级协调器,上行受控状态使用独立命令。
|
|
999
|
+
this.pi.registerCommand(this.role === "lead" ? "lead-status" : "worker-status", {
|
|
968
1000
|
description: "查看当前 Worker 受控状态",
|
|
969
1001
|
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
970
1002
|
const status = this.conn ? "已连接到 Controller" : "未连接 / 已脱钩";
|