fix(dsh): 角色工具白名单先分区再 restrict,实现文档迁入插件目录

缺陷:dsh-ops 把 ops_* 注册在 agent 自己的作用域层
(inheritable:false),全局层名册里没有这些名字。角色白名单
一旦命中 ops_*,首次 restrict 就抛错,整份策略应用失败,成员
工具面完全不设防——四个专精角色此前实际没拿到过白名单。

修复:白名单改走「先分区、再 restrict」两步——作用域层名字由
分区器摘除交策略层,全局层一次性交 restrict。三条路径(初始
注入 / 降级重试 / rebind 重放)共用同一个分区器,行为逐字一致。

两条刻意设计:
- 白名单全被分区掉时 allow 集合为空,必须显式发 {"allow":[]}
  (fail closed;省略即不限制,会静默放开全部工具)
- 未向任何提供方注册的名字报 not visible yet and not
  restrictable,不得误报成「未注册」——注册时机问题不能把
  将来能用的名字从白名单里丢掉

真机验收(宿主重启后取证):目标角色 doc-writer 走
applied in one pass (allow=35),白名单 43 项 = 4 作用域层 +
4 不可解析 + 35 进限制,与 diag 逐行自洽;成员工具面
qq_*/workbuddy_*/ImageGen 全部不可见;persona 逐字注入。

能力边界报备(未修,文档已写明):ops_discover_tools 可激活
写侧作用域工具绕过白名单——白名单是初始可见面裁剪,不是安全
边界;要封锁写权限须连它一起排除。

文档:实现说明从 docs/环境与部署 迁入插件自带 docs/(内容全部
是本插件内部实现,按知识各归其位原则);AGENTS.md 与 docs
索引同步改指向,全仓 doc-links 与 mermaid 门禁绿。
This commit is contained in:
2026-11-16 16:42:59 +08:00
parent 9e538d2809
commit 1b740e07b3
6 changed files with 337 additions and 52 deletions
@@ -0,0 +1,332 @@
# 子Agent角色自动注入实现说明
> **定位**:`spawn_teammate` 的 `@role:<角色id>` persona 自动注入功能的**实现参考 + 排障参照**——换机、升级宿主、或再次调试注入问题时照本篇复原。使用侧口径(可用角色清单、`@role:` 怎么写、`tools` 字段怎么填)归 `.dsh/roles/README.md`;宿主侧「委派策略」一句话口径归根 `AGENTS.md`「委派策略(Agent Teams 优先)」节。三处分工:同一事实只在一处详述。
>
> **版本事实**:本篇全部事件面与时序结论 = 宿主 `@deepseek-ai/dsh` **0.2.2-rc.1** + fork 插件 `dsh-plugin-subagent-roles` **0.5.2-team-fork** 的台架实证快照(2026-11-13 探针实测;0.5.2 新增复活持久绑定,见 §5.1,2026-11-16 实测确认缺口后修复)。2026-11-16 又修了两处工具白名单缺陷(幻影工具名、`ops_*` 结构上不可限制),实现由"抛异常后求交集"改为"先分区再 restrict",见 §4。事件面是**观测行为,不是宿主 API 契约**——宿主升级后可能变化,出问题先按 §8 查诊断日志,再动插件代码。
---
## 1. 目的与本篇边界
这节说清该功能解决什么问题、本篇只覆盖哪条路径。读者读完应能判断自己的问题是否归本篇管。
**问题**:`spawn_teammate` 的 `prompt` 参数就是一段普通任务文本,宿主**不会**替它读取 `.dsh/roles/<角色id>.md`——不做任何处理时,teammate 子会话会以无角色 persona、无工具策略的裸 agent 起跑。而插件自带的 `subagent_role` 委派工具路径,上游本就自动应用角色(persona + 工具策略 + 调用预算),所以本篇讲的**只是 Agent Teams 路径的增量**:让 `prompt` **首行**的 `@role:<角色id>` 标记获得与 `subagent_role` 同等的自动注入。
**目标**(验收判据):子会话的**首轮模型请求组装之前**,其系统提示词已含角色 persona、工具白名单已生效——Lead 侧无需手工拼接 persona 文本。
**本篇不管的**:
| 内容 | 去处 |
|---|---|
| 有哪些角色、职责范围、怎么选 | `.dsh/roles/README.md`(使用侧) |
| 委派策略总口径(Agent Teams 优先、首行必须写标记) | 根 `AGENTS.md`「委派策略」节 |
| `tools` 字段的保留工具名单与容错口径(使用侧) | `.dsh/roles/README.md`「`tools` 字段说明」节 |
| 工具调用预算(`maxToolCalls`)在 team 路径**不生效** | 见下文 §1.1 |
### 1.1 已知边界:注入路径不带预算
`lib/budget.js` 的预算监视器靠 `arm()` 挂账,而 `arm()` 只在 `subagent_role` 委派工具启动子会话时调用;`spawn_teammate` 起的子会话没有经过它,所以**角色文件 frontmatter 里的 `maxToolCalls` 当前只对 `subagent_role` 路径生效**,对 teammate 子会话不起约束作用(2026-11-13 读码确认,注入段落代码里也没有预算逻辑)。以后要给 team 路径补预算,这是显式的缺口。
### 1.2 已知边界:注入路径不带模型路由
`spawn_teammate` 起的 teammate **不读角色文件里的 `provider`/`model`/`reasoningEffort`**——这三个字段只有 `subagent_role` 委派路径会解析(`lib/tool.js` 的 `resolveRoleRoute()` + `preflightRoleRoute()`),team 注入段(`lib/index.js` 尾部)只取 `role.persona` 与 `role.toolFilter` 两样东西,对路由字段零引用。
于是 teammate 的模型来自这两处,优先级从高到低:
1. **宿主默认模型**:profile 的 `agent-default-model` 配置(本机 `workbuddy` / `deepseek-v4.1-flash`)。
2. 已存在的成员被唤醒时,沿用该成员会话自己记录的路由。
`list_agents` 会回显每个成员的 `model`,这是判断"这个成员跑在哪个模型上"的最快口径。要给成员换模型有两条路:
| 场景 | 做法 | 生效时机 |
|---|---|---|
| 成员还活着 | `team_member_revive({ target, provider, model })` | 立即(内部走 `agent.model.select()`,与 GUI 模型选择器同一个入口) |
| 成员是冷会话 | 同上,带 provider/model | 挂起到该会话被唤醒、agent 重新物化那一瞬应用 |
只想唤醒、不改模型时省略 `provider`/`model` 即可(纯唤醒)。
**若确实需要"某角色固定跑某模型"**,有两条路可选,各有代价:
- 在角色文件里写 `provider`/`model`,然后**只走 `subagent_role` 路径**——team 路径会静默忽略,等于两套语义并存,容易误判。
- 改插件注入段,让它在 `installRoleOn()` 里读 `role.provider`/`role.model` 并调 `agent.model.select()`——需要确认调用点早于该成员首个 `step/start`(宿主 `dsh-agent-loop` 在 step 准备完成后会校验路由未被中途改写,晚调会抛 `agent/request proposed ... after step preparation fixed ...`)。这条路目前**未实现**。
> 现状口径:team 成员的模型由宿主默认模型决定,与角色无关;要按角色区分模型,只能靠 `team_member_revive` 手工指定。
### 1.3 代码落点
注入实现整体在 `.dsh/plugins/dsh-plugin-subagent-roles/lib/index.js` **尾部**以标记注释 `// ---- Agent Teams role injection (team fork v8, ...)` 起始的段落里(含段落头的主机事实注释块);该文件前半是上游原有的目录/委派工具/预算/裁剪逻辑,与本篇无关。段落内关键函数(均在下文按名字锚定,本文不写行号):`roleIdFromText()` 解析标记、`findAgentBySession()` 按会话 id 找 agent、`applyToolPolicy()` 工具白名单落地(先分区再 restrict,§4)、`installRoleOn()` 真正注入、`persistBindings()` + `agent/created` 还原观察者(§5.1)。整段注册包在插件的 `safely()` 里——注册期抛异常只失去注入能力,不会拖垮 profile 启动。
---
## 2. 注入时序:在 lead 会话侧接力
这节回答"persona 为什么能赶上子会话首轮"。关键结论:**不要等子会话把 prompt 吐出来**(那时首轮请求已经组装完),而是在 lead 会话上截获 spawn 调用、提前注册角色,等 `subagent/catalog` 事件把子 agent 身份送到手上再注入。
```mermaid
sequenceDiagram
participant L as lead会话事件流
participant P as 插件 session/event 观察者
participant C as 子会话事件流
L->>P: tool/call name=spawn_teammate (prompt 首行 @role)
P->>P: roleIdFromText 解析角色 id, 存入 pendingByLabel
L->>P: subagent/catalog 带 childId 与 label(=description)
P->>P: agents.get(childId) 取到子 agent 句柄
P->>C: systemPrompt.section 注入 persona 到 deployment:persona-prefix
P->>C: applyToolPolicy 先分区再 restrict, 一次落地
Note over C: 以下才轮到子会话首轮, 注入已完成
Note over C: system/message 首轮请求组装, persona 已在其中
Note over C: user/message 里 @role 标记出现, 兜底路径凭去重集合跳过
```
三段接力(锚点都在 `lib/index.js` 尾部 `Agent Teams role injection` 段内的 `ctx.on('session/event', ...)` 单一观察者里):
1. **截获(lead 的 `tool/call` 事件)**:`data.name == "spawn_teammate"` 时取 `data.arguments`(对象或 JSON 串,两种都解析)里的 `{name, description, prompt}`。`roleIdFromText()` 只看 prompt **第一行**、且只在**前 200 字符**窗口内找——标记匹配模块级正则 `ROLE_MARKER_PATTERN`(`/^@role:([a-z0-9]+(?:-[a-z0-9]+)*)\s*$/m`:角色 id 只允许小写字母数字加连字符,行内 id 之后不允许再带其他词)。命中后以 `d:<description>` 和 `n:<name>` 两个键把 `{roleId, cwd, applied}` 存进 `pendingByLabel`。
2. **识身份(lead 的 `subagent/catalog` 事件)**:payload 带 `data.childId` 与 `data.label`;台架实证 **label 就是 spawn 的 `description`**(同文本),所以先按 `d:` 键查、再按 `n:` 键兜底。拿到 childId 后 `ctx.get('agents').get(childId)` 取子 agent 句柄;失败再试 `findAgentBySession('session-<childId>')`(`agents.list()` 里按 `a.id` / `a.session.header.id` / `a.session.id` 三种字段匹配)。还取不到就记一行 `not live yet`,留给 §5 兜底路径追注。
3. **注入(`installRoleOn()`)**:`agent.ctx.systemPrompt.section({ name: 'deployment:persona-prefix', order, text: persona })`——order 取该 agent 上 `getSectionOrder('DEPLOYMENT_PERSONA_PREFIX')`,拿不到回退 0,即落在宿主部署 persona 前缀区;persona 来自 `loader.loadSync(cwd)` 加载的角色文件(项目 `.dsh/roles/` 覆盖全局 `~/.dsh/roles/`,使用侧细节归 `.dsh/roles/README.md`)。随后 `applyToolPolicy()` 应用工具白名单(§4)。注入成功后把 `agent.id` 记入 `injectedAgents`、其会话 id 记入 `injectedSessions` 两个去重集合。
**时序为什么赶得上**:lead 的 `tool/call` 与 `subagent/catalog` 都发生在**子会话事件流开跑之前**。2026-11-13 探针实测:`spawn captured` → `catalog` 223 ms、`catalog` → `injected` 12 ms;代码注释口径 catalog 事件比子会话首轮组装早约 270 ms,探针取证口径注入早于首轮组装约 224 ms——两个口径同为"约 0.2~0.3 秒量级",结论一致:注入发生在子会话 `system/message`(首轮请求组装完成点)**之前**。
---
## 3. 宿主事件面事实(2026-11-13 台架快照)
这节是实现所依赖的主机行为清单。改插件前逐条对照;宿主升级后注入坏了,第一嫌疑就是这张表里的某条变了。
### 3.1 回调签名:session/event 是两参
`ctx.on('session/event', (sessionObject, event) => {...})`——**第一参是会话对象**(`header.id`、`header.cwd`、`eventsSnapshot` 即该会话既有事件列表的快照),**第二参才是事件本体** `{type, seq, time, data}`。把第一参当事件本体来读 `type` 是早期版本的失败根因(教训见 §6);插件从第一参取会话 id/cwd,从第二参取事件类型与载荷。
### 3.2 子会话的事件顺序
子会话从创建到首轮回复的事件流(台架观测,按 seq 递增):
```
subagent/descriptor → sandbox/mode → approval/policy → permission/preset
→ agent/inbox/spliced → turn/start → step/start
→ system/message(首轮请求已组装完毕)
→ user/message(spawn 的 prompt 在这里出现,含 @role: 首行)
→ request/header → assistant/message
```
关键约束:`system/message` 出现时首轮请求**已经组装完**,`user/message` 必然在它之后——**在子会话侧做任何基于 prompt 内容的注入都注定晚首轮一步**,这是 §2 整套 lead 侧接力的存在理由。
### 3.3 lead 会话上的两个关键事件
| 事件 | 载荷 | 台架实证口径 |
|---|---|---|
| `tool/call` | `data.name == "spawn_teammate"`;`data.arguments` 含 `{name, description, prompt}` | 工具参数在宿主提交调用时已成串,可直接拿到完整 prompt |
| `subagent/catalog` | `data.childId`(子 agent id)+ `data.label` | **label == spawn 的 description**;实测比子会话 `step/start` 早数百毫秒(量级见 §2 末段) |
lead 会话上也会看到 `team/member`、`tool/result` 等后续事件,注入不需要它们。
### 3.4 用到的宿主服务面
| 触点 | 用途 | 备注 |
|---|---|---|
| `ctx.get('agents')` 的 `get(id)` / `list()` | childId → agent 句柄 | `get` 直接命中;`list` 供按会话 id 兜底匹配 |
| `agent.ctx.systemPrompt.section({name, order, text})` | 注册 persona 段 | 名字固定 `deployment:persona-prefix`;order 对齐宿主 `DEPLOYMENT_PERSONA_PREFIX` 区 |
| `agent.ctx.tools.restrict(filter)` | 应用工具白名单 | **只校验全局层的名字表**,作用域层的名字必须预先剔除,见 §4 |
---
## 4. 工具白名单如何落地:先分区,再 restrict
这节解释为什么白名单不能整串交给 `restrict()`,以及现在的实现怎么在不抛异常的前提下把它拆开。
**背景白话**:工具名册分两层。**全局层**挂在宿主顶层名册上(本宿主如 `edit` `write` `web_search` `send_message` `present` `skill` `mnemon_*` `qq_*` `workbuddy_*`);**作用域层**由插件束在 agent 物化时注册到 agent 自己那层(OPS 插件的 `ops_bash` `ops_grep` `ops_glob` `ops_inspect_local_file` `ops_discover_tools`,团队协作插件的 `team_task_*` `team_gate_*` `spawn_teammate` `wait_agent`)。宿主 `dsh-tools` 的 `view(scope)` 只把**继承来的**名字收进 `restrictableNames`,agent 自己那层只进 `knownNames` 与 `visible`。因此 `tools.restrict()` **只对全局层做校验**,白名单里混进任何一个作用域层名字,整个调用直接抛错——不是逐个警告、更不是部分生效。
**为什么旧做法必须换掉**:旧实现在 `restrict()` 抛错后再调一次,只为捕获错误文本、用正则反推 `known global tools:` 全集、与白名单求交集重试,成功就写一句 `tool policy applied via reduced list`。问题有三层:① 每次注入都必然先付一次异常开销;② 那行诊断与"真失败"在日志里长得一模一样,`applied via reduced list` 既可能是正常降级也可能是真出问题;③ 反推依赖宿主报错文本格式,属于对内部实现的硬依赖。
**现在的算法**(`lib/policy.js` 的 `partitionToolFilter()`,调用方 `applyToolPolicy()`):先把白名单切成三桶,再只把第一桶交给 `restrict()`。
| 桶 | 判据 | 处理 | 代价 |
|---|---|---|---|
| 可限制 | 在 `restrictableNames` 里(全局层) | 进 `allow`/`deny`,真正生效 | 无 |
| `scopeLocal` | 不在 `restrictableNames`,但在 `visible` 里 | 从 `allow` 剔除 | 无损——它在不在白名单里都一样可见 |
| `unresolved` | 既不在 `restrictableNames` 也不在 `visible` | 剔除 + 写诊断 | 此刻未生效;多为注入后才惰性注册 |
| `unenforceable` | 想 `deny` 但属作用域层 | 保留在报告里,无法强制 | 真实能力缺口,必须告知而非吞掉 |
两处刻意的设计:
- **全 `scopeLocal` 的 `allow` 必须塌成空数组,不能塌成 `undefined`**。空 `allow` 的语义是"一个工具都不给"(fail closed),缺省 `allow` 的语义是"完全不限制"(fail open)。若角色白名单恰好全是不受限制的名字而实现把 key 删掉,成员就会静默拿到全量工具面——这是比"策略没生效"更危险的失败方向。
- **`unresolved` 的措辞只能说"此刻不可见",不能说"本部署未注册"**。`team_task_*` 这类工具是 agent 物化之后才惰性注册的,注入那一刻查不到与"角色文件写了错名字"在注册表视图里**完全无法区分**。措辞把时序假象说成角色文件 bug,会把排障引到错误方向。
诊断日志的三种行(2026-11-16 重启后台架实测原文):
```text
[2026-11-15T17:46:19.827Z] tool policy for role "doc-writer": omitted 4 scope-local name(s) (visible either way): ops_grep,ops_glob,ops_bash,ops_inspect_local_file
[2026-11-15T17:46:19.828Z] tool policy for role "doc-writer": 4 name(s) not visible yet and not restrictable, so left out of the enforced policy: ops_discover_tools,team_task_get,team_task_list,team_task_update
[2026-11-15T17:46:19.845Z] tool policy applied in one pass for role "doc-writer" (allow=35)
```
判读口径:`applied in one pass` = 首次 `restrict()` 即成功(健康态);`applied via reduced list` = 旧降级路径(当前代码已不再产生,若日志里出现说明运行的是旧模块,见 §7)。
**效果实测**(2026-11-16,doc-writer 角色,43 项白名单):4 项落 `scopeLocal` + 4 项落 `unresolved`,剩 35 项进 `allow`,与 diag 的 `allow=35` 精确吻合;`restrict()` 一次成功,零异常。成员工具面 47~49 项,`qq_*` / `workbuddy_*` / `ImageGen` / `ImageSearch` 全部不可见,persona 正常。
### 4.1 一个必须知道的能力边界
白名单管得住**注入那一刻**的可见面,管不住**注入之后**被 `ops_discover_tools` 激活出来的工具。2026-11-16 实测:`@role:doc-writer` 成员白名单里没有 `ops_write_file`/`ops_edit_file`/`ops_diff`,但它调用一次 `ops_discover_tools(query="grep file content search")` 后,这三个写侧工具就出现在它的工具面里了——discovery 激活的正是作用域层,而 `restrict()` 够不着作用域层。
因此:**角色白名单是"初始可见面的裁剪",不是安全边界**。真要对成员做写权限封锁,必须连 `ops_discover_tools` 一起从白名单里去掉。使用侧同一口径 → `.dsh/roles/README.md`「`tools` 字段说明」。
---
## 5. 兜底路径与去重
这节讲主路径断链时的保险丝,以及怎么识别"只有兜底在起作用"。
**机制**:同一个事件观察者对**子会话**事件也解析标记——`deepText()` 从事件载荷的嵌套结构(`content`/`parts`/`text`,再深一层 `message`/`data`)里提取文本,命中首行 `@role:` 就记入 `pendingMarker`(会话 id → 角色 id),并用 `findAgentBySession()` 找 agent 注入;agent 暂时找不到就等该会话的下一个事件再试。因为 `user/message` 晚于首轮的 `system/message`,兜底注入的 persona **从第 2 步起才可见**。
**去重**:`injectedAgents`(按 `agent.id`)与 `injectedSessions`(按会话 id)两张 **Map**(键 → 上次成功注入的角色 id,不是 Set)。用 Map 而非 Set 是刻意的:早期用 Set 记"尝试过",一次失败(角色文件缺失)会让该 agent 被永久当作"已注入",之后即便换了正确 cwd 再来也静默返回成功而不注入任何东西——失败被记成了成功。记角色 id 还能支持"同一 agent 换了角色"的判定。主路径注入成功后,子会话后续事件再带标记也会被跳过——防止同一 persona 被重复注册成多个同名 section。已 `injected` 但 agent 迟到的场景由 `pendingMarker` 分支追赶补注。
**台架实证"兜底必然晚一步"**(2026-11-13 早轮旧格式探针日志 [示例],该轮还没有主路径):
```text
[2026-11-13T12:22:10.668Z] evt#9 s=ce3bf8 type=system/message ← 首轮请求已组装
[2026-11-13T12:22:10.669Z] evt#10 s=ce3bf8 type=user/message head=@role:doc-writer ...
[2026-11-13T12:22:10.672Z] injected role "doc-writer" (4739 chars) into agent b4194190-...-db66ffce3bf8
```
注入落在首轮组装之后 4 ms——persona 从第 2 步才可见,这正是当初必须做 lead 侧接力的原因。
**识别法**:一次注入在诊断日志里若只出现 `injected role` 一行、前面没有 `spawn captured` 与 `catalog` 两行 = 主路径断链、兜底在干活——按 §8 修主路径,不要满足于"反正注入了"。
**一处未深究的观察**:兜底路径的事件匹配不分会话归属,lead 自己会话里若出现首行 `@role:` 的文本理论上也进该路径,但台架多轮实测**没有发生向 lead 注入**(诊断日志无此类行;机制未深究,可能与 `agents` 服务不含顶层交互会话有关)。不要把标记写进给 Lead 的消息里,此行为不可依赖。
### 5.1 复活持久绑定(0.5.2 新增)
**为什么必须有它**:persona 的 section 与工具白名单都只是**运行中 agent 对象的状态**,不落盘。宿主重启后把老成员冷恢复出来,得到的是一个**既没有 persona、也没有白名单**的全新 agent——2026-11-16 实测:一个 doc-writer 成员被唤醒后能看到全量工具面(含 qq_* / workbuddy_* / ImageGen),**这比"成员死了"更危险**,是一次静默的权限放大。
**机制**:主路径或兜底路径成功注入时,把 `childId → { roleId, cwd }` 写进 `~/.dsh/role-inject-bindings.json`(`persistBindings()` 去抖 500 ms 落盘)。再注册一个 `agent/created` 观察者:每个 agent 对象物化时(冷恢复必然经过这里)按规范化 id(剥 `session-` 前缀)查绑定,命中就重放 persona + 白名单。
**判据**:诊断日志出现 `loaded N spawn bindings`(启动时)与 `restored role "<id>" on materialization of <agentId>`(复活时)两行。
**边界**:绑定表只增不减(成员可复活,历史绑定必须留着);角色文件被删或改名时,复活那一侧会打 `role "..." not found` 并**退回无 persona 状态**——此时应显式处理该成员,而不是放任它带着全量工具干活。
**已知缺口:只管"上线之后"新派的成员**。绑定是在注入成功那一刻才写盘的,所以 0.5.2 上线**之前**就已存在的成员,重启后表里没有它们,还原无从谈起(2026-11-16 实测:`doc-role-inject` 冷恢复后工具面含 `qq_send_message`/`ImageGen` 等全量工具,诊断日志无 `restored role` 行、绑定文件为空)。
**补救通道 `team_member_rebind`**(同版本新增,Lead 专用):给一个存量成员补绑定——按名查 roster 拿到会话 id,如果它的 agent 正驻留就当场重放 persona + 白名单,**无论是否驻留都写盘**(不驻留的等下次物化还原)。参数 `{ target, roleId? }`:省略 `roleId` 时用表里已有的记录,表里也没有就必须显式给。返回 `{ ok, roleId, live, injected }`——`live:false` 表示当前不驻留,绑定已排队。对本项目而言,那批存量成员都是注入调试期的临时探针,**直接弃用比补救划算**,这个工具主要是给真实工作成员的意外失配兜底。
**自省的边界(台架教训)**:成员自报"我的提示词里有没有 persona"不可全信——可见上下文可能被压缩代理重写过,运行期注入的稳定前缀段不一定回显。**判 persona 在不在,看诊断日志与宿主侧请求 dump;成员自报可信的只有"我当前能调用哪些工具"**(那是本回合真实装配的函数清单)。2026-11-16 那次两面结论不一致,就是先按成员自报下了"persona 没了"的判断,实际主路径注入是成功的。
---
## 6. 失败模式史:四条死路各换一条教训
这节记录定稿"纯事件观察"(段落头自称 v7)之前台架试错过的四条 hook 路径。升级宿主后想加新 hook,先读这节,别重蹈覆辙。
| 尝试 | 主机实际行为 | 教训 |
|---|---|---|
| 包装 `ctx.subagents.startActivation`,指望子会话启动时进 wrapper | wrapper 从未被调用 | **先实证功能真实入口再埋点**:`spawn_teammate` 根本不走 subagent 激活服务,宿主内部走 Agent Teams 自己的 spawn 路径(台架取证指向 `ctx.agentTeams.spawnTeammate`——内部实现名、非公开 API,不要依赖其存在,只作"它不在 subagents 面上"的指认) |
| 直接给 ctx 拿到的服务对象属性赋值包 wrapper | 赋值"成功",但所有调用从不进 wrapper | **服务面改写在宿主侧走不通**:宿主交给插件的是它包的一层代理(白话:插件读写这份"对象"只是在对复印件写字,宿主内部真对象纹丝不动,属性写被静默吞掉)——此后定案:插件只做纯事件观察,不改任何服务 |
| 在 `agent/created` 事件里从 `session.snapshotEvents` 读 prompt | 该 API 不存在;且该事件载荷的 header 里没有 name/teamId | **agent 创建事件自带的信息不足以识身份**:既拿不到 prompt,也无法把 created 关联到具体 teammate——关联只能靠 lead 侧 `subagent/catalog` 的 childId(§3.3) |
| 只观察子会话 `user/message` 的标记 | 注入能成功,但晚首轮一步 | **时序仗只能在 lead 侧打**:子会话事件流开跑时首轮请求已在组装(§3.2),这条降级为 §5 兜底 |
---
## 7. 部署与生效链
这节回答"我改了插件代码,何时生效、怎么确认生效"。换机复原时按本节顺序搭链。
```
仓库 fork(唯一事实源,入库)
.dsh/plugins/dsh-plugin-subagent-roles/
│ pnpm file: 依赖 = 一次性拷贝(不是链接)
▼
web profile 运行时实际读的那份
~/.dsh/profiles/web/node_modules/dsh-plugin-subagent-roles/
▲
│ 重启 dsh web 进程才重新加载
核心树(@deepseek-ai/dsh 安装目录)——没有该插件副本,属正常
```
- **拷贝而非链接,三处证据钉死**:profile 的 `package.json` dependencies 里该条目写 `"dsh-plugin-subagent-roles": "file:<仓库插件目录绝对路径>"`;同目录 `pnpm-lock.yaml` 的 specifier 同为该 `file:` 路径;`node_modules/` 下对应条目经 `ls -la` 确认是**真实目录不是符号链接**。后果:**改仓库里的插件文件不会自动反映到运行时**,每次改完必须手工同步。
- **手工同步 + 重启(台架实走路径)**,改 `lib/index.js` 为例:
```bash
cp "<repo>/.dsh/plugins/dsh-plugin-subagent-roles/lib/index.js" \
"$HOME/.dsh/profiles/web/node_modules/dsh-plugin-subagent-roles/lib/index.js"
# 回读确认(应能 grep 到段落头)
grep -c "Agent Teams role injection" \
"$HOME/.dsh/profiles/web/node_modules/dsh-plugin-subagent-roles/lib/index.js"
```
然后重启该 profile 的宿主进程(`dsh web`)。改了 `lib/` 其他文件同理一并拷贝。
- **生效判据(最硬的一条)**:重启后 `~/.dsh/role-inject-diag.log` 尾部出现新的一行
`event-path injection v8 registered (spawn-capture + tool-restrict fallback + durable bindings restore)`——
没有它,后面一切免谈(插件没装载/拷错文件/没重启)。
- **一次性开发工具(存在即可,不要求长期保留)**:注入段早期不是手改 index.js,而是维护在独立段落文件里由拼接脚本幂等写入——`ci-artifacts/role_inject_section.txt`(v7 段全文)与 `ci-artifacts/splice_role_inject.py`(把该段拼进 `lib/index.js`:缺 `node:fs`/`node:os` 两行 import 才插、缺模块级 `ROLE_MARKER_PATTERN` 常量才插、从 `// ---- Agent Teams role injection` 标记起替换到文件末尾)。`ci-artifacts/` 在 gitignore 内,工具丢了不影响复原——照本篇读码重建,或直接编辑 fork 尾部段落。
---
## 8. 排障速查
这节给"症状 → 查哪一行 → 结论"的对照表。总原则:**先查诊断日志,再动插件**;宿主升级后先验证 §3 事件面快照哪条变了,不要凭记忆改代码。
### 8.1 诊断日志本体
插件的 `ctx.logger` 在会话侧不可见,全部取证靠 `diag()` 直接 `appendFileSync` 到 **`~/.dsh/role-inject-diag.log`**(= `os.homedir()/.dsh/`,Windows 本机形如 `C:/Users/<用户名>/.dsh/`)。每行 `[ISO时间戳(UTC)] 消息`;文件无上限增长,太大直接截断/删除(只损失历史取证)。注意 spawn 消息里的时间是 UTC,比对本地时刻要 +8。
一次健康注入 = 4 行(2026-11-16 重启后台架实测原文,`restore` 路径多一行 `restored role`):
```text
[2026-11-15T17:46:19.827Z] tool policy for role "doc-writer": omitted 4 scope-local name(s) (visible either way): ops_grep,ops_glob,ops_bash,ops_inspect_local_file
[2026-11-15T17:46:19.828Z] tool policy for role "doc-writer": 4 name(s) not visible yet and not restrictable, so left out of the enforced policy: ops_discover_tools,team_task_get,team_task_list,team_task_update
[2026-11-15T17:46:19.845Z] tool policy applied in one pass for role "doc-writer" (allow=35)
[2026-11-15T17:46:19.845Z] injected role "doc-writer" (5217 chars) into agent 76b3eb7a-4bbb-4e8a-b3c2-49b2ae62b6dd (pre=?)
[2026-11-15T17:46:19.846Z] restored role "doc-writer" on materialization of 76b3eb7a-4bbb-4e8a-b3c2-49b2ae62b6dd
```
注意"一次健康注入 = 4 行"里的第 3 行现在是 `applied in one pass`;若一次注入里 `scopeLocal` 与 `unresolved` 两桶都为空,这两行不会出现,此时只剩 `applied in one pass` 与 `injected role` 两行——这也是健康态,不是缺行。
行尾 `(pre=x)` 只是诊断信息:注入时观察者**已经**在该子会话上数到过事件(`x`)与否(`?`),不代表成败。
### 8.2 症状对照表
排查顺序按注入生命周期走:装载行 → 截获行 → 识身份行 → 注入行 → 工具策略行,**第一处断在哪一环,问题就在哪一环**。
| 症状(diag 所见) | 结论 | 动作 |
|---|---|---|
| 重启后没有新的 `event-path injection v8 registered` | 插件没装载:profile 没重启 / 同步拷错或没拷 | 走 §7 生效链重做一遍 |
| 有 registered,但 spawn 后无 `spawn captured` | 标记没被认出:不在 prompt 第一行 / 角色 id 含大写或非法字符 / 首行有额外词 / 标记落在前 200 字符窗口外 / 宿主 `tool/call` 事件面变了 | 先核对写法(正则见 §2 步骤 1),再对照 §3 验事件名 |
| `catalog: ... matched=false`(伴随你的 spawn) | catalog 的 label 与 `pendingByLabel` 对不上:多半 `tool/call` 那环没截获(回上一行查) | 若同时有 `spawn captured`,说明宿主 label 不再等于 description——事件面变了 |
| 后台任务频出 `catalog: ... matched=false`(如 label=Mnemon idle checkpoint review) | **无害噪声**:非本插件发起的 catalog 事件,永远不匹配 | 忽略 |
| `catalog: child <id> not live yet` | `agents.get` 与 `list` 兜底都没拿到子 agent | 观察是否随后出现兜底 `injected` 行;频发则查 `agents` 服务面变化 |
| `role "<id>" not found (cwd=...)` | 角色文件缺失/在别的目录树/frontmatter 解析失败 | 查 `<cwd>/.dsh/roles/<id>.md` 与 `~/.dsh/roles/<id>.md`;使用侧格式归 `.dsh/roles/README.md` |
| `install skipped: no systemPrompt.section on agent ...` | 宿主 agent 句柄形状变了(`ctx.systemPrompt` 没了或不是 section 注册面) | 对照 §3.4 重新取证服务面 |
| `tool policy applied via reduced list` | 运行的是**旧模块**(当前代码只产 `applied in one pass`)——多半是插件文件同步了但宿主没重启,或 profile 拷贝晚于宿主启动 | 按 §7 重做同步 + 重启;判据看 diag 里的新措辞,不看文件时间戳 |
| `... N name(s) not visible yet and not restrictable ...` | 正常态:这 N 个名字此刻属作用域层或尚未惰性注册(`team_task_*` 最常见) | 无需动作。**不要**据此改角色文件;只有名字确实拼错且反复出现才查 |
| `... omitted N scope-local name(s) (visible either way) ...` | 正常态:这 N 个名字属 agent 自己那层,剔除无损 | 无需动作 |
| `tool policy: no enforceable entry remains` | 白名单切完三桶后没剩任何可限制项(如 `deny` 列表全是作用域名) | 成员保持继承来的全量面;按需求改写 `allow`,不要指望 `deny` 作用域名 |
| `tool policy: cannot deny N scope-local tool(s), they stay visible` | 角色文件想 `deny` 作用域层工具,无法强制 | 属真实能力缺口;改用 `allow` 收窄,或连 `ops_discover_tools` 一起排除 |
| 有 `injected role` 行、无 `spawn captured`/`catalog` 行 | 主路径断链,兜底在干活(persona 第 2 步才可见) | 按 §5 识别法确认后回查截获/识身份两环 |
| 有 `injected role` 行但子 agent 自报没有 persona | section 名字/order 与宿主装配面冲突,或注入到的不是被请求的那个会话对象 | 核对 `deployment:persona-prefix` 是否仍被宿主采纳;用 childId 与会话 id 对应关系核"注错对象" |
| `session/event handler threw: ...` | 某事件载荷形状意外,被总 try 兜住 | 看尾部异常文本定位是哪条事件;修 `deepText`/字段假设 |
---
## 9. 验收证据
这节钉死最近一轮端到端验收的实况,日后升级后拿它当对照基线。两条历史基线都留着:12:27 那轮是"旧降级路径能用"的证据,11-16 那轮是"分区后一次落地"的证据。
### 9.1 历史基线:降级路径(2026-11-13 探针)
- **主路径 4 行**:即 §8.1 引用的 12:27 轮——`spawn captured`(12:27:17.104) → `catalog matched=true childId=fda63569`(12:27:17.327) → `tool policy applied via reduced list` → `injected role "doc-writer" (4739 chars)`(12:27:17.339);注入早于子会话首轮组装约 224 ms(探针取证口径)。
- **persona 真实可见**:探针子会话首轮回复自报系统提示词中存在角色 persona,并准确引用 `.dsh/roles/doc-writer.md` persona 正文首句原文(「你是 STM32F4-Base 项目的**技术文档写手**」)——证明注入进的是它本轮在用的那份系统提示词,不是旁路。
- **可复现性**:同日 12:31 与 12:49 两轮同链复跑均 4 行齐(后一轮即本篇写作会话 `doc-role-inject` 自己的出生记录,childId 5605001c)。
- **降级路径实证**:`tool policy applied via reduced list` 行本身;doc-writer 白名单中的 `ops_bash` 等被交集剔除后策略照常生效、这些作用域工具实测仍可用。
> 该轮的 `applied via reduced list` 属**旧实现**产物,2026-11-16 换成先分区后 restrict 后不再出现,保留此处仅作历史对照。
### 9.2 当前基线:分区后一次落地(2026-11-16 重启后实测)
判据三连(重启后窗口内计数):`not visible yet and not restrictable` 出现 2 次、`role file names unregistered tool` **0 次**、`applied in one pass` 3 次且 `applied via reduced list` 0 次。
- **真实目标角色取证**:`@role:doc-writer` 成员的 restore 路径(agent `76b3eb7a`)打出 `omitted 4 scope-local` + `4 name(s) not visible yet...` + `applied in one pass (allow=35)` 三行——同一场景在旧实现里被误报成「角色文件写了未注册工具」。
- **白名单算术自洽**:doc-writer 的 43 项 = 4 `scopeLocal` + 4 `unresolved` + 35 进 `allow`,与 diag 的 `allow=35` 精确吻合。
- **成员工具面收窄**:47 项;`qq_send_message` / `qq_status` / `workbuddy_status` / `workbuddy_web_search` / `ImageGen` / `ImageSearch` 全不可见;`web_search` 与 5 个 `ops_*` 可见;persona 与 `.dsh/roles/doc-writer.md` 正文首句逐字一致。
- **强制 `unresolved` 的合成探针**:一次性角色写 `ops_no_such_tool_xyz` 后,diag 正确打出 `1 name(s) not visible yet and not restrictable ... ops_no_such_tool_xyz`——证明该行在 `unresolved` 非空时必然出现,可当正向指纹用(探针用完即删)。
- **生效判据的教训**:判定"新代码是否加载"不能看 diag 里某一行**没出现**,要看它**出现**了什么。2026-11-16 首次重启时 profile 拷贝晚于宿主启动 2 分 29 秒,宿主内存里仍是旧模块,`unregistered tool` 那行只能来自内存——磁盘上三份拷贝全部 0 命中,这是最快的鉴别方法。
> 自查本篇链接与围栏的本地命令(门禁时机是提交期,全量留给 pre-commit):
> `& '.venv\Scripts\python.exe' scripts/check_doc_links.py .dsh/plugins/dsh-plugin-subagent-roles/docs/子Agent角色自动注入实现说明.md` 与 `scripts/check_mermaid.py` 同法;两闸各自的详解 → `docs/门禁说明/doc-links.md`、`docs/门禁说明/mermaid-syntax.md`,章节引用口径 → `docs/文档规范.md` §3.5。
@@ -23,6 +23,7 @@ import { createToolCallBudgetMonitor } from './budget.js'
import { Config } from './config.js'
import { renderRoleCatalog } from './catalog.js'
import { createRoleLoader } from './roles.js'
import { partitionToolFilter, restrictableNameSet } from './policy.js'
import { createTrimPolicySource } from './settings.js'
import { registerChildPromptTrim } from './trim.js'
import { LOG_PREFIX, createRoleListTool, createRoleTool } from './tool.js'
@@ -256,8 +257,13 @@ export function apply(ctx, config = {}) {
const diag = (msg) => {
try { appendFileSync(diagPath, `[${new Date().toISOString()}] ${msg}\n`) } catch { /* best effort */ }
}
const injectedAgents = new Set()
const injectedSessions = new Set()
// agentId -> roleId of the LAST SUCCESSFUL injection. A Set is not enough:
// an early "already injected" short-circuit keyed on *attempts* is what made
// a failed install (role file missing) look installed forever, so a later
// call with a correct cwd silently returned true without injecting anything.
// Keyed by agentId AND sessionId so a re-materialized agent is retried.
const injectedAgents = new Map()
const injectedSessions = new Map()
const pendingByLabel = new Map() // label or name -> { roleId, cwd, applied }
const pendingMarker = new Map() // sessionId -> roleId
const evtCounts = new Map()
@@ -334,10 +340,53 @@ export function apply(ctx, config = {}) {
return undefined
}
const applyToolPolicy = (tools, filter) => {
/**
* The names one agent's scope can actually see, for the partition's
* unresolved-vs-scope-local distinction. Undefined (not an empty set) when the
* registry cannot answer, so a failure never looks like "nothing visible".
*/
const visibleNameSet = (tools, agent) => {
try {
const view = typeof tools?.view === 'function' ? tools.view(agent) : undefined
const visible = view?.visible
return visible instanceof Map ? new Set(visible.keys()) : undefined
} catch {
return undefined
}
}
const applyToolPolicy = (tools, filter, context = {}) => {
if (filter === undefined) return
const attempt = (f) => { try { tools.restrict(f); return true } catch { return false } }
if (attempt(filter)) return
// Split off names `restrict()` cannot accept BEFORE the first attempt, so
// the policy lands cleanly instead of degrading through a thrown
// exception. Without this every role whitelist that mentions a
// scope-local tool (the `ops_*` family lives on the agent's own layer)
// paid a guaranteed exception per injection and the diag could only ever
// say "applied via reduced list" — indistinguishable from a real failure.
const partition = partitionToolFilter(filter, context)
if (partition.scopeLocal.length > 0 || partition.unresolved.length > 0 || partition.unenforceable.length > 0) {
const role = context.roleId === undefined ? '' : ` for role "${context.roleId}"`
if (partition.scopeLocal.length > 0) diag(`tool policy${role}: omitted ${partition.scopeLocal.length} scope-local name(s) (visible either way): ${partition.scopeLocal.join(',')}`)
// "not visible yet", never "not registered": a lazily registered
// scope-local tool looks identical to a typo at this instant.
if (partition.unresolved.length > 0) diag(`tool policy${role}: ${partition.unresolved.length} name(s) not visible yet and not restrictable, so left out of the enforced policy: ${partition.unresolved.join(',')}`)
if (partition.unenforceable.length > 0) diag(`tool policy${role}: cannot deny ${partition.unenforceable.length} scope-local tool(s), they stay visible: ${partition.unenforceable.join(',')}`)
}
const planned = partition.filter
if (planned === undefined) {
// Nothing enforceable survived (e.g. a `deny` list made entirely of
// scope-local names). Restricting with the original filter would throw
// and re-enter the reactive path, so stop here and say why.
diag(`tool policy${context.roleId === undefined ? '' : ` for role "${context.roleId}"`}: no enforceable entry remains; the child keeps its inherited surface`)
return
}
if (attempt(planned)) {
// The clean path now leaves a record too: a silent success is what made
// "did the whitelist actually bind?" unanswerable from the log alone.
diag(`tool policy applied in one pass${context.roleId === undefined ? '' : ` for role "${context.roleId}"`} (allow=${planned?.allow?.length ?? 'n/a'}${planned?.deny === undefined ? '' : `, deny=${planned.deny.length}`})`)
return
}
let reduced = filter
try {
const msg = (() => { try { tools.restrict(filter) } catch (e) { return String(e?.message ?? e) } return '' })()
@@ -352,23 +401,44 @@ export function apply(ctx, config = {}) {
diag(`tool policy reduce threw: ${String(error?.message ?? error)}`)
return
}
if (attempt(reduced)) diag(`tool policy applied via reduced list`)
const allowOf = (f) => (Array.isArray(f) ? f : (f?.allow ?? f?.allowedTools))
const before = allowOf(filter) ?? []
const after = new Set(allowOf(reduced) ?? [])
const dropped = before.filter((n) => !after.has(n))
if (attempt(reduced)) diag(`tool policy applied via reduced list (dropped ${dropped.length}: ${dropped.join(',') || 'none'})`)
else diag(`tool policy still failed after reduce`)
}
const installRoleOn = (agent, roleId, cwd) => {
if (agent === undefined) return false
if (injectedAgents.has(agent.id)) return true
const result = tryInstallRoleOn(agent, roleId, cwd)
if (!result.ok) {
// Negative record: without it, "no binding in the file" cannot be told
// apart from "binding written and then failed", so verification step 2
// could never prove a negative. Keyed the same way as a real binding.
const sessionId = agent?.id !== undefined ? normId(agent.id) : undefined
if (typeof sessionId === 'string' && !bindings.has(sessionId)) {
diag(`install FAILED for role "${roleId}" on agent ${String(agent?.id)}: ${result.reason}`)
}
}
return result.ok
}
const tryInstallRoleOn = (agent, roleId, cwd) => {
if (agent === undefined) return { ok: false, reason: 'agent undefined' }
// Only a SUCCESSFUL install for THIS role counts as done. A different
// role, or a previous attempt that failed to find its file, must be
// retried — otherwise one bad cwd poisons the agent for its lifetime.
if (injectedAgents.get(agent.id) === roleId) return { ok: true, reason: 'already' }
const sysPrompt = agent?.ctx?.systemPrompt
if (sysPrompt === undefined || typeof sysPrompt.section !== 'function') {
diag(`install skipped: no systemPrompt.section on agent ${String(agent?.id)}`)
return false
return { ok: false, reason: 'no systemPrompt.section' }
}
const { roles } = loader.loadSync(cwd, { freshDiagnostics: false })
const role = roles.find((r) => r.id === roleId)
if (role === undefined || role.persona === undefined) {
diag(`role "${roleId}" not found (cwd=${String(cwd)})`)
return false
return { ok: false, reason: `role not found at cwd=${String(cwd)}` }
}
const order = Number(sysPrompt.getSectionOrder?.('DEPLOYMENT_PERSONA_PREFIX'))
sysPrompt.section({
@@ -376,12 +446,20 @@ export function apply(ctx, config = {}) {
order: Number.isFinite(order) ? order : 0,
text: role.persona,
})
applyToolPolicy(agent?.ctx?.tools, role.toolFilter)
injectedAgents.add(agent.id)
// Hand the partition its two facts: which names the child's scope can
// restrict, and which ones it can see at all. Both come from the child's
// own registry view, never from the parent's — the whole point is that
// the two views differ.
applyToolPolicy(agent?.ctx?.tools, role.toolFilter, {
roleId,
restrictableNames: restrictableNameSet(agent?.ctx?.tools, agent),
visibleNames: visibleNameSet(agent?.ctx?.tools, agent),
})
injectedAgents.set(agent.id, roleId)
const sid = agent?.session?.header?.id ?? agent?.session?.id
if (typeof sid === 'string') injectedSessions.add(sid)
if (typeof sid === 'string') injectedSessions.set(sid, roleId)
diag(`injected role "${roleId}" (${role.persona.length} chars) into agent ${String(agent?.id)} (pre=${evtCounts.get(sid) === undefined ? '?' : 'x'})`)
return true
return { ok: true, reason: 'injected' }
}
if (typeof ctx.on !== 'function') { diag('ctx.on unavailable at apply time'); return }
@@ -464,7 +542,13 @@ export function apply(ctx, config = {}) {
// agent with the full tool surface.
ctx.on('agent/created', ({ agent }) => {
try {
if (agent === undefined || injectedAgents.has(agent.id)) return
if (agent === undefined) return
// Skip only when THIS role already landed on this agent instance.
if (injectedAgents.get(agent.id) !== undefined) {
const already = injectedAgents.get(agent.id)
diag(`restore skipped: role "${already}" already present on ${String(agent.id)}`)
return
}
const keys = [normId(agent.id), normId(agent?.session?.header?.id), normId(agent?.session?.id)]
let binding
for (const key of keys) {
@@ -51,6 +51,84 @@ export function parseUnrestrictableToolNames(error) {
return [...new Set(names)]
}
/**
* Read the set of names `tools.restrict()` will actually accept in one scope.
*
* The core only restricts INHERITED GLOBAL tools: a tool registered on the
* agent's own scope layer (the `ops_*` family, for instance) is visible to that
* agent but unknown to `restrict()`, which throws on it. That distinction is
* invisible from `schemas()` alone, so a role whitelist that lists such a name
* always loses its first `restrict()` call to an exception and silently
* degrades through the reactive "drop what the error named" path.
*
* @param tools - the tools service (or a scoped view of it).
* @param scope - the viewing scope (the agent).
* @returns the restrictable names, or undefined when the registry cannot say.
*/
export function restrictableNameSet(tools, scope) {
try {
const view = typeof tools?.view === 'function' ? tools.view(scope) : undefined
const names = view?.restrictableNames
return names instanceof Set ? names : undefined
} catch {
return undefined
}
}
/**
* Split a filter into the part `restrict()` accepts and the parts it cannot.
*
* Three buckets, because the three causes need three different responses:
* `scopeLocal` names are visible but owned by the agent's own layer, so they
* stay visible whether or not the policy names them — omitting them is lossless
* and it is what keeps `restrict()` from throwing; `unresolved` names are
* neither restrictable nor visible AT THIS INSTANT and are a role-file error
* only when the name is genuinely absent (see the caveat below);
* `unenforceable` names were asked to be DENIED but cannot be, which is a real
* capability gap the caller must report rather than swallow.
*
* CAVEAT on `unresolved`: a scope-local tool registered LAZILY — after this
* scope is composed, or behind a `when` admission — is indistinguishable here
* from a typo, because both are absent from the registry view at this instant.
* Callers must therefore word the finding as "not visible now", never as "this
* deployment does not register it": the latter is a claim this function cannot
* support, and asserting it turns a timing artifact into a false role-file bug.
*
* @param filter - normalized `{ allow?, deny? }`.
* @param options - `restrictableNames` and `visibleNames` sets.
* @returns `{ filter?, scopeLocal, unresolved, unenforceable }`; `filter` is the
* original filter untouched when `restrictableNames` is unavailable (never
* fail open by guessing which names the core would reject).
*/
export function partitionToolFilter(filter, options = {}) {
const restrictable = options.restrictableNames instanceof Set ? options.restrictableNames : undefined
const visible = options.visibleNames instanceof Set ? options.visibleNames : undefined
const scopeLocal = []
const unresolved = []
const unenforceable = []
if (restrictable === undefined) return { filter, scopeLocal, unresolved, unenforceable }
const classify = (name, bucket) => {
if (restrictable.has(name)) return true
if (visible !== undefined && !visible.has(name)) unresolved.push(name)
else bucket.push(name)
return false
}
const kept = {}
// An `allow` that survives as an EMPTY list must be kept, not dropped: an
// empty allow means "no tools" (fail closed), while omitting the key means
// "no restriction at all" (fail open). A role whose whitelist happens to be
// entirely scope-local names must not silently escalate to the full surface.
if (filter?.allow !== undefined) kept.allow = filter.allow.filter((name) => classify(name, scopeLocal))
if (filter?.deny !== undefined) {
const deny = filter.deny.filter((name) => classify(name, unenforceable))
if (deny.length > 0) kept.deny = deny
}
if (kept.allow === undefined && kept.deny === undefined) {
return { filter: undefined, scopeLocal, unresolved, unenforceable }
}
return { filter: kept, scopeLocal, unresolved, unenforceable }
}
/**
* Copy a normalized filter without the named entries. An explicit `allow` list
* is preserved even when it becomes empty (that still means "no tools").
@@ -21,6 +21,8 @@ import {
expandToolFilter,
isUnrestrictableToolName,
parseUnrestrictableToolNames,
partitionToolFilter,
restrictableNameSet,
sumSchemaChars,
} from './policy.js'
import { resolveRoleRoute } from './route.js'
@@ -56,8 +58,25 @@ function visibleToolSchemas(ctx, agent) {
}
}
/** Serialized-schema length per tool name, for budget diagnostics. */
function schemaCharsByName(schemas) {
/**
* The names one agent's scope can see, for the partition's unresolved-vs-scope-local
* distinction. Undefined (not an empty set) when the registry cannot answer, so
* a failure never looks like "nothing is visible".
* @param tools - the tools service.
* @param agent - the viewing agent scope.
* @returns the visible names, or undefined.
*/
function visibleNameSet(tools, agent) {
try {
const view = typeof tools?.view === 'function' ? tools.view(agent) : undefined
const visible = view?.visible
return visible instanceof Map ? new Set(visible.keys()) : undefined
} catch {
return undefined
}
}
/** Serialized-schema length per tool name, for budget diagnostics. */function schemaCharsByName(schemas) {
const map = {}
for (const schema of schemas) {
if (schema === null || typeof schema !== 'object' || typeof schema.name !== 'string') continue
@@ -814,8 +833,17 @@ export function createRoleTool(options) {
}
const tools = child?.ctx?.tools
if (composition.toolFilter !== undefined && typeof tools?.restrict === 'function') {
// Partition against the CHILD's own view: the caller already partitioned
// against the delegating agent's view, but the two scopes need not expose
// the same restrictable set. Doing it here too means the normal path never
// depends on catching an exception.
const partition = partitionToolFilter(composition.toolFilter, {
restrictableNames: restrictableNameSet(tools, child),
visibleNames: visibleNameSet(tools, child),
})
const planned = partition.filter ?? composition.toolFilter
try {
tools.restrict(composition.toolFilter)
tools.restrict(planned)
} catch (error) {
// A tool registered on the delegating agent's own layer is visible to the
// parent but unknown to the child's scope. Drop exactly those names and
@@ -824,7 +852,7 @@ export function createRoleTool(options) {
// original failure is kept and surfaces from `startDelegation`.
if (composition.onMissing === 'error') throw error
const names = parseUnrestrictableToolNames(error)
const next = names.length === 0 ? undefined : dropToolFilterNames(composition.toolFilter, names)
const next = names.length === 0 ? undefined : dropToolFilterNames(planned, names)
if (next === undefined) throw error
tools.restrict(next)
ctx.logger?.warn?.(`[${LOG_PREFIX}] the child's scope cannot restrict ${names.map((name) => `"${name}"`).join(', ')}; they were dropped from the role's tool policy`)
@@ -965,6 +993,31 @@ export function createRoleTool(options) {
warnings.push(message)
ctx.logger?.warn?.(`[${LOG_PREFIX}] ${message}`)
}
// Split off the names `restrict()` cannot accept BEFORE handing the
// filter to the child, so the policy lands on the first attempt instead
// of degrading through a thrown exception. A scope-local name (the
// `ops_*` family is registered on the agent's own layer) stays visible
// regardless, so dropping it from `allow` costs nothing; a denied one
// cannot be enforced at all and is reported instead of silently kept.
const partition = partitionToolFilter(toolFilter, {
restrictableNames: restrictableNameSet(ctx.tools, agent),
visibleNames,
})
toolFilter = partition.filter
if (partition.scopeLocal.length > 0) {
ctx.logger?.info?.(`[${LOG_PREFIX}] role "${role.id}": ${partition.scopeLocal.length} scope-local tool(s) omitted from the enforced policy (they stay visible either way): ${partition.scopeLocal.join(', ')}`)
}
if (partition.unresolved.length > 0) {
// Wording matters: at composition time a lazily registered tool and a
// typo are indistinguishable, so this reports what was observed (not
// visible yet) rather than what would be a role-file bug.
ctx.logger?.info?.(`[${LOG_PREFIX}] role "${role.id}": ${partition.unresolved.length} name(s) not visible yet at composition time: ${partition.unresolved.join(', ')}`)
}
if (partition.unenforceable.length > 0) {
const message = `${ERROR_PREFIX} role "${role.id}" denies tool(s) it cannot restrict; they stay visible to the child: ${partition.unenforceable.join(', ')}`
warnings.push(message)
ctx.logger?.warn?.(`[${LOG_PREFIX}] ${message}`)
}
if (toolFilter?.allow?.length === 0) {
const message = `${ERROR_PREFIX} role "${role.id}" allows no currently available tool; the child will see an empty tool set`
warnings.push(message)
@@ -1277,6 +1330,17 @@ export function createRoleListTool(options) {
lines.push(` budget: ${sumSchemaChars(chars, filter.allow)} of ${totalVisible} visible tool-schema chars`)
}
if (expansion.dropped.length > 0) lines.push(` unavailable: ${expansion.dropped.join(', ')}`)
// What the child's own scope can enforce differs from what this scope
// can see: scope-local tools are visible here but not restrictable
// there. Show the difference so a role file is not read as binding
// names it structurally cannot bind.
const partition = partitionToolFilter(expansion.filter, {
restrictableNames: agent === undefined ? undefined : restrictableNameSet(ctx.tools, agent),
visibleNames: new Set(Object.keys(chars)),
})
if (partition.scopeLocal.length > 0) lines.push(` not enforceable (scope-local, stays visible): ${partition.scopeLocal.join(', ')}`)
if (partition.unresolved.length > 0) lines.push(` not visible at composition time (scope-local or not yet registered): ${partition.unresolved.join(', ')}`)
if (partition.unenforceable.length > 0) lines.push(` deny not enforceable (stays visible): ${partition.unenforceable.join(', ')}`)
}
}
if (diagnostics.length > 0) {