diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/CHANGELOG.md b/.dsh/plugins/dsh-plugin-subagent-roles/CHANGELOG.md new file mode 100644 index 00000000..a6b0aa5f --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/CHANGELOG.md @@ -0,0 +1,283 @@ +# 更新日志 + +本文件记录 `dsh-plugin-subagent-roles` 的所有重要变更。 + +格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循[语义化版本](https://semver.org/lang/zh-CN/)。 + +## [0.5.0] - 2026-10-18 + +这一版把插件移植到 **DSH 0.2.1**。0.2.1 移除了 `subagents.start` / `startContinuable`、start 请求里的 `persona` / `toolFilter`、`SubagentRun.localAgent`、`dsh-subagent` 的 `settleRun` 导出,以及客户端设置服务与插件设置命名空间。**角色文件格式、项目/全局优先级、每角色模型绑定、预算与目录均不变。** + +### 破坏性变更 + +- 只支持 DSH **0.2.1-rc.1+**(`engines.dsh: ^0.2.1-rc.1`)。0.2.0 及更早继续用 0.4.3。 + +### 委派 + +- `ctx.subagents.start(provider, request)` / `startContinuable(spec)` → `startActivation(spec)`: + - `label` / `signal` 移到 spec 上,`delivery: 'parent'`; + - 返回 `SubagentActivation`:`childId`、`result`、`dispose()`; + - foreground 仍等待结果后释放,background 仍经 `ctx.jobs` 结算,continuable 仍只返回 durable id 并保留 resident 子代理。 +- background 的结算改为插件自带的 `settleActivation`(0.2.0 的 `settleRun` 语义:completed 带最终文本、本地 aborted 记 `killed`、带 diagnostic 的 aborted 记 `failed`)。0.2.1 只导出低层的 `settleRunResult`,其参数契约与本插件的 job 结果不同。 +- 删除 `startToleratingUnrestrictableNames` 的重试路径;不可限制的工具名现在在子上下文安装 restriction 时就地丢弃一次(`onMissingTool: 'error'` 时仍然报错)。 + +### Composition + +- persona 与 toolFilter 不再随 request 下发(0.2.1 的 `SubagentStartRequest` 已删除这两个字段,transport 能力位也不再声明它们)。插件在 `subagent/start` 事件里把两者安装到子上下文: + - persona 仍是 `deployment:persona-prefix` section,order 取 `DEPLOYMENT_PERSONA_PREFIX`,插值语义不变; + - toolFilter 仍按父上下文可见工具展开后调用子上下文的 `tools.restrict()`。 +- **确定性关联**:`startActivation` 允许调用方指定 `childId`,插件先生成 id 并登记 composition;`subagent/start` 在宿主 materialize 内、初始 prompt 提交之前同步触发,因此首轮 assembly 就能看到 persona 与限制后的工具集。provider 若忽略该 id 或发布不了本地子代理,插件在 start 返回后按 `activation.childId` 再尝试一次并告警。 +- 能力门禁只保留 `agentOptions` / `depthLimit`;`persona` / `toolFilter` 不再是 transport 能力,旧能力位(有或没有)都不再影响委派。 + +### 设置 + +- 删除 `settings.register` 的命名空间:0.2.1 的 Settings 服务没有该 API。裁剪与预算的六个旋钮以**行 config** 为准。 +- 浏览器半边在 0.2.1 上不再挂载卡片(`settingsScope` / `settings.plugin.item` 均已移除),只打印一次说明后不注册 slot;不会因为缺少服务让整行停在 `pending`。 + +### 预算与可观测性 + +- `run.localAgent` → `ctx.agents.get(childId)`;wrap-up 通知、可观测性告警与 `session/event` 计数按 `childId` 关联。 +- `SubagentActivation.dispose()` 仍由 foreground / background 的结算路径拥有;continuable 不释放,由 runtime 的 interrupt 收口。 + +### 元数据与验证 + +- `engines.dsh` / peer 依赖改为 `^0.2.1-rc.1`;开发依赖固定 `0.2.1-rc.2` 并在仓库内本地安装,不再借用 `~/.dsh/profiles/node_modules` 的 0.2.0 副本。 +- `node --test` **331 项全过**;`npm run lint` 通过。 +- 官方 `subagent` 工具在 0.2.1 改为 fire-and-return activation id、不再等待结果,因此 `test/parity.test.js` 的逐字节对照在 0.2.1 上跳过(脚本保留给 0.2.0 线),由本插件自己的委派/预算/能力测试覆盖。 + +## [0.4.3] - 2026-09-30 + +这一版收掉 0.4.2 独立确认 review 提出的 5 条非阻塞项:其中 2 条是**已发布的文档/注释说了不实的话**,1 条是**真实的静默失败**,其余是结构与注释的准确性。 + +### 修复 + +- **诊断去重改为「按当前装配做差集」,去掉一个真实的静默失败**:原实现是「报过就永久记住」,而被遮蔽的角色文件自身解析成功且命中 mtime 缓存、`loadRecord` 提前返回,于是**解除遮蔽后再被遮蔽时永远不会告警**。现在每次 per-step 读取都会算出本次该根下的全部诊断,与上一次该路径的「standing 原因集」比较:新出现的才上报,消失的(修好 / 解除遮蔽 / 删除改名)立即遗忘,并且**整体替换而非并集**。行为边界:新实现**不会少报**任何真正新出现的发现(对抗式 review 用 400 步差分 fuzz 加独立 oracle 验证 `under=0`,并覆盖了「cwd 变化导致某个根本次未被扫到」这类场景)。与旧实现的差别是:旧实现会在「发现仍然 standing、但被遮蔽的那个文件被改写/触碰」时再刷一次,新实现此时保持静默(更少、更准);新实现只在「发现曾经离开装配又回来」或「原因切换回来」时多报一次。「同一仍然存在的发现不重复刷屏」与全局角色根「每 loader 一次」的语义都不变。 +- **去重结构由 `Set` 改为 `Map<角色根, Map<精确路径, Set<原因>>>`**:原先每次文件解析成功都要遍历整个已报告集合做前缀匹配(O(全部已报告),极端场景实测 +78ms),现在单路径清除只与该路径的原因数成正比;精确路径键也彻底移除了「一个路径是另一个路径前缀」的误删面。 +- **修正不实措辞(不改行为)**:代码注释曾称诊断「the agent is always told」以及「the delegating agent can only correct what it is told about」,而事实是**委派工具与 catalog 两条路径都只把诊断写进操作者日志(`ctx.logger.warn`)**——loader 返回的 `diagnostics` 不进委派工具结果,catalog 只返回角色清单。需要说清楚的是:可选的 `subagent_roles` 诊断工具(`enableListTool`,默认关闭)**本身**就会把完整清单返回给调用它的模型,那正是它的用途。注释已按此收窄,并新增断言钉死「委派工具返回值不携带诊断」。 +- **`test/wiring.test.js` 注释与事实对齐**:它只钉 catalog 路径(去掉 `lib/index.js` 的 `freshDiagnostics` 才会红),委派路径由 `test/delegation.test.js` 的用例钉,两路共用同一份去重由新增集成测试钉。 + +### 验证 + +- `node --test` **345 项全过**(0.4.2 为 338),`node --check` 全部通过。 +- 两条依赖线都跑过:本地 0.1.5-rc.3 线与干净安装的 `0.2.0-rc.2` 线(CI 实际解析结果)均 345/345。 +- 6 处变异验证(仓库外副本把修复改回旧写法):整体回退旧实现 → 遮蔽复现 / 换因换回 / 删除重建 3 条红;去掉 `\0` 边界的前缀删 → 前缀安全测试红;折叠根级去重 → 多根同名测试红;分别去掉两条路径的 `freshDiagnostics` → 各自的「只报一次」测试红;诊断工具改为带 flag 读 → 全量清单测试红。 + +## [0.4.2] - 2026-09-30 + +这一版收掉 0.4.1 之后的三个「轻微」遗留项,以及它们引出的对抗式复审发现(复审在仓库外副本里独立复验了每条回归测试「有没有牙齿」,并逐条推翻了或确认了作者的声称)。 + +### 修复 + +- **坏角色文件的诊断不再每次委托都刷屏**:委派路径的 `loadSync` 现在与目录(catalog)路径共用 loader 的「已报告诊断」集合(identity = `path\0reason`)。**首次一定告知模型**,同文件同原因每条只报一次;同文件换原因仍会再报。旧测试 `skipped role files are reported on every delegation` 把「每次委托都报」钉成了预期,已**有意识改写**为新语义——旧行为正是本项要消除的噪音。 +- **诊断去重不再吞掉「修好后复发」**:该集合原先没有任何过期机制,于是「坏 → 修好 → 用同样原因再改坏」会永久静默。现在文件**解析成功即遗忘该路径的所有已报告原因**,再次损坏会重新告警。 +- **委派 info 日志有界**:原先把完整 `toolFilter`(`allow: ['*']` 会展开成全部可见工具)与路由 JSON 内嵌进一行。现在 info 只写有界摘要(`allow=N[前4个名字,…]`、`provider/model[/effort]`、`inherit+effort=`),完整对象降级到 `debug`。 +- **只绑定 `reasoningEffort` 的角色不再被误报为继承**:`summarizeRoute` 原先只看 provider/model,两者皆空就报 `inherit`,而子代理实际拿到 `{ reasoningEffort: 'high' }`——在合法配置下把真实路由报成了相反的值(且 `debug` 低于默认日志级别,默认部署只能看到这个错值)。现在输出 `inherit+effort=high`;该函数此前**完全没有测试**,这正是漏网原因,已补。 +- **裁剪不再靠异常兜底**:`section.text.length` / `context.text.length` 在 `text` 缺失时抛错,被外层 catch 兜成「整份 assembly 这一次不裁剪」。现在 `textLength()` 把缺失文本视为 0:该 part 视为空、内容规则不触发、不计入 saved、**其余 part 照常裁剪**,也不再产生误导性的 skipped 警告(同函数的 context 分支同一潜伏问题一并处理)。 + +### 文档 + +- README(中英)安装段补上**桌面版(DSH 桌面 App)**通道:侧栏 **Plugins** 页按包名或绝对路径安装;并说明 `desktop` profile 由 App 独占、`dsh plugin --profile desktop …` 会被明确拒绝,Plugins 页才是受支持通道;宿主行即时加载、客户端界面需刷新一次页面;**0.1.5 与 0.2.0 两条依赖线都支持**及其设置通道差异。 + +### 验证 + +- `node --test` **338 项全过**(0.4.1 为 333),`node --check` 全部通过。 +- **两条依赖线都跑过**:本地 0.1.5-rc.3 线与干净安装的 `0.2.0-rc.2` 线(CI 实际解析结果)均 338/338。 +- 每条新回归测试都做了**变异验证**(在仓库外副本把修复改回旧写法,确认对应测试会红):诊断去重、跨路径共用集合、路由摘要有界、只绑 effort 的路由、去重过期,共 5 处。 +- 对抗式复审确认:工具 schema、prompt 文案与返回值均未改动,`subagent_roles` 诊断工具的全量清单仍完整。**唯一触及模型可见内容的是裁剪降级本身**——某个 part 缺 `text` 时,旧行为是「整份 assembly 这一次不裁剪」,新行为是「该 part 视为空、其余照常裁剪」,即子代理提示词的组成在异常装配下会变;这是该修复的目的,而不是无副作用,0.4.3 起在此更正表述。 + +## [0.4.1] - 2026-09-30 + +### 修复 + +- **DSH 0.2.0 冷启动直接失败**(`web boot: 1 entry did not activate` / `dsh-plugin-subagent-roles: pending (waiting for service: settingsScope)`)。浏览器半边原先把客户端 `settingsScope` 服务声明为**必需**依赖;0.2.0 移除了该服务(连同插件可注册的设置命名空间),于是这一行永远停在 pending,而**只要有一个行没激活,整个 web boot 就失败**——热加载时不校验,所以只有冷启动才暴露。 + - `exports.inject` 由 `['slots', 'settingsScope']` 改为 `['slots']`:`settingsScope` 变成**可选**读取(属性访问包了 try/catch,且要求 `bind` 是函数),缺失时卡片主动让位并**只打印一次**说明,宿主半边(角色目录、按角色工具过滤、工具调用预算)继续按行配置正常工作。 + - **服务晚到不再永久丢卡片**:一次性读取失败后改为监听 `internal/service` 注册事件,`settingsScope` 稍后出现即补挂。此处刻意**不用** `ctx.inject(['settingsScope'], …)`:那会创建一个 pending fiber,而「有行未激活」正是本次要消除的 boot 失败形态。 + - 卡片 claim 改为**按上下文归属**(`claimOwner`):HMR 下 apply/dispose 两种顺序都不会丢卡片、也不会重复注册;`settings.plugin.item` 的 inject 交由 `ctx.effect` 拥有,注册残留不再可能。 +- **子代理 run 泄漏**:前台/后台两条委托路径上,`onRun` / `track()`(预算 arm)/ logger 任一抛错都会跳过 `settleRun` / `settleForegroundRun`——而它们是 `run.dispose()` 的唯一调用点,run 会泄漏到整个会话结束。现在这些调用各自独立围栏,settle 始终执行,失败照旧上报(`failed` 判定不变)。 +- **激活路径上的 logger 不再能拖垮整行**:`apply` 主路径缺 `systemPrompt` 时的 warn 改为与同文件其余日志一致的 `safely(...)` 包裹——抛错的 logger 在桌面版上等于 boot 失败。 +- `readModelSelection` 对 0.2.0 的 `settings` 服务(无 `get`)改为**特性检测**,不再是抛错后落进空 catch 的死分支。 +- **测试套件适配 0.2.0 依赖线**(此前 CI 在 `0.2.0-rc.2` 的 peer 下全红,本地用 0.1.5 线却是绿的):parity 测试实例化官方工具时缺了 0.2.0 新增的 `ctx.subagents.resolveMaxDepth` 校验依赖;核心 `settleRun` 把文本字段由 `output` 改名为 `result`;`run_in_background` 的官方描述文案在 **0.1.5 线与 0.2.0 线并不一致**(桌面版 bundle 用旧文案),因此 parity 断言改为「必须是官方两种文案之一」——出现**第三种**文案仍会让该测试失败,这正是它存在的意义。以上只动测试,不改生产行为。 +- 0.2.0 上的设置改在 profile 补丁里本插件的**挂载行 `config`** 上(键名与设置卡片完全相同);卡片本身待按 0.2.0 的 `settings.section` 扩展点重做(见 README「Settings」)。 + +## [0.4.0] - 2026-09-22 + +### ⚠️ 不兼容提示(务必先读) + +- **角色文件与插件版本从此绑定。** 本插件的 frontmatter **未知键会被拒绝**(见 README「文件格式」),因此任何使用了 `maxToolCalls` / `maxToolCallsScope` / `onToolCallBudget` / `graceToolCalls` 的角色文件,在**旧版插件**上会直接报 `unknown frontmatter key` 并被跳过。给角色加额度 = 每台使用该工作区的机器都必须把插件升到 **≥ 0.4.0**。 +- 新增一个**运行时依赖** `@deepseek-ai/dsh-llm`(peer + dev):收尾通知需要用核心自己的 `createUserMessage` 构造,才能带上正确的 `plugin` 来源(见下方「说明」)。 + +### 新增 + +- **角色级工具调用预算硬上限**(`maxToolCalls`):可选、可继承、由插件**强制执行**,不依赖模型自律。计量单位钉死为**「次」而不是「轮」**——这正是口头「8 步」约定失效的根因(§1 实测:两个只读角色分别跑到 19 / 25 次且都未披露)。 + - **计数来源是框架自己的 `tool/call` 事件**,不解析模型输出、不采信模型自报。同一步内并行调用**各计 1**;被策略/guard 拒绝的调用计 1、取消后跳过的调用也计 1(核心在 `startCall()` 第一行就无条件落盘 `tool/call`,拒绝/跳过随后补 `tool/result`,因此口径对三种情形一致)。`used === limit` **不触发**,第 `limit + 1` 次才触发。 + - 四个 frontmatter 字段:`maxToolCalls`(`0` = 不限)、`maxToolCallsScope`(`delegation`(默认)/ `session`)、`onToolCallBudget`(`wrap-up`(默认)/ `interrupt` / `off`)、`graceToolCalls`(默认 `1`;`0` 等价 `interrupt`)。 + - 四个行配置:`defaultMaxToolCalls`(默认 `0`,**刻意不硬编码全局默认数字**)、`maxToolCallsHardCap`(默认 `0`)、`onToolCallBudget`、`graceToolCalls`。角色文件优先于行/设置默认值;`maxToolCallsHardCap > 0` 时角色值被 `min` 削顶并告警——但**永不削顶「不限」的 `0`**(`0` 是哨兵而不是计数)。 + - `scope: delegation` 在已知子会话观察到 `turn/start` 时重置计数,这是「每次后台唤醒各起一个新计数」唯一可观测的定义;`scope: session` 跨唤醒累计。 +- **三条委派路径各自收口**:continuable 子代理走 `SubagentRuntime.interrupt(childId, { kind: 'ancestor', agent })`。**前台/后台 one-shot 走插件自持的取消信号**——因为 `interrupt` 对 one-shot/未知目标是**被接受的 no-op**(核心文档原文:「including a one-shot or unknown id」),若只依赖它会得到「看着生效、实际不生效」的最坏失败形态。前台路径把 `exec.signal` 的取消转发进插件自己的 controller;后台路径复用既有 job controller。 +- **收口记录写进子会话**:收尾通知就是这次收口的**持久审计记录**(携带 `used`/`limit`/`scope`/`mode`),因此在**每次收口**时都会投递——包括 `interrupt`——而不是只在 `wrap-up`。这正是需求 5.3/§7「同一事实写入子会话」「可回放到停在哪一次、剩多少」:对一个被直接杀掉的子代理,宿主日志回答不了这个问题。`off` 只告警、不收口,因此不写子会话记录(已在 README 说明)。 +- **`wrap-up` 在下一个 step 边界注入收尾通知**:用 `Agent.inject()`(`send(msg, 'next-step', false)`)而不是 `steer()`/`followup()`——后者 `wakeup: true` 会把**空闲**子代理唤醒成一个新轮次,等于把收尾指令变成额外工作量。通知是一条**显式 `plugin` 来源**的 `user` 消息:省略 source 会被解析成 `user`,那等于让机器生成的指令**冒充人类输入**并继承人类权威。远程传输不发布本地子代理对象(`SubagentRun.localAgent` 为 `undefined`)时,子代理跑在本进程之外:`tool/call` 到达不了护栏(既数不到也停不下),通知也投递不了——插件在**委派时**就告警,而不是把一个并未受保护的角色报成已受保护。进程内传输不受影响。 +- **超限对主代理是「正常结果 + 状态字段」,不是错误**:前台返回 `status: 'tool-call-budget-exceeded'`、`reason: 'tool-call-budget'`、`role`/`used`/`limit`/`scope`/`mode` 与可选的 `partialOutput`,让主代理明确选择「再派一次更窄的任务 / 放宽额度 / 接受部分结论」;抛错会被当成可重试的工具故障,恰好相反。后台 job 的 detail 写明预算收口,从而不再与「用户 kill」混淆。 +- **与 `timeoutMs` 正交**:预算先到 → 上面的结构化结果;deadline 先到 → 核心自己的 `TOOL_TIMEOUT` 错误(核心的 timeout 包装器在 `next()` 返回后按自己的 deadline 命中**替换**结果,插件无法也不应抢这条通道)。两者都有 `breached` / `isTornDown` 判定,绝不互相误报。 +- **可在 Settings → Plugins 里改**:预算四个键与裁剪两个键共用同一个宿主 namespace `subagent-roles`(宿主按 namespace 整体服务,第二次注册同名 namespace 会被拒),行 config 仍是 `base` 层。浏览器卡片改为**声明式字段表**驱动,并对每个键做类型化转换(计数以**数字**写入,非法文本折叠为回退值而绝不写出宿主会拒绝的值)。 +- **可观测**:`subagent_roles` 每个角色多一行 `tool-call budget: 30 (role, scope delegation, mode wrap-up, grace 1)`,来源标注角色文件 / 行默认 / 不限;超限日志固定一行 `[subagent-roles] role=… tool-call budget exceeded: used=… limit=… scope=… mode=…`;收尾通知本身持久化在子会话日志里,因此停在哪一次、剩多少都可回放。 + +### 说明 + +- **不改 DSH 核心**。核心确实没有 `maxSteps` / `maxToolCalls` 类旋钮(已 grep 确认),因此护栏全部落在本插件的配置与角色文件格式内。 +- **收口按轮次限流为一次**:`scope: session` 的计数永不复位,因此父代理再次唤醒已超额的 continuable 子代理时会被**再次**停下(第一版把「已上报」与「已收口」合成一个锁,导致只有第一次唤醒会被拦——已修);但被停下那一批里从未启动的调用(核心会为它们补 `tool/call`)不会各自重复一遍停止。首次触发的事实(`usedAtBreach`)不会被后续唤醒改写。 +- **`maxToolCallsHardCap` 的告警按来源措辞**:削顶的是角色文件就点名角色,削顶的是行/设置默认值就说「the row/Settings default asked for …」,不再把继承来的默认值说成角色自己要求的。 +- **`maxToolCallsHardCap` 的削顶告警也进诊断工具**:`subagent_roles` 多一行 `warning: …`,否则它只显示被削后的数字而不说为什么。 +- **超时与预算的次序**:两者独立呈现——预算收口是结构化结果,超时保留核心的 `TOOL_TIMEOUT`。已补「配置了 `timeoutMs` 但预算先到」的用例;反向的窄竞态(预算已开始收口、deadline 在拆卸期间到期导致核心替换结果)已在 README 已知边界里如实写明。 +- **需求 3.1 的「报错信息带上该键需要插件 ≥ x.y」未实现**:旧版插件的未知键报错只能列出它**自己认识**的键,一个不认识 `maxToolCalls` 的版本不可能在报错里提到它——该要求对已发布版本逻辑上不可达。已改为文档层面的版本绑定(README 文件格式表 + 本文件顶部的不兼容提示)。 +- **计数精度与保证边界**:收口是**反应式**的——跨过上限的那次调用已经写进会话日志,插件是在它结束前停下子代理,而不是阻止它开始。保证的是「子代理会停」,计数则是精确的。 +- **`0` 语义**:额度 `0` 表示不限,且 `maxToolCallsHardCap` **不削顶它**。逃生口优先于上限是刻意的:硬上限的用途是削回一个已声明的数字,而不是禁止「不限」。 +- **零成本**:`0`(不限)不会登记任何计数记录,也不参与事件处理;记录表有上限(256 条,**按插入序**淘汰,不是 LRU),且这只是防泄漏兜底:记录会在子会话 `session/disposed`、或委派结算时正常释放(前台/后台在 `finally` 里释放,continuable 靠 `session/disposed`),因此活记录不会被淘汰掉。 +- **`childPromptTrim: 'off'` 的既有语义保留**:它仍会连同 Settings 卡片一起卸掉整个 namespace,因此预算旋钮也一并在 UI 里消失(额度此时只来自角色文件与行 config)。这是原「off 是不可被 UI 翻回来的关闭开关」约定,未改动。 +- 预算**不出现在角色目录文本里**,只有 `subagent_roles` 报告它,因此带预算的角色对提示词体积没有影响。 + +### 测试 + +- 新增 `test/budget.test.js`(41 例):frontmatter 四种字段的合法/拒绝、额度解析与优先级、硬上限削顶与「不削顶 0」、计数语义(恰好等于上限不触发 / 第 `limit+1` 次触发 / 并行各计 1 / 非 `tool/call` 事件不计 / 未登记会话不计)、三种姿态与 grace 边界(`grace: 0` 等价 `interrupt`)、两种 scope 的隔离与 `turn/start` 重置、健壮性(已在拆卸中的委派不误报 / enforce 与 inject 抛错不外泄 / 通知投递失败要告警 / 记录表有界)、结构化结果的形状。 +- `test/delegation.test.js` 扩到 72 例:三条路径端到端(前台断言 run 信号被 abort 而**不是** `interrupt`、continuable 断言 `interrupt` 参数与 ancestor authority、后台断言 job detail)、收尾通知**必须是 plugin 来源**(防回归到冒充人类输入)、`interrupt` 也必须投递那条持久通知、deadline 先到**不得**产生预算结果、**配置了 `timeoutMs` 但预算先到**必须返回预算结果、`session` 作用域的 continuable 在**下一次唤醒**会被再次停下、子会话 `session/disposed` 会释放记录、远程 provider 降级、行默认生效、诊断工具三态来源与削顶告警。 +- `test/parity.test.js` 把「输出 schema」那条从「完全相同」改为「官方三支逐字节相同 + 追加的 budget-stop 支被显式钉死」,并把两处刻意偏离写进该文件的说明。 +- `test/settings.test.js` / `test/client.test.js` 跟着 namespace 扩到六个键:`base` 层必须带上全部键(否则会静默落到 schema 默认而非行 config)、卡片字段表必须与宿主 schema 的键集**完全一致**、计数以数字写入、非法计数文本折叠为回退值。 +- 新增 `test/seam.test.js`:用**真实的 cordis Context + 真实 SessionStore**(无 LLM、无 profile)验证整条护栏所依赖的**唯一假设**——带 `{ global: true }` 的 `session/event` 订阅确实能收到**子会话**已提交的事件(cordis 默认按 context 过滤监听器,写错就会「静默什么都数不到」,正是本插件已经吃过一次的失败形态)。同时钉住「恰好等于上限不触发 / 跨过才触发 / 未登记会话不计 / `turn/start` 重置 delegation 计数」。这两个包是 devDependencies;缺失时该套件按原因 skip 而不是失败。 + +## [0.3.0] - 2026-09-16 + +### 新增 + +- **子代理提示词裁剪**(`childPromptTrim`):核心把大多数工具说明注册成静态文本,只有 `dsh-tool-fs`、`dsh-tool-fs-search`、`dsh-tool-web`、`dsh-file-reference-local` 会按 scope 求值,因此角色策略藏掉一个工具后,子代理仍在为它的说明付费,还继续读 Web GUI、harness checkout、交付链接这些它永远用不上的段落。现由**一个 host 层 `system-prompt/assemble` 监听器**精确丢弃这些死文本: + - `tool:` 说明——当 `` 是注册表里**真实存在**的工具、而该 scope 看不到它时丢弃(规则从活的注册表推导,无需维护); + - 组标签说明(`tool:jobs`、`tool:goal`)——其名字不是工具名,改为在它**自身文本**里按整词匹配已知工具名,全部不可见时才丢弃; + - `full` 模式额外丢弃 `childPromptTrimNames` 命名的提示词片段(默认 `harness:source`、`app:web-surface`、`ui:deliverable-file-references`、`context:file-reference`),**同一份名单同时匹配 section 与 context**。 +- 两个行配置:`childPromptTrim`(**`full`(默认)** / `tools` / `off`)与 `childPromptTrimNames`。**默认即裁剪**,零配置生效;`off` 是安全阀,`tools` 是"只删死文本、保留 GUI/checkout 那几段"的保守档。 +- **可在 Web 的 Settings → Plugins 里改**:裁剪策略以宿主 settings namespace `subagent-roles` 发布,配一张浏览器侧卡片。行 config 是 namespace 的 `base` 层,卡片把用户层写进 `~/.dsh/settings.yaml`,`applies: live` —— 下一次子代理轮次生效,不用重启。卡片遵循宿主约定:编辑先暂存、Save 才写、每字段可 Reset 回组合默认、并标出被覆盖的字段。 +- 卡片**逐条对照宿主的 `PluginCard`** 自画外壳:可折叠表头(标题/说明/旋转箭头)、未保存徽标、底部 Reset / Discard / Save,沿用 `--dsw-alias-*` design token。宿主只铺一列并派发 slot,"chrome, controls, and copy" 全归插件;画成扁平常展开的盒子会与同排的 bash / agent-loop / subagent 卡片格格不入。 +- 只注册一张卡,不额外占 Settings 导航分组(dshmarket 那样的分组是因为它有一整页浏览界面)。 +- **编辑遵循宿主的卡片约定**:暂存 → Save 才写、Discard 丢草稿、**Reset 只暂存组合默认(写入的是 unset,让字段重新继承部署配置)**、清空保存后自动折叠、保存失败保持展开并保留草稿。 +- **修掉一个已发出的低级错误**:Save 按钮的颜色用了不存在的 `--dsw-alias-label-inverse`,而 `--dsw-alias-brand-primary` 解析出来就是 `label-primary`(深色主题下≈白)→ **深色主题下白字白底,对比度 1.0:1**。现完全照抄宿主 `.save` 规则(`background: label-primary; color: bg-layer-3`,浅色 18.9:1、深色 11.6:1),并加了两道防线:**token 白名单**(只允许主题里真实存在的 `--dsw-alias-*`)与 **Save 配色成对断言**。 +- **文案跟随 Language 设置**:注册 `zh` / `en` 两份同键词典并在注册项上声明 `locale: `,由渲染层绑定 `t`(`props.t`);无 locale 服务时依次退回自身绑定与英文词典。此前那版把"中英并列"硬编码进文案,既不跟随语言设置、在两种语言下都别扭,也偏离了生态里 dshmarket / task-board 的做法。 +- 插件因此新增**浏览器半边**:`lib/client.js`(手写,走 `window.__ModuleLoader__` 信封,`react` 取自平台基线模块,**不引入任何构建步骤**,`node --check` 仍能检查它)、`exports["./client"]` 与 `dsh.client.platform: "web"` 声明。宿主侧只注册 namespace 是**不够的**:Plugins 页只为「已服务的 namespace × 注册在该 key 下的卡片」的交集渲染内容,没有卡片就是一个空标签页。 + +### 说明 + +- **只动子代理**:深度为 0 的顶层 agent 提示词逐字节不变(同一次实测里父子两次运行的父提示词逐字节相同,均为 6,431 字符)。真实委派实测:角色子代理提示词 **5,765 → 1,904 字符(−67%)**——该数字是**默认配置**(不带任何 override)跑出来的。 +- 为什么默认连 GUI / harness checkout / 交付链接 / `@` 路径四段一起删:它们对验证者、审查者这类子代理是纯噪声,而父代理随时能在派发提示词里补上任何真正需要的上下文。若某个部署确实需要(例如派子代理改 DSH 本身、或 fork 子代理的回答直接面向 GUI 用户),把 `childPromptTrimNames` 清空即可全部保留。 +- 规则基于**活的工具注册表**,因此 `tools` 模式不依赖任何写死的 section 名;`full` 模式的名单是版本敏感的,核心改名后该段只是不再被裁剪(安全方向),不会报错。 +- 作用于宿主所见**每一个**子代理的组装,而不只是本插件发起的角色子代理——运行时不在子代理上记录角色标记。注册在 agent 自身作用域的工具(`subagent`、`list_agents`)不在全局视图里,其说明永不被裁剪。 + +### 说明(settings 侧) + +- 没有 settings provider 的部署仍以行 config 为唯一权威;namespace 注册失败(存量配置非法、与另一行撞名、`ctx.get`/`inject` 抛错)只记告警并退回行 config —— 设置出问题不该让插件行倒下,更不该让裁剪失效。 +- 卡片只覆盖默认行的 namespace;用改名 `toolName` 挂的第二行属于 `subagent-roles-`,没有卡片,直接改 `settings.yaml`。 +- 实测(真实 `dsh-settings-file` 服务 + 真实 headless 委派):行 config 写 `tools`、用户层写 `full` 时,子代理提示词按 `full` 裁剪(3,882 → 1,904 字符);删掉用户层后回到 `tools`(1,627 字符的命名段落保留)。`settings.describe()` 带出组合 base,写入落进 settings 文档,`replace({})` 后重新继承行 config。 + +### 修复(第二轮:独立审查复核后) + +- **`off` 之前并不生效**:`trimChildPrompt` 只在 `full` 分支上判断模式,R1/R1b 无条件执行,于是 Settings 里的 `off` 与 `tools` **行为完全相同**(实测:两者都丢掉 `tool:workflow`)。现 `off` 直接原样返回,并补了两条回归用例——一条纯函数、一条**驱动真实的 Settings 切换路径**(桩服务现在会 commit 并触发 watch,否则该断言会假通过)。 +- **Reset 后继续编辑会被静默丢弃**:`patch` 从不清除该字段的暂存,Save 于是写 unset、把用户刚输入的值丢掉。现编辑会取消该字段的暂存(`applyEdit` 纯函数 + 回归用例)。 +- **没改动的字段会被写成覆盖值**:用户层里"存在"即"已覆盖",只改模式也会把名单钉住、让以后改部署配置失效。现 `planSave` 只写真正变化的字段(未改动且未暂存则不写)。 +- 补防线:token 白名单**改为从已安装主题派生**(CI 无主题时回退手抄清单)、删掉一条"匹配源码文本"的空洞断言、换成语义级的保存计划用例;状态行补 `role="status"`;重复点 Save 加在飞守卫;"与宿主逐条一致"的说法改为写明两处刻意偏离。 + +### 修复(第一轮) + +- **实测发现的真 bug**:`context:file-reference`(`@路径` 说明)在当前核心里是以 **section** 注册的(`dsh-file-reference-local` 里 `systemPrompt.section({ name: "context:file-reference" })`),尽管名字带 `context:`。原先按 "section 名单 / context 名单" 分开匹配,导致这一段在真实会话里**没有被裁剪**——是重启后的活体会话验证抓到的(子代理仍带 `@路径`,另外三段已消失)。现在合并为**一份 kind-agnostic 名单**,对两个数组都匹配;回归用例 `a name is dropped wherever it appears — section or context` 钉住它。 +- 记录一条实测踩坑并据以设计规则:直接把 `tool:` 的 `` 当工具名,会把组标签 `tool:jobs` / `tool:goal` 误判为「工具 jobs/goal 不存在」,从而删掉 1,116 字符仍然有效的说明(子代理明明有 `job_output`、`create_goal` 等工具)。规则必须先与注册表已知工具名求交集。 +- 组标签规则的工具名匹配用**整词**而非子串:`already` 里含有 `read`,子串匹配会让一段无关文字被当成"点到了 read 工具"。 + +## [0.2.1] - 2026-09-13 + +本次为**文档与基建补丁**,不含运行期行为变更。 + +### 其他 + +- 新增本文件(`CHANGELOG.md`,中文),追溯 0.1.0 以来的全部版本,并纳入 `files` 随包发布。 +- 发版工作流增加门禁:`CHANGELOG.md` 中没有 `## [<版本号>]` 条目即拒绝发布。发出去就收不回来,所以更新日志条目是发布的前置条件,而不是约定。 +- 两份 README 的发版段落改写为三步(先补日志 → 再 `npm version` 推标签 → 工作流校验后发布),并互加更新日志入口。 + +## [0.2.0] - 2026-09-13 + +### 新增 + +- `timeoutMs` 行配置:前台委派的工具级超时。核心的 timeout policy 会替换 `exec.signal`,而前台路径本就把该 signal 传给 `ctx.subagents.start`,因此子代理随调用一起结束;后台委派立即返回,不受影响。 +- `personaVariables` 行配置:扩充 persona 允许引用的提示词变量。默认仍是 agent loop 注册的 `cwd`、`model`、`provider`;不合核心语法的名字会被过滤。 +- `listToolName` 行配置:诊断工具改名,使同一 profile 可以挂两行。 +- `projectRootTtlMs` 行配置:项目根结果被信任多久后重新向上查找(此前 loader 支持但配置层触达不到)。 +- 支持传输 provider 的 `agentRouteDefaults`:按官方语义合在角色自身绑定之下,且绝不会用来复活一个刚被授权清单拒绝的路由。 +- **同一 profile 可挂两行**:角色目录的 section 名改为由 `toolName` 派生(`:catalog`),诊断工具名走 `listToolName`。此前两者都是写死的常量,第二行的注册会抛"already registered"并被静默吞掉 —— 结果是第二行的角色永远不进目录,而插件看起来"半好"。 +- 与官方 delegation 工具(`@deepseek-ai/dsh-tool-subagent`)的**对照测试**:同一形态的宿主桩挂载官方实现,两边用同一个假子代理结果驱动,凡"本应逐字一致"的部分断言相等。该包作为 devDependency 引入。 + +### 变更 + +- **路由改为真预检**:角色绑定的路由在子代理存在之前经 `llm.resolveCallConfig({provider, model, reasoningEffort}, signal)` 解析。角色文件里 `model` 写错、或 `reasoningEffort` 不为 adapter 所认,现在会当场报出可对症修正的错误,而不是从子代理创建深处抛出晦涩失败。旧部署没有该 seam 时降级回 provider 成员检查。 +- **`respectModelSelection` 改为分层读取**:优先采用会话已捕获的策略(与官方委派工具写入的同一个 session projection `subagentModelSelectionPolicy`),没有捕获时才回退实时 `subagent-model-selection` 设置,子会话再回退其父会话。实时设置只用于给新会话播种,因此改动不再追溯影响运行中的会话。 +- 委派日志改报**本次调用实际执行**的模式(此前直接抄 `backgroundMode`,在 `enableRunInBackground: false` + `backgroundMode: continuable` 时报了一个根本不会走的模式),并带上解析后的路由层级。 + +### 说明(settings 侧) + +- 没有 settings provider 的部署仍以行 config 为唯一权威;namespace 注册失败(存量配置非法、与另一行撞名、`ctx.get`/`inject` 抛错)只记告警并退回行 config —— 设置出问题不该让插件行倒下,更不该让裁剪失效。 +- 卡片只覆盖默认行的 namespace;用改名 `toolName` 挂的第二行属于 `subagent-roles-`,没有卡片,直接改 `settings.yaml`。 +- 实测(真实 `dsh-settings-file` 服务 + 真实 headless 委派):行 config 写 `tools`、用户层写 `full` 时,子代理提示词按 `full` 裁剪(3,882 → 1,904 字符);删掉用户层后回到 `tools`(1,627 字符的命名段落保留)。`settings.describe()` 带出组合 base,写入落进 settings 文档,`replace({})` 后重新继承行 config。 + +### 修复 + +- `displayName` 撞名(例如项目角色与全局角色同名)时静默取先加载者,现明确告警并列出候选 id。 +- 发现缓存(文件、目录、项目根、已告警诊断)按绝对路径无界增长,宿主常驻时会持续膨胀;现统一 512 条上限并淘汰最旧,结果不受影响。 +- `route.js` 的 `layer` 只产出、无人消费,现接入委派日志。 +- 诊断脚本的 `--project` / `--grep` 缺值会抛 TypeError 或去找字面量 `undefined`,现统一报错退出;裸 flag 不再被当作会话目录。 + +### 其他 + +- CI 增加 `npm run lint`(对 `lib/`、`scripts/`、`test/` 做 `node --check`),零依赖,能抓住不被任何测试 import 的文件的语法错误。 +- `.gitignore` 忽略 `package-lock.json` —— 与本仓库"有意不提交 lockfile"的约定保持一致。 +- README(中英同步):补 `name` frontmatter 字段与上述新增配置项;改写 `respectModelSelection`、`timeoutMs` 两条已知边界;补多行共存与缓存上限说明。 + +## [0.1.2] - 2026-09-13 + +### 说明(settings 侧) + +- 没有 settings provider 的部署仍以行 config 为唯一权威;namespace 注册失败(存量配置非法、与另一行撞名、`ctx.get`/`inject` 抛错)只记告警并退回行 config —— 设置出问题不该让插件行倒下,更不该让裁剪失效。 +- 卡片只覆盖默认行的 namespace;用改名 `toolName` 挂的第二行属于 `subagent-roles-`,没有卡片,直接改 `settings.yaml`。 +- 实测(真实 `dsh-settings-file` 服务 + 真实 headless 委派):行 config 写 `tools`、用户层写 `full` 时,子代理提示词按 `full` 裁剪(3,882 → 1,904 字符);删掉用户层后回到 `tools`(1,627 字符的命名段落保留)。`settings.describe()` 带出组合 base,写入落进 settings 文档,`replace({})` 后重新继承行 config。 + +### 修复 + +- **子代理非正常结束时,provider 自己的 `diagnostic` 被整段丢弃**,主代理只拿到一句 `subagent run failed`,既无法自救也无法上报。现随报错一并给出(与官方工具逐字一致),并补上输出块的类型守卫。 +- **fork 型传输 provider 下工具对模型说的是假话**:描述与 `prompt` 参数写死"子代理看不到本对话",而 fork 的子代理其实已带上本会话已完成的轮次。现按 `provider.inheritsParentContext` 切换措辞。 +- **角色文件若是指向 FIFO 或字符设备的符号链接,`readFileSync` 会在提示词组装中同步永久阻塞**(无 signal、无 timeout 可打断),宿主当场冻死。现要求链接解析后仍是普通文件。 +- **`maxBodyBytes` 此前在读完文件之后才比较**,`statSync` 已经给出的 `size` 形同虚设:10 字节的上限照样会把 64 MB 整份读进内存。守卫前移到读取之前,并留出 64 KiB frontmatter 余量。 +- 诊断脚本的归属判定依赖"self-contained"字样,在 fork 措辞下会把自家工具误报为他人注册。 + +### 文档 + +- README / README.zh:说明委派措辞随传输 provider 变化。 + +## [0.1.1] - 2026-09-13 + +### 变更 + +- CI 在 Node.js 20、22、24 上运行测试。 +- 发版改为 npm trusted publishing(OIDC)并附 provenance 证明,仓库不再保存长期 token。 + +## [0.1.0] - 2026-09-13 + +### 新增 + +- 首次发布。文件定义子代理角色:`<项目>/.dsh/roles/.md` 与 `~/.dsh/roles/.md`,项目同名角色优先。 +- YAML frontmatter 承载 `description`、`displayName`、`whenToUse`、`provider`/`model`、`reasoningEffort`、`tools`/`toolFilter`;正文是该子代理的 persona。 +- 紧凑角色目录:一个提示词 section,每个角色一行,仅在委派工具对该 agent 可见且工作区确有角色时渲染。 +- 逐角色工具策略:允许清单 / 拒绝清单,支持 `*`、`?` 通配,按委派时可见的工具名展开;`run_code` 与子代理作用域内注册的工具名有专门处理。 +- 逐角色模型路由,遵守官方 `subagent-model-selection` 授权清单。 +- 可选诊断工具 `subagent_roles`;诊断脚本 `scripts/inspect-session-budget.mjs`。 + +[0.4.3]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.4.2...v0.4.3 +[0.4.2]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.4.1...v0.4.2 +[0.4.1]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.4.0...v0.4.1 +[0.4.0]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.3.0...v0.4.0 +[0.3.0]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.2.1...v0.3.0 +[0.2.1]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.2.0...v0.2.1 +[0.2.0]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.1.2...v0.2.0 +[0.1.2]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/troytse/dsh-plugin-subagent-roles/compare/v0.1.0...v0.1.1 +[0.1.0]: https://github.com/troytse/dsh-plugin-subagent-roles/releases/tag/v0.1.0 diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/LICENSE b/.dsh/plugins/dsh-plugin-subagent-roles/LICENSE new file mode 100644 index 00000000..cbd5c16f --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 troytse + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/README.md b/.dsh/plugins/dsh-plugin-subagent-roles/README.md new file mode 100644 index 00000000..6e7ce9c7 --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/README.md @@ -0,0 +1,274 @@ +# dsh-plugin-subagent-roles + +English | [中文](README.zh.md) | [Changelog (中文)](CHANGELOG.md) + +[![npm](https://img.shields.io/npm/v/dsh-plugin-subagent-roles)](https://www.npmjs.com/package/dsh-plugin-subagent-roles) +[![CI](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml/badge.svg)](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml) +[![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +## Summary + +`dsh-plugin-subagent-roles` defines subagent roles as files. A role is one Markdown file: YAML frontmatter carries a display name, a routing description, an optional LLM route, a tool policy, and an optional tool-call budget; the body is the persona the child runs with. Project roles live in `/.dsh/roles/`, global roles in `~/.dsh/roles/`, and a project role wins when the same id exists in both. + +The plugin registers one delegation tool and advertises the roles found for the current workspace with a compact catalog line. When a role is delegated to, the child starts with that role's persona and only the tools its policy allows — the delegating agent never carries the persona text, and a project without role files sees no catalog at all. A role may also cap how many tool calls its child gets: the cap is a hard, observable limit counted from the framework's own `tool/call` events, so a child that will not stop is stopped. + +## Install + +**DSH desktop app** — install it from the app's own **Plugins** page (sidebar → Plugins): paste the package name to pull it from npm, or an **absolute path** to install a local checkout. + +``` +dsh-plugin-subagent-roles +# or a local checkout +/path/to/dsh-plugin-subagent-roles +``` + +The `desktop` profile belongs to the application — `dsh plugin --profile desktop …` is refused on purpose (`profile "desktop" is managed exclusively by the Electron application`) — so the Plugins page is the supported channel there. It installs the package, appends the bundle to the profile, and the row then appears in the Settings inventory. Host-side rows load immediately; client-side surfaces — another plugin's sidebar, task or usage pages — need one page refresh before they show up. + +**CLI profiles (`dsh web`, TUI, headless)** — install into that profile by name, or link a checkout: + +```sh +# from npm +dsh plugin --profile web add dsh-plugin-subagent-roles + +# or a local checkout +dsh plugin --profile web add link:/path/to/dsh-plugin-subagent-roles +``` + +Restart the profile afterwards (`dsh web`). The package ships a bundle patch, so it inserts its single row without any composition edit. Requires Node.js 20 or newer, together with a DSH deployment that provides `@deepseek-ai/dsh-tools` and `@deepseek-ai/dsh-subagent`. + +**Version line**: 0.5.x supports **DSH 0.2.1-rc.1+** only; stay on 0.4.3 for 0.2.0 and earlier. 0.2.1 removed `subagents.start` / `startContinuable`, the request's `persona` / `toolFilter`, and the client settings service; 0.5.0 rewrote delegation and composition against the new API while keeping the role-file format and per-role model binding unchanged. + +## Quick start + +Create a role file in the project: + +```markdown +--- +displayName: Code Reviewer +description: Reviews a diff for correctness, security, and missing tests, and reports findings by severity. +provider: deepseek-official +model: deepseek-v4-flash +reasoningEffort: low +tools: [read, grep, glob] +--- +You are a code reviewer. Read the diff before judging it, separate blocking +issues from suggestions, and cite file and line for every finding. +``` + +Then ask the agent to delegate — “have the code-reviewer role review this diff” — or call the tool directly: + +```js +subagent_role({ role: "code-reviewer", prompt: "Review the staged diff.", description: "review staged diff" }) +``` + +Roles are read when the prompt is assembled and again when a delegation starts, so editing a role file takes effect without restarting DSH. `examples/delegation-prompts.md` has dispatch prompts in the same style ([中文](examples/delegation-prompts.zh.md)). + +## Role files + +### Where roles are read from + +| Precedence | Path | Notes | +|---|---|---| +| 1 | `/.dsh/roles/.md` | `` is the nearest ancestor of the session working directory that contains a project marker (`.git` by default); the working directory itself when no marker is found. | +| 2 | `~/.dsh/roles/.md` | Shared across projects. `dshHome` overrides the location. | + +A role file may be a symlink. Files are read by name, so the id is the file stem and must be kebab-case. + +### File format + +The frontmatter is a YAML mapping; the body is the persona. + +| Field | Required | Meaning | +|---|---|---| +| `description` | yes | One line shown in the catalog; the delegating agent routes on it. | +| `name` | no | Must equal the file id when present; a guard against renaming a file without its declaration. | +| `displayName` | no | Human-readable name; defaults to the id. | +| `whenToUse` | no | Extra routing hint appended to the catalog line. | +| `provider`, `model` | no | LLM route for the child. Declare both or neither; omitting them inherits the parent's route. | +| `reasoningEffort` | no | Effort for the child; applies together with the route. | +| `tools` | no | Allow list shorthand, e.g. `[read, grep, glob]`. | +| `toolFilter` | no | Explicit policy: `{ allow: [...], deny: [...] }`. | +| `maxToolCalls` | no | Hard cap on the child's tool calls: a whole number. Omit it to inherit the row's `defaultMaxToolCalls`; set `0` for explicitly unlimited, which **overrides** the row default. | +| `maxToolCallsScope` | no | `delegation` (default) restarts the count at each delegation — and at each `turn/start` of a continuable child, which is what a background wake opens. `session` accumulates for the child's whole life. | +| `onToolCallBudget` | no | What happens at the cap: `wrap-up` (default), `interrupt`, or `off`. | +| `graceToolCalls` | no | Extra calls `wrap-up` tolerates after its notice; defaults to `1`, and `0` stops on the crossing call itself. | + +`tools` and `toolFilter` are mutually exclusive. Unknown frontmatter keys are rejected rather than ignored, so a typo cannot silently widen a role's tools. + +The `maxToolCalls` family requires **plugin ≥ 0.4.0**. An older version knows none of those keys and refuses the whole file, so a role file and the plugin version are bound together: adding a budget to a role means every machine running that workspace needs the newer plugin. + +The persona body may reference the prompt variables `{{cwd}}`, `{{model}}`, and `{{provider}}` — exactly the three the agent loop registers; they are interpolated by the harness for the child. A deployment that registers more can list them in `personaVariables`; a reference to anything else is rejected when the file is read, because an unknown variable throws on *every* turn of the child that uses it. References are matched exactly (no spaces inside the braces), and the catalog fields — `description`, `displayName`, `whenToUse` — must not contain `{{` at all, because catalog text passes through the same interpolation before it reaches the model. + +## Configuration + +The row accepts these options; pass them by overriding the row by id in the profile patch: + +```yaml +# ~/.dsh/profiles/web/cordis.patch.yml +- id: subagent-roles + name: dsh-plugin-subagent-roles + config: + catalogDescriptionMaxLength: 120 +``` + +| Option | Default | Meaning | +|---|---|---| +| `toolName` | `subagent_role` | Model-facing delegation tool name. | +| `subagentProvider` | `spawn` | Subagent transport provider. | +| `backgroundMode` | `one-shot` | `one-shot` or `continuable`. | +| `enableRunInBackground` | `true` | Expose `run_in_background` on the tool. | +| `maxDepth` | unset | Numeric delegation-depth cap; unset leaves it to the provider. `0` refuses every delegation. | +| `defaultRole` | unset | Role used when a call omits `role`. | +| `catalog` | `compact` | `compact` renders the role catalog; `off` renders nothing. | +| `catalogScope` | `main` | `main` advertises roles to top-level agents; `all` includes subagents. | +| `catalogDescriptionMaxLength` | `160` | Per-role description cap in the catalog line. | +| `projectRootMarkers` | `['.git']` | Markers searched upward from the session working directory. | +| `projectRootTtlMs` | `5000` | How long a resolved project root is trusted before the tree is re-walked, so a `git init` under a live session is noticed. | +| `dshHome` | `$DSH_HOME` or `~/.dsh` | Location of the global `roles/` directory. | +| `maxBodyBytes` | `65536` | Persona size limit, counted in UTF-8 bytes. A file larger than this plus 64 KiB of frontmatter is refused before it is read. | +| `personaVariables` | `['cwd', 'model', 'provider']` | Prompt variables a persona may reference. Extend only for variables the deployment really registers. | +| `respectModelSelection` | `true` | Honor the official `subagent-model-selection` allow list: a Session's captured policy first, otherwise the live setting. | +| `onMissingTool` | `drop` | Unavailable tool names: `drop` warns and continues, `error` refuses the delegation. | +| `timeoutMs` | unset | Tool-call deadline for one foreground delegation. Unset leaves it unbounded. | +| `defaultMaxToolCalls` | `0` | Tool-call budget for a role whose file declares none. `0` means unlimited, which stays the default on purpose: a 2,277-file repository and a small project disagree about what a reasonable call count is, so the number belongs in the role file. | +| `maxToolCallsHardCap` | `0` | Ceiling a role file cannot exceed, so a project cannot open a budget to a meaningless size. `0` disables the ceiling, and never clamps an explicit `maxToolCalls: 0` — "unlimited" is a sentinel, not the number zero. | +| `onToolCallBudget` | `wrap-up` | Row default for the exhaustion posture; a role file overrides it. | +| `graceToolCalls` | `1` | Row default for the grace calls; a role file overrides it. | +| `enableListTool` | `false` | Register the diagnostic tool. | +| `listToolName` | `subagent_roles` | Name of the diagnostic tool, so a second row can coexist with the first. | +| `childPromptTrim` | `full` | Trim a SUBAGENT's prompt: `full` drops tool guidance the child cannot use PLUS the named prompt parts, `tools` keeps the named parts, `off` disables the listener. A top-level agent's prompt is never touched. | +| `childPromptTrimNames` | `['harness:source', 'app:web-surface', 'ui:deliverable-file-references', 'context:file-reference']` | Prompt parts `full` mode drops, matched against sections AND contexts. Empty the list to keep them all. | + +## Tool policy + +A role's policy decides which tools its child can see and call. `tools` (and `toolFilter.allow`) is an allow list: everything not listed disappears from the child — schema and prompt guidance together — and calls to it are refused. `toolFilter.deny` removes named tools while keeping the rest. Entries accept the glob characters `*` and `?`, e.g. `mcp__demo__*`. + +Globs are expanded at delegation time against the tool names visible to the delegating agent, so a name that is not registered yet cannot fail the delegation. An unavailable literal name is dropped with a warning; `onMissingTool: 'error'` turns that into a refusal instead. An allow list that expands to nothing is passed through as an empty allow list, which hides every inherited tool rather than granting everything. + +Two cases are handled explicitly: + +- `run_code`, the presentation transport for PTC deployments, is never passed to a policy: the tool registry can list it, but the core refuses to restrict by that name. +- Tools that the delegating agent registers in its own scope are inherited by the parent but are not part of a child's scope chain. Naming one makes the core reject the child. The plugin drops those names, retries the delegation once, and warns. + +## Tool-call budget + +A role file's `maxToolCalls` is a **hard** cap the plugin enforces; it never relies on the child cooperating. The count comes from the framework's own `tool/call` events, never from the child's self-report and never from parsing its output. + +### What counts as one call + +The unit is **calls, not turns** — the ambiguity that made an earlier verbal "8 steps" guard meaningless in practice: + +| Situation | Counts as | +|---|---| +| Parallel calls inside one step | one each | +| A call the scheduler appended before a policy/guard denial | 1 | +| A call skipped because the run was cancelled mid-step | 1 | +| The wrap-up notice itself (a message, not a tool call) | 0 | +| A child's own sub-delegations | only the child's own calls; each grandchild is budgeted separately | + +`used === limit` is **not** a breach. The call that crosses the limit is, and enforcement is reactive: that call is already in the session log, so the child is stopped before it finishes. The guarantee is "the child stops", not "the crossing call never starts". + +### What happens at the cap + +| Posture | Behaviour | +|---|---| +| `wrap-up` (default) | Deliver the plugin-attributed notice ("budget exhausted — produce your partial conclusions"), then tolerate `graceToolCalls` further calls before stopping the child. | +| `interrupt` | Deliver the same notice and stop the child on the crossing call itself. | +| `off` | Warn once and never stop — and therefore write nothing durable into the child session. | + +`graceToolCalls: 0` is exactly `interrupt`: the same notice and the same stop, on the same call. + +The stop mechanism depends on how the delegation runs, and this is a core detail worth knowing: `SubagentRuntime.interrupt()` is an accepted **no-op for a one-shot run**, so a foreground or background one-shot child is stopped through the signal its run was started with, and only a `continuable` child is interrupted through the runtime. A remote transport that publishes no local child agent runs its child outside this process, so its tool calls are neither counted nor stopped — the plugin warns at delegation time instead of pretending the role is guarded. + +### How the child is told, and how the parent is told + +The notice is a `user`-role message carrying an explicit `plugin` source, delivered through `Agent.inject()` so it lands at the next step boundary **without waking an idle child into a fresh turn**. The explicit source matters: an omitted source resolves to `user`, which would let a machine-generated instruction impersonate human input. + +That same notice is the **durable record of the stop**: it carries `used`/`limit`/`scope`/`mode` into the child session's own log, so a stopped delegation can be replayed — *where did it stop, and how much was left*. It is therefore delivered on **every** stop, `interrupt` included, not only under `wrap-up`; a bare host log line cannot answer that question for a child that was killed. `off` is the one posture that never stops anything and so writes no child-session record. + +A stopped **foreground** delegation returns a normal, structured result — `status: 'tool-call-budget-exceeded'`, plus `reason`, `role`, `used`, `limit`, `scope`, `mode`, and any `partialOutput`. It is deliberately not an error: a thrown error reads as a retriable tool fault, whereas what the delegating agent should choose is a narrower task, a raised budget, or the partial result. A **background** delegation settles its job with a detail naming the budget stop, so it cannot be mistaken for a user kill. + +`timeoutMs` and the budget are orthogonal guards. Whichever fires first owns the report: a budget stop is the structured result above, while a deadline keeps the core's own `TOOL_TIMEOUT` error. The two are never merged into one failure. + +## Diagnostics + +Enable `enableListTool` to register `subagent_roles`, which reports every role with its source, file path, bound route, persona size, the expanded policy, its schema-character budget, and its **tool-call budget with its provenance** (role file / row default / unlimited), plus any file that was skipped and why. + +To inspect a finished delegation, read the child's session log: + +```sh +node scripts/inspect-session-budget.mjs --project +node scripts/inspect-session-budget.mjs --all --grep "You are a code reviewer" +``` + +The script decodes a session log read-only and prints the system-prompt size, the tool schemas the session requested, and whether the role catalog reached that session. + +## Settings + +**There is no Settings card on DSH 0.2.1**: 0.2.1 removed the client `settingsScope` service, plugin-registered settings namespaces, and the `settings.plugin.item` slot. The six trim/budget knobs are the plugin's **row config**; write them under this row's `config` in the profile's `cordis.patch.yml` and restart the profile (the row re-activates). + +| Key | Default | Meaning | +| --- | --- | --- | +| `childPromptTrim` | `full` | `full` / `tools` / `off` | +| `childPromptTrimNames` | built-in list | extra section/context names dropped in `full` mode | +| `defaultMaxToolCalls` | `0` | budget when a role file omits one; 0 is unlimited | +| `maxToolCallsHardCap` | `0` | ceiling a role file cannot exceed; 0 disables | +| `onToolCallBudget` | `wrap-up` | `wrap-up` / `interrupt` / `off` | +| `graceToolCalls` | `1` | grace calls after the wrap-up notice | + +A role file's own `maxToolCalls` still wins; the row config supplies the omission default and the hard cap. + +The missing GUI card is a deliberate trade-off: a 0.2.1 config page requires the plugin to implement a `plugins.row.config` component bound to `configForms`. This release prioritizes host-side correctness; the browser half still loads, explains the situation once, and registers no slot, so a missing service can never leave the row `pending`. + +## How it works + +- **Catalog.** One prompt section, rendered per assembly, lists the roles of the assembling agent's workspace: a framing line plus `- (): ` per role. It renders empty — and costs nothing — when a project has no roles, when the catalog is switched off, when the agent is a subagent, or when the delegation tool is not visible to that agent. +- **Delegation.** `subagent_role` resolves the role against the delegating agent's working directory, then starts a child through `ctx.subagents` with the role's persona, route, and tool filter. The model-facing wording follows the transport provider: a fork provider already seeds the child with this conversation's completed turns, so the tool says to build on them instead of demanding a fully self-contained prompt. The route is preflighted through `llm.resolveCallConfig()` before the child exists, so a typo in a role's `model` or `reasoningEffort` is reported to the delegating agent rather than thrown from inside child creation. +- **Multiple rows.** The catalog section and the diagnostic tool are named after the row (`:catalog`, `listToolName`), so a profile can mount a second row for another transport provider (`toolName: subagent_role_fork`) without either registration colliding. +- **Child prompt trim.** Core registers most tool-guidance sections as plain text — only `dsh-tool-fs`, `dsh-tool-fs-search`, `dsh-tool-web`, and `dsh-file-reference-local` evaluate the scope — so a child keeps paying for guidance whose tool the role's policy hid from it, plus the Web GUI, harness-checkout, and deliverable instructions it can never act on. One host-plane `system-prompt/assemble` listener drops exactly that dead text: `tool:` guidance for a registered tool the child cannot see, group guidance (`tool:jobs`, `tool:goal`) when every tool its own text names is invisible, and — in `full` mode, the default — the named prompt parts. The rule-derived part needs no maintenance; the named part is per-row overridable because whether a child should still see the harness-checkout or deliverable line is a deployment judgement, not a fact. One list covers both arrays on purpose: the installed core registers `context:file-reference` as a SECTION despite its name, which a contexts-only list silently let through. Measured on a real delegation: a role child's prompt went from 5,765 to 1,904 characters (−67%) while the parent's stayed byte-identical. +- **Inheritance.** A child joins its parent's agent preset, so it keeps the parent's prompt and tools except where the role's policy removes them. The role persona shadows the deployment persona prefix for that child only. +- **Tool-call budget.** One host-plane `session/event` observer per row counts the committed `tool/call` events of every child Session the row started, plus a `session/disposed` release so a finished child's record does not linger. A delegation arms a record when it starts — `0` (unlimited) arms nothing, so an unbudgeted role pays nothing. Crossing the limit delivers one plugin-attributed notice through `Agent.inject()` (which doubles as the durable audit record), and a stopping posture then ends the child either through its run signal (one-shot) or `SubagentRuntime.interrupt()` (continuable). Enforcement is gated to once per turn, so the calls a stopped batch never started cannot repeat one stop. The count is keyed by child session id, so parents, siblings, and grandchildren never share one. + +## Limitations + +- Tools registered into a child's own scope are not affected by a role's tool policy; the core applies restrictions to inherited tools only. The delegation runtime and some tool plugins register per agent, so a child can end up with a small number of tools beyond its allow list. +- Hiding a tool removes its schema and any scope-aware prompt guidance. Prompt sections with static text stay in the child's prompt — which is what `childPromptTrim` removes, and why `tools` mode needs no maintenance while `full` mode matches section names that a future core release may rename (a renamed section stops being trimmed; nothing breaks). +- A role persona replaces the deployment persona prefix for the child. The persona suffix, such as the working-directory line, is kept. +- `respectModelSelection` prefers the policy a Session captured (the same durable projection the official delegation tool writes) and falls back to the live `subagent-model-selection` setting, which is what seeds a fresh Session. A change therefore applies to Sessions that have not captured a policy yet. +- `childPromptTrim` applies to EVERY subagent assembly the host plane observes, not only to children this plugin started: the runtime records no role marker on a child, so `subagent` and counterpart rows benefit too. Tools registered in an agent's own scope (`subagent`, `list_agents`) are absent from the registry's global view, so their guidance is never trimmed — a child that really can call one keeps its instructions. +- The delegation tool declares no `timeoutMs` unless you set one; an unbounded foreground delegation can outlive the conversation that started it. Bound long runs with `timeoutMs`, `maxDepth`, or the dispatch prompt. +- The tool-call budget is enforced **reactively**: the call that crosses the limit is already in the session log, so the child is stopped before that call finishes rather than being prevented from starting it. The count itself is exact. +- A remote transport that publishes no local child agent (`SubagentRun.localAgent` is undefined, as with an out-of-process provider) runs its child outside this process, so its `tool/call` events never reach the guard: the budget can neither count nor stop that child, and the notice cannot be delivered. The plugin warns at delegation time rather than reporting a role as guarded when it is not. In-process transports are unaffected. +- `timeoutMs` and the budget are independent, and so are the ways they surface — but if a budget stop has already begun and the tool-call deadline then expires while the stopped run is still being torn down, the core's own timeout wrapper replaces the result with its `TOOL_TIMEOUT` error. The child is stopped either way; only the report can be the later guard's. +- `scope: session` enforcement is gated to once per turn: an over-budget continuable child that a parent wakes again is stopped again, but the calls a stopped batch never started do not each repeat the stop. +- Conversely, per-turn gating means a `scope: delegation` budget that has already fired stays quiet for the REST of that turn even if `used` keeps rising; the next turn starts a fresh count (and a fresh stop). +- The monitor's record table is bounded (256 entries) and evicts by **insertion order, not by use** — it is a leak backstop, not the lifecycle. Records are normally released when their child session is disposed or their delegation settles, so an eviction should only ever reach an abandoned entry; a live entry evicted under extreme churn would lose its cap silently. +- `maxToolCallsHardCap` does not bound an explicit `maxToolCalls: 0` / `defaultMaxToolCalls: 0`. `0` is the "unlimited" sentinel rather than a count, so the escape hatch outranks the ceiling by design — use the ceiling to scale back a declared number, not to forbid "unlimited". +- A role's budget is counted per child session. Two concurrent delegations of one role never share a count, and `scope: session` keeps counting across the wakes of a continuable child until the row unloads or the bounded record table evicts it. +- The per-role budget is **not** advertised in the role catalog — only `subagent_roles` reports it, so the prompt cost of a budgeted role is unchanged. +- Discovery caches are bounded (512 entries), so a very large number of distinct projects in one host process re-stats files more often than it otherwise would. Results are unaffected. +- The diagnostic script needs Node.js 22.15 or newer for multi-frame zstd decoding; the plugin itself runs on Node.js 20. + +## Development + +```sh +npm test # unit tests (node --test) +npm run lint # node --check over lib/, scripts/, test/ +node --test --experimental-test-coverage # per-file coverage +``` + +The runtime lives in `lib/`: `roles.js` (discovery and parsing), `catalog.js` (catalog text), `policy.js` (tool policies), `route.js` (LLM route), `budget.js` (tool-call budget resolution and counting), `tool.js` (delegation and diagnostic tools), `config.js` (row options), `settings.js` (the settings namespace), and `index.js` (plugin wiring). + +CI runs `npm run lint` and `npm test` on Node.js 20, 22, and 24. + +### Releasing + +1. Add a `## []` entry to `CHANGELOG.md` (written in Chinese). The publish workflow refuses to ship a version the changelog does not document. +2. `npm version ` commits the bump and creates the tag; push the commit and the tag. +3. `.github/workflows/publish.yml` then runs the tests, checks that the tag matches `package.json`, checks the changelog entry, and publishes through npm trusted publishing (OIDC) with a provenance attestation, so no long-lived token is stored in the repository. + +Register `publish.yml` as a trusted publisher on the package's npm settings page before the first automated release. + +## License + +MIT diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/README.zh.md b/.dsh/plugins/dsh-plugin-subagent-roles/README.zh.md new file mode 100644 index 00000000..db2d1061 --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/README.zh.md @@ -0,0 +1,274 @@ +# dsh-plugin-subagent-roles + +[English](README.md) | 中文 | [更新日志](CHANGELOG.md) + +[![npm](https://img.shields.io/npm/v/dsh-plugin-subagent-roles)](https://www.npmjs.com/package/dsh-plugin-subagent-roles) +[![CI](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml/badge.svg)](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml) +[![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +## 概述 + +`dsh-plugin-subagent-roles` 用文件来定义子代理角色。一个角色就是一个 Markdown 文件:frontmatter 里是显示名、路由描述、可选的模型路由、工具策略和可选的工具调用预算,正文是子代理要遵循的 persona。项目级角色放在 `<项目>/.dsh/roles/`,全局角色放在 `~/.dsh/roles/`;同 id 同时存在时项目级生效。 + +插件注册一个委派工具,并把当前工作区里的角色以一行行的紧凑目录告知主代理。委派到某个角色时,子代理带着该角色的 persona 启动,且只保留策略允许的工具——主代理的上下文里不会出现 persona 正文,没有角色文件的项目也不会看到任何目录。角色还可以限制子代理能用多少次工具:这是由框架自己的 `tool/call` 事件计数的**硬**上限,因此不肯收尾的子代理会被强制停下。 + +## 安装 + +**桌面版(DSH 桌面 App)**——在 App 侧栏的 **Plugins** 页里安装:粘包名即从 npm 拉取,粘**绝对路径**则安装本地检出。 + +``` +dsh-plugin-subagent-roles +# 或本地检出 +/path/to/dsh-plugin-subagent-roles +``` + +`desktop` 这个 profile 归 App 独占——`dsh plugin --profile desktop …` 会被明确拒绝(`profile "desktop" is managed exclusively by the Electron application`),所以桌面版走 Plugins 页。它会安装包、把 bundle 追加进 profile,随后该行会出现在设置页的清单里。宿主侧的行会即时加载;客户端界面(其它插件的侧栏/任务页/用量页)需要刷新一次页面才会出现。 + +**命令行 profile(`dsh web`、TUI、headless)**——按名字装进对应 profile,或 link 一个检出: + +```sh +# 从 npm 安装 +dsh plugin --profile web add dsh-plugin-subagent-roles + +# 或本地 checkout +dsh plugin --profile web add link:/path/to/dsh-plugin-subagent-roles +``` + +装好后重启该 profile(`dsh web`)。包内自带 bundle patch,会自行插入它的那一行组合,无需手改 composition。要求 Node.js 20 以上,以及提供 `@deepseek-ai/dsh-tools` 与 `@deepseek-ai/dsh-subagent` 的 DSH 部署。 + +**版本线**:0.5.x 只支持 **DSH 0.2.1-rc.1+**;0.2.0 及更早请继续用 0.4.3。0.2.1 移除了 `subagents.start` / `startContinuable`、请求里的 `persona` / `toolFilter` 以及客户端设置服务,0.5.0 已按新 API 重写委派与 composition,角色文件格式与模型绑定不变。 + +## 快速开始 + +在项目里创建一个角色文件: + +```markdown +--- +displayName: 代码审查员 +description: 审查改动的正确性、安全性与测试覆盖,按严重级别给出结论。 +provider: deepseek-official +model: deepseek-v4-flash +reasoningEffort: low +tools: [read, grep, glob] +--- +你是代码审查员。先读改动再下结论,区分阻塞项与建议项, +每条问题都给出文件与行号。 +``` + +然后让主代理委派——“让代码审查员角色审一下这个改动”——或直接调用工具: + +```js +subagent_role({ role: "code-reviewer", prompt: "审查已暂存的改动。", description: "审查暂存改动" }) +``` + +角色在组装提示词时读取、在委派开始时再读取一次,因此改角色文件**不需要重启 DSH**。同风格的派发提示词见 `examples/delegation-prompts.zh.md`。 + +## 角色文件 + +### 角色从哪里读取 + +| 优先级 | 路径 | 说明 | +|---|---|---| +| 1 | `<项目>/.dsh/roles/.md` | `<项目>` 是从会话工作目录向上找到的第一个含项目标记(默认 `.git`)的目录;找不到标记时就是工作目录本身。 | +| 2 | `~/.dsh/roles/.md` | 跨项目共用。可用 `dshHome` 改位置。 | + +角色文件可以是符号链接。文件按文件名寻址,因此 id 就是文件名(去掉 `.md`),必须是 kebab-case。 + +### 文件格式 + +frontmatter 是 YAML 映射,正文是 persona。 + +| 字段 | 必填 | 含义 | +|---|---|---| +| `description` | 是 | 目录里显示的一行描述,主代理据此判断要不要委派。 | +| `name` | 否 | 写了就必须与文件 id 一致,用来拦住"改了文件名却没改声明"。 | +| `displayName` | 否 | 人可读的名字,默认取 id。 | +| `whenToUse` | 否 | 追加在目录行末尾的补充路由提示。 | +| `provider`、`model` | 否 | 子代理的模型路由。两者必须同时出现或同时省略;省略时继承主代理的路由。 | +| `reasoningEffort` | 否 | 子代理的思考力度,随路由一起生效。 | +| `tools` | 否 | 允许清单简写,如 `[read, grep, glob]`。 | +| `toolFilter` | 否 | 显式策略:`{ allow: [...], deny: [...] }`。 | +| `maxToolCalls` | 否 | 子代理工具调用次数的硬上限,整数。**省略**则继承行配置的 `defaultMaxToolCalls`;写 `0` 表示**显式不限**,它会**覆盖**行默认值。 | +| `maxToolCallsScope` | 否 | `delegation`(默认)每次委派重新计数——continuable 子代理的每个 `turn/start`(即一次后台唤醒)也算新的一次;`session` 则按该子代理整个生命周期累计。 | +| `onToolCallBudget` | 否 | 额度耗尽时的行为:`wrap-up`(默认)、`interrupt` 或 `off`。 | +| `graceToolCalls` | 否 | `wrap-up` 注入通知后额外放行的调用次数,默认 `1`;`0` 表示在触发的那一次调用上直接收口。 | + +`tools` 与 `toolFilter` 只能二选一。**未知的 frontmatter 键会被拒绝**而不是忽略,避免拼写错误悄悄放宽角色的工具范围。 + +`maxToolCalls` 族字段需要**插件 ≥ 0.4.0**。旧版本完全不认识这些键,会把整个角色文件判为非法而跳过,因此**角色文件与插件版本是绑定的**:给某个角色加上额度,就意味着每个使用该工作区的机器都要升级插件。 + +persona 正文可以使用 `{{cwd}}`、`{{model}}`、`{{provider}}`——**恰好是 agent loop 注册的那三个**,由框架在子代理侧插值。部署里若另有插件注册了更多变量,可在 `personaVariables` 中列出;除此之外的任何引用都会在读取角色文件时被拒绝,因为未知变量会让**该子代理的每一轮**都抛错。引用按精确规则匹配(花括号内不能有空格);而目录字段——`description`、`displayName`、`whenToUse`——**完全不能出现 `{{`**,因为目录文本在到达模型之前同样会经过插值。 + +## 配置 + +行配置如下;在 profile patch 里按 id 覆盖即可: + +```yaml +# ~/.dsh/profiles/web/cordis.patch.yml +- id: subagent-roles + name: dsh-plugin-subagent-roles + config: + catalogDescriptionMaxLength: 120 +``` + +| 选项 | 默认 | 含义 | +|---|---|---| +| `toolName` | `subagent_role` | 模型可见的委派工具名。 | +| `subagentProvider` | `spawn` | 子代理传输 provider。 | +| `backgroundMode` | `one-shot` | `one-shot` 或 `continuable`。 | +| `enableRunInBackground` | `true` | 是否在工具上暴露 `run_in_background`。 | +| `maxDepth` | 不设 | 委派深度上限;不设则由 provider 决定。`0` 表示拒绝任何委派。 | +| `defaultRole` | 不设 | 调用未给 `role` 时使用的角色。 | +| `catalog` | `compact` | `compact` 渲染角色目录;`off` 完全不渲染。 | +| `catalogScope` | `main` | `main` 只向顶层 agent 展示角色;`all` 连子代理也展示。 | +| `catalogDescriptionMaxLength` | `160` | 目录行里每条描述的截断长度。 | +| `projectRootMarkers` | `['.git']` | 从会话工作目录向上寻找项目根的标记。 | +| `projectRootTtlMs` | `5000` | 项目根结果被信任多久后重新向上查找,好让会话运行中 `git init` 也能被发现。 | +| `dshHome` | `$DSH_HOME` 或 `~/.dsh` | 全局 `roles/` 目录所在位置。 | +| `maxBodyBytes` | `65536` | persona 体积上限,按 UTF-8 字节计。超过该值加 64 KiB frontmatter 余量的文件**在读取之前**就被拒绝。 | +| `personaVariables` | `['cwd', 'model', 'provider']` | 允许 persona 引用的提示词变量。仅当部署确实注册了更多变量时才扩充。 | +| `respectModelSelection` | `true` | 是否遵守官方 `subagent-model-selection` 允许清单:先看会话已捕获的策略,再看实时设置。 | +| `onMissingTool` | `drop` | 不可用的工具名:`drop` 告警后继续,`error` 直接拒绝委派。 | +| `timeoutMs` | 不设 | 单次前台委派的工具调用超时。不设则不限时。 | +| `defaultMaxToolCalls` | `0` | 角色文件未声明额度时使用的工具调用预算。`0` 表示不限,且**默认就是 0**:2277 个文件的大仓和一个小项目对"合理调用数"的定义不同,所以这个数字属于角色文件而不是全局硬编码。 | +| `maxToolCallsHardCap` | `0` | 角色文件不得超过的上限,防止项目侧把额度开到失去意义。`0` 表示不设上限,且**永不削顶显式的 `maxToolCalls: 0`**——"不限"是哨兵值而不是数值零。 | +| `onToolCallBudget` | `wrap-up` | 额度耗尽行为的行级默认值,可被角色文件覆盖。 | +| `graceToolCalls` | `1` | 宽限次数的行级默认值,可被角色文件覆盖。 | +| `enableListTool` | `false` | 是否注册诊断工具。 | +| `listToolName` | `subagent_roles` | 诊断工具的名字,让第二行能与之共存。 | +| `childPromptTrim` | `full` | 裁剪**子代理**提示词:`full` 丢弃子代理用不上的工具说明,外加命名过的提示词片段;`tools` 只丢前者;`off` 不注册该监听器。主代理的提示词永不改动。 | +| `childPromptTrimNames` | `['harness:source', 'app:web-surface', 'ui:deliverable-file-references', 'context:file-reference']` | `full` 模式下丢弃的提示词片段名,**section 与 context 一并匹配**。清空该列表即全部保留。 | + +## 工具策略 + +角色的策略决定子代理能看见、能调用哪些工具。`tools`(以及 `toolFilter.allow`)是允许清单:未列出的一切都会从子代理消失——schema 与对应提示词一起——调用也会被拒。`toolFilter.deny` 只移除指定工具、保留其余。条目支持通配符 `*` 与 `?`,例如 `mcp__demo__*`。 + +通配符在委派时按**主代理当时可见的工具名**展开,所以某个工具还没注册也不会让委派失败。不可用的字面名会被丢弃并告警;`onMissingTool: 'error'` 会改为直接拒绝。允许清单展开为空时会原样传下去(空允许清单 = 隐藏全部继承来的工具),而不是放开全部工具。 + +两类情况单独处理: + +- `run_code`(PTC 部署的呈现传输)永远不会进入策略:工具注册表会列出它,但核心不允许按这个名字做限制。 +- 主代理**自己作用域**里注册的工具会被父代理继承,但不属于子代理的作用域链。写出这类名字会导致核心拒绝创建子代理;插件会把这些名字剔除、重试一次委派,并告警。 + +## 工具调用预算 + +角色文件里的 `maxToolCalls` 是插件**强制执行**的硬上限,**不依赖子代理自觉**。计数取自框架自己记录的 `tool/call` 事件,既不采信子代理自报,也不解析它的输出。 + +### 什么算"一次" + +计量单位是**次**而不是**轮**——这正是当初"8 步"口头约定失效的原因: + +| 情形 | 计为 | +|---|---| +| 同一步内并行发起的多个调用 | 各计 1 | +| 调度器已落盘、随后被策略/guard 拒绝的调用 | 1 | +| 同一步中被取消而跳过的调用 | 1 | +| wrap-up 注入的收尾通知本身(是消息,不是工具调用) | 0 | +| 子代理自己再派生的孙代理 | 只计该子代理自身;每个孙代理独立计数 | + +`used === limit` **不算超限**;跨过上限的那一次才算。收口是**反应式**的:那次调用已经写进会话日志,插件是在它结束前把子代理停下。所以保证的是"子代理会停",而不是"触发的那次调用不会开始"。 + +### 额度耗尽时 + +| 模式 | 行为 | +|---|---| +| `wrap-up`(默认) | 投递一条插件署名的收尾通知("预算已耗尽,请产出部分结论"),再宽限 `graceToolCalls` 次调用,之后才停下子代理。 | +| `interrupt` | 投递**同一条**通知,并在触发的那一次调用上立即停下。 | +| `off` | 只告警一次,永不拦截——因此也**不往子会话写入任何持久记录**。 | + +`graceToolCalls: 0` 就是 `interrupt`:同一条通知、同一次调用上的同一个停止点。 + +收口机制取决于委派路径,这一点值得记住:`SubagentRuntime.interrupt()` 对 one-shot run 是**被接受的 no-op**,因此前台/后台的 one-shot 子代理是通过它启动时所用的信号被取消的,只有 `continuable` 子代理才走运行时中断。远程传输若不发布本地子代理对象,它的子代理就**跑在本进程之外**:其 `tool/call` 事件到达不了护栏,既数不到也停不下,wrap-up 通知也投递不了——插件会在委派时就告警,而不是把一个并未受保护的角色报成已受保护。 + +### 如何通知子代理与主代理 + +收尾通知是一条带**显式 `plugin` 来源**的 `user` 角色消息,通过 `Agent.inject()` 投递,因此它落在下一个 step 边界,且**不会把空闲子代理唤醒成一个新轮次**。显式来源是必须的:省略 source 会被解析成 `user`,等于让机器生成的指令冒充人类输入。 + +同一条通知就是**这次收口的持久记录**:它把 `used`/`limit`/`scope`/`mode` 写进子会话自己的日志,因此被停下的委派可以回放——**停在哪一次、还剩多少**。正因如此,它在**每一次**收口时都会投递(包括 `interrupt`),而不只是 `wrap-up`:对一个被直接杀掉的子代理,光靠宿主日志回答不了这个问题。`off` 是唯一从不收口的姿态,因此不写子会话记录。 + +被停下的**前台**委派返回一个正常的结构化结果——`status: 'tool-call-budget-exceeded'`,外加 `reason`、`role`、`used`、`limit`、`scope`、`mode` 与可能的 `partialOutput`。它**故意不是错误**:抛错会被主代理当成可重试的工具故障,而这里真正该选的是"派更窄的任务 / 放宽额度 / 接受部分结论"。**后台**委派则让 job 的 detail 明确写出预算收口,从而不会与"用户 kill"混淆。 + +`timeoutMs` 与预算是**正交**的两个护栏,谁先到就由谁出报告:预算收口是上面那个结构化结果,而超时保留核心自己的 `TOOL_TIMEOUT` 错误。两者不会被混成同一个失败。 + +## 诊断 + +打开 `enableListTool` 后会注册 `subagent_roles`:它逐个列出角色及其来源、文件路径、绑定路由、persona 体积、展开后的策略、schema 字符预算,以及**工具调用额度与它的来源**(角色文件 / 行默认 / 不限),还有被跳过的文件和原因。 + +要核对一次已完成的委派,读子代理的会话日志即可: + +```sh +node scripts/inspect-session-budget.mjs --project <项目目录> +node scripts/inspect-session-budget.mjs <会话目录> --all --grep "你是代码审查员" +``` + +该脚本只读地解码会话日志,打印系统提示体积、该会话请求的工具 schema,以及角色目录是否到达了那个会话。 + +## 设置界面 + +**DSH 0.2.1 上本插件没有 Settings 卡片**:0.2.1 移除了客户端 `settingsScope` 服务、插件可注册的设置命名空间与 `settings.plugin.item` slot。裁剪与预算的六个旋钮就是本插件的**行 config**;在 profile 的 `cordis.patch.yml` 里写在本行 `config` 下,改动后重启该 profile(行会重新激活)。 + +| 键 | 默认 | 含义 | +| --- | --- | --- | +| `childPromptTrim` | `full` | `full` / `tools` / `off` | +| `childPromptTrimNames` | 内置名单 | `full` 模式下额外丢弃的 section/context 名 | +| `defaultMaxToolCalls` | `0` | 角色文件未声明时的默认额度;0 不限 | +| `maxToolCallsHardCap` | `0` | 角色文件不得超过的硬上限;0 不设 | +| `onToolCallBudget` | `wrap-up` | `wrap-up` / `interrupt` / `off` | +| `graceToolCalls` | `1` | wrap-up 通知后的宽限调用数 | + +角色文件自己声明的 `maxToolCalls` 仍然优先;行 config 只提供「角色文件省略时的默认值」与硬上限。 + +没有 GUI 卡片是刻意的取舍:0.2.1 的插件配置页要求插件自己实现 `plugins.row.config` 组件并绑定 `configForms`。本版优先保证宿主半边的行为正确;浏览器半边仍会加载,只打印一次说明后不注册任何 slot,绝不会因为缺少服务让整行停在 `pending`。 + +## 工作原理 + +- **目录**:一个提示词 section,按每次组装求值,列出该 agent 工作区的角色:一行说明,加每个角色一行 `- (<显示名>): <描述>`。在以下情况渲染为空且不占上下文——项目没有角色、目录被关闭、当前是子代理、或该 agent 看不到委派工具。 +- **委派**:`subagent_role` 按主代理的工作目录解析角色,然后经 `ctx.subagents` 启动子代理,带上该角色的 persona、路由与工具策略。工具面向模型的说明会跟随传输 provider:fork 型 provider 的子代理已带上本会话已完成的轮次,此时说明改成「在已有轮次上继续」,而不是「必须自带完整上下文」。路由在子代理存在之前就会经 `llm.resolveCallConfig()` 预检,因此角色文件里 `model` 或 `reasoningEffort` 写错时,报错会回到主代理手上,而不是从子代理创建过程里抛出。 +- **多行共存**:目录 section 与诊断工具都按行命名(`:catalog`、`listToolName`),所以同一个 profile 可以为另一种传输 provider 再挂一行(`toolName: subagent_role_fork`),两边都不会撞名。 +- **子代理提示词裁剪**:核心把大多数工具说明注册成**静态文本**(只有 `dsh-tool-fs`、`dsh-tool-fs-search`、`dsh-tool-web`、`dsh-file-reference-local` 会按 scope 求值),于是子代理既继续为「被角色策略藏掉的工具」付说明费,也继续读它永远用不上的 Web GUI、harness checkout 与交付链接说明。一个 host 层的 `system-prompt/assemble` 监听器只丢这些死文本:子代理看不到的**已注册**工具的 `tool:` 说明;组标签说明(`tool:jobs`、`tool:goal`)在它自身文本点到的工具全部不可见时丢弃;`full` 模式(默认)再丢命名过的提示词片段。真实委派实测:角色子代理提示词 5,765 → 1,904 字符(−67%),而主代理逐字节不变。规则推导的部分无需维护;命名的那部分是逐行可覆盖的——子代理该不该继续看到 harness checkout 或交付链接属于部署判断,不是事实。**一份名单同时匹配 section 与 context 是刻意的**:实测发现当前核心把 `context:file-reference` 注册成了 section(尽管名字里有 `context:`),只匹配 context 的名单会静默放过它。 +- **继承与 composition**:不传 `agentPreset` 时子代理加入父代理的 agent preset,因此保留父代理的提示词与工具。角色 persona 与工具策略在 `subagent/start` 时安装到子上下文——该事件在宿主 materialize 内、初始 prompt 提交之前同步触发,所以首轮 assembly 就能看到它们。角色 persona 只对该子代理遮蔽部署 persona 前缀。 +- **工具调用预算**:每行一个 host 层 `session/event` 观察者,统计本行发起过的每个子会话所提交的 `tool/call` 事件;另有一个 `session/disposed` 释放钩子,避免已结束子会话的记录滞留。委派启动时登记一条记录——`0`(不限)不登记任何东西,因此没有预算的角色零成本。跨过上限时通过 `Agent.inject()` 投递一条插件署名通知(它同时就是持久审计记录),随后由收口姿态用两种机制之一结束子代理:one-shot 用其 run 信号,continuable 用 `SubagentRuntime.interrupt()`。收口按轮次限流为一次,因此被停下那一批里从未启动的调用不会把同一次停止重复一遍。计数按子会话 id 索引,父代理、兄弟与孙代理互不共享。 + +## 已知边界 + +- 子代理**自己作用域**里注册的工具不受角色工具策略影响:核心的 restrict 只作用于继承来的工具。委派运行时与部分工具插件会按 agent 注册,因此子代理可能比允许清单多出少量工具。 +- 隐藏工具会移除它的 schema 以及作用域感知的提示词段落;纯静态文本的段落仍会留在子代理提示词里——这正是 `childPromptTrim` 要处理的部分,也是 `tools` 模式无需维护、而 `full` 模式依赖 section 名的原因(未来核心改名后该段只是不再被裁剪,不会报错)。 +- 角色 persona 会替换子代理的部署 persona 前缀;persona 后缀(例如工作目录那一行)保留。 +- `respectModelSelection` 优先使用会话已捕获的策略(与官方委派工具写入的同一个持久 projection),没有捕获时才回退到实时 `subagent-model-selection` 设置——实时设置只用于给新会话播种。因此改动只对**尚未捕获策略**的会话生效。 +- `childPromptTrim` 作用于宿主所见**每一个**子代理的组装,而不只是本插件发起的角色子代理:运行时不在子代理上记录角色标记,所以 `subagent` 等其他行的子代理同样受益。注册在 agent 自身作用域里的工具(`subagent`、`list_agents`)不在注册表的全局视图里,因此它们的说明永不被裁剪——真的能调用它的子代理会保住自己的说明。 +- 委派工具默认不声明 `timeoutMs`,前台委派因此可能比发起它的对话活得更久;长任务请用 `timeoutMs`、`maxDepth` 或派发提示词约束。 +- 工具调用预算是**反应式**收口的:跨过上限的那一次调用已经写进会话日志,插件是在它结束前停下子代理,而不是阻止它开始。计数本身是精确的。 +- 远程传输若不发布本地子代理对象(`SubagentRun.localAgent` 为 `undefined`,例如进程外 provider),其子代理跑在本进程之外,`tool/call` 事件到达不了护栏:预算既数不到也停不下它,通知也投递不了。插件会在委派时告警,而不是把一个并未受保护的角色报成已受保护。进程内传输不受影响。 +- `timeoutMs` 与预算是相互独立的,但它们**呈现**结果的方式也独立——如果预算收口已经开始、而工具调用 deadline 在停止后的 run 仍在拆卸时到期,核心自己的 timeout 包装器会用 `TOOL_TIMEOUT` 错误替换掉那个结构化结果。子代理两种情况下都会被停下,只是"报告"可能归后到的那个护栏。 +- `scope: session` 的收口按轮次限流为一次:被父代理再次唤醒的、已超额的 continuable 子代理会被**再次**停下,但被停下那一批里从未启动的调用不会各自重复一遍停止。 +- 反过来,按轮次限流也意味着:`scope: delegation` 的额度一旦触发,在**该轮剩余时间里**会保持安静,即使 `used` 继续增长;下一轮重新计数(也会重新收口)。 +- 监视器的记录表有上限(256 条),淘汰顺序是**插入序而不是使用序**——它是防泄漏的兜底,不是生命周期本体。记录通常会在其子会话被 dispose、或委派结算时释放,所以淘汰理应只碰到被遗弃的条目;极端churn 下若真有活记录被淘汰,那个角色的额度会静默失效。 +- `maxToolCallsHardCap` **不会**约束显式的 `maxToolCalls: 0` / `defaultMaxToolCalls: 0`。`0` 是"不限"哨兵而不是计数,因此逃生口优先于上限——请用上限去削一个已声明的数字,而不是用它禁止"不限"。 +- 额度按子会话计数:同名角色的两个并发委派不会共享计数;`scope: session` 会跨 continuable 子代理的多次唤醒持续累计,直到插件行卸载或那个有上限的记录表把它淘汰。 +- 角色额度**不会**出现在角色目录里,只有 `subagent_roles` 会报告它,因此带预算的角色对提示词体积没有影响。 +- 发现缓存有上限(512 条),因此同一宿主进程里访问过极多不同项目时,会比其他情况更频繁地重新 stat 文件;结果不受影响。 +- 诊断脚本需要 Node.js 22.15 以上(多帧 zstd 解码);插件本身在 Node.js 20 上运行。 + +## 开发 + +```sh +npm test # 单元测试(node --test) +npm run lint # 对 lib/、scripts/、test/ 做 node --check +node --test --experimental-test-coverage # 逐文件覆盖率 +``` + +运行时在 `lib/`:`roles.js`(发现与解析)、`catalog.js`(目录文本)、`policy.js`(工具策略)、`route.js`(模型路由)、`budget.js`(工具调用预算的解析与计数)、`tool.js`(委派与诊断工具)、`config.js`(行配置)、`settings.js`(设置命名空间)、`index.js`(插件装配)。 + +CI 在 Node.js 20、22、24 上运行 `npm run lint` 与 `npm test`。 + +### 发版 + +1. 先在 `CHANGELOG.md` 补一条 `## [<版本号>]` 记录。发版工作流会拒绝发布一个更新日志里没有的版本。 +2. `npm version ` 会提交版本号变更并打 tag,推送提交与 tag。 +3. `.github/workflows/publish.yml` 会跑测试、校验 tag 与 `package.json` 版本一致、校验更新日志条目,再通过 npm trusted publishing(OIDC)发布并附带 provenance 证明,因此仓库里不保存任何长期 token。 + +首次自动发版前,需要先在 npm 的包设置页把 `publish.yml` 登记为 trusted publisher。 + +## 许可 + +MIT diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/cordis.patch.yml b/.dsh/plugins/dsh-plugin-subagent-roles/cordis.patch.yml new file mode 100644 index 00000000..f519600d --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/cordis.patch.yml @@ -0,0 +1,13 @@ +# dsh-plugin-subagent-roles bundle patch. +# +# Adds the plugin's single row. It MUST land at the PROFILE ROOT (the host +# plane): the role catalog's visibility guard reads the global tool layer, so a +# copy mounted inside an agent preset would advertise nothing. It publishes no +# service, so it needs no `isolate` realm — it only consumes the host `tools`, +# `subagents`, and `systemPrompt` registries. +# +# Install: dsh plugin --profile add link: +# Restart `dsh --profile ` after installing. +- insert: + - id: subagent-roles + name: dsh-plugin-subagent-roles diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.md b/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.md new file mode 100644 index 00000000..608dc6e2 --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.md @@ -0,0 +1,96 @@ +# Role delegation prompts (web verifier) + +English | [中文](delegation-prompts.zh.md) + +> This is a template: replace the angle-bracket placeholders with your own values. +> Roles are defined in `/.dsh/roles/.md` (frontmatter: `provider` / `model` / `reasoningEffort` / `tools` / `maxToolCalls`; body: persona). +> Editing a role file takes effect immediately — no `dsh web` restart. + +--- + +## 0. What you say to the main agent + +**Natural trigger** — the main agent picks the role from the catalog itself: + +```text +Use web-verifier to verify the changes to "": run and report against the full-coverage criteria in . Do not drive the browser yourself. +``` + +**Add boundaries when they matter:** + +```text +The verifier only verifies: it does not modify files and does not touch the backend. If a service needs a restart, you (the main agent) do that first. +``` + +--- + +## 1. Dispatch template (main agent → subagent) + +```text +TASK — state it first: verify with a real browser that still works, and report full coverage. + +TARGET +- Project root: +- Frontend directory: (dev URL ) +- Backend: — read-only for you; do not start or stop it +- Verification SOP (read it first): /.dsh/skills//SKILL.md + +STEPS +1. If the project has a lease or mutex convention for shared resources (dev servers, devices): take the lock, refresh its heartbeat after every step, and release it when done. Read-only probes need no lock. +2. Read the project's own instructions (AGENTS.md and friends) and the SOP above, then confirm service state: . +3. Run the cases: cd && . Credentials come from the project docs. +4. If the SOP asks for a "feature list → test cases" mapping table, complete it before running, and cover every interactive control on the page: search, filter and reset, every row action, and every control inside drawers and dialogs. +5. Console guard: a [Global Error] or an uncaught exception fails the run. Rate-limit noise (for example 429) may be filtered, but report it when it affects an assertion. +6. If the project is localized: switch language with the real control, assert that the interface text changes, then switch back. + +ACCEPTANCE +- The result of , plus a per-item coverage verdict (covered / not covered) in the project's own terms. +- Anything you could not cover must be listed as an explicit "not covered" item with status WAITING; "N passed" on its own is not acceptance. +- On failure, attach reproducible evidence: DOM state, logs, screenshots, or a trace path. + +FORBIDDEN +- Modifying any project file — edit/write and shell redirection are out; only the lease directory may be created. +- Starting or stopping the backend, running migrations or database resets, reading or writing the database, seeding data through curl or API calls. +- Starting another dev server or changing ports; do not bypass the project's own start script. +- Calling tools unrelated to the task (other MCP tools, delegation tools, and so on). + +REPORT: 1 what you did (start with the tool name and the target path) 2 what you observed (case names, pass/fail, coverage verdict) 3 problems and suggestions 4 status: DONE or WAITING +``` + +--- + +## 2. Budgeting a role (plugin >= 0.4.0) + +A role file may cap how many tool calls its child gets. Give a read-only explorer +enough to finish the inventory, and a run-time verifier far less — it mostly waits +on commands: + +```yaml +--- +description: Inventory a cross-cutting change (read-only) +tools: [read, grep, glob, bash] +maxToolCalls: 30 # measured in CALLS, not turns: parallel calls each count +maxToolCallsScope: delegation +onToolCallBudget: wrap-up # inject "wrap up now", then tolerate graceToolCalls more +graceToolCalls: 1 +--- + +You are a read-only explorer. Never modify a file; report findings and open questions. +``` + +Rules of thumb, from real runs (a 19-call inventory and a 25-call review both blew +through a verbal "8 steps" guard that nothing enforced): + +| Role type | Suggested `maxToolCalls` | +|---|---| +| Read-only exploration (>= 5 files) | 30–40 | +| Static review | 40–60 | +| Run-time verification (mostly commands) | 15–20 | +| Omitted or `0` | unlimited — the escape hatch for a very large repository | + +Two things worth knowing: + +- **The unit is calls, not turns.** Three parallel reads in one step are three calls, + and a call refused by policy still counts — the child already spent the decision. +- **Crossing the limit triggers**, not reaching it, and that call is stopped before it + finishes. `graceToolCalls: 0` makes `wrap-up` behave exactly like `interrupt`. diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.zh.md b/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.zh.md new file mode 100644 index 00000000..746e93ff --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/examples/delegation-prompts.zh.md @@ -0,0 +1,91 @@ +# 角色委派 prompt 模板(web 验证者) + +[English](delegation-prompts.md) | 中文 + +> 这是**模板**,尖括号处按你自己的项目替换。角色定义在 `<项目根>/.dsh/roles/.md` +> (frontmatter 是 `provider`/`model`/`reasoningEffort`/`tools`/`maxToolCalls`,正文是 persona)。 +> 角色文件改动**不需要重启 `dsh web`**(每次提示词组装按 mtime 读取)。 + +--- + +## 0. 主代理侧(你在项目会话里说的话) + +**自然触发**(主代理会照角色目录自己选角色): + +```text +用 web-verifier 验证「<页面/功能>」这次改动,跑 <你的 E2E 命令>,按 <你的验证 SOP> 的全覆盖口径给我结论;你不要自己跑浏览器。 +``` + +**想同时明确边界时**加一句: + +```text +验证者只做验证、不改文件、不碰后端;服务如果要重启由你(主代理)先做。 +``` + +--- + +## 1. web-verifier 派发模板(主代理 → 子代理) + +```text +【唯一任务】用真实浏览器验证 <页面/功能> 的这次改动是否可用,并给出全覆盖结论。 + +【目标】 +- 项目根:<项目根> +- 前端目录:<前端目录>(dev 地址 ) +- 后端:<后端地址>(你只读观察,不启停) +- 验证 SOP(先读):<项目根>/.dsh/skills/<你的验证技能>/SKILL.md + +【步骤】 +1. 若项目对共享资源(dev server、设备等)有租约/互斥约定:先按约定取锁并在每步刷新心跳,任务结束立即释放;只读探活不需要锁。 +2. 先读项目说明(AGENTS.md 之类)与上面的 SOP,确认服务状态:<状态检查命令>。 +3. 跑用例:cd <前端目录> && ;账号见项目说明。 +4. 若 SOP 要求「功能清单 → 用例」映射表:先补齐再跑,逐项覆盖页面内每个可交互控件(搜索/筛选/重置、每个行操作、弹层与抽屉内每个控件)。 +5. 浏览器 console 断言:出现 [Global Error] / 未捕获异常即判失败;限流类噪声(如 429)可过滤,但若影响断言须如实回报。 +6. 若项目支持多语言:用真实控件切换语言,断言界面文案随之变化,再切回。 + +【验收】 +- 的结果 + 按项目口径的**逐项**覆盖结论(覆盖/未覆盖) +- 覆盖不到的控件必须单列「未覆盖清单」并置 WAITING,不得以「N passed」收尾 +- 失败时附上可复现的 DOM/日志/截图或 trace 路径 + +【禁止】 +- 修改任何项目文件(edit/write/落盘全禁;仅租约协议自身的取锁目录例外) +- 启停/重启后端、跑迁移或重置数据库、直接读写数据库、用 curl/API 造数 +- 另起 dev server 或改端口;不要绕过项目的启动脚本自己拉起服务 +- 调用与本任务无关的工具(其它 MCP 工具、委派类工具等) + +【回报】1 做了什么(以「工具名 + 目标路径」开头) 2 观察结果(用例名 + passed/failed + 覆盖结论) 3 问题与建议 4 状态:DONE 或 WAITING +``` + +--- + +## 2. 给角色加上调用额度(插件 >= 0.4.0) + +角色文件可以限制子代理能用多少次工具。给只读探索者留够完成盘点的量,给运行时验证者留得少得多——后者主要在等命令返回: + +```yaml +--- +description: 盘点一次跨端改动(只读) +tools: [read, grep, glob, bash] +maxToolCalls: 30 # 单位是「次」不是「轮」:并行调用各计 1 +maxToolCallsScope: delegation +onToolCallBudget: wrap-up # 先注入「请立即收尾」,再宽限 graceToolCalls 次 +graceToolCalls: 1 +--- + +你是只读探索者。不要修改任何文件;只汇报发现与未决问题。 +``` + +依据实测的经验值(一次 19 次的盘点与一次 25 次的审查,都突破了没人强制的口头「8 步」护栏): + +| 角色类型 | 建议 `maxToolCalls` | +|---|---| +| 只读探索(>= 5 个文件) | 30–40 | +| 静态审查 | 40–60 | +| 运行时验证(以跑命令为主) | 15–20 | +| 省略或 `0` | 不限——超大仓库的逃生口 | + +两点值得记住: + +- **单位是「次」不是「轮」。** 同一步里三次并行读取就是三次;被策略拒绝的调用同样计数——那次决策已经被消耗掉了。 +- **跨过上限才触发**(等于上限不算),并且那一次调用会在结束前被停下。`graceToolCalls: 0` 让 `wrap-up` 与 `interrupt` 行为完全一致。 diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/lib/budget.js b/.dsh/plugins/dsh-plugin-subagent-roles/lib/budget.js new file mode 100644 index 00000000..a1133b29 --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/lib/budget.js @@ -0,0 +1,328 @@ +/** + * Tool-call budget: how many tool calls a role's child may make, and what + * happens when it runs out. + * + * Counting is event-sourced. The monitor folds committed `tool/call` events of + * the Sessions this plugin started — the framework records those, so the guard + * never parses model output and never trusts the child's self-report. One + * `tool/call` is one "call": parallel calls inside one step each count, and a + * call the scheduler appended before a policy denial or a post-cancellation skip + * counts too, because the model already spent that decision. + * + * The enforcement ACTION is deliberately not decided here. A delegation hands in + * `enforce` / `injectWrapUp` closures, because the three delegation routes need + * three different mechanisms: a foreground one-shot child is stopped by aborting + * the signal its run was started with, a background one-shot child by aborting + * the job's controller, and a continuable child by + * `SubagentRuntime.interrupt()` — which is documented as an accepted no-op for a + * one-shot or unknown target, so it cannot be the only mechanism. + * + * This module holds no `ctx` dependency: `observe()` is the whole seam, which + * keeps the counting rules unit-testable without a host. + */ + +/** Structured-result discriminator; mirrored by the delegation output schema. */ +export const TOOL_CALL_BUDGET_STATUS = 'tool-call-budget-exceeded' +/** Machine-readable reason, kept distinct from the core's own `TOOL_TIMEOUT`. */ +export const TOOL_CALL_BUDGET_REASON = 'tool-call-budget' +/** Default bounded size of the per-child record table. */ +const DEFAULT_MAX_RECORDS = 256 + +/** A count that is a non-negative safe integer, or undefined. */ +function asCount(value) { + return Number.isSafeInteger(value) && value >= 0 ? value : undefined +} + +/** + * Resolve one delegation's effective budget. + * + * Precedence is `role file` over `settings/row-config default`; `0` means + * unlimited and is a sentinel rather than a count, so `maxToolCallsHardCap` + * never clamps it — the escape hatch outranks the ceiling by design. + * @param options - the role, the resolved row/settings defaults, and the hard cap. + * @returns the effective policy, its provenance, and any clamp warning. + */ +export function resolveToolCallBudget(options = {}) { + const { role, defaults, hardCap } = options + const declared = asCount(role?.maxToolCalls) + const fallback = asCount(defaults?.maxToolCalls) ?? 0 + const requested = declared ?? fallback + const cap = asCount(hardCap) ?? 0 + // Name the actual source of the value being clamped: a clamped row/Settings + // default is not the role file asking for something. + const origin = declared === undefined ? 'the row/Settings default' : `role "${role?.id ?? '(unknown)'}"` + const warnings = [] + let limit = requested + if (cap > 0 && limit > cap) { + warnings.push(`${origin} asked for maxToolCalls ${limit}, over the configured maxToolCallsHardCap ${cap}; using ${cap}`) + limit = cap + } + const mode = role?.onToolCallBudget ?? defaults?.onToolCallBudget ?? 'wrap-up' + return { + limit, + scope: role?.maxToolCallsScope ?? 'delegation', + mode, + grace: asCount(role?.graceToolCalls) ?? asCount(defaults?.graceToolCalls) ?? 1, + source: declared === undefined ? (limit > 0 ? 'row-default' : 'unlimited') : (limit > 0 ? 'role' : 'unlimited'), + warnings, + } +} + +/** + * The structured, non-error value a budget-stopped delegation returns. + * + * Deliberately not thrown: a thrown error reads to the delegating agent as a + * tool fault worth retrying, which is the opposite of the intended "choose a + * smaller task, raise the budget, or accept the partial result". + * @param record - the breached budget record. + * @param partialOutput - child text preserved before the stop, when there is any. + * @returns the value the delegation output schema declares. + */ +export function toolCallBudgetFailure(record, partialOutput) { + const { limit, scope, mode } = record.policy + const used = record.usedAtBreach ?? record.used + return { + kind: 'budget-exceeded', + status: TOOL_CALL_BUDGET_STATUS, + reason: TOOL_CALL_BUDGET_REASON, + role: record.roleId, + used, + limit, + scope, + mode, + ...(typeof partialOutput === 'string' && partialOutput.length > 0 ? { partialOutput } : {}), + note: `role "${record.roleId}" used ${used} of its ${limit} tool calls (scope ${scope}, mode ${mode}) and was stopped. Re-delegate a narrower task, raise maxToolCalls in the role file, or accept the partial output.`, + } +} + +/** + * Create the per-row budget monitor. + * + * Registers ONE `session/event` observer for every child Session of the host (a + * child lives in its own context, so the observer must bypass the context filter) + * plus a `session/disposed` release, and keeps a bounded table of the delegations + * that armed it. + * @param options - the plugin `ctx` and a warning sink. + * @returns the arm/release seam, the raw `observe` fold, and a disposer. + */ +export function createToolCallBudgetMonitor(options = {}) { + const { ctx, log } = options + const maxRecords = asCount(options.maxRecords) || DEFAULT_MAX_RECORDS + const records = new Map() + + const warn = (message) => { + try { + log?.(message) + } catch { + // A warning sink that throws must not escape into the Session commit path. + } + } + + /** + * Insert a record, evicting the OLDEST INSERTION when the table is full. + * + * Not an LRU: a live record whose delegation keeps running is not re-ordered by + * use, so an eviction is a real (if remote) loss of enforcement. The table is a + * backstop against a leak, not the primary lifecycle — `release()` on disposal + * is. + */ + function remember(record) { + if (!records.has(record.childSessionId) && records.size >= maxRecords) { + for (const oldest of records.keys()) { + records.delete(oldest) + break + } + } + records.set(record.childSessionId, record) + } + + /** + * Deliver the plugin-authored notice, at most once per delegation. + * + * The notice is the DURABLE audit record: it carries `used`/`limit`/`scope`/ + * `mode` into the child Session's own log, so a stop can be replayed even when + * the child never gets another step. It is delivered on every stop, not only + * under `wrap-up`, because an interrupted child is exactly the case a bare host + * log line cannot answer "where did it stop, and how much was left". + */ + function deliverNotice(record, used) { + if (record.noticeSent === true) return + record.noticeSent = true + let delivered = false + try { + delivered = record.injectNotice?.(used) === true + } catch (error) { + warn(`[subagent-roles] role=${record.roleId} could not inject the wrap-up notice: ${String(error?.message ?? error)}`) + } + if (!delivered) { + warn(`[subagent-roles] role=${record.roleId} wrap-up notice could not be delivered (no live local child agent); the stop is recorded in this log only`) + } + } + + /** + * Report and enforce one budget stop. + * + * A delegation already being torn down is skipped: the core's own deadline and + * the budget are orthogonal guards, and each must report itself rather than the + * other's teardown being mislabelled as a budget breach. + * + * Enforcement runs at most ONCE PER TURN. A `session` budget stays breached for + * the child's whole life and is never reset, so a parent that wakes the child + * again must be able to stop it again — but a single crossing is followed by the + * calls the scheduler appends for a stopped batch, each of which is a + * `tool/call` too, and re-enforcing on those would only repeat one stop. + */ + function breach(record, used, turn) { + // The teardown predicate is what keeps the two orthogonal guards apart: when + // the core's own deadline (or a user cancel) already aborted this delegation, + // the stop is that guard's to report, not this one's. Contained because a + // bookkeeping throw in here would disable the cap for the rest of the run. + try { + if (typeof record.isTornDown === 'function' && record.isTornDown() === true) return + } catch (error) { + warn(`[subagent-roles] role=${record.roleId} could not read the teardown state: ${String(error?.message ?? error)}`) + return + } + if (turn !== undefined && record.enforcedTurn === turn) return + record.enforcedTurn = turn + // The FIRST crossing owns the reported facts; a later wake's larger count + // must not rewrite what the delegation is reported to have stopped at. + if (record.breached !== true) { + record.breached = true + record.usedAtBreach = used + } + const { limit, scope, mode } = record.policy + warn(`[subagent-roles] role=${record.roleId} tool-call budget exceeded: used=${used} limit=${limit} scope=${scope} mode=${mode}`) + deliverNotice(record, used) + try { + record.enforce?.() + } catch (error) { + warn(`[subagent-roles] role=${record.roleId} could not enforce the tool-call budget: ${String(error?.message ?? error)}`) + } + } + + /** + * Apply the pinned threshold rules to one already-counted call. + * + * `used === limit` is NOT a breach. The call that crosses the limit tells the + * child to wrap up; `wrap-up` then tolerates `grace` further calls before the + * stop, while `interrupt` stops on that same call. `grace: 0` therefore IS + * `interrupt`: the same notice and the same stop, on the same call. + */ + function onToolCall(record, used, turn) { + const { limit, mode, grace } = record.policy + if (limit <= 0 || used <= limit) return + if (mode === 'off') { + // Warn once per crossing, not once per call beyond the limit. + if (used === limit + 1) { + warn(`[subagent-roles] role=${record.roleId} tool-call budget exhausted: used=${used} limit=${limit} scope=${record.policy.scope} mode=off`) + } + return + } + if (mode === 'interrupt') { + breach(record, used, turn) + return + } + // wrap-up: tell the child first, then tolerate the grace calls. + deliverNotice(record, used) + if (used >= limit + 1 + grace) breach(record, used, turn) + } + + /** + * Fold one committed Session event. + * + * Synchronous and fully contained on purpose: this runs inside + * `Session.append()`'s commit path, so an exception escaping here would + * corrupt the very log the guard reads. + * @param session - the Session that committed the event. + * @param event - the committed event (`{ type, data, ... }`). + */ + function observe(session, event) { + try { + const id = session?.id + const record = id === undefined ? undefined : records.get(id) + if (record === undefined) return + if (event?.type === 'tool/call') { + record.used += 1 + onToolCall(record, record.used, event.data?.turn) + return + } + // A continuable child's wake opens a new turn, which is the only + // observable definition of "one count per background wake". + if (event?.type === 'turn/start' && record.policy.scope === 'delegation') { + record.used = 0 + record.noticeSent = false + // The reported latch clears with the count: a new turn IS a new delegation + // under this scope, and leaving it set would let the guard fire once per + // child session and leave every later wake unbounded. + record.breached = false + record.usedAtBreach = undefined + record.enforcedTurn = undefined + } + } catch (error) { + warn(`[subagent-roles] tool-call budget monitor failed: ${String(error?.message ?? error)}`) + } + } + + /** + * Track one delegation. Call after `start` resolves, when the child Session id + * is known — a child cannot have made a tool call before its first model + * request, which is always after `start` fulfilled. + * @param spec - child session id, role id, policy, and the enforcement + * closures: `enforce` (stop the child), `injectNotice(used)` (deliver the + * durable notice), and `isTornDown` (whether another guard already stopped it). + * @returns the record the delegation reports from. + */ + function arm(spec) { + const record = { + childSessionId: spec.childSessionId, + roleId: spec.roleId, + policy: spec.policy, + enforce: spec.enforce, + injectNotice: spec.injectNotice, + isTornDown: spec.isTornDown, + used: 0, + noticeSent: false, + breached: false, + } + remember(record) + return record + } + + /** Forget one delegation. Safe to call twice. */ + function release(childSessionId) { + records.delete(childSessionId) + } + + const detach = [] + if (typeof ctx?.on === 'function') { + // `global: true` bypasses context-filter checks; without it a child Session's + // events would never reach this host-plane row. + detach.push(ctx.on('session/event', observe, { global: true })) + // The primary lifecycle, so a dead child's record does not sit in the bounded + // table until an eviction takes a LIVE one with it. + detach.push(ctx.on('session/disposed', (session) => { + if (session?.id !== undefined) release(session.id) + }, { global: true })) + } + + return { + arm, + release, + observe, + /** Number of tracked delegations (diagnostics and tests). */ + get size() { + return records.size + }, + dispose: () => { + for (const disposer of detach) { + try { + if (typeof disposer === 'function') disposer() + } catch { + // A disposed fiber already removed the listener. + } + } + records.clear() + }, + } +} diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/lib/catalog.js b/.dsh/plugins/dsh-plugin-subagent-roles/lib/catalog.js new file mode 100644 index 00000000..6ad2677a --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/lib/catalog.js @@ -0,0 +1,55 @@ +/** + * The role catalog line — the ONLY role text that ever reaches a delegating + * agent's context. Role personas stay on disk until a delegation needs them. + * + * Kept deliberately small: one framing line naming the delegation tool, plus + * one `- id (displayName): description` line per role with the description + * capped. Every extra line here is re-sent on every request of every agent that + * sees the catalog, so the catalog spends its budget on routing information + * only. + */ + +/** Default per-role description cap inside the catalog line. */ +const DEFAULT_DESCRIPTION_MAX_LENGTH = 160 + +/** + * Collapse whitespace and truncate one description for a catalog line. + * @param value - the raw description. + * @param maxLength - the cap in characters. + * @returns the normalized, capped text. + */ +export function catalogDescription(value, maxLength = DEFAULT_DESCRIPTION_MAX_LENGTH) { + const normalized = String(value ?? '').replaceAll(/\s+/g, ' ').trim() + if (normalized.length <= maxLength) return normalized + return `${normalized.slice(0, Math.max(0, maxLength - 3))}...` +} + +/** + * Render the role catalog section text. + * @param roles - the merged role records. + * @param options - `toolName` (the configured delegation tool name) and + * `descriptionMaxLength`. + * @returns the section text, or '' when there are no roles (the section is + * then dropped by the prompt registry and costs nothing). + */ +export function renderRoleCatalog(roles, options = {}) { + const list = Array.isArray(roles) ? roles : [] + if (list.length === 0) return '' + const descriptionMaxLength = options.descriptionMaxLength ?? DEFAULT_DESCRIPTION_MAX_LENGTH + // The framing line must name the CONFIGURED tool: a renamed tool would + // otherwise send the model after a name that does not exist. The global role + // directory is described generically because `dshHome` is configurable. + const toolName = options.toolName ?? 'subagent_role' + const lines = [ + `Roles come from role files: \`.dsh/roles\` in this project, plus a global \`roles/\` directory. Delegate with \`${toolName}\`, not the generic \`subagent\`: only it applies the role persona and tool policy.`, + ] + for (const role of list) { + const named = role.displayName !== undefined && role.displayName !== role.id + // Collapse whitespace: a display name with a newline would break the + // one-line-per-role invariant of the catalog. + const label = named ? ` (${String(role.displayName).replaceAll(/\s+/g, ' ').trim()})` : '' + const extra = role.whenToUse !== undefined ? ` ${catalogDescription(role.whenToUse, descriptionMaxLength)}` : '' + lines.push(`- \`${role.id}\`${label}: ${catalogDescription(role.description, descriptionMaxLength)}${extra}`) + } + return lines.join('\n') +} diff --git a/.dsh/plugins/dsh-plugin-subagent-roles/lib/client.js b/.dsh/plugins/dsh-plugin-subagent-roles/lib/client.js new file mode 100644 index 00000000..8090ce06 --- /dev/null +++ b/.dsh/plugins/dsh-plugin-subagent-roles/lib/client.js @@ -0,0 +1,737 @@ +/** + * Browser half: the Settings → Plugins card for this plugin's trim namespace. + * + * The Plugins tab pairs every settings namespace the Host serves with a card + * registered under the SAME key (a KEYED slot: `key: `, dispatched + * with `entryKey`), so a host namespace without a card renders nothing. The tab + * lays out one flex column and nothing else — the host's contract is that "a + * plugin that ships a browser half owns its own card: chrome, controls, and + * copy" — so the collapsible header, chevron, footer, and spacing below mirror + * the host's `PluginCard`, using the host's own rules and `--dsw-alias-*` tokens. + * Two deliberate deviations: the unsaved badge is hand-drawn rather than the + * host's `Tag` primitive (that would need a non-baseline module request), and the + * failure line uses `--dsw-alias-state-error-primary` because the host's own + * `--dsw-alias-label-error` is not defined in the installed theme. + * + * Hand-written rather than bundled: the loader envelope is the whole contract, + * `react` is a baseline platform module, and the repository deliberately stays + * build-step free — `node --check` still lints it. + */ +window.__ModuleLoader__.load({ + id: 'dsh-plugin-subagent-roles', + factory: (require) => { + var module = { exports: {} } + var exports = module.exports + + const React = require('react') + + /** Settings namespace + slot key of the default row (see lib/settings.js). */ + const NAMESPACE = 'subagent-roles' + /** The trim postures the Host accepts, labelled through the locale seat. */ + const MODES = [ + { value: 'full', key: 'modeFull' }, + { value: 'tools', key: 'modeTools' }, + { value: 'off', key: 'modeOff' }, + ] + /** The tool-call budget postures. */ + const BUDGET_MODES = [ + { value: 'wrap-up', key: 'budgetWrapup' }, + { value: 'interrupt', key: 'budgetInterrupt' }, + { value: 'off', key: 'budgetOff' }, + ] + /** + * Every settings key this card edits, in render order. + * + * Declared as DATA because the card must cover the WHOLE namespace: a key the + * Host serves but this list forgets would be invisible in the UI while + * `settings.yaml` still honoured it. `test/client.test.js` pins this list + * against the settings schema exactly so that cannot happen silently. + * + * `kind` decides the control and the value conversion — `select` keeps a + * string, `list` maps text to a string array, `count` maps text to a + * non-negative integer (the Host stores a number, not a digit string). + * `fallback` answers for a missing or unusable value; the row config always + * supplies one through the `base` layer, so it is a last resort. + */ + const FIELDS = [ + { settingsKey: 'childPromptTrim', kind: 'select', options: MODES, fallback: 'full', label: 'mode', hint: 'modeHint' }, + { settingsKey: 'childPromptTrimNames', kind: 'list', fallback: [], label: 'names', hint: 'namesHint' }, + { settingsKey: 'defaultMaxToolCalls', kind: 'count', fallback: 0, label: 'maxToolCalls', hint: 'maxToolCallsHint' }, + { settingsKey: 'maxToolCallsHardCap', kind: 'count', fallback: 0, label: 'hardCap', hint: 'hardCapHint' }, + { settingsKey: 'onToolCallBudget', kind: 'select', options: BUDGET_MODES, fallback: 'wrap-up', label: 'budgetMode', hint: 'budgetModeHint' }, + { settingsKey: 'graceToolCalls', kind: 'count', fallback: 1, label: 'grace', hint: 'graceHint' }, + ] + /** The field keys the card writes through, derived so the two cannot drift. */ + const FIELD_KEYS = FIELDS.map((field) => field.settingsKey) + + /** + * Card copy, registered as this plugin's locale dictionaries so the card + * follows the Language setting like every other DSH surface. `en` doubles as + * the fallback for a deployment with no locale service. + */ + const COPY = { + en: { + title: 'Subagent roles', + description: 'Child prompt trim and the tool-call budget — subagent sessions only; the main agent prompt is never touched.', + mode: 'Mode', + modeFull: 'full — tool, surface and harness sections', + modeTools: 'tools — tool guidance only', + modeOff: 'off — disable the trim', + modeHint: 'Applies to the next child turn. "tools" keeps the Web GUI, harness-checkout, deliverable, and @-path parts.', + names: 'Dropped prompt parts', + namesHint: 'Comma-separated names, matched against sections and contexts. Empty keeps every part.', + maxToolCalls: 'Default tool-call budget', + maxToolCallsHint: 'Used when a role file declares no maxToolCalls. 0 means unlimited; a role file always wins.', + hardCap: 'Tool-call hard cap', + hardCapHint: 'Ceiling a role file cannot exceed. 0 disables the ceiling, and never clamps an "unlimited" 0.', + budgetMode: 'On budget exhaustion', + budgetWrapup: 'wrap-up — inject a notice, then allow the grace calls', + budgetInterrupt: 'interrupt — stop the child immediately', + budgetOff: 'off — warn only, never stop', + budgetModeHint: 'Counted in tool CALLS, not turns: parallel calls in one step each count.', + grace: 'Grace calls', + graceHint: 'Extra calls wrap-up tolerates after its notice. 0 stops on the crossing call itself.', + overridden: 'overridden', + unsaved: 'unsaved', + save: 'Save', + saving: 'Saving…', + discard: 'Discard', + reset: 'Reset all to deployment defaults', + resetField: 'Reset', + saved: 'saved', + saveFailed: 'save failed', + unavailable: 'settings are not served by this deployment', + expand: 'expand', + collapse: 'collapse', + }, + zh: { + title: '子代理角色', + description: '子代理提示词裁剪与工具调用预算——只作用于子代理会话,主代理提示词永不改动。', + mode: '模式', + modeFull: 'full — 工具、界面与 harness 段落一并裁剪', + modeTools: 'tools — 只裁剪工具说明', + modeOff: 'off — 关闭裁剪', + modeHint: '下一个子代理轮次即生效。"tools" 会保留 Web GUI、harness checkout、交付链接与 @路径 这几段。', + names: '丢弃的提示词片段', + namesHint: '逗号分隔的名字,section 与 context 一并匹配;清空即全部保留。', + maxToolCalls: '默认工具调用额度', + maxToolCallsHint: '角色文件未声明 maxToolCalls 时使用;0 表示不限。角色文件永远优先。', + hardCap: '工具调用硬上限', + hardCapHint: '角色文件不得超过的上限;0 表示不设上限,且永不削顶「不限」的 0。', + budgetMode: '额度耗尽时', + budgetWrapup: 'wrap-up — 先注入收尾通知,再放行 grace 次调用', + budgetInterrupt: 'interrupt — 立即中断子代理', + budgetOff: 'off — 只告警,不拦截', + budgetModeHint: '计量单位是「次」而非「轮」:同一步内并行调用分别计 1。', + grace: '宽限调用次数', + graceHint: 'wrap-up 注入通知后额外放行的调用次数;0 表示在触发的那一次调用上直接收口。', + overridden: '已覆盖', + unsaved: '未保存', + save: '保存', + saving: '保存中…', + discard: '放弃', + reset: '全部重置为部署默认', + resetField: '重置', + saved: '已保存', + saveFailed: '保存失败', + unavailable: '本部署未提供设置服务', + expand: '展开', + collapse: '收起', + }, + } + + /** English fallback for a deployment that serves no locale service. */ + const FALLBACK_T = (key) => COPY.en[key] ?? key + + /** + * Card chrome. Every declaration below is copied from the host's own + * `PluginCard.module.css` — same rules, same `--dsw-alias-*` tokens — with a + * plugin-scoped class prefix, because a client bundle may not import host + * values (bundle purity) but must not invent its own palette either. An + * earlier revision invented a `label-inverse` alias for the Save button; + * no such token exists, so the colour fell back to white over a light + * background and the label became invisible. + */ + const CSS = [ + '.dsr-card{border:.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-3);border-radius:16px;list-style:none;transition:border-color .16s,background .16s}', + '.dsr-card:hover{border-color:var(--dsw-alias-label-dimmed)}', + '.dsr-cardOpen{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}', + '.dsr-header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}', + '.dsr-header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}', + '.dsr-headText{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}', + '.dsr-name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}', + '.dsr-description{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}', + '.dsr-pending{flex:none;border:.5px solid var(--dsw-alias-border-l2);border-radius:6px;padding:1px 8px;font-size:11px;line-height:1.6;color:var(--dsw-alias-label-secondary)}', + '.dsr-chevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}', + '.dsr-chevronOpen{transform:rotate(180deg)}', + '.dsr-body{border-top:.5px solid var(--dsw-alias-border-l2);margin:0 16px;padding-bottom:8px}', + '.dsr-field{display:flex;flex-direction:column;gap:5px;padding-top:12px}', + '.dsr-labelRow{display:flex;align-items:center;justify-content:space-between;gap:8px}', + '.dsr-label{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}', + '.dsr-link{appearance:none;font:inherit;font-size:12px;line-height:1.5;cursor:pointer;border:0;background:0 0;padding:0;color:var(--dsw-alias-link)}', + '.dsr-link:disabled{opacity:.4;cursor:default}', + '.dsr-overridden{color:var(--dsw-alias-label-tertiary)}', + '.dsr-hint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5}', + '.dsr-input,.dsr-select{appearance:none;width:100%;box-sizing:border-box;font:inherit;font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-3);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:5px 10px}', + '.dsr-input:focus-visible,.dsr-select:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}', + '.dsr-input:disabled,.dsr-select:disabled{opacity:.4;cursor:default}', + '.dsr-footer{border-top:.5px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:12px 0 4px;display:flex}', + '.dsr-reset{margin-right:auto}', + '.dsr-button,.dsr-save{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}', + '.dsr-button{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0}', + '.dsr-button:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}', + '.dsr-save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}', + '.dsr-button:disabled,.dsr-save:disabled{opacity:.4;cursor:default}', + '.dsr-button:focus-visible,.dsr-save:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}', + '.dsr-status{min-width:0;flex:1;margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}', + '.dsr-statusFailed{color:var(--dsw-alias-state-error-primary)}', + ].join('') + + /** Install the stylesheet once per page, like the host's own client plugins do. */ + function installStyles() { + const tagId = 'dsh-plugin-subagent-roles/card.css' + if (typeof document === 'undefined') return + if (document.querySelector(`style[data-plugin-css=${JSON.stringify(tagId)}]`) !== null) return + const tag = document.createElement('style') + tag.dataset.plugin = 'dsh-plugin-subagent-roles' + tag.dataset.pluginCss = tagId + tag.textContent = CSS + document.head.appendChild(tag) + } + + /** Comma-joined text for the name-list field. */ + function toText(value) { + return Array.isArray(value) ? value.join(', ') : '' + } + + /** Split a staged list field back into the array the Host stores. */ + function toList(text) { + return String(text ?? '') + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + } + + /** The control text for one resolved settings value. */ + function fieldText(field, value) { + if (field.kind === 'list') return toText(value ?? field.fallback) + if (field.kind === 'count') return String(Number.isSafeInteger(value) ? value : field.fallback) + return typeof value === 'string' ? value : field.fallback + } + + /** + * The settings value one staged text stands for. + * + * A count is parsed strictly: the Host stores `z.natural()`, so "8.5", "-1", + * and "" must not become a number it would refuse. Unusable text folds to the + * field's fallback, which keeps Save from ever writing an invalid count. + */ + function fieldValue(field, text) { + if (field.kind === 'list') return toList(text) + if (field.kind === 'count') { + const trimmed = String(text ?? '').trim() + if (!/^\d+$/.test(trimmed)) return field.fallback + const parsed = Number.parseInt(trimmed, 10) + return Number.isSafeInteger(parsed) ? parsed : field.fallback + } + return text + } + + /** Whether two staged texts describe the same settings value. */ + function sameFieldValue(field, left, right) { + if (field.kind === 'list') return sameNames(left, right) + if (field.kind === 'count') return fieldValue(field, left) === fieldValue(field, right) + return left === right + } + + /** + * The writes one Save performs. + * + * A staged field is CLEARED, not written: clearing re-inherits the + * composition layer, while writing today's default would pin it as an + * override the deployment can no longer retune. A field whose staged text + * still equals the resolved value is NOT written at all — presence in the + * user layer is what marks a field overridden, so writing it would shadow a + * later deployment change to a field the user never touched. Pure, so the + * semantics are unit-testable without a DOM. + */ + function planSave(staged, shown, current) { + const steps = [] + for (const field of FIELDS) { + if (staged.includes(field.settingsKey)) { + steps.push({ kind: 'unset', field: field.settingsKey }) + continue + } + if (sameFieldValue(field, shown[field.settingsKey], current[field.settingsKey])) continue + steps.push({ kind: 'set', field: field.settingsKey, value: fieldValue(field, shown[field.settingsKey]) }) + } + return steps + } + + /** + * Apply one edit to the staged state. + * + * Editing a field also CANCELS a reset staged for it: what the user typed is + * what Save must write, and keeping the field staged would silently throw + * that edit away in favour of a clear. + * @param state - the current `draft` (or undefined), `shown`, and `staged`. + * @param field - the field being edited. + * @param next - the partial value to merge into the draft. + * @returns the next draft and staged list. + */ + function applyEdit(state, field, next) { + return { + draft: { ...(state.draft ?? state.shown), ...next }, + staged: state.staged.filter((entry) => entry !== field), + } + } + + /** Subscribe a component to one settings namespace snapshot. */ + function useSettings(scope) { + const subscribe = React.useCallback((onChange) => scope.subscribe(onChange), [scope]) + const getSnapshot = React.useCallback(() => scope.getSnapshot(), [scope]) + return React.useSyncExternalStore(subscribe, getSnapshot) + } + + /** + * One staged field: label row (with an inline reset), control, hint. + * + * The control is rendered by the caller with the id this component mints, so + * the `