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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
  4. package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
  5. package/package.json +63 -4
  6. package/skills/pi-subagents-extend/SKILL.md +312 -0
  7. package/skills/pi-subagents-extend-context/SKILL.md +103 -0
  8. package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
  9. package/src/bash/env.ts +108 -0
  10. package/src/bash/index.ts +27 -0
  11. package/src/bash/network.ts +97 -0
  12. package/src/bash/programs.ts +367 -0
  13. package/src/bash/rules.ts +247 -0
  14. package/src/bash/tokens.ts +169 -0
  15. package/src/bash/unreachable.ts +429 -0
  16. package/src/budgets.ts +89 -0
  17. package/src/child-context.ts +24 -0
  18. package/src/context-scope.ts +93 -0
  19. package/src/deliverable.ts +216 -0
  20. package/src/dependencies.ts +320 -0
  21. package/src/handoff-hint.ts +69 -0
  22. package/src/index.ts +181 -0
  23. package/src/main-context.ts +30 -0
  24. package/src/main-skills.ts +77 -0
  25. package/src/notices.ts +299 -0
  26. package/src/paths/index.ts +165 -0
  27. package/src/policy/glob.ts +146 -0
  28. package/src/policy/index.ts +36 -0
  29. package/src/policy/payload.ts +312 -0
  30. package/src/probe.ts +495 -0
  31. package/src/role-config.ts +434 -0
  32. package/src/sandbox/grants.ts +339 -0
  33. package/src/sandbox/helper.ts +137 -0
  34. package/src/sandbox/index.ts +12 -0
  35. package/src/sandbox/spec.ts +285 -0
  36. package/src/sandbox-note.ts +194 -0
  37. package/src/wiring/agent-start.ts +371 -0
  38. package/src/wiring/context.ts +216 -0
  39. package/src/wiring/misc.ts +55 -0
  40. package/src/wiring/session-start.ts +69 -0
  41. package/src/wiring/tool-call/anchor.ts +138 -0
  42. package/src/wiring/tool-call/bash-path.ts +0 -0
  43. package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
  44. package/src/wiring/tool-call/judge.ts +585 -0
  45. package/src/wiring/tool-call/original-args.ts +64 -0
  46. package/src/wiring/tool-call/paths.ts +235 -0
  47. package/src/wiring/tool-result.ts +68 -0
  48. package/src/worktree-default.ts +27 -0
@@ -0,0 +1,371 @@
1
+ import type { BeforeAgentStartEvent, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { spawn } from "node:child_process";
3
+ import { closeSync, lstatSync, mkdirSync, openSync, readlinkSync, realpathSync, unlinkSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, join, resolve, sep } from "node:path";
6
+ import { DenyCounter } from "../budgets.ts";
7
+ import { deliverableTarget, ensureDeliverableLink, mainRepoRoot } from "../deliverable.ts";
8
+ import { canonical } from "../paths/index.ts";
9
+ import { denyAll } from "../policy/index.ts";
10
+ import { agentMdDirs, outputFromBlock, parseRoleName, policyFromBlock, readExtendBlock, resolveAgentFile, resolveRoleFromPrompt, setupFromBlock, worktreeFromBlock } from "../role-config.ts";
11
+ import { setDeliverableTargetPath } from "../sandbox/index.ts";
12
+ import { dropSubagentOnlySkills } from "../main-skills.ts";
13
+ import type { Wiring } from "./context.ts";
14
+
15
+ /**
16
+ * before_agent_start 的正文,连同它专用的接线簇(deliverableGrant / wireDeliverable /
17
+ * wireWorktree / wirePreExec / nodeModulesWriteHint)逐字搬自 index.ts。模块级状态
18
+ * worktreeNodeModules 只被这条链写入,所以住在本模块;uiWarning 曾经也是(模块级 let
19
+ * + setUiWarning),现在是 Wiring 的字段(见 wiring/context.ts):session_start、
20
+ * judgeToolCall 与本处理器都注册各自的通道,最近一次写入的生效。四个导出的接线函数
21
+ * 由 index.ts 原样再导出(阶段 3 的测试从 index.ts 取它们)。
22
+ */
23
+
24
+ const DELIVERABLE_SECTION = "pi_subagents_extend_deliverable";
25
+
26
+ /**
27
+ * 交付物授权只给主检出里的一个普通文件:目录会把整棵子树变成写面,软链会把授权指到树外。
28
+ * 不存在时用 wx 落位——检查和落位之间被换成软链就宁可失败,绝不跟着链接写。
29
+ * 落位前后都按 canonical 的主检出根做边界检查:先挡住软链父目录,再校验最终授权。
30
+ */
31
+ function deliverableGrant(target: string, root: string, warn: (message: string) => void): string | undefined {
32
+ let stat: ReturnType<typeof lstatSync> | undefined;
33
+ try {
34
+ stat = lstatSync(target);
35
+ } catch (error) {
36
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
37
+ warn(`pi-subagents-extend: cannot inspect deliverable ${target}: ${error instanceof Error ? error.message : String(error)}; granting nothing`);
38
+ return undefined;
39
+ }
40
+ }
41
+ if (stat) {
42
+ if (stat.isSymbolicLink() || !stat.isFile()) {
43
+ const kind = stat.isSymbolicLink() ? "a symbolic link" : "a directory or special file";
44
+ warn(`pi-subagents-extend: deliverable ${target} is not a regular file (${kind}); granting nothing (a directory would open its whole subtree, a link could point outside the main checkout)`);
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ const rootCanonical = canonical(root);
50
+ const insideCheckout = (candidate: string): boolean =>
51
+ candidate === rootCanonical || candidate.startsWith(rootCanonical + sep);
52
+
53
+ // 落位前先解析父目录(取最深已存在祖先):软链父目录会把新文件写到主检出之外。
54
+ // 旧的 realpathSync(grant) !== resolve(grant) 是空操作——grant 已由 canonical 解析,两边必然相等。
55
+ const parentCanonical = canonical(dirname(target));
56
+ if (!insideCheckout(parentCanonical)) {
57
+ warn(`pi-subagents-extend: deliverable ${target} resolves outside the main checkout (${join(parentCanonical, basename(target))}); granting nothing`);
58
+ return undefined;
59
+ }
60
+
61
+ if (!stat) {
62
+ try {
63
+ // helper 只接受已存在的路径;空文件先落位,真正的写入仍交给子代理。
64
+ mkdirSync(dirname(target), { recursive: true });
65
+ closeSync(openSync(target, "wx"));
66
+ } catch (error) {
67
+ warn(`pi-subagents-extend: unable to create deliverable file ${target}: ${error instanceof Error ? error.message : String(error)}; granting nothing`);
68
+ return undefined;
69
+ }
70
+ }
71
+
72
+ const grant = canonical(target);
73
+ if (!insideCheckout(grant)) {
74
+ warn(`pi-subagents-extend: deliverable ${target} resolves outside the main checkout (${grant}); granting nothing`);
75
+ return undefined;
76
+ }
77
+ return grant;
78
+ }
79
+
80
+ /**
81
+ * output.deliverable 的接线:建软链、把真实文件加进写授权、并给子代理一条提示段落。
82
+ * 抽成具名函数是为了让阶段 3 的测试能直接走同一条路径,而不是复制一份判定。
83
+ */
84
+ export function wireDeliverable(
85
+ cwd: string,
86
+ block: Record<string, unknown> | undefined,
87
+ policy: { absoluteWrite: string[] },
88
+ options: { sections?: Record<string, string> } | undefined,
89
+ warn: (message: string) => void,
90
+ ): { link?: ReturnType<typeof ensureDeliverableLink>; target?: string } {
91
+ setDeliverableTargetPath(undefined);
92
+ const { output, problems } = outputFromBlock(block ?? {});
93
+ for (const problem of problems) warn(`pi-subagents-extend: ${problem}`);
94
+ if (!output?.deliverable) return {};
95
+ const deliverable = output.deliverable;
96
+ const anchor = mainRepoRoot(cwd);
97
+ if (anchor.root === null) {
98
+ warn(`pi-subagents-extend: cannot locate the main repository from ${cwd}; tried: ${anchor.tried.join(" | ")}`);
99
+ return {};
100
+ }
101
+ const link = ensureDeliverableLink(cwd, anchor.root, deliverable);
102
+ if ("warning" in link) warn(`pi-subagents-extend: ${link.warning}`);
103
+ const target = deliverableTarget(anchor.root, deliverable);
104
+ const grant = deliverableGrant(target, anchor.root, warn);
105
+ if (!grant) return { link, target };
106
+ if (!policy.absoluteWrite.includes(grant)) policy.absoluteWrite.push(grant);
107
+ setDeliverableTargetPath(grant);
108
+ if (options) {
109
+ options.sections = {
110
+ ...(options.sections ?? {}),
111
+ [DELIVERABLE_SECTION]: `Write the deliverable to \`${deliverable}\`. Name the file in your final message; the parent reads it at \`${grant}\`.`,
112
+ };
113
+ }
114
+ return { link, target };
115
+ }
116
+
117
+ /** 会话级记住 nodeModules 的选择;写在拒绝文案里的提示只在 keep / 缺席时给,remove 后给就是假提示。 */
118
+ let worktreeNodeModules: "keep" | "remove" = "keep";
119
+
120
+ /** 写目标是否穿过 cwd/node_modules 这条软链,包括子代理直接写出主检出的真实路径。 */
121
+ export function nodeModulesWriteHint(cwd: string, target: string): string {
122
+ if (worktreeNodeModules !== "keep") return "";
123
+ const link = resolve(cwd, "node_modules");
124
+ let absolute: string;
125
+ try {
126
+ if (!lstatSync(link).isSymbolicLink()) return "";
127
+ absolute = resolve(cwd, target);
128
+ } catch {
129
+ return "";
130
+ }
131
+ if (absolute !== link && !absolute.startsWith(link + sep)) {
132
+ try {
133
+ const real = realpathSync(link);
134
+ if (!absolute.startsWith(real + sep)) return "";
135
+ } catch {
136
+ return "";
137
+ }
138
+ }
139
+ return " Set worktree.nodeModules: remove in the role md to unlink the shared node_modules link.";
140
+ }
141
+
142
+ /** worktree.nodeModules: remove 只解掉工作树侧的软链,目标(主检出里的依赖)必须留下。 */
143
+ export function wireWorktree(
144
+ cwd: string,
145
+ block: Record<string, unknown> | undefined,
146
+ warn: (message: string) => void,
147
+ ): { action: "none" | "removed" | "skipped" } {
148
+ const { worktree, problems } = worktreeFromBlock(block ?? {});
149
+ for (const problem of problems) warn(`pi-subagents-extend: ${problem}`);
150
+ worktreeNodeModules = worktree?.nodeModules ?? "keep";
151
+ if (worktree?.nodeModules !== "remove") return { action: "none" };
152
+
153
+ const link = resolve(cwd, "node_modules");
154
+ let target: string;
155
+ let stat: ReturnType<typeof lstatSync>;
156
+ try {
157
+ stat = lstatSync(link);
158
+ } catch {
159
+ return { action: "none" };
160
+ }
161
+ if (!stat.isSymbolicLink()) {
162
+ warn(`pi-subagents-extend: ${link} is a real directory; left it untouched`);
163
+ return { action: "skipped" };
164
+ }
165
+ try {
166
+ target = resolve(dirname(link), readlinkSync(link));
167
+ } catch (error) {
168
+ warn(`pi-subagents-extend: unable to read link ${link}: ${error instanceof Error ? error.message : String(error)}`);
169
+ return { action: "skipped" };
170
+ }
171
+ const anchor = mainRepoRoot(cwd);
172
+ if (anchor.root === null || (target !== anchor.root && !target.startsWith(anchor.root + sep))) {
173
+ warn(`pi-subagents-extend: ${link} points to ${target}, outside the main checkout; left it untouched`);
174
+ return { action: "skipped" };
175
+ }
176
+ try {
177
+ unlinkSync(link);
178
+ } catch (error) {
179
+ warn(`pi-subagents-extend: unable to unlink ${link}: ${error instanceof Error ? error.message : String(error)}`);
180
+ return { action: "skipped" };
181
+ }
182
+ warn(`pi-subagents-extend: removed ${link}; the target ${target} was left untouched`);
183
+ return { action: "removed" };
184
+ }
185
+
186
+ /** setup.preExec 每个子会话跑一次;失败只告警,绝不让派单半路停下。 */
187
+ export async function wirePreExec(
188
+ cwd: string,
189
+ block: Record<string, unknown> | undefined,
190
+ warn: (message: string) => void,
191
+ ): Promise<{ ran: boolean; status?: number | null }> {
192
+ const { setup, problems } = setupFromBlock(block ?? {});
193
+ for (const problem of problems) warn(`pi-subagents-extend: ${problem}`);
194
+ const command = setup?.preExec;
195
+ if (!command) return { ran: false };
196
+
197
+ // 冷工作树里装依赖常常要好几分钟,所以给足 10 分钟。这里故意不走 helper:命令要往
198
+ // 工作树(以及包管理器缓存)里写,而 helper 的可写面只覆盖本次写授权,天然罩不住安装。
199
+ let child: ReturnType<typeof spawn>;
200
+ try {
201
+ // detached 让命令自带进程组;超时杀整组,不留装依赖时 fork 出去的孙进程。
202
+ child = spawn(command, { shell: true, cwd, detached: true, stdio: ["ignore", "pipe", "pipe"] });
203
+ } catch (error) {
204
+ warn(`pi-subagents-extend: setup.preExec could not start: ${error instanceof Error ? error.message : String(error)}; continuing`);
205
+ return { ran: true };
206
+ }
207
+
208
+ const pid = child.pid;
209
+ const maxOutput = 4 * 1024 * 1024;
210
+ let output = "";
211
+ const collect = (chunk: Buffer | string): void => {
212
+ output = (output + chunk.toString("utf8")).slice(-maxOutput);
213
+ };
214
+ child.stdout?.on("data", collect);
215
+ child.stderr?.on("data", collect);
216
+
217
+ let timedOut = false;
218
+ const timer = setTimeout(() => {
219
+ timedOut = true;
220
+ if (pid !== undefined) {
221
+ try {
222
+ process.kill(-pid, "SIGKILL");
223
+ } catch {
224
+ // 进程组已经退出;组杀失败无需处理。
225
+ }
226
+ }
227
+ }, 600_000);
228
+ // 子进程及其 stdout/stderr 管道会撑住事件循环,超时对运行中的子进程照样生效;unref 只防止
229
+ // 会话先结束时被这个十分钟的定时器吊住(进程退出时 clearTimeout 会把它摘掉)。
230
+ timer.unref();
231
+
232
+ const outcome = await new Promise<{ status: number | null; error?: Error }>((resolve) => {
233
+ child.once("error", (error) => {
234
+ clearTimeout(timer);
235
+ resolve({ status: null, error });
236
+ });
237
+ child.once("close", (status) => {
238
+ clearTimeout(timer);
239
+ resolve({ status });
240
+ });
241
+ });
242
+
243
+ if (outcome.error || outcome.status !== 0) {
244
+ const tail = output.split(/\r?\n/).slice(-20).join("\n").slice(-2000) || "(no output)";
245
+ const code = outcome.error
246
+ ? `no exit code (${outcome.error.message})`
247
+ : timedOut
248
+ ? "no exit code (timed out after 600000ms; killed the process group)"
249
+ : outcome.status === null
250
+ ? "no exit code (killed by signal)"
251
+ : String(outcome.status);
252
+ warn(`pi-subagents-extend: setup.preExec exited with code ${code}; continuing. Output tail:\n${tail}`);
253
+ }
254
+ return { ran: true, status: outcome.status };
255
+ }
256
+
257
+ /**
258
+ * before_agent_start 的正文(逐字搬自 index.ts 的处理器):认子会话身份,按角色 md 补
259
+ * 基线,再依次接交付物、worktree 与 preExec。preExec 最长等十分钟,期间同一键的再次
260
+ * 触发在 roleWirings 上 await 在飞的接线,不重跑。
261
+ */
262
+ export async function wireAgentStart(w: Wiring, event: BeforeAgentStartEvent, ctx: ExtensionContext): Promise<void> {
263
+ const raw = (event as { systemPrompt?: unknown }).systemPrompt;
264
+ const prompt = typeof raw === "string" ? raw : "";
265
+ const cwd = ctx.cwd ?? process.cwd();
266
+ // 实测:前台子代理的 process.env.PI_SUBAGENT_CHILD 是 null —— pi-subagents 只为
267
+ // host === "runner" 的后台子代理设它,前台在父进程里 restoreProcessEnv。
268
+ // 所以子会话另看 bindings 载荷与提示里的角色身份;别把这行简化回只看 PI_SUBAGENT_CHILD。
269
+ const child =
270
+ process.env.PI_SUBAGENT_CHILD === "1" ||
271
+ w.call.config !== undefined ||
272
+ w.call.error !== undefined ||
273
+ parseRoleName(prompt) !== null ||
274
+ resolveRoleFromPrompt(prompt, cwd, homedir()).role !== null;
275
+ if (!child) {
276
+ // 主会话:把 frontmatter 声明 subagent-only: true 的 skill 从可用列表摘掉
277
+ // (机制与理由见 main-skills.ts)。子会话不分前台后台一律不碰 skills——
278
+ // 子代理的 skill 列表属于给它定的那次派单。
279
+ dropSubagentOnlySkills(event);
280
+ return;
281
+ }
282
+ if (w.roleResolved) return;
283
+ const tag = parseRoleName(prompt);
284
+ const wiringKey = `${cwd}\u0000${tag}`;
285
+ const inFlight = w.roleWirings.get(wiringKey);
286
+ if (inFlight) {
287
+ await inFlight;
288
+ return;
289
+ }
290
+ let finishWiring!: () => void;
291
+ const wiring = new Promise<void>((resolve) => { finishWiring = resolve; });
292
+ w.roleWirings.set(wiringKey, wiring);
293
+ try {
294
+ // 模块级状态在子会话开始时清零,不依赖 session_start 与 before_agent_start 的先后顺序。
295
+ setDeliverableTargetPath(undefined);
296
+ worktreeNodeModules = "keep";
297
+ const ui = ctx.ui as { notify?: (m: string, t?: string) => void } | undefined;
298
+ w.uiWarning = (message) => { ui?.notify?.(message, "warning"); };
299
+ for (const name of w.call.ignored ?? []) {
300
+ const mdKey = name === "setup" ? "setup.preExec" : "output.deliverable";
301
+ w.uiWarning?.(`pi-subagents-extend: ${name} in extensionBindings is ignored; put ${mdKey} in the role md`);
302
+ }
303
+ const home = homedir();
304
+ // 标签找不到时再用正文探针认角色(systemPromptMode: replace 会丢标签)。
305
+ // 扫描只在这里发生:前面的 roleResolved / roleWirings 闸门保证每轮接线最多跑一次。
306
+ const resolved = resolveRoleFromPrompt(prompt, cwd, home);
307
+ for (const warning of resolved.warnings) w.uiWarning?.(warning);
308
+ const role = resolved.role;
309
+ if (!role) {
310
+ let warning = w.policy.active
311
+ ? `pi-subagents-extend: no active_agent role was found in the system prompt, so the role md limits are NOT applied; the only configuration in effect is ${w.policy.source}.`
312
+ : "pi-subagents-extend: no active_agent role was found in the system prompt, so the role md limits are NOT applied; no configuration is in effect, so tool calls in this child are unconstrained.";
313
+ if (resolved.extendMdSeen) {
314
+ // 有 md 声明了 extend 却没认出身份,点明最可能的成因与改法,免得反复撞限制。
315
+ warning += `\npi-subagents-extend: a role md declares an extend block, but the prompt has no <active_agent> tag and no md body matched; systemPromptMode: replace drops the tag — use append (or keep the md body intact) so the role can be identified.`;
316
+ }
317
+ w.uiWarning?.(warning);
318
+ // 这次发射没有身份(无标签、正文也无唯一命中):不能在这里闩上
319
+ // roleResolved——会话重发且第二次带上 <active_agent> 标签时,角色 md 必须
320
+ // 仍然生效(preExec 也从未跑过,晚到的那次接线照跑一次)。落闩的只有两条
321
+ // 路:认出角色走完整接线(见本函数末尾),以及 md 坏掉的 denyAll 路径
322
+ // (坏 md 绝不静默降级成「无角色」,也不逐轮重试)。
323
+ return;
324
+ }
325
+ const file = resolveAgentFile(role, cwd, home);
326
+ if (!file) {
327
+ w.uiWarning?.(
328
+ `pi-subagents-extend: no role md was found for role "${role}"; the role md limits are NOT applied. Looked in: ${agentMdDirs(cwd, home).join(", ")}`,
329
+ );
330
+ w.roleResolved = true;
331
+ return;
332
+ }
333
+ const read = readExtendBlock(file);
334
+ const converted = read.block ? policyFromBlock(read.block) : { problems: [] as string[] };
335
+ const problems = [...read.problems, ...converted.problems];
336
+ for (const problem of problems) {
337
+ w.uiWarning?.(`pi-subagents-extend: ${role} (${file}): ${problem}`);
338
+ }
339
+ // md 存在且声明了策略却用不上 = 配置坏了,必须 fail closed:用户配的限制一样都没生效,
340
+ // 静默放开比全拒危险。全拒并把 md 路径与问题原文点名进拒绝文案——那是父代理改错的唯一线索。
341
+ // 两个不算问题的缺口保持原样:md 没有 extend 块(不表达限制是合法角色)与找不到 md
342
+ // (内置角色本来就没有,全拒会把普通子代理锁死)。
343
+ if (problems.length > 0) {
344
+ w.roleSource = `role md ${file}`;
345
+ w.probe?.dispose();
346
+ w.policy = denyAll(
347
+ `role md ${file} could not be applied (${problems.join("; ")}); everything is refused — fix the extend block in the md, then dispatch again`,
348
+ );
349
+ w.denyCounter = new DenyCounter(w.policy.maxDenies);
350
+ w.writeDenyCounter = new DenyCounter(w.policy.maxWriteDenies, "write");
351
+ w.armProbe();
352
+ } else if (converted.policy && Object.keys(converted.policy).length > 0) {
353
+ w.roleBaseline = converted.policy;
354
+ w.roleSource = `role md ${file}`;
355
+ w.applyRoleBaseline();
356
+ }
357
+ wireDeliverable(
358
+ cwd,
359
+ read.block,
360
+ w.policy,
361
+ (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions,
362
+ (message) => w.uiWarning?.(message),
363
+ );
364
+ wireWorktree(cwd, read.block, (message) => w.uiWarning?.(message));
365
+ await wirePreExec(cwd, read.block, (message) => w.uiWarning?.(message));
366
+ } finally {
367
+ w.roleWirings.delete(wiringKey);
368
+ finishWiring();
369
+ }
370
+ w.roleResolved = true;
371
+ }
@@ -0,0 +1,216 @@
1
+ import { DenyCounter } from "../budgets.ts";
2
+ import { bindingKey, type RolePolicy } from "../role-config.ts";
3
+ import { BINDINGS_ENV, asObject, denyAll, extractCallConfig, parsePolicyObject, type Policy } from "../policy/index.ts";
4
+ import { stringList } from "../bash/index.ts";
5
+ import { Probe, parseProbeConfig } from "../probe.ts";
6
+
7
+ /** activate() 的接线选项。profile 层已移除,目前没有字段;新选项按需加在这里。 */
8
+ export interface ActivateOptions {}
9
+
10
+ /** 未配置时的策略:全拒、只读、不计数。与 denyAll 的「坏了」不同,这是「没配」。 */
11
+ const INACTIVE: Policy = {
12
+ globs: [],
13
+ regexps: [],
14
+ writeGlobs: [],
15
+ absoluteWrite: [],
16
+ writeRegexps: [],
17
+ source: "not configured",
18
+ readOnly: true,
19
+ maxReads: 0,
20
+ allowTools: [],
21
+ tools: {},
22
+ probe: undefined,
23
+ maxDenies: 0,
24
+ maxWriteDenies: 0,
25
+ active: false,
26
+ };
27
+
28
+ /**
29
+ * activate() 的全部可变会话状态。七个事件处理器原本直接读 activate 闭包里的
30
+ * 这批变量;收进一个对象,是为了让处理器可以逐个搬出 index.ts 而不带走闭包。
31
+ * 字段初始化就是 activate() 原来的声明序(见 createWiring)。
32
+ */
33
+ export interface WiringState {
34
+ /**
35
+ * bindings 在激活时定格:前台子代理的 bindings 环境变量只在会话启动前存在,
36
+ * tool_call 里读不到,必须在这里取。角色 md(含派单的 worktree 默认值)按会话 cwd
37
+ * 读,在各自的事件处理器里解析。
38
+ */
39
+ call: ReturnType<typeof extractCallConfig>;
40
+ policy: Policy;
41
+ /** 角色 md 的基线:before_agent_start 里按子代理身份填入,只补 bindings 没给的字段。 */
42
+ roleBaseline: RolePolicy | undefined;
43
+ roleSource: string | undefined;
44
+ roleResolved: boolean;
45
+ /**
46
+ * before_agent_start 可能在 preExec 等待期间再次触发;同一个键的发射者 await 在飞的接线,
47
+ * 不同键(另一个子会话)各走各的。失败时 finally 删键,下一轮可重试,不缓存 rejected promise。
48
+ */
49
+ roleWirings: Map<string, Promise<void>>;
50
+ baseConfig: Record<string, unknown> | undefined;
51
+ baseSource: string;
52
+ baseRequireScope: boolean;
53
+ baseBroken: boolean;
54
+ /** toolCallId → 这次 bash 的 spec 摘要(写清单、cwd、是否离线)。 */
55
+ sandboxSpecs: Map<
56
+ string,
57
+ { write: string[]; cwd: string; offline: boolean; command: string; specFile?: string }
58
+ >;
59
+ /**
60
+ * helper 的「网络已隔离」提示每会话只播报一次:第一条离线命令照常播报,之后的
61
+ * 离线命令由 wrapInSandbox 加 quiet 前缀。住在会话状态上而不是模块级变量上 ——
62
+ * 模块级的记牌会跨会话泄漏,第二个会话的第一条命令就被静音了。
63
+ */
64
+ sandboxNetworkNoticeAnnounced: boolean;
65
+ denyCounter: DenyCounter;
66
+ /** 写拒单独计数:写拒的正解是换交付方式(回报告),跟「授权写错」不是一类信号。 */
67
+ writeDenyCounter: DenyCounter;
68
+ allowedReads: number;
69
+ /**
70
+ * 停机是硬停:每个被拦的结果都带 terminate,pi 在整批结果都 terminating 时结束本轮
71
+ * (docs/extensions.md:"terminate only applies to a blocked call; the agent stops early
72
+ * only when every finalized result in the batch is terminating")。停止后整批都会被拦,
73
+ * 所以不留「一切都拒绝、模型还在反复试」的软状态。
74
+ */
75
+ stopped: boolean;
76
+ currentCtx: { cwd?: string; actions?: unknown; ui?: unknown } | undefined;
77
+ probe: Probe | undefined;
78
+ /**
79
+ * UI 提示通道:这条告警是给父代理看的配置问题,不该写进模型上下文,所以只走 UI
80
+ * (ctx.ui.notify)。session_start / judgeToolCall / before_agent_start 每次拿到
81
+ * 自己的 ctx 时覆盖写入,最近一次写入的生效——告警跟着最新的事件上下文走。
82
+ */
83
+ uiWarning?: (message: string) => void;
84
+ }
85
+
86
+ /** 状态加上三个改状态的方法:处理器读字段、调方法,不再碰闭包。 */
87
+ export interface Wiring extends WiringState {
88
+ stop(reason: string): { block: true; reason: string; terminate: true };
89
+ /** 按当前 policy 建探针。角色基线重算策略后会重新上探针,所以这里可重跑。 */
90
+ armProbe(): void;
91
+ /**
92
+ * bindings 已经有值的键优先,md 基线只填缺失的那几个
93
+ * (scope、writeScope、readOnly、allowTools、maxDenies、maxWriteDenies)。
94
+ */
95
+ applyRoleBaseline(): void;
96
+ }
97
+
98
+ /**
99
+ * 逐字搬自 activate() 的声明段:先取 call、按坏/好分支定 policy、
100
+ * 再建两个计数器,最后 armProbe()。顺序与条件都保持原样。
101
+ */
102
+ export function createWiring(): Wiring {
103
+ const call = extractCallConfig(process.env[BINDINGS_ENV]);
104
+ let policy: Policy = INACTIVE;
105
+ if (call.error) {
106
+ policy = denyAll(call.error);
107
+ } else if (call.config) {
108
+ policy = parsePolicyObject(call.config, `extensionBindings ${bindingKey()}`, { requireScope: true });
109
+ }
110
+ const wiring: Wiring = {
111
+ call,
112
+ policy,
113
+ roleBaseline: undefined,
114
+ roleSource: undefined,
115
+ roleResolved: false,
116
+ roleWirings: new Map<string, Promise<void>>(),
117
+ baseConfig: call.config,
118
+ baseSource: `extensionBindings ${bindingKey()}`,
119
+ baseRequireScope: Boolean(call.config),
120
+ baseBroken: Boolean(call.error),
121
+ sandboxSpecs: new Map<
122
+ string,
123
+ { write: string[]; cwd: string; offline: boolean; command: string; specFile?: string }
124
+ >(),
125
+ sandboxNetworkNoticeAnnounced: false,
126
+ denyCounter: new DenyCounter(policy.maxDenies),
127
+ writeDenyCounter: new DenyCounter(policy.maxWriteDenies, "write"),
128
+ allowedReads: 0,
129
+ stopped: false,
130
+ currentCtx: undefined,
131
+ probe: undefined,
132
+ stop(reason: string) {
133
+ this.stopped = true;
134
+ // 详细理由只回给触发停机的那一次;后续调用拿 stopNotice,见 activate 里的 stopNotice 注释。
135
+ return { block: true, reason, terminate: true } as const;
136
+ },
137
+ armProbe(): void {
138
+ const probeCfg = parseProbeConfig(this.policy.probe);
139
+ this.probe =
140
+ this.policy.active && probeCfg
141
+ ? new Probe({
142
+ config: probeCfg,
143
+ readOnly: this.policy.readOnly,
144
+ hooks: {
145
+ warn: (text) => {
146
+ const ui = this.currentCtx?.ui as { notify?: (m: string, t?: string) => void } | undefined;
147
+ ui?.notify?.(`pi-subagents-extend: ${text}`, "warning");
148
+ },
149
+ },
150
+ })
151
+ : undefined;
152
+ },
153
+ applyRoleBaseline(): void {
154
+ if (this.baseBroken || !this.roleBaseline || Object.keys(this.roleBaseline).length === 0) return;
155
+ // 上层自己写了 readOnly 且没写 writeScope:写范围就是空的(与 mergeConfig 同语义),
156
+ // md 不能把写授权重新放出来。
157
+ const readOnlyWithoutWrite = Object.hasOwn(this.baseConfig ?? {}, "readOnly") && this.baseConfig?.readOnly === true && !Object.hasOwn(this.baseConfig ?? {}, "writeScope");
158
+ const fields: Record<string, unknown> = { ...(this.baseConfig ?? {}) };
159
+ let mdContributed = false;
160
+ for (const [key, value] of Object.entries(this.roleBaseline)) {
161
+ if (key === "writeScope" && readOnlyWithoutWrite) continue;
162
+ // bash.deny 是硬底线(与 mergeConfig 同语义):派单整块声明了 bash 也不拆 md 的禁令。
163
+ // 效果 = payload 的 bash 原样 + deny 与 md 的并集;其余字段仍是 payload 优先,
164
+ // payload 没声明 bash(或写坏了)时 md 的整块照旧按下面的缺失补齐走。
165
+ // 并集确实补进了新条目才算 md 有贡献——没有新条目就不重算,source 也不多一层。
166
+ if (key === "bash" && Object.hasOwn(fields, "bash")) {
167
+ const payloadBash = asObject(fields.bash);
168
+ const mdBash = asObject(value);
169
+ if (payloadBash && mdBash) {
170
+ const payloadDeny = stringList(payloadBash.deny);
171
+ const deny = [...new Set([...payloadDeny, ...stringList(mdBash.deny)])];
172
+ if (deny.length > payloadDeny.length) {
173
+ fields.bash = { ...payloadBash, deny };
174
+ mdContributed = true;
175
+ }
176
+ }
177
+ continue;
178
+ }
179
+ if (!Object.hasOwn(fields, key)) {
180
+ fields[key] = value;
181
+ mdContributed = true;
182
+ }
183
+ }
184
+ // md 一个字段都没补进来就不重算策略:来源也不能凭空多出一层。
185
+ if (!mdContributed) return;
186
+ // 拒绝文案里的 source 是父代理判断「该改哪个文件」的唯一线索,只列真正贡献过的层。
187
+ // baseSource 是激活时定格的 bindings 来源(createWiring),排在 md 之前。
188
+ // 「补了字段」不等于「改了结果」:md 写的若本来就是默认值(bash.writable: false,
189
+ // 或没有任何写范围时的 readOnly: true),有效策略与只有载荷时完全相同,source 再
190
+ // 多出 md 这层就是误导——父代理会去改一个改不动的 md。所以按两次解析的结果判
191
+ // 贡献,而不是按补没补字段。
192
+ const mdLabel = this.roleSource ?? "role md";
193
+ let source = this.baseConfig ? `${this.baseSource} + ${mdLabel}` : mdLabel;
194
+ try {
195
+ const withMd = parsePolicyObject(fields, "", { requireScope: this.baseRequireScope });
196
+ const payloadOnly = parsePolicyObject({ ...(this.baseConfig ?? {}) }, "", {
197
+ requireScope: this.baseRequireScope,
198
+ });
199
+ // 两份策略同出 parsePolicyObject 一条构造路径,键序固定,JSON 直比即稳定。
200
+ // source 正是我们在此要决定的,先归一再比;编译出的 RegExp 两边都序列化成
201
+ // {},内容差异已由 globs / writeGlobs 本身承载。
202
+ if (JSON.stringify({ ...withMd, source: "" }) === JSON.stringify({ ...payloadOnly, source: "" })) {
203
+ source = this.baseSource;
204
+ }
205
+ } catch {
206
+ // 载荷单独解析抛错:按 md 有贡献处理(与今天一致),不让异常悄悄改策略。
207
+ }
208
+ this.policy = parsePolicyObject(fields, source, { requireScope: this.baseRequireScope });
209
+ this.denyCounter = new DenyCounter(this.policy.maxDenies);
210
+ this.writeDenyCounter = new DenyCounter(this.policy.maxWriteDenies, "write");
211
+ this.armProbe();
212
+ },
213
+ };
214
+ wiring.armProbe();
215
+ return wiring;
216
+ }
@@ -0,0 +1,55 @@
1
+ import type { ContextEvent, ContextEventResult, ResourcesDiscoverResult } from "@earendil-works/pi-coding-agent";
2
+ import { fileURLToPath } from "node:url";
3
+ import { handoffHintFor, withHint } from "../handoff-hint.ts";
4
+ import { sweepStaleSpecFiles } from "../sandbox/index.ts";
5
+ import type { Wiring } from "./context.ts";
6
+ import { textOf } from "./tool-result.ts";
7
+
8
+ /**
9
+ * 随包发布的用法 skill 目录,经 resources_discover 注册,扩展加载即生效。
10
+ * 三个:范围与 bash 白名单、探针判据与停机语义、上下文隔离(AGENTS.md 标记与主代理专属文件)。
11
+ * 逐字搬自 index.ts;本文件在 wiring/ 下深一层,所以 URL 前缀从 ../skills 改成 ../../skills。
12
+ */
13
+ const SKILL_DIRS = ["pi-subagents-extend", "pi-subagents-extend-probes", "pi-subagents-extend-context"].map((name) =>
14
+ fileURLToPath(new URL(`../../skills/${name}`, import.meta.url)),
15
+ );
16
+
17
+ /**
18
+ * resources_discover 的正文:受管(active)的会话不注册用法 skill——它写给父代理看,
19
+ * 子代理会话里只会占上下文。只读 Wiring 上的 policy,不持有会话状态。
20
+ */
21
+ export function discoverResources(w: Wiring): ResourcesDiscoverResult {
22
+ return w.policy.active ? {} : { skillPaths: SKILL_DIRS };
23
+ }
24
+
25
+ /**
26
+ * session_shutdown 的正文:释放探针,再兜底清掉 spec 文件。
27
+ * 只读 Wiring 上的 probe,不持有自己的会话状态 —— 状态的唯一一份仍在 createWiring() 里。
28
+ */
29
+ export function disposeOnShutdown(w: Wiring): void {
30
+ w.probe?.dispose();
31
+ // 兜底:清掉本次会话(以及之前被中断的会话)遗留的 spec 文件。
32
+ sweepStaleSpecFiles();
33
+ }
34
+
35
+ /**
36
+ * context 的正文:只读入参 event,不碰 Wiring 上的任何字段。
37
+ * 就地补一句交接提示;内容是模型实际看到的,别改动注入的文案。
38
+ */
39
+ export function injectHandoffNotes(event: ContextEvent): ContextEventResult | undefined {
40
+ let changed = false;
41
+ const messages = event.messages.map((message) => {
42
+ if (message.role !== "custom" && message.role !== "user") return message;
43
+ const text = textOf(message.content);
44
+ // 便宜的前置筛:没有 handoff 字样就不进正则。
45
+ if (!text.includes("handoff")) return message;
46
+ const hint = handoffHintFor(text);
47
+ if (!hint) return message;
48
+ changed = true;
49
+ const content = Array.isArray(message.content)
50
+ ? withHint(message.content, hint)
51
+ : withHint(message.content, hint);
52
+ return { ...message, content };
53
+ });
54
+ return changed ? { messages } : undefined;
55
+ }