pi-subagents-extend 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
- package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
- package/package.json +63 -4
- package/skills/pi-subagents-extend/SKILL.md +312 -0
- package/skills/pi-subagents-extend-context/SKILL.md +103 -0
- package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
- package/src/bash/env.ts +108 -0
- package/src/bash/index.ts +27 -0
- package/src/bash/network.ts +97 -0
- package/src/bash/programs.ts +367 -0
- package/src/bash/rules.ts +247 -0
- package/src/bash/tokens.ts +169 -0
- package/src/bash/unreachable.ts +429 -0
- package/src/budgets.ts +89 -0
- package/src/child-context.ts +24 -0
- package/src/context-scope.ts +93 -0
- package/src/deliverable.ts +216 -0
- package/src/dependencies.ts +320 -0
- package/src/handoff-hint.ts +69 -0
- package/src/index.ts +181 -0
- package/src/main-context.ts +30 -0
- package/src/main-skills.ts +77 -0
- package/src/notices.ts +299 -0
- package/src/paths/index.ts +165 -0
- package/src/policy/glob.ts +146 -0
- package/src/policy/index.ts +36 -0
- package/src/policy/payload.ts +312 -0
- package/src/probe.ts +495 -0
- package/src/role-config.ts +434 -0
- package/src/sandbox/grants.ts +339 -0
- package/src/sandbox/helper.ts +137 -0
- package/src/sandbox/index.ts +12 -0
- package/src/sandbox/spec.ts +285 -0
- package/src/sandbox-note.ts +194 -0
- package/src/wiring/agent-start.ts +371 -0
- package/src/wiring/context.ts +216 -0
- package/src/wiring/misc.ts +55 -0
- package/src/wiring/session-start.ts +69 -0
- package/src/wiring/tool-call/anchor.ts +138 -0
- package/src/wiring/tool-call/bash-path.ts +0 -0
- package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
- package/src/wiring/tool-call/judge.ts +585 -0
- package/src/wiring/tool-call/original-args.ts +64 -0
- package/src/wiring/tool-call/paths.ts +235 -0
- package/src/wiring/tool-result.ts +68 -0
- package/src/worktree-default.ts +27 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 交接单提示:父代理看到 worktree 交接单路径时,补一句「该看哪个键、什么已经失效」。
|
|
3
|
+
*
|
|
4
|
+
* 背景:pi-subagents 的 worktree 单正常收尾后,工作树与分支都会被删掉
|
|
5
|
+
* (捕获补丁 → 写 handoff.json → 校验通过 → `worktree remove --force` + `branch -D`),
|
|
6
|
+
* 成果只剩 patch 文件;而父代理收到的只有一行
|
|
7
|
+
* `Worktree handoff: <handoff.json> (1 children, 1 changed patches, cleanup complete)`
|
|
8
|
+
* 既不说明去哪个键取货,也不说明子代理报告里的分支名/SHA 已经失效。
|
|
9
|
+
*
|
|
10
|
+
* 这里不重复上游的机制描述,只补这两件事。文本面向模型、英文、尽量短
|
|
11
|
+
* (每次 worktree 派单都会进上下文)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 已经补过提示的标记,同时作为幂等判据:tool_result 与 message_end 两条路可能都命中。 */
|
|
15
|
+
const MARK = "[worktree handoff]"
|
|
16
|
+
|
|
17
|
+
/** `Worktree handoff: <path> (…)` / `Parallel handoff: <path>`;`… unavailable: …` 不匹配。 */
|
|
18
|
+
const HANDOFF_LINE = /(?:Worktree|Parallel) handoff: (\S+)/
|
|
19
|
+
|
|
20
|
+
/** 交接单写失败时上游打印的那句:此时工作树与分支都被保留,但没有任何交接单。 */
|
|
21
|
+
const UNAVAILABLE = /Worktree handoff unavailable/i
|
|
22
|
+
|
|
23
|
+
/** 追加的 part;字面量类型让调用方原有的 content 联合类型保持可用。 */
|
|
24
|
+
type TextPart = { type: "text"; text: string }
|
|
25
|
+
|
|
26
|
+
/** 从一段文本里取交接单路径;已补过提示时返回 undefined。 */
|
|
27
|
+
export function handoffPath(text: string): string | undefined {
|
|
28
|
+
if (!text || text.includes(MARK)) return undefined
|
|
29
|
+
return HANDOFF_LINE.exec(text)?.[1]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 要补的那段提示。`cleanup` 为 complete 与 partial 两种结局分别说清。 */
|
|
33
|
+
export function handoffHint(path: string): string {
|
|
34
|
+
return [
|
|
35
|
+
`${MARK} read ${path} before calling this delegation done.`,
|
|
36
|
+
"groups[].children[].patch is the deliverable: diffStat / filesChanged / insertions show what was produced.",
|
|
37
|
+
'cleanup "complete": the worktree and branch are gone, so a branch name or short SHA quoted by the child no longer resolves.',
|
|
38
|
+
"Nothing was applied to this checkout; apply the patch yourself.",
|
|
39
|
+
'cleanup "partial": the worktree was kept — tasks[].reason says why.',
|
|
40
|
+
].join("\n")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 交接单没写成时补的提示:工作树没被删,但也没有任何记录。 */
|
|
44
|
+
export function unavailableHint(): string {
|
|
45
|
+
return [
|
|
46
|
+
`${MARK} the handoff manifest could not be written; the worktree and branch were left in place, not deleted.`,
|
|
47
|
+
"Check `git worktree list` under the configured base dir — uncommitted work may still be there.",
|
|
48
|
+
].join("\n")
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 文本里出现交接单信息时给出提示文本(路径或不可用),否则 undefined。 */
|
|
52
|
+
export function handoffHintFor(text: string): string | undefined {
|
|
53
|
+
const path = handoffPath(text)
|
|
54
|
+
if (path) return handoffHint(path)
|
|
55
|
+
// 已经补过提示的不再追加(路径与不可用共用同一个标记)。
|
|
56
|
+
if (text.includes(MARK)) return undefined
|
|
57
|
+
return UNAVAILABLE.test(text) ? unavailableHint() : undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 把提示追加到内容里,并保持调用方的类型形状:字符串仍是字符串,
|
|
62
|
+
* parts 数组变成「原元素 + 一个 text part」的元组,可以直接赋回 pi 的 content 字段。
|
|
63
|
+
*/
|
|
64
|
+
export function withHint(content: string, hint: string): string
|
|
65
|
+
export function withHint<T extends readonly unknown[]>(content: T, hint: string): [...T, TextPart]
|
|
66
|
+
export function withHint(content: string | readonly unknown[], hint: string): string | readonly unknown[] {
|
|
67
|
+
if (typeof content === "string") return `${content}\n\n${hint}`
|
|
68
|
+
return [...content, { type: "text", text: hint } satisfies TextPart]
|
|
69
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-subagents-extend — 把一个会话(主要是子代理)能碰的文件限制在任务范围内。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标:父代理委派子代理时指定本次任务的文件/目录范围,子代理会话里
|
|
5
|
+
* 范围之外的 tool_call 一律拒绝(fail closed),防止子代理漫无目的地扫仓库。
|
|
6
|
+
*
|
|
7
|
+
* 配置有两条来源:
|
|
8
|
+
* 1. pi-subagents 的 extensionBindings(派单载荷)。父代理在 subagent 工具调用里传:
|
|
9
|
+
* extensionBindings: { "pi-subagents-extend/1": { "permissions": { "scope": ["src/auth/**"], "maxReads": 20 } } }
|
|
10
|
+
* 命名空间键下只放 permissions;worktree 是它的同级键,不放进 permissions。
|
|
11
|
+
* pi-subagents 把它编码进 PI_SUBAGENT_EXTENSION_BINDINGS 传给子代理,本扩展在
|
|
12
|
+
* 激活时(factory)一次性读取。前台子代理的这个环境变量只在会话启动前存在,
|
|
13
|
+
* 之后父进程环境被恢复,所以不能在 tool_call 里懒读。
|
|
14
|
+
* 2. 角色 md(.pi/agents/<role>.md 等,见 role-config.ts)的 extend 块:子代理侧按
|
|
15
|
+
* <active_agent> 身份解析成基线,只补 bindings 没给的字段;worktree 的派单默认值
|
|
16
|
+
* 也从这里解析。
|
|
17
|
+
*
|
|
18
|
+
* 两条都没有时扩展不生效:父会话和未绑定范围的子代理不受影响。
|
|
19
|
+
*
|
|
20
|
+
* 扩展还随包带一个用法 skill(../skills/pi-subagents-extend),经 resources_discover
|
|
21
|
+
* 注册给会话:扩展加载到哪个会话,父代理侧就能看到「委派时如何传 bindings」的约定,
|
|
22
|
+
* 不需要往 AGENTS.md 里写。
|
|
23
|
+
*
|
|
24
|
+
* 生效时的规则:
|
|
25
|
+
* - read / edit / write / grep / find / ls:解析 path(缺省为 cwd),命中范围
|
|
26
|
+
* 放行,否则拒绝;readOnly 时 edit / write 一律拒绝(走写预算,出路是回报告)
|
|
27
|
+
* - bash:默认拒绝。bindings 里写 bash.allow(命令前缀白名单,如 "pnpm run typecheck")
|
|
28
|
+
* 后,只有命中白名单的命令放行,并且改写成交给沙箱 helper 执行:读写范围由
|
|
29
|
+
* Landlock 强制(内核 ABI 7 起),网络默认断(bash.network 可开):断网时连
|
|
30
|
+
* UDP/DNS 一起断,靠私有网络命名空间 + 盖掉解析器套接字;可写面只有写范围覆盖到的路径
|
|
31
|
+
* (bash.writable 时)、git 真正要写的目录与 bash.writablePaths,防止用 shell 绕过范围去改文件
|
|
32
|
+
* 读面不收紧(工具链在 /nix/store,收窄读根会打死所有命令);只读类命令另加一条路径引导:
|
|
33
|
+
* 参数里看起来像路径的 token 按真实路径判,落在范围外就被点名拒绝,并指回去用 read 工具
|
|
34
|
+
* - powershell / codemode:一律拒绝(没有路径可判,能绕过范围)
|
|
35
|
+
* - structured_output / todo 与 allowTools 里列出的工具:放行(执行器类不可放行;
|
|
36
|
+
* todo 是会话运行时工具,只在停机闸门之后放行,也不豁免拒绝计数的归零)
|
|
37
|
+
* - 其余未知工具:拒绝
|
|
38
|
+
*
|
|
39
|
+
* 通配符:** 任意层目录;* 单层内任意字符;? 单个字符。纯路径 glob 额外匹配
|
|
40
|
+
* 该目录自身与其下所有内容;"dir/**" 也匹配 "dir" 本身。
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
44
|
+
import type { BashRule } from "./bash/index.ts";
|
|
45
|
+
import { bindingKey } from "./role-config.ts";
|
|
46
|
+
import { judgeToolCall, RUNTIME_TOOLS, SAFE_TOOLS } from "./wiring/tool-call/judge.ts";
|
|
47
|
+
import { annotateToolResult } from "./wiring/tool-result.ts";
|
|
48
|
+
import { discoverResources, disposeOnShutdown, injectHandoffNotes } from "./wiring/misc.ts";
|
|
49
|
+
import { wireAgentStart } from "./wiring/agent-start.ts";
|
|
50
|
+
import { wireSessionStart } from "./wiring/session-start.ts";
|
|
51
|
+
import { createWiring, type ActivateOptions } from "./wiring/context.ts";
|
|
52
|
+
import { bashBlocker, describePnpmStore, helperPath, sandboxWritableDirs } from "./sandbox/index.ts";
|
|
53
|
+
export { dropHiddenGrants, findWorktreeRoot, privatisedDirs, resolveComparable } from "./paths/index.ts";
|
|
54
|
+
export { dependencyScope, sortedEntries, sortByName } from "./dependencies.ts";
|
|
55
|
+
export { buildSpec, detectPnpmStore, describeHelper, helperCandidates, sandboxWritableDirs, wrapInSandbox, type HelperCapabilities } from "./sandbox/index.ts";
|
|
56
|
+
export { nodeModulesWriteHint, wireDeliverable, wirePreExec, wireWorktree } from "./wiring/agent-start.ts";
|
|
57
|
+
export { hasUnquotedShellControl } from "./wiring/tool-call/judge.ts";
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* /permission 的 allow 列:writable:false 时标注整列,不逐条判定。
|
|
61
|
+
* 条目只是前缀或正则,同一条匹配的不同命令读写判定可能不同(git tag 与能跑的
|
|
62
|
+
* git tag -l),对单条下结论必然失真;把「写会被拒」说成列的性质才准确。
|
|
63
|
+
*/
|
|
64
|
+
function permissionAllowColumn(rule: BashRule): string {
|
|
65
|
+
const entries = rule.allow.join(" | ") || "(none)";
|
|
66
|
+
if (rule.allow.length === 0) return `bash allow: ${entries}`;
|
|
67
|
+
// 空列没有可匹配的条目,写拒分支根本进不去,所以不标注一条不存在的机制。
|
|
68
|
+
return rule.writable === false
|
|
69
|
+
? `bash allow (no write access: commands that write are refused): ${entries}`
|
|
70
|
+
: `bash allow: ${entries}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
export type { ActivateOptions } from "./wiring/context.ts";
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
export function activate(pi: ExtensionAPI, options: ActivateOptions = {}) {
|
|
81
|
+
const w = createWiring();
|
|
82
|
+
// 绑定与方法约定(skill)一起提供给会话:扩展被加载,skill 就进系统提示的
|
|
83
|
+
// 可用列表;父代理据此知道委派时传 extensionBindings。已上锁的会话不注册——
|
|
84
|
+
// 它不委派,也不该去读一个自己被范围拦住的文件。
|
|
85
|
+
|
|
86
|
+
/** 工具名 → schema 里的路径入参名;一处缓存,避免每次调用都问一遍注册表。 */
|
|
87
|
+
const schemaPathArgs = new Map<string, string | undefined>();
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
pi.on("resources_discover", async () => discoverResources(w));
|
|
92
|
+
pi.on("before_agent_start", async (event, ctx) => wireAgentStart(w, event, ctx));
|
|
93
|
+
|
|
94
|
+
pi.on("session_start", async (event, ctx) => wireSessionStart(w, options, event, ctx));
|
|
95
|
+
|
|
96
|
+
pi.on("session_shutdown", async () => disposeOnShutdown(w));
|
|
97
|
+
|
|
98
|
+
// tool_result 干三件事:
|
|
99
|
+
// 1. 探针 3 要看 bash 的输出;
|
|
100
|
+
// 2. 子代理的 worktree 单会在这里返回交接单路径,就地补一句「该看哪个键」;
|
|
101
|
+
// 3. 离线沙箱里的网络失败要就地说明「这是主代理没授权」,否则子代理会当成
|
|
102
|
+
// 环境坏了,换 registry / 加 timeout 反复重试。
|
|
103
|
+
pi.on("tool_result", async (event) => annotateToolResult(w, event));
|
|
104
|
+
|
|
105
|
+
// 后台子代理完成后,pi-subagents 用 sendMessage 把通知注入会话(正文带 `Parallel handoff:`)。
|
|
106
|
+
// 实测 message_end 不会为这种注入消息触发,所以改用 context:每次 LLM 调用前拿到完整
|
|
107
|
+
// 消息表,就地补一句。它就是模型实际看到的内容,不依赖通知用什么 role 送达。
|
|
108
|
+
pi.on("context", async (event) => injectHandoffNotes(event));
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
112
|
+
const verdict = await judgeToolCall({ pi, w, schemaPathArgs, event, ctx });
|
|
113
|
+
// 放行的调用把两类「连续」计数都清零。判据是连续而不是累计:子代理改了做法就该重新计数,
|
|
114
|
+
// 否则早期的一次误判会在几十轮之后把任务判死。
|
|
115
|
+
//
|
|
116
|
+
// 求援通道不清零:它是报告,不是进展。否则每次试探之间插一句 contact_supervisor 就能
|
|
117
|
+
// 求援通道不清零:它是报告,不是进展。否则每次试探之间插一句 contact_supervisor 就能
|
|
118
|
+
// 永远停在「警告」档,硬停判据直接失效。
|
|
119
|
+
//
|
|
120
|
+
// RUNTIME_TOOLS(todo)同样不清零,理由同源:它是会话自身的簿记,不是任务进展。
|
|
121
|
+
// 若放行的 todo 也归零,子代理就能在两次拒之间插一句 todo 把连续计数洗掉,
|
|
122
|
+
// 永远到不了硬停 —— 与求援通道被排除在归零之外是同一个道理。
|
|
123
|
+
if (verdict === undefined && !SAFE_TOOLS.includes(event.toolName) && !RUNTIME_TOOLS.includes(event.toolName)) {
|
|
124
|
+
w.denyCounter.reset();
|
|
125
|
+
w.writeDenyCounter.reset();
|
|
126
|
+
}
|
|
127
|
+
return verdict;
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
pi.registerCommand("permission", {
|
|
131
|
+
description: "Show the current task scope, the bash allowlist and the probe state",
|
|
132
|
+
handler: async (_args, ctx) => {
|
|
133
|
+
const cwd = ctx.cwd ?? process.cwd();
|
|
134
|
+
// helper 只查一次:它要 fork 一个进程读 --describe。
|
|
135
|
+
const helper = helperPath();
|
|
136
|
+
const helperLine = w.policy.bash
|
|
137
|
+
? `Helper: ${bashBlocker(helper) ?? helper}`
|
|
138
|
+
: undefined;
|
|
139
|
+
const lines = w.policy.active
|
|
140
|
+
? [
|
|
141
|
+
`Source: ${w.policy.source}`,
|
|
142
|
+
`Bindings: ${bindingKey()}`,
|
|
143
|
+
`Mode: ${w.policy.readOnly ? "read-only" : "read-write"}`,
|
|
144
|
+
w.policy.readOnly || [...w.policy.writeGlobs, ...w.policy.absoluteWrite].join("\n") === w.policy.globs.join("\n")
|
|
145
|
+
? undefined
|
|
146
|
+
: `Write scope: ${[...w.policy.writeGlobs, ...w.policy.absoluteWrite].join(" | ") || "(none)"}`,
|
|
147
|
+
`Read scope: ${w.policy.globs.join(" | ") || "(none)"}`,
|
|
148
|
+
`Read denials: ${w.denyCounter.status()} · write denials: ${w.writeDenyCounter.status()}`,
|
|
149
|
+
w.policy.bash
|
|
150
|
+
? permissionAllowColumn(w.policy.bash)
|
|
151
|
+
: "bash: off",
|
|
152
|
+
w.policy.bash && (w.policy.bash.read.length > 0 || w.policy.bash.write.length > 0)
|
|
153
|
+
? `bash (legacy columns, migrate to allow): read ${w.policy.bash.read.join(" | ") || "(none)"} | write ${w.policy.bash.write.join(" | ") || "(none)"}`
|
|
154
|
+
: undefined,
|
|
155
|
+
w.policy.bash && w.policy.bash.deny.length > 0
|
|
156
|
+
? `bash deny (cannot be lifted): ${w.policy.bash.deny.join(" | ")}`
|
|
157
|
+
: undefined,
|
|
158
|
+
w.policy.bash
|
|
159
|
+
? `Sandbox: ${w.policy.bash.network ? "network on" : "offline"}, ${w.policy.bash.writable ? "scope writable" : "read-only root"}`
|
|
160
|
+
: undefined,
|
|
161
|
+
helperLine,
|
|
162
|
+
w.policy.bash
|
|
163
|
+
? `Sandbox writable paths: ${
|
|
164
|
+
sandboxWritableDirs(w.policy, cwd, w.policy.bash, { create: false })
|
|
165
|
+
.map((d) => d.replace(cwd, "."))
|
|
166
|
+
.join(" | ") || "(none)"
|
|
167
|
+
}`
|
|
168
|
+
: undefined,
|
|
169
|
+
w.policy.bash ? `pnpm store: ${describePnpmStore(cwd)}` : undefined,
|
|
170
|
+
`Reads: ${w.allowedReads}${w.policy.maxReads > 0 ? `/${w.policy.maxReads}` : ""}`,
|
|
171
|
+
...(w.probe ? w.probe.status() : ["Probe: off"]),
|
|
172
|
+
].filter((l): l is string => Boolean(l))
|
|
173
|
+
: ["Inactive (no pi-subagents-extend bindings in this session)"];
|
|
174
|
+
ctx.ui.notify(`pi-subagents-extend:\n${lines.join("\n")}`, "info");
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export default function (pi: ExtensionAPI) {
|
|
180
|
+
activate(pi);
|
|
181
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 主代理侧入口:装上就能用,`pi` 自动加载它(`package.json` 的 pi.extensions)。
|
|
3
|
+
*
|
|
4
|
+
* 两个方向各管一段路:
|
|
5
|
+
*
|
|
6
|
+
* - 主会话:把 `.pi/main-only.md` 作为 section 注入提示词。项目里没这个文件就什么
|
|
7
|
+
* 都不做。
|
|
8
|
+
* - 后台子代理:它们加载同一份环境扩展,所以这里必须把标记段剥回去,否则主代理
|
|
9
|
+
* 专属内容会顺着环境扩展漏进子代理。
|
|
10
|
+
*
|
|
11
|
+
* 前台子代理不加载环境扩展,因此不会走到这里——它们靠 `child-context.ts`。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { injectMainOnly, stripMarkedSections, unbalancedWarning } from "./context-scope.ts";
|
|
16
|
+
|
|
17
|
+
export default function (pi: ExtensionAPI) {
|
|
18
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
19
|
+
const options = event.systemPromptOptions;
|
|
20
|
+
if (!options) return;
|
|
21
|
+
|
|
22
|
+
if (process.env.PI_SUBAGENT_CHILD === "1") {
|
|
23
|
+
const warning = unbalancedWarning(stripMarkedSections(options.contextFiles));
|
|
24
|
+
if (warning) ctx.ui?.notify?.(`pi-subagents-extend: ${warning}`, "warning");
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
injectMainOnly(options, ctx.cwd);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 主会话侧的 skill 可见性:frontmatter 里声明 `subagent-only: true` 的 skill,从主会话的
|
|
3
|
+
* systemPromptOptions.skills 里摘掉;子会话的列表一个不动(主/子的判定住在
|
|
4
|
+
* wiring/agent-start.ts,这里只做摘除本身)。
|
|
5
|
+
*
|
|
6
|
+
* 为什么不用 frontmatter 的 disable-model-invocation 达成同一目的:那个标志会把 skill 从
|
|
7
|
+
* 主代理的 <available_skills> 广告里也藏掉(pi 的 formatSkillsForPrompt 按它过滤),而
|
|
8
|
+
* pi-subagents 是把 skill 内容直接注入子代理提示文本的——子代理没有 pi 层的 skill 目录
|
|
9
|
+
* 可剥,却会跟着这个标志一起失去 skill。两个机制必须分开,这正是本模块存在的理由。
|
|
10
|
+
*
|
|
11
|
+
* frontmatter 用逐行扫描而不是 yaml 解析:这里只需要读一个布尔值,扫描对写坏的 YAML
|
|
12
|
+
* 天然容忍(没闭合、值不合法都安静地按 false 处理),一个 skill 文件坏掉不该把别的
|
|
13
|
+
* skill 一起弄坏,也不能靠 try/catch 把「解析失败」和「没声明」搅在一起。(来源扩展的
|
|
14
|
+
* 注释给的理由是加载期 import yaml 会拖进 SDK barrel、慢几百毫秒;本仓库 role-config.ts
|
|
15
|
+
* 在加载期就已经 import yaml,那个理由在这里不成立——留下扫描是为了上面的容错。)
|
|
16
|
+
*
|
|
17
|
+
* 读结果按路径 + mtime 缓存:before_agent_start 每轮发射都过这里,同一个 skill 文件
|
|
18
|
+
* 没必要每轮重读盘;文件被改过(mtime 变了)才重读。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync, statSync } from "node:fs";
|
|
22
|
+
import type { BeforeAgentStartEvent, Skill } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
|
|
24
|
+
/** 把 skill 标成子代理专用的 frontmatter 键。 */
|
|
25
|
+
const FRONTMATTER_KEY = "subagent-only";
|
|
26
|
+
|
|
27
|
+
/** frontmatter 的读结果,按文件路径缓存;mtime 没变就直接用缓存值。 */
|
|
28
|
+
const cache = new Map<string, { mtimeMs: number; subagentOnly: boolean }>();
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 从 frontmatter 原文里扫出一个键的布尔值;没有 frontmatter、没闭合、键的值不是 true
|
|
32
|
+
* 都算 false。只认 `key: true`(大小写不敏感),别的值一律不展开。
|
|
33
|
+
*/
|
|
34
|
+
function frontmatterFlag(raw: string, key: string): boolean {
|
|
35
|
+
if (!raw.startsWith("---")) return false;
|
|
36
|
+
const end = raw.indexOf("\n---", 3);
|
|
37
|
+
if (end === -1) return false;
|
|
38
|
+
for (const line of raw.slice(3, end).split("\n")) {
|
|
39
|
+
const match = /^\s*([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line);
|
|
40
|
+
if (!match || match[1] !== key) continue;
|
|
41
|
+
return match[2].trim().toLowerCase() === "true";
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 这个 skill 文件有没有声明 subagent-only。读不到的 skill 不藏:pi 找到了它,就保留。 */
|
|
47
|
+
function isSubagentOnly(skill: Skill): boolean {
|
|
48
|
+
try {
|
|
49
|
+
const stat = statSync(skill.filePath);
|
|
50
|
+
const cached = cache.get(skill.filePath);
|
|
51
|
+
if (cached && cached.mtimeMs === stat.mtimeMs) return cached.subagentOnly;
|
|
52
|
+
const subagentOnly = frontmatterFlag(readFileSync(skill.filePath, "utf8"), FRONTMATTER_KEY);
|
|
53
|
+
cache.set(skill.filePath, { mtimeMs: stat.mtimeMs, subagentOnly });
|
|
54
|
+
return subagentOnly;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 主会话路径的 skill 过滤(调用点在 wiring/agent-start.ts 的 !child 分支):
|
|
62
|
+
*
|
|
63
|
+
* - frontmatter 声明 `subagent-only: true` 的 skill 摘掉,其余保留;
|
|
64
|
+
* - 用户提示里点名了的 skill 保留——主代理明确点名要它,摘掉就是抗旨。判据读的是
|
|
65
|
+
* event.prompt(宿主在 messageType: "user" 的发射里带的原始用户提示),不是
|
|
66
|
+
* event.systemPrompt:渲染后的 system prompt 含 <available_skills> 广告,本来就有
|
|
67
|
+
* 每个 skill 的名字,拿它判「点名」等于永远保留,这个功能就死了;
|
|
68
|
+
* - 一条都摘不掉就不动 options——不凭空换一个新数组给宿主。
|
|
69
|
+
*/
|
|
70
|
+
export function dropSubagentOnlySkills(event: BeforeAgentStartEvent): void {
|
|
71
|
+
const options = event.systemPromptOptions;
|
|
72
|
+
const skills = options?.skills;
|
|
73
|
+
if (!skills?.length) return;
|
|
74
|
+
const request = typeof (event as { prompt?: unknown }).prompt === "string" ? (event as { prompt: string }).prompt : "";
|
|
75
|
+
const kept = skills.filter((skill) => request.includes(skill.name) || !isSubagentOnly(skill));
|
|
76
|
+
if (kept.length !== skills.length) options.skills = kept;
|
|
77
|
+
}
|
package/src/notices.ts
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NOTICES 层:扩展说给人(父代理的 UI 告警)与模型(注解、提示)听的话里,关于授权本身的
|
|
3
|
+
* 那一部分:不可达条目的原因与改法、legacy 配置的迁移提示、角色 md 未跟踪的告警。
|
|
4
|
+
* 措辞只在这里写一份;index.ts 只做接线。UI 告警通道由调用方传入:模块级函数拿不到 `ctx`。
|
|
5
|
+
* 模块拆分第五步:以下声明从 index.ts 原样搬出,行为不变。
|
|
6
|
+
*/
|
|
7
|
+
import { execFileSync } from "node:child_process";
|
|
8
|
+
import { existsSync, statSync } from "node:fs";
|
|
9
|
+
import { relative, resolve } from "node:path";
|
|
10
|
+
import { allEntries, classifyCommand, commandNeedsNoManifest, firstToken, leadingAssignments, listedJoin, MAX_LISTED, unreachableEntries, type BashRule, type UnreachableEntry } from "./bash/index.ts";
|
|
11
|
+
import { mainRepoRoot } from "./deliverable.ts";
|
|
12
|
+
|
|
13
|
+
/** 旧一代 bindings 文件的位置(相对会话 cwd),仅用于兼容层提示。 */
|
|
14
|
+
export const PROFILE_FILE = ".pi/subagent-bindings.json";
|
|
15
|
+
|
|
16
|
+
/** 老一代 agent profile 目录(相对会话 cwd),仅用于兼容层提示。 */
|
|
17
|
+
const AGENT_PROFILES_DIR = ".pi/agent-profiles";
|
|
18
|
+
|
|
19
|
+
/** worktree 默认值依赖的角色 md:确认未被 git 跟踪的只提示一次(session_start 清空)。 */
|
|
20
|
+
export const reportedUntrackedWorktreeProfiles = new Set<string>();
|
|
21
|
+
/** 迁移告警:legacy bash.read / bash.write 只说一次(session_start 清空)。 */
|
|
22
|
+
export const warnedLegacyBashColumns = new Set<string>();
|
|
23
|
+
|
|
24
|
+
/** 兼容层文件提示按绝对路径去重,整进程只说一次;不在 session_start 清空。 */
|
|
25
|
+
const warnedCompatLayer = new Set<string>();
|
|
26
|
+
|
|
27
|
+
/** 沙箱注解的前缀:与 `sandbox-note.ts` 里的注解同一个标记。 */
|
|
28
|
+
const SANDBOX_MARK = "[sandbox]";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 「没有候选包带这个脚本」这一句:告警和工具结果共用,措辞只能有一份。
|
|
32
|
+
*
|
|
33
|
+
* 分成两处各写一遍,两边的措辞就会慢慢分开(一边大写、一边小写就够让读者以为是两件
|
|
34
|
+
* 不同的事),而这条消息的全部价值就在于它说的是一件确定的事。
|
|
35
|
+
*/
|
|
36
|
+
function scriptMissingClause(script: string): string {
|
|
37
|
+
return `no candidate has a \`${script}\` script`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 同一句话放在句首时用这个:只动首字母,措辞不另写一份。 */
|
|
41
|
+
function sentenceCase(text: string): string {
|
|
42
|
+
return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 候选超过上限时的补充说明;没被截断时不给。 */
|
|
46
|
+
function truncationNote(list: string[]): string {
|
|
47
|
+
return list.length > MAX_LISTED ? ` (only the first ${MAX_LISTED} are listed)` : "";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 候选提示:给不出可靠改法时,把候选列出来让父代理挑。
|
|
52
|
+
*
|
|
53
|
+
* 多个包时「这条授权原本指哪个包」只有父代理知道:随便挑一个再给一条 `--dir`
|
|
54
|
+
* 建议,会把命令指到别的包上。
|
|
55
|
+
*
|
|
56
|
+
* `scriptMissing` 有值时不许再写「挑一个」:那个包里连脚本都没有,挑它跑出来是
|
|
57
|
+
* "Command not found",改包目录治不好这件事。说清「没有候选带这个脚本」才是真事实。
|
|
58
|
+
* 候选超过上限时截断(见 `listedJoin`),并用 `truncationNote` 说一句「没列全」:
|
|
59
|
+
* 几百个包路径拼进一条告警没人读得完,但让人去挑看不见的那几个同样不行。
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
function candidateHint(item: UnreachableEntry): string {
|
|
63
|
+
if (item.fix) return "";
|
|
64
|
+
if (item.scriptMissing) return `; ${scriptMissingClause(item.scriptMissing)}`;
|
|
65
|
+
const list = item.candidates ?? [];
|
|
66
|
+
if (!list.length) return "";
|
|
67
|
+
return `; candidates: ${listedJoin(list)} — pick the one this entry meant${truncationNote(list)}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 注解里「那该怎么办」的那一句。四种事实各说各的,不含糊:
|
|
72
|
+
*
|
|
73
|
+
* - 有可靠改法(恰好一个候选、且它有这个脚本)→ 直接给改法;
|
|
74
|
+
* - 一个候选但缺脚本 → 说清「没有候选带这个脚本」,别再让人去挑;
|
|
75
|
+
* - 多个候选 → 列出来让父代理挑(它才知道这条授权原本指谁);
|
|
76
|
+
* - 连候选都没有 → 只能由父代理指明一个带 manifest 的目录。
|
|
77
|
+
*
|
|
78
|
+
* 顺序不能换:`scriptMissing` 一定同时有 `candidates`,先判候选就会把「脚本不存在」
|
|
79
|
+
* 说成「包选错了」,而改包目录治不好后者。
|
|
80
|
+
*/
|
|
81
|
+
function remedyFor(item: UnreachableEntry): string {
|
|
82
|
+
if (item.fix) return `Use ${item.fix} instead.`;
|
|
83
|
+
if (item.scriptMissing) return `${sentenceCase(scriptMissingClause(item.scriptMissing))}.`;
|
|
84
|
+
if (item.candidates && item.candidates.length) {
|
|
85
|
+
return `Candidates: ${listedJoin(item.candidates)} — pick the one this entry meant${truncationNote(item.candidates)}.`;
|
|
86
|
+
}
|
|
87
|
+
return "The parent has to point this entry at a directory that has the manifest.";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 「命令被放行了,但它在 cwd 下跑不起来」的注解。
|
|
92
|
+
*
|
|
93
|
+
* 白名单里的命令进了沙箱,包管理器自己报 "No package.json found":子代理只看到那句
|
|
94
|
+
* 原始报错,看不出这是配置问题(授权指向的地方没有 manifest)。这条注解把原因与改法
|
|
95
|
+
* 写进工具结果,父代理与子代理在同一条消息里看到。
|
|
96
|
+
*
|
|
97
|
+
* 只在失败时补:成功的输出里混一句「跑不起来」会误导。
|
|
98
|
+
*/
|
|
99
|
+
export function unreachableCommandNote(text: string, command: string, rule: BashRule, cwd: string): string | undefined {
|
|
100
|
+
if (text.includes(SANDBOX_MARK)) return undefined;
|
|
101
|
+
// 别在这里再推一遍匹配:直接问 allowlist「是**哪一条**放行这条命令的」,再查那一条是否
|
|
102
|
+
// 不可达。自己匹配会出错,而且已经错过两次:按首 token 比,会让同程序名的无关条目被点名;
|
|
103
|
+
// 在不可达子集里按 `allEntries` 顺序取第一条命中,会让一条**比命令更短**的宽条目(`pnpm`)
|
|
104
|
+
// 顶替真正放行它的那条。`classifyCommand` 用的是判定本身的规则(write 列优先、第一条命中),
|
|
105
|
+
// 所以它给的答案就是唯一的答案。
|
|
106
|
+
// 命令**自己**不需要 manifest 时,一句都不要说:宽条目 `pnpm` 会被判成不可达,但它放行的
|
|
107
|
+
// `pnpm --version` / `pnpm store path` / `pnpm --dir x run build` 跟 cwd 有没有 manifest
|
|
108
|
+
// 无关,失败原因是别的东西。把原因安到不成立的前提上,比不说更糟。
|
|
109
|
+
if (commandNeedsNoManifest(command)) return undefined;
|
|
110
|
+
const granted = classifyCommand(rule, command);
|
|
111
|
+
const bad = granted === undefined ? undefined : unreachableEntries([granted.entry], cwd)[0];
|
|
112
|
+
if (!bad) return undefined;
|
|
113
|
+
const remedy = remedyFor(bad);
|
|
114
|
+
return `${SANDBOX_MARK} this command ran, but "${bad.entry}" cannot work from ${bad.lookedIn ?? cwd}: ${bad.why}. ${remedy}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 把「授权写了却永远命中不了」这件事告诉父代理一次。
|
|
119
|
+
*
|
|
120
|
+
* 命中不了指的不是语法不匹配(那种情况命令会被拒,拒绝文案里会说清),而是这条命令在会话的
|
|
121
|
+
* 工作目录下**根本跑不起来**:仓库根没有 package.json,`pnpm run x` 只会报
|
|
122
|
+
* "No package.json found"。子代理没有 `cd`、也没有 `&&`,于是这条授权永远用不上,它只能
|
|
123
|
+
* 自己找一个等价写法 —— 那正是要避免的坑。
|
|
124
|
+
*
|
|
125
|
+
* 聚合成一条发出去:一条警告说清全部,比 N 条各说一条更容易被父代理一次读完。
|
|
126
|
+
*/
|
|
127
|
+
export function reportUnreachableEntries(rule: BashRule, cwd: string, warn: ((message: string) => void) | undefined): void {
|
|
128
|
+
const unreachable = unreachableEntries(allEntries(rule), cwd);
|
|
129
|
+
if (unreachable.length === 0) return;
|
|
130
|
+
// 条目本身也要封顶:一个大白名单里十几条 pnpm 条目同时不可达时,一条告警会长到没人读。
|
|
131
|
+
const shown = unreachable.slice(0, MAX_LISTED);
|
|
132
|
+
const hidden = unreachable.length - shown.length;
|
|
133
|
+
const list = `${shown.map((item) => `${item.entry} (${item.why}${candidateHint(item)})`).join(", ")}${hidden > 0 ? `, … and ${hidden} more` : ""}`;
|
|
134
|
+
// 改法按条目给:每条建议里带着自己的脚本名,读者能对上是哪一条。
|
|
135
|
+
const fixes = shown.map((item) => item.fix).filter((fix): fix is string => fix !== undefined);
|
|
136
|
+
// 隐藏条目的改法换不出来:候选是同一份列表,全列一遍只会让这条告警更长。总数照实说,
|
|
137
|
+
// 并明说下面的改法只覆盖列出来的这几条 —— 不说的话读者会以为改法覆盖了全部。
|
|
138
|
+
const covered = hidden > 0 ? " (the forms below cover the listed entries only)" : "";
|
|
139
|
+
const tail = fixes.length > 0 ? ` Use the package-relative form instead: ${fixes.join("; ")}${covered}` : "";
|
|
140
|
+
warn?.(
|
|
141
|
+
`pi-subagents-extend: ${unreachable.length} allowlist entries can never match from ${unreachable[0]?.lookedIn ?? cwd}: ${list}. Commands run in the session's working directory; there is no \`cd\`.${tail}`
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 拒绝文案里的「同首 token 条目」提示。
|
|
147
|
+
*
|
|
148
|
+
* 命令被拒时,子代理最想知道的是「为什么没匹配上、该改哪里」。同首 token 的条目就是它该看的
|
|
149
|
+
* 地方:条目按词前缀匹配,`pnpm run lint` 放行 `pnpm run lint --x`,但不放行
|
|
150
|
+
* `pnpm run typecheck`。首 token 不同的条目与此无关,不写进来(不臆测)。
|
|
151
|
+
*
|
|
152
|
+
* 这些条目里若有永远命中不了的(见 `unreachableEntries`),把「为什么」与「改成什么」一起
|
|
153
|
+
* 写进这条拒绝文案:撞墙的原因和出路在同一条消息里,子代理不必再猜。
|
|
154
|
+
*/
|
|
155
|
+
export function headEntriesHint(rule: BashRule, command: string, cwd: string): string {
|
|
156
|
+
// 前缀赋值先剥掉:匹配时剥得掉,这里也得剥,否则 `HOME=/tmp/x pnpm test` 的首 token
|
|
157
|
+
// 会算成 `HOME=/tmp/x`,与白名单里的 `pnpm` 对不上。
|
|
158
|
+
const head = firstToken(leadingAssignments(command).rest);
|
|
159
|
+
if (!head) return "";
|
|
160
|
+
const mine = allEntries(rule).filter((entry) => entry.startsWith("re:") ? false : firstToken(entry) === head);
|
|
161
|
+
// 正则条目无法按首 token 归到某一组,但又确实可能是唯一放行这条命令的条目:只数不列,
|
|
162
|
+
// 否则既可能很长,也可能让子代理以为「列出的都对不上 = 这个程序没被允许」。
|
|
163
|
+
const patterns = allEntries(rule).filter((entry) => entry.startsWith("re:")).length;
|
|
164
|
+
const siblings = mine.slice(0, 3);
|
|
165
|
+
if (siblings.length === 0 && patterns === 0) return "";
|
|
166
|
+
const unreachable = unreachableEntries(allEntries(rule), cwd);
|
|
167
|
+
const details = siblings.map((entry) => {
|
|
168
|
+
const bad = unreachable.find((item) => item.entry === entry);
|
|
169
|
+
if (!bad) return entry;
|
|
170
|
+
const fix = bad.fix ? `; use instead: ${bad.fix}` : "";
|
|
171
|
+
return `${entry} (${bad.why}${candidateHint(bad)}${fix})`;
|
|
172
|
+
});
|
|
173
|
+
// 被拒的这条命令本身也可能跑不起来(同一个 cwd、同一个程序名):那是子代理真正要改的
|
|
174
|
+
// 东西,所以它的改法也写进去。
|
|
175
|
+
const own = unreachableEntries([command], cwd)[0];
|
|
176
|
+
const ownFix = own?.fix ? `; run it as: ${own.fix}` : "";
|
|
177
|
+
const listed = details.length > 0 ? details.join(", ") : "none";
|
|
178
|
+
const other = patterns > 0 ? ` (plus ${patterns} regex ${patterns === 1 ? "entry" : "entries"} that may match anything, not evaluated here)` : "";
|
|
179
|
+
return ` — entries for \`${head}\`: ${listed}${other}; a prefix entry matches only if the command starts with it word for word, and there is no \`cd\` — commands run in ${cwd}${ownFix}`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 文件在 git 里是否被跟踪。三态:true 已跟踪、false 确认未跟踪、undefined 判不了
|
|
184
|
+
* (不在仓库里、git 不在 PATH、超时)。`--error-unmatch` 的退出码 1 才是「没跟踪」这个确定
|
|
185
|
+
* 答案;其它失败一律当未知,宁可少说也不误报。
|
|
186
|
+
*/
|
|
187
|
+
function trackedInGit(cwd: string, relPath: string): boolean | undefined {
|
|
188
|
+
try {
|
|
189
|
+
execFileSync("git", ["ls-files", "--error-unmatch", "--", relPath], {
|
|
190
|
+
cwd,
|
|
191
|
+
encoding: "utf8",
|
|
192
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
193
|
+
timeout: 5000,
|
|
194
|
+
});
|
|
195
|
+
return true;
|
|
196
|
+
} catch (error) {
|
|
197
|
+
return typeof error === "object" && error !== null && (error as { status?: number }).status === 1
|
|
198
|
+
? false
|
|
199
|
+
: undefined;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** 还在用 legacy bash.read / bash.write 的配置提示一次:新写法是单列 bash.allow。 */
|
|
204
|
+
export function warnLegacyBashColumns(config: Record<string, unknown> | undefined, source: string, warn: ((message: string) => void) | undefined): void {
|
|
205
|
+
if (!config || warnedLegacyBashColumns.has(source)) return;
|
|
206
|
+
const bash = config.bash;
|
|
207
|
+
if (!bash || typeof bash !== "object" || Array.isArray(bash)) return;
|
|
208
|
+
const legacy = ["read", "write"].filter((key) => Object.hasOwn(bash, key));
|
|
209
|
+
if (legacy.length === 0) return;
|
|
210
|
+
warnedLegacyBashColumns.add(source);
|
|
211
|
+
warn?.(
|
|
212
|
+
`pi-subagents-extend: ${source} still spells bash.${legacy.join(" and bash.")}, which are legacy columns; bash.allow is the single allowlist column now and read/write is judged internally. The legacy columns keep working until the compatibility layer is removed.`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 老的 .pi 配置文件还在时各提示一次:它们已被忽略,也不会再被读取;配置写在角色 md 的 extend 块。
|
|
218
|
+
* worktree 的 cwd 里没有主检出的配置,所以主检出根和 cwd 都查;两个文件路径只认普通文件,
|
|
219
|
+
* 目录会让 existsSync 为真;老一代 profile 目录本身就是一个目录,由下面的 existsSync 分支单独判。
|
|
220
|
+
*/
|
|
221
|
+
export function warnCompatLayer(cwd: string, warn: ((message: string) => void) | undefined): void {
|
|
222
|
+
const isFile = (path: string): boolean => {
|
|
223
|
+
try {
|
|
224
|
+
return statSync(path).isFile();
|
|
225
|
+
} catch {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
const anchor = mainRepoRoot(cwd);
|
|
230
|
+
const roots = anchor.root === null ? [cwd] : [...new Set([cwd, anchor.root])];
|
|
231
|
+
for (const root of roots) {
|
|
232
|
+
const bindingsFile = resolve(root, PROFILE_FILE);
|
|
233
|
+
if (isFile(bindingsFile) && !warnedCompatLayer.has(bindingsFile)) {
|
|
234
|
+
warnedCompatLayer.add(bindingsFile);
|
|
235
|
+
warn?.(
|
|
236
|
+
`pi-subagents-extend: ${PROFILE_FILE} is from the older configuration layer and is now ignored; put configuration in the role md's extend: block.`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
// 目录按目录判:老一代 profile 目录本身就是一个目录,不能套用上面的 isFile。
|
|
240
|
+
const profilesDir = resolve(root, AGENT_PROFILES_DIR);
|
|
241
|
+
if (existsSync(profilesDir) && !warnedCompatLayer.has(profilesDir)) {
|
|
242
|
+
warnedCompatLayer.add(profilesDir);
|
|
243
|
+
warn?.(
|
|
244
|
+
`pi-subagents-extend: ${AGENT_PROFILES_DIR}/*.ts is from the older configuration layer and is now ignored; put configuration in the role md's extend: block.`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* 补 worktree 默认值时,若默认值来自角色 md 而该文件没被 git 跟踪,告诉父代理一次:
|
|
251
|
+
* worktree 副本里不会有这份 md,子代理认不出自己的角色,也就没有任何角色策略
|
|
252
|
+
* (fail open)。只在确认未跟踪时提示,判不了就不说;同一路径只提示一次
|
|
253
|
+
* (集合在 session_start 清空)。
|
|
254
|
+
*/
|
|
255
|
+
export function warnUntrackedWorktreeProfile(cwd: string, mdFile: string, warn: ((message: string) => void) | undefined): void {
|
|
256
|
+
if (reportedUntrackedWorktreeProfiles.has(mdFile)) return;
|
|
257
|
+
const relPath = relative(cwd, mdFile);
|
|
258
|
+
if (trackedInGit(cwd, relPath) !== false) return;
|
|
259
|
+
reportedUntrackedWorktreeProfiles.add(mdFile);
|
|
260
|
+
warn?.(
|
|
261
|
+
`pi-subagents-extend: \`worktree: true\` runs the subagent in a worktree copy, but the role md ${relPath} is not tracked by git, so the worktree copy will not contain it and the child will run with no role policy. Commit the role md so the worktree child can identify its role.`
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* check 2 的护栏:派单点名了一个解析不到 md 的角色名,每个名字整进程只说一次。
|
|
267
|
+
* 不挂在 session_start 清空的那组集合里(那份清单由 session-start.ts 负责,本文件
|
|
268
|
+
* 的授权清单里没有它);与 warnedCompatLayer 同一取舍 —— 同一个名字解析不到 md 这件
|
|
269
|
+
* 事实在进程内不会变,重复提醒只是刷屏。
|
|
270
|
+
*/
|
|
271
|
+
export const warnedUnresolvedAgentNames = new Set<string>();
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* check 2 —— 派单点名了一个从生效 cwd 解析不到任何角色 md 的名字。
|
|
275
|
+
*
|
|
276
|
+
* 只告警不拒绝:builtin 代理(worker、scout、delegate…)本来就没有 md,拒了会把
|
|
277
|
+
* 现有最常见的用法打死。要说清三件事:生效 cwd、查过哪些目录、以及 pi-subagents
|
|
278
|
+
* 可能把名字落到 builtin 别名上 —— 那时角色 md 的策略完全不生效,起作用的是
|
|
279
|
+
* builtin 自己的工具面。这条告警本来能救的是这种派单:名字实际命中了别名,调用方
|
|
280
|
+
* 却以为有一个带策略的角色 md 在管着子代理。
|
|
281
|
+
*/
|
|
282
|
+
export function warnUnresolvedAgentName(agent: string, cwd: string, dirs: string[], warn: ((message: string) => void) | undefined): void {
|
|
283
|
+
if (warnedUnresolvedAgentNames.has(agent)) return;
|
|
284
|
+
warnedUnresolvedAgentNames.add(agent);
|
|
285
|
+
warn?.(
|
|
286
|
+
`pi-subagents-extend: no ${agent}.md is visible from the dispatch cwd ${cwd} — consulted: ${listedJoin(dirs)}. pi-subagents may resolve "${agent}" to a builtin alias instead, in which case the role md's policy will not apply and the builtin agent's own tool list governs. If a role md was meant, put it in one of the consulted directories, or dispatch with the cwd that contains it.`
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* check 1 —— 角色 md 的 frontmatter `tools:` 里声明了宿主工具面上没有的工具。
|
|
292
|
+
* pi-subagents 在 spawn 之后会用同一份声明检查子代理的工具面,检查不过就是一句
|
|
293
|
+
* 没人能照着改的拒绝(实测 fbdf1d81:md 声明 edit,宿主被 pi-hashline-edit-pro
|
|
294
|
+
* 换掉了 edit,整条派单两秒内死掉)。这里在 spawn 之前拒掉同一件事,点名缺的
|
|
295
|
+
* 工具与最可能的原因。
|
|
296
|
+
*/
|
|
297
|
+
export function dispatchToolFaceRefusal(agent: string, mdFile: string, missing: string[]): string {
|
|
298
|
+
return `pi-subagents-extend: dispatch refused before spawn: the agent md ${mdFile} for "${agent}" declares tools this host does not offer: ${missing.join(", ")}. Most likely an extension in this host replaced the tool set (pi-hashline-edit-pro, for example, swaps out the built-in edit family), so the agent definition and the host disagree; pi-subagents would refuse this dispatch anyway, with a message nobody can act on. Fix the md's tools: list, or restore the tools in the host's active tool set.`;
|
|
299
|
+
}
|