feat(dsh): 门禁账本插件接入 + 角色绑定跨重启还原
二、门禁与唤醒(新插件 dsh-plugin-team-ledger 0.2.0)
宿主 Agent Teams 缺两块能力,补在独立仓
D:/Code/AI/dsh-plugin-team-ledger:
- 状态存放:<工作区>/.dsh/team/gate.jsonl 追加账本,记验收
清单、实测证据、认领历史,跨重启存活;canonical JSON +
fsync,坏尾行截断恢复。
- 唤醒模型:门禁推进后按事件计划唤醒下一责任人,借活体
Lead 作 caller 走宿主 sendMessage;无定时器;30 分钟滑动
窗口限 4 次防复活风暴。
- 验收独立性由机器强制:执行人/历史认领者不能 accept,
checklist 逐项 passed=true 缺一不可。
- team_member_revive(Lead 专用):成员模型路由死亡后的
复活通道——可换 provider/model,再经 subagents.sendMessage
冷恢复唤醒,绕过宿主 roster 的 phase=active 门禁。
二、角色绑定跨重启还原(roles fork 0.5.2)
persona 与工具白名单只有运行中 agent 的内存态,宿主重启后
冷恢复的成员既无 persona 也无白名单——实测出现 doc-writer
成员带全量工具面(qq_*/ImageGen),属静默权限放大。改为
注入成功时持久化 childId -> {roleId, cwd} 到
~/.dsh/role-inject-bindings.json,并在 agent/created 时重放。
追加 team_member_rebind 补绑定,覆盖 0.5.2 之前已存在的成员。
三、配套
- .dsh/roles 八个角色白名单加入门禁工具;AGENTS.md 委派策略
补门禁/复活/重绑三套操作口径。
- docs/环境与部署/子Agent角色自动注入实现说明.md 新增
§5.1,记录绑定机制、存量成员缺口与「成员自省不可全信」的
台架教训。
This commit is contained in:
@@ -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<path\0reason>` 改为 `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=<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:<name>` 说明——当 `<name>` 是注册表里**真实存在**的工具、而该 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: <namespace>`,由渲染层绑定 `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-<tool>`,没有卡片,直接改 `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:<x>` 的 `<x>` 当工具名,会把组标签 `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` 派生(`<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-<tool>`,没有卡片,直接改 `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-<tool>`,没有卡片,直接改 `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/<id>.md` 与 `~/.dsh/roles/<id>.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
|
||||
@@ -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.
|
||||
@@ -0,0 +1,274 @@
|
||||
# dsh-plugin-subagent-roles
|
||||
|
||||
English | [中文](README.zh.md) | [Changelog (中文)](CHANGELOG.md)
|
||||
|
||||
[](https://www.npmjs.com/package/dsh-plugin-subagent-roles)
|
||||
[](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml)
|
||||
[](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 `<project>/.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 | `<project>/.dsh/roles/<id>.md` | `<project>` 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/<id>.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 <project-dir>
|
||||
node scripts/inspect-session-budget.mjs <session-dir> --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 `- <id> (<displayName>): <description>` 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 (`<toolName>: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:<name>` 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 `## [<version>]` entry to `CHANGELOG.md` (written in Chinese). The publish workflow refuses to ship a version the changelog does not document.
|
||||
2. `npm version <patch|minor|major>` 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
|
||||
@@ -0,0 +1,274 @@
|
||||
# dsh-plugin-subagent-roles
|
||||
|
||||
[English](README.md) | 中文 | [更新日志](CHANGELOG.md)
|
||||
|
||||
[](https://www.npmjs.com/package/dsh-plugin-subagent-roles)
|
||||
[](https://github.com/troytse/dsh-plugin-subagent-roles/actions/workflows/ci.yml)
|
||||
[](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/<id>.md` | `<项目>` 是从会话工作目录向上找到的第一个含项目标记(默认 `.git`)的目录;找不到标记时就是工作目录本身。 |
|
||||
| 2 | `~/.dsh/roles/<id>.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 工作区的角色:一行说明,加每个角色一行 `- <id> (<显示名>): <描述>`。在以下情况渲染为空且不占上下文——项目没有角色、目录被关闭、当前是子代理、或该 agent 看不到委派工具。
|
||||
- **委派**:`subagent_role` 按主代理的工作目录解析角色,然后经 `ctx.subagents` 启动子代理,带上该角色的 persona、路由与工具策略。工具面向模型的说明会跟随传输 provider:fork 型 provider 的子代理已带上本会话已完成的轮次,此时说明改成「在已有轮次上继续」,而不是「必须自带完整上下文」。路由在子代理存在之前就会经 `llm.resolveCallConfig()` 预检,因此角色文件里 `model` 或 `reasoningEffort` 写错时,报错会回到主代理手上,而不是从子代理创建过程里抛出。
|
||||
- **多行共存**:目录 section 与诊断工具都按行命名(`<toolName>: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:<name>` 说明;组标签说明(`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 <patch|minor|major>` 会提交版本号变更并打 tag,推送提交与 tag。
|
||||
3. `.github/workflows/publish.yml` 会跑测试、校验 tag 与 `package.json` 版本一致、校验更新日志条目,再通过 npm trusted publishing(OIDC)发布并附带 provenance 证明,因此仓库里不保存任何长期 token。
|
||||
|
||||
首次自动发版前,需要先在 npm 的包设置页把 `publish.yml` 登记为 trusted publisher。
|
||||
|
||||
## 许可
|
||||
|
||||
MIT
|
||||
@@ -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 <name> add link:<absolute checkout path>
|
||||
# Restart `dsh --profile <name>` after installing.
|
||||
- insert:
|
||||
- id: subagent-roles
|
||||
name: dsh-plugin-subagent-roles
|
||||
@@ -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 `<project>/.dsh/roles/<id>.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 "<page/feature>": run <your E2E command> and report against the full-coverage criteria in <your verification SOP>. 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 <page/feature> still works, and report full coverage.
|
||||
|
||||
TARGET
|
||||
- Project root: <project root>
|
||||
- Frontend directory: <frontend directory> (dev URL <dev URL>)
|
||||
- Backend: <backend URL> — read-only for you; do not start or stop it
|
||||
- Verification SOP (read it first): <project root>/.dsh/skills/<your verification skill>/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: <status command>.
|
||||
3. Run the cases: cd <frontend directory> && <E2E command>. 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 <E2E command>, 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`.
|
||||
@@ -0,0 +1,91 @@
|
||||
# 角色委派 prompt 模板(web 验证者)
|
||||
|
||||
[English](delegation-prompts.md) | 中文
|
||||
|
||||
> 这是**模板**,尖括号处按你自己的项目替换。角色定义在 `<项目根>/.dsh/roles/<id>.md`
|
||||
> (frontmatter 是 `provider`/`model`/`reasoningEffort`/`tools`/`maxToolCalls`,正文是 persona)。
|
||||
> 角色文件改动**不需要重启 `dsh web`**(每次提示词组装按 mtime 读取)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 主代理侧(你在项目会话里说的话)
|
||||
|
||||
**自然触发**(主代理会照角色目录自己选角色):
|
||||
|
||||
```text
|
||||
用 web-verifier 验证「<页面/功能>」这次改动,跑 <你的 E2E 命令>,按 <你的验证 SOP> 的全覆盖口径给我结论;你不要自己跑浏览器。
|
||||
```
|
||||
|
||||
**想同时明确边界时**加一句:
|
||||
|
||||
```text
|
||||
验证者只做验证、不改文件、不碰后端;服务如果要重启由你(主代理)先做。
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. web-verifier 派发模板(主代理 → 子代理)
|
||||
|
||||
```text
|
||||
【唯一任务】用真实浏览器验证 <页面/功能> 的这次改动是否可用,并给出全覆盖结论。
|
||||
|
||||
【目标】
|
||||
- 项目根:<项目根>
|
||||
- 前端目录:<前端目录>(dev 地址 <dev 地址>)
|
||||
- 后端:<后端地址>(你只读观察,不启停)
|
||||
- 验证 SOP(先读):<项目根>/.dsh/skills/<你的验证技能>/SKILL.md
|
||||
|
||||
【步骤】
|
||||
1. 若项目对共享资源(dev server、设备等)有租约/互斥约定:先按约定取锁并在每步刷新心跳,任务结束立即释放;只读探活不需要锁。
|
||||
2. 先读项目说明(AGENTS.md 之类)与上面的 SOP,确认服务状态:<状态检查命令>。
|
||||
3. 跑用例:cd <前端目录> && <E2E 命令>;账号见项目说明。
|
||||
4. 若 SOP 要求「功能清单 → 用例」映射表:先补齐再跑,逐项覆盖页面内每个可交互控件(搜索/筛选/重置、每个行操作、弹层与抽屉内每个控件)。
|
||||
5. 浏览器 console 断言:出现 [Global Error] / 未捕获异常即判失败;限流类噪声(如 429)可过滤,但若影响断言须如实回报。
|
||||
6. 若项目支持多语言:用真实控件切换语言,断言界面文案随之变化,再切回。
|
||||
|
||||
【验收】
|
||||
- <E2E 命令> 的结果 + 按项目口径的**逐项**覆盖结论(覆盖/未覆盖)
|
||||
- 覆盖不到的控件必须单列「未覆盖清单」并置 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` 行为完全一致。
|
||||
@@ -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()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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: <namespace>`, 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 `<label htmlFor>` association is real rather than implied by nesting.
|
||||
*/
|
||||
function Field(props) {
|
||||
const id = React.useId()
|
||||
const resettable = props.onReset !== undefined
|
||||
return React.createElement(
|
||||
'div',
|
||||
{ className: 'dsr-field' },
|
||||
React.createElement(
|
||||
'span',
|
||||
{ className: 'dsr-labelRow' },
|
||||
React.createElement(
|
||||
'label',
|
||||
{ className: 'dsr-label', htmlFor: id },
|
||||
props.label,
|
||||
props.overridden
|
||||
? React.createElement('span', { className: 'dsr-overridden' }, ` · ${props.t('overridden')}`)
|
||||
: null,
|
||||
),
|
||||
resettable
|
||||
? React.createElement(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'dsr-link',
|
||||
disabled: props.disabled === true,
|
||||
onClick: props.onReset,
|
||||
},
|
||||
props.t('resetField'),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
props.renderControl(id),
|
||||
props.hint === undefined ? null : React.createElement('span', { className: 'dsr-hint' }, props.hint),
|
||||
)
|
||||
}
|
||||
|
||||
/** A 14px chevron that rotates with the card, matching the host's icon. */
|
||||
function Chevron(props) {
|
||||
return React.createElement(
|
||||
'svg',
|
||||
{
|
||||
className: `dsr-chevron${props.open ? ' dsr-chevronOpen' : ''}`,
|
||||
width: 14,
|
||||
height: 14,
|
||||
viewBox: '0 0 14 14',
|
||||
'aria-hidden': 'true',
|
||||
},
|
||||
React.createElement('path', {
|
||||
d: 'M3.5 5.25 7 8.75l3.5-3.5',
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
strokeWidth: 1.4,
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether two staged lists describe the same names, in the same order. */
|
||||
function sameNames(left, right) {
|
||||
const a = toList(left)
|
||||
const b = toList(right)
|
||||
return a.length === b.length && a.every((entry, index) => entry === b[index])
|
||||
}
|
||||
|
||||
/**
|
||||
* The card: host-shaped collapsible chrome over a staged form.
|
||||
*
|
||||
* Follows the host's editing conventions: every control renders staged text,
|
||||
* nothing is written before Save, Discard drops the drafts, a reset STAGES
|
||||
* the composed default (it does not write, and it does not silently discard
|
||||
* the other field's draft), a clean save collapses the card, and a failed
|
||||
* save keeps the drafts open for correction.
|
||||
*/
|
||||
function TrimSettingsCard(props) {
|
||||
const scope = props.scope
|
||||
// The renderer binds `t` to the locale namespace this card declares; the
|
||||
// plugin's own binding (or its English dictionary) answers otherwise.
|
||||
const t = typeof props.t === 'function' ? props.t : props.fallbackT ?? FALLBACK_T
|
||||
const snapshot = useSettings(scope)
|
||||
const value = snapshot.value ?? {}
|
||||
const user = snapshot.user ?? {}
|
||||
const base = snapshot.base ?? {}
|
||||
const writable = snapshot.writable === true
|
||||
const [open, setOpen] = React.useState(false)
|
||||
// `undefined` means "not editing yet": the draft then follows the Host.
|
||||
const [draft, setDraft] = React.useState(undefined)
|
||||
// Fields staged for a reset: Save CLEARS them so they re-inherit.
|
||||
const [staged, setStaged] = React.useState(() => [])
|
||||
const [status, setStatus] = React.useState('idle')
|
||||
const [errorText, setErrorText] = React.useState('')
|
||||
const [busy, setBusy] = React.useState(false)
|
||||
const savingRef = React.useRef(false)
|
||||
|
||||
// Every field renders staged TEXT; the settings value is derived on save.
|
||||
// `base` is the deployment's row config (the namespace's base layer), so a
|
||||
// reset stages the DEPLOYMENT default rather than today's resolved value.
|
||||
const baseText = {}
|
||||
const currentText = {}
|
||||
for (const field of FIELDS) {
|
||||
baseText[field.settingsKey] = fieldText(field, base[field.settingsKey])
|
||||
currentText[field.settingsKey] = fieldText(field, value[field.settingsKey] ?? base[field.settingsKey])
|
||||
}
|
||||
const shown = draft ?? currentText
|
||||
const overridden = (field) => Object.hasOwn(user, field)
|
||||
const dirty = staged.length > 0 || (draft !== undefined
|
||||
&& FIELDS.some((field) => !sameFieldValue(field, shown[field.settingsKey], currentText[field.settingsKey])))
|
||||
const patch = (field, next) => {
|
||||
const edited = applyEdit({ draft, shown, staged }, field, next)
|
||||
setDraft(edited.draft)
|
||||
setStaged(edited.staged)
|
||||
}
|
||||
const stageReset = (field, text) => {
|
||||
setStaged((previous) => (previous.includes(field) ? previous : [...previous, field]))
|
||||
setDraft({ ...shown, [field]: text })
|
||||
}
|
||||
|
||||
// The host collapses a card once its save settles clean.
|
||||
React.useEffect(() => {
|
||||
if (busy || status !== 'saved') return
|
||||
setOpen(false)
|
||||
}, [busy, status])
|
||||
|
||||
const resetDrafts = () => {
|
||||
setDraft(undefined)
|
||||
setStaged([])
|
||||
setStatus('idle')
|
||||
setErrorText('')
|
||||
}
|
||||
|
||||
const write = (operations) => {
|
||||
// `busy` is state and lands a render later, so a fast double-click could
|
||||
// start two write sequences; the ref closes that window.
|
||||
if (savingRef.current) return
|
||||
savingRef.current = true
|
||||
setBusy(true)
|
||||
setStatus('idle')
|
||||
setErrorText('')
|
||||
Promise.resolve()
|
||||
.then(operations)
|
||||
.then(() => {
|
||||
// The namespace snapshot is authoritative again once the write
|
||||
// lands; keeping the drafts would leave the card marked unsaved.
|
||||
setDraft(undefined)
|
||||
setStaged([])
|
||||
setStatus('saved')
|
||||
})
|
||||
.catch((error) => {
|
||||
setErrorText(String(error?.message ?? error))
|
||||
setStatus('failed')
|
||||
})
|
||||
.finally(() => {
|
||||
savingRef.current = false
|
||||
setBusy(false)
|
||||
})
|
||||
}
|
||||
|
||||
const save = () => write(async () => {
|
||||
for (const step of planSave(staged, shown, currentText)) {
|
||||
if (step.kind === 'unset') await scope.unset(step.field)
|
||||
else await scope.set(step.field, step.value)
|
||||
}
|
||||
})
|
||||
|
||||
/** The control one field's `kind` calls for. */
|
||||
const renderControl = (field, id) => {
|
||||
if (field.kind === 'select') {
|
||||
return React.createElement(
|
||||
'select',
|
||||
{
|
||||
id,
|
||||
className: 'dsr-select',
|
||||
disabled: !writable || busy,
|
||||
value: shown[field.settingsKey],
|
||||
onChange: (event) => patch(field.settingsKey, { [field.settingsKey]: event.target.value }),
|
||||
},
|
||||
...field.options.map((option) => React.createElement('option', { key: option.value, value: option.value }, t(option.key))),
|
||||
)
|
||||
}
|
||||
return React.createElement('input', {
|
||||
id,
|
||||
className: 'dsr-input',
|
||||
disabled: !writable || busy,
|
||||
...(field.kind === 'count' ? { inputMode: 'numeric' } : {}),
|
||||
value: shown[field.settingsKey],
|
||||
onChange: (event) => patch(field.settingsKey, { [field.settingsKey]: event.target.value }),
|
||||
})
|
||||
}
|
||||
|
||||
const title = t('title')
|
||||
const blocked = !writable || busy || !dirty
|
||||
|
||||
return React.createElement(
|
||||
'li',
|
||||
{ className: `dsr-card${open ? ' dsr-cardOpen' : ''}` },
|
||||
React.createElement(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'dsr-header',
|
||||
'aria-expanded': open,
|
||||
'aria-label': `${t(open ? 'collapse' : 'expand')}: ${title}`,
|
||||
onClick: () => {
|
||||
// A fresh look at an expanded card should not show the previous
|
||||
// save's confirmation.
|
||||
if (!open) setStatus('idle')
|
||||
setOpen(!open)
|
||||
},
|
||||
},
|
||||
React.createElement(
|
||||
'span',
|
||||
{ className: 'dsr-headText' },
|
||||
React.createElement('span', { className: 'dsr-name' }, title),
|
||||
React.createElement('span', { className: 'dsr-description' }, t('description')),
|
||||
),
|
||||
dirty ? React.createElement('span', { className: 'dsr-pending' }, t('unsaved')) : null,
|
||||
React.createElement(Chevron, { open }),
|
||||
),
|
||||
!open
|
||||
? null
|
||||
: React.createElement(
|
||||
'div',
|
||||
{ className: 'dsr-body' },
|
||||
...FIELDS.map((field) => React.createElement(Field, {
|
||||
key: field.settingsKey,
|
||||
t,
|
||||
label: t(field.label),
|
||||
overridden: overridden(field.settingsKey),
|
||||
disabled: !writable || busy,
|
||||
hint: t(field.hint),
|
||||
...(overridden(field.settingsKey) || staged.includes(field.settingsKey)
|
||||
? { onReset: () => stageReset(field.settingsKey, baseText[field.settingsKey]) }
|
||||
: {}),
|
||||
renderControl: (id) => renderControl(field, id),
|
||||
})),
|
||||
React.createElement(
|
||||
'div',
|
||||
{ className: 'dsr-footer' },
|
||||
React.createElement(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'dsr-button dsr-reset',
|
||||
disabled: !writable || busy,
|
||||
onClick: () => {
|
||||
setStaged([...FIELD_KEYS])
|
||||
setDraft({ ...baseText })
|
||||
},
|
||||
},
|
||||
t('reset'),
|
||||
),
|
||||
status === 'saved'
|
||||
? React.createElement('p', { className: 'dsr-status', role: 'status' }, t('saved'))
|
||||
: null,
|
||||
status === 'failed'
|
||||
? React.createElement('p', { className: 'dsr-status dsr-statusFailed', role: 'status' }, `${t('saveFailed')}: ${errorText}`)
|
||||
: null,
|
||||
// Reachable even for a dispatched namespace: a connection that keeps
|
||||
// preferences process-local reports `unavailable`.
|
||||
snapshot.status === 'unavailable'
|
||||
? React.createElement('p', { className: 'dsr-status', role: 'status' }, t('unavailable'))
|
||||
: null,
|
||||
React.createElement(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'dsr-button',
|
||||
disabled: !dirty || busy,
|
||||
onClick: resetDrafts,
|
||||
},
|
||||
t('discard'),
|
||||
),
|
||||
React.createElement(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'dsr-button dsr-save',
|
||||
disabled: blocked,
|
||||
onClick: save,
|
||||
},
|
||||
busy ? t('saving') : t('save'),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this page already applied the plugin.
|
||||
*
|
||||
* A duplicated client injection (the module factory executing twice in one
|
||||
* page lifetime) would otherwise register the card twice under the same
|
||||
* namespace key. The claim is released when the fiber unloads, so a rebuilt
|
||||
* bundle can claim the page again.
|
||||
*/
|
||||
/** The context that owns the mounted card; compare it to survive HMR re-apply. */
|
||||
let claimOwner
|
||||
/** Latched so a build without the service explains itself once, not per reload. */
|
||||
let reportedMissingScope = false
|
||||
|
||||
/**
|
||||
* Register the card under the key the Plugins tab dispatches.
|
||||
*
|
||||
* `settings.plugin.item` is a KEYED slot: the tab renders it once per served
|
||||
* namespace with `entryKey: ns`, and cards claim a namespace with `key`. An
|
||||
* `id` (the LIST-slot field) silently renders nothing.
|
||||
*
|
||||
* `settingsScope` exists only on pre-0.2.0 builds. 0.2.0 removed the client
|
||||
* settings-scope service along with plugin-registered settings namespaces,
|
||||
* and a row that still waits for it never activates — which fails the WHOLE
|
||||
* web boot, not just this card. So the service is optional here: without it
|
||||
* the card stands down and the Host half (role catalog, per-role tool
|
||||
* gating, the tool-call budget) keeps working off the row config.
|
||||
* @param ctx - client root context (services: slots; settingsScope on < 0.2.0).
|
||||
*/
|
||||
/**
|
||||
* Read the legacy settings-scope service when this build serves one.
|
||||
*
|
||||
* Never throws: a context that refuses an uninjected service must not cost
|
||||
* the boot, and a build that serves no such service is the 0.2.0 norm.
|
||||
* @param ctx - client root context.
|
||||
* @returns the service, or undefined on a build that does not serve it.
|
||||
*/
|
||||
function readSettingsScope(ctx) {
|
||||
try {
|
||||
const service = ctx.settingsScope
|
||||
return typeof service?.bind === 'function' ? service : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount the card for the context claiming the page.
|
||||
* @param ctx - the context claiming the page.
|
||||
* @param settingsScope - the service the card binds its namespace to.
|
||||
*/
|
||||
function mountCard(ctx, settingsScope) {
|
||||
if (claimOwner !== undefined) return
|
||||
claimOwner = ctx
|
||||
ctx.effect(() => () => {
|
||||
// Only the owner may release the claim: an HMR disposer that runs after
|
||||
// the replacement claimed the page must not clear the NEW claim.
|
||||
if (claimOwner === ctx) claimOwner = undefined
|
||||
}, 'subagent-roles: apply claim')
|
||||
installStyles()
|
||||
const scope = settingsScope.bind({ namespace: NAMESPACE })
|
||||
// The card follows the Language setting: register this plugin's
|
||||
// dictionaries, declare the locale namespace so the renderer binds `t`,
|
||||
// and keep our own binding as the fallback prop.
|
||||
let localeField = {}
|
||||
let fallbackT = FALLBACK_T
|
||||
try {
|
||||
const locale = ctx.get('locale')
|
||||
if (locale !== undefined && typeof locale.register === 'function') {
|
||||
ctx.effect(() => locale.register(NAMESPACE, COPY), 'subagent-roles: card copy')
|
||||
localeField = { locale: NAMESPACE }
|
||||
if (typeof locale.bind === 'function') fallbackT = locale.bind(NAMESPACE)
|
||||
}
|
||||
} catch {
|
||||
// No locale service: the English dictionary answers.
|
||||
}
|
||||
// The fiber owns the inject disposer, so a throwing seam leaves no orphan
|
||||
// registration behind and the card cannot outlive its context.
|
||||
ctx.effect(() => ctx.slots.inject('settings.plugin.item', () => {
|
||||
try {
|
||||
const unregister = ctx.slots.register({
|
||||
name: 'settings.plugin.item',
|
||||
key: NAMESPACE,
|
||||
...localeField,
|
||||
inject: () => ({ scope, fallbackT }),
|
||||
}, TrimSettingsCard)
|
||||
return () => unregister()
|
||||
} catch (error) {
|
||||
// A deployment without the settings extension point keeps the Host
|
||||
// side only; the card must never break the browser boot.
|
||||
console.warn(`[subagent-roles] settings card not registered: ${String(error?.message ?? error)}`)
|
||||
return () => {}
|
||||
}
|
||||
}), 'subagent-roles: settings card')
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim the Plugins card for this context, or wait for the service to appear.
|
||||
*
|
||||
* `settingsScope` is NOT a declared dependency: 0.2.0 removed it, and a row
|
||||
* that waits for it never activates — which fails the whole web boot, not
|
||||
* just this card. On pre-0.2.0 builds the client settings plugin may also
|
||||
* activate AFTER this one, so a one-shot read is not enough either; the
|
||||
* registration event is the wait, and unlike a pending `inject` it owns no
|
||||
* fiber for a boot check to count.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
function apply(ctx) {
|
||||
const available = readSettingsScope(ctx)
|
||||
if (available !== undefined) {
|
||||
mountCard(ctx, available)
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (typeof ctx.on === 'function') {
|
||||
const off = ctx.on('internal/service', (name) => {
|
||||
if (name !== 'settingsScope') return
|
||||
const arrived = readSettingsScope(ctx)
|
||||
if (arrived === undefined) return
|
||||
try {
|
||||
off?.()
|
||||
} catch {
|
||||
// A throwing disposer must not cost the card it just unblocked.
|
||||
}
|
||||
mountCard(ctx, arrived)
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// A client context without registration events simply keeps the row config.
|
||||
}
|
||||
if (!reportedMissingScope) {
|
||||
reportedMissingScope = true
|
||||
console.info('[subagent-roles] no settings card on this build: DSH 0.2.1 removed the client settings service and the settings.plugin.item slot. '
|
||||
+ 'The trim and tool-call budget knobs are the plugin row config — edit them in the profile patch.')
|
||||
}
|
||||
}
|
||||
|
||||
exports.apply = apply
|
||||
exports.inject = ['slots']
|
||||
/**
|
||||
* Pure pieces, exposed for this package's Node smoke test only. The browser
|
||||
* loader reads `apply`/`inject` and ignores everything else, and no DOM is
|
||||
* needed to pin these.
|
||||
*/
|
||||
exports.__internals = {
|
||||
planSave, applyEdit, sameNames, toList, toText, COPY, CSS,
|
||||
NAMESPACE, FIELDS, FIELD_KEYS, fieldText, fieldValue, sameFieldValue,
|
||||
}
|
||||
return module.exports
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Cordis composition-entry Config for `subagent-roles`.
|
||||
*
|
||||
* Every knob is a plugin-row concern; per-role facts (route, tools, persona)
|
||||
* live in the role FILES, never here. Defaults are the recommended values, so
|
||||
* a deployment normally mounts the row with no config at all.
|
||||
*/
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { DEFAULT_CHILD_NAMES } from './trim.js'
|
||||
import { PERSONA_VARIABLES } from './roles.js'
|
||||
|
||||
/** Schemastery schema for the row config. */
|
||||
export const Config = z.object({
|
||||
/** Model-facing delegation tool name (kept as `subagent_role` for compatibility). */
|
||||
toolName: z.string().min(1).default('subagent_role'),
|
||||
/** Subagent transport provider registered on `ctx.subagents`. */
|
||||
subagentProvider: z.string().min(1).default('spawn'),
|
||||
/** Background mode: one-shot waits for the result; continuable returns the durable child id. */
|
||||
backgroundMode: z.union(['one-shot', 'continuable']).default('one-shot'),
|
||||
/** Whether the tool exposes `run_in_background`. */
|
||||
enableRunInBackground: z.boolean().default(true),
|
||||
/**
|
||||
* Optional numeric delegation-depth cap; omit for provider-managed. Note that
|
||||
* `0` is accepted and means "no delegation at all": a child's depth starts at
|
||||
* 1, so the core rejects every start with a depth error.
|
||||
*/
|
||||
maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const('provider-managed')]),
|
||||
/** Role id used when a call omits `role`. */
|
||||
defaultRole: z.string(),
|
||||
/** `compact` renders the role catalog section; `off` renders nothing. */
|
||||
catalog: z.union(['compact', 'off']).default('compact'),
|
||||
/** `main` advertises roles to top-level agents only; `all` includes subagents. */
|
||||
catalogScope: z.union(['main', 'all']).default('main'),
|
||||
/** Per-role description cap inside the catalog line. */
|
||||
catalogDescriptionMaxLength: z.natural().min(16).default(160),
|
||||
/** Project-root markers searched upward from the session cwd. */
|
||||
projectRootMarkers: z.array(z.string()).default(['.git']),
|
||||
/**
|
||||
* How long a resolved project root is trusted before the tree is re-walked, in
|
||||
* milliseconds. Bounded so a `git init` under a live session is noticed.
|
||||
*/
|
||||
projectRootTtlMs: z.natural().default(5000),
|
||||
/** Harness home holding the global `roles/` directory. */
|
||||
dshHome: z.string(),
|
||||
/** Persona size guard, in bytes. */
|
||||
maxBodyBytes: z.natural().min(1).default(65536),
|
||||
/**
|
||||
* Prompt variables a persona body may reference. Defaults to the three the
|
||||
* agent loop registers (`cwd`, `model`, `provider`); extend this only when the
|
||||
* deployment really registers more, because an unknown reference throws on
|
||||
* EVERY turn of the child that uses it.
|
||||
*/
|
||||
personaVariables: z.array(z.string()).default([...PERSONA_VARIABLES]),
|
||||
/** Honor the official `subagent-model-selection` authorized model list. */
|
||||
respectModelSelection: z.boolean().default(true),
|
||||
/** Unknown-filter-name posture: `drop` warns and continues, `error` refuses before starting. */
|
||||
onMissingTool: z.union(['drop', 'error']).default('drop'),
|
||||
/**
|
||||
* Tool-call deadline for one foreground delegation, in milliseconds. Unset
|
||||
* leaves the call unbounded; a background delegation returns immediately and is
|
||||
* never subject to it.
|
||||
*/
|
||||
timeoutMs: z.natural().min(1),
|
||||
/**
|
||||
* Tool calls a child may make when its role file declares no `maxToolCalls`.
|
||||
* `0` means unlimited, and stays the default on purpose: 2,277 files and 26k
|
||||
* symbols do not define "a reasonable call count" the way a small project
|
||||
* does, so the budget belongs in the role file rather than in a global number
|
||||
* baked in here.
|
||||
*/
|
||||
defaultMaxToolCalls: z.natural().default(0),
|
||||
/**
|
||||
* Ceiling a role file may not exceed, so a project cannot open a budget to a
|
||||
* meaningless size. `0` disables the ceiling — and deliberately does NOT clamp
|
||||
* a `maxToolCalls: 0` "unlimited" declaration, which is a sentinel rather than
|
||||
* a count.
|
||||
*/
|
||||
maxToolCallsHardCap: z.natural().default(0),
|
||||
/** What happens when a child exhausts its tool-call budget; a role file may override. */
|
||||
onToolCallBudget: z.union(['interrupt', 'wrap-up', 'off']).default('wrap-up'),
|
||||
/** Extra tool calls `wrap-up` tolerates after injecting its wrap-up notice. */
|
||||
graceToolCalls: z.natural().default(1),
|
||||
/** Opt-in `subagent_roles` diagnostic tool. */
|
||||
enableListTool: z.boolean().default(false),
|
||||
/** Name of the diagnostic tool, so a second row can coexist with the first. */
|
||||
listToolName: z.string().min(1).default('subagent_roles'),
|
||||
/**
|
||||
* Child-prompt trimming. Core registers most tool-guidance sections as plain
|
||||
* text, 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. `full` (the default) drops all of that: `tool:<name>`
|
||||
* guidance for a registered tool the child cannot call, group guidance whose
|
||||
* tools are all invisible there, and the named prompt parts below. `tools`
|
||||
* keeps the named parts; `off` disables the listener. Only SUBAGENT
|
||||
* assemblies are touched — a top-level agent's prompt is left exactly as
|
||||
* composed.
|
||||
*/
|
||||
childPromptTrim: z.union(['off', 'tools', 'full']).default('full'),
|
||||
/**
|
||||
* Prompt parts `full` mode drops from a child prompt, matched against sections
|
||||
* AND contexts (core registers `context:file-reference` as a section despite
|
||||
* its name). Defaults are the four core parts registered without a scope
|
||||
* guard; a renamed part simply stops being trimmed, which is the safe
|
||||
* direction. Empty the list to keep them all — one deployment may want the
|
||||
* harness-checkout line in its children.
|
||||
*/
|
||||
childPromptTrimNames: z.array(z.string()).default([...DEFAULT_CHILD_NAMES]),
|
||||
})
|
||||
@@ -0,0 +1,539 @@
|
||||
/**
|
||||
* `subagent-roles` — file-defined subagent roles for DeepSeek Harness.
|
||||
*
|
||||
* Host-plane plugin row (a profile bundle). It publishes no service, so it
|
||||
* needs no `isolate` realm; it consumes the host `tools`, `subagents`, and
|
||||
* `systemPrompt` registries.
|
||||
*
|
||||
* Three contributions:
|
||||
* 1. a scope-aware role catalog section (compact; empty when a project has no
|
||||
* roles, when the delegation tool is not visible to that agent, or when
|
||||
* the catalog is switched off);
|
||||
* 2. the `subagent_role` delegation tool, which applies the role persona and
|
||||
* the role's tool policy to the child;
|
||||
* 3. an opt-in `subagent_roles` diagnostic tool.
|
||||
*
|
||||
* Role definitions live in FILES: `<projectRoot>/.dsh/roles/<id>.md` (project)
|
||||
* and `~/.dsh/roles/<id>.md` (global), project winning on id collision.
|
||||
*/
|
||||
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { delegationDepthOf } from '@deepseek-ai/dsh-subagent'
|
||||
import { createToolCallBudgetMonitor } from './budget.js'
|
||||
import { Config } from './config.js'
|
||||
import { renderRoleCatalog } from './catalog.js'
|
||||
import { createRoleLoader } from './roles.js'
|
||||
import { createTrimPolicySource } from './settings.js'
|
||||
import { registerChildPromptTrim } from './trim.js'
|
||||
import { LOG_PREFIX, createRoleListTool, createRoleTool } from './tool.js'
|
||||
|
||||
export { Config }
|
||||
|
||||
/** Cordis plugin name. */
|
||||
export const name = 'subagent-roles'
|
||||
/** Hard dependencies: the tool registry and the subagent registry. */
|
||||
export const inject = ['tools', 'subagents']
|
||||
|
||||
/** Role-binding marker expected at the top of a teammate prompt. */
|
||||
const ROLE_MARKER_PATTERN = /^@role:([a-z0-9]+(?:-[a-z0-9]+)*)\s*$/m
|
||||
|
||||
/**
|
||||
* The catalog section name for one delegation tool.
|
||||
*
|
||||
* Deliberately namespaced under the tool rather than the official
|
||||
* `tool:<toolName>` convention: this is a global (host-plane) section that must
|
||||
* never collide with the scoped `tool:<name>` sections tool plugins register,
|
||||
* even when a deployment renames this plugin's tool to `subagent`. Deriving it
|
||||
* from the tool name — rather than hardcoding one — is what lets a profile mount
|
||||
* a SECOND row (another transport provider) without the second row's
|
||||
* registration silently throwing and leaving its roles unadvertised.
|
||||
* @param toolName - the configured delegation tool name.
|
||||
* @returns the section name.
|
||||
*/
|
||||
export function catalogSectionName(toolName) {
|
||||
return `${toolName ?? 'subagent_role'}:catalog`
|
||||
}
|
||||
|
||||
/** Default catalog section name (the default tool name). */
|
||||
export const CATALOG_SECTION_NAME = catalogSectionName('subagent_role')
|
||||
|
||||
/**
|
||||
* Register the role catalog section, the delegation tool, and (optionally) the
|
||||
* diagnostic tool.
|
||||
* @param ctx - the plugin context.
|
||||
* @param config - the resolved row config.
|
||||
*/
|
||||
export function apply(ctx, config = {}) {
|
||||
const toolName = config.toolName ?? 'subagent_role'
|
||||
const providerName = config.subagentProvider ?? 'spawn'
|
||||
const sectionName = catalogSectionName(toolName)
|
||||
const loader = createRoleLoader({
|
||||
projectRootMarkers: config.projectRootMarkers,
|
||||
projectRootTtlMs: config.projectRootTtlMs,
|
||||
dshHome: config.dshHome,
|
||||
maxBodyBytes: config.maxBodyBytes,
|
||||
personaVariables: config.personaVariables,
|
||||
})
|
||||
/**
|
||||
* A roles plugin must never take the harness down with it: a failure here is
|
||||
* logged and the contribution is skipped, so a bad config or an unexpected
|
||||
* host shape costs roles, not the whole profile boot.
|
||||
*/
|
||||
const safely = (label, run) => {
|
||||
try {
|
||||
return run()
|
||||
} catch (error) {
|
||||
ctx.logger?.error?.(`[${LOG_PREFIX}] ${label} failed: ${String(error?.message ?? error)}`)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
// ---- tool-call budget monitor -------------------------------------------
|
||||
// One observer per row, folding the committed `tool/call` events of the child
|
||||
// Sessions this row starts. It is created independently of any transport
|
||||
// provider so a provider that appears later is governed from its first
|
||||
// delegation; `0` (unlimited) costs nothing because a delegation arms a record
|
||||
// only when its role is actually budgeted.
|
||||
let budgetMonitor
|
||||
safely('registering the tool-call budget monitor', () => {
|
||||
budgetMonitor = createToolCallBudgetMonitor({
|
||||
ctx,
|
||||
log: (message) => ctx.logger?.warn?.(message),
|
||||
})
|
||||
ctx.effect(() => () => budgetMonitor?.dispose(), 'subagent-roles: tool-call budget')
|
||||
})
|
||||
|
||||
// ---- row policy source --------------------------------------------------
|
||||
// DSH 0.2.1 removed plugin-registered settings namespaces, so the ROW CONFIG is
|
||||
// the policy. Created BEFORE the delegation tool, which captures the reader.
|
||||
// `childPromptTrim: 'off'` is the operator's kill switch and still unmounts the
|
||||
// trim listener; the budget defaults below stay on the row config either way.
|
||||
const policySource = (config.childPromptTrim ?? 'full') === 'off'
|
||||
? undefined
|
||||
: safely('creating the row settings source', () => createTrimPolicySource({ ctx, config }))
|
||||
const readBudgetSettings = policySource === undefined ? undefined : () => policySource.readBudgetDefaults()
|
||||
if (policySource !== undefined) {
|
||||
safely('registering the row settings source', () => {
|
||||
ctx.effect(() => () => policySource.dispose(), 'subagent-roles: row settings source')
|
||||
})
|
||||
}
|
||||
|
||||
// ---- delegation tool ----------------------------------------------------
|
||||
let definition
|
||||
let disposeTool
|
||||
const backgroundEnabled = config.enableRunInBackground !== false
|
||||
const mount = (provider) => safely(`registering ${toolName} on transport "${providerName}"`, () => {
|
||||
const capabilities = provider.capabilities ?? {}
|
||||
if (typeof config.maxDepth === 'number' && !capabilities.depthLimit) {
|
||||
throw new Error(`provider "${provider.name}" cannot enforce maxDepth (no depthLimit capability) — set maxDepth: 'provider-managed'`)
|
||||
}
|
||||
// Continuable children are only ever started from the background path, so
|
||||
// the capability is required exactly when that path is reachable.
|
||||
if ((config.backgroundMode ?? 'one-shot') === 'continuable') {
|
||||
if (!backgroundEnabled) {
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] backgroundMode "continuable" is inactive while enableRunInBackground is false; delegations run one-shot`)
|
||||
} else if (provider.prepareContinuable === undefined) {
|
||||
throw new Error(`provider "${provider.name}" does not support backgroundMode: continuable — switch the subagent provider or use backgroundMode: "one-shot"`)
|
||||
}
|
||||
}
|
||||
const created = createRoleTool({ ctx, config, provider, loader, budgetMonitor, readBudgetSettings })
|
||||
disposeTool = ctx.effect(() => ctx.tools.register(created), 'subagent-roles: delegation tool')
|
||||
// Only a REGISTERED definition may advertise the catalog: the section's
|
||||
// visibility guard compares against this exact object.
|
||||
definition = created
|
||||
ctx.logger?.info?.(`[${LOG_PREFIX}] registered ${toolName} on subagent transport "${providerName}" (backgroundMode ${config.backgroundMode ?? 'one-shot'})`)
|
||||
})
|
||||
ctx.on('subagent/provider-added', (provider) => {
|
||||
if (provider.name === providerName && disposeTool === undefined) mount(provider)
|
||||
})
|
||||
ctx.on('subagent/provider-removed', (removed) => {
|
||||
if (removed !== providerName || disposeTool === undefined) return
|
||||
disposeTool()
|
||||
disposeTool = undefined
|
||||
definition = undefined
|
||||
})
|
||||
safely('mounting the delegation tool', () => {
|
||||
const present = ctx.subagents.getProvider(providerName)
|
||||
if (present !== undefined) mount(present)
|
||||
else ctx.logger?.info?.(`[${LOG_PREFIX}] subagent provider "${providerName}" is not registered yet; ${toolName} will register when it appears`)
|
||||
})
|
||||
|
||||
// ---- role catalog section ----------------------------------------------
|
||||
const systemPrompt = safely('reading the systemPrompt service', () => ctx.get('systemPrompt'))
|
||||
if (systemPrompt === undefined) {
|
||||
// No prompt registry means no catalog. Say so: otherwise the plugin looks
|
||||
// installed while the model is never told which roles exist.
|
||||
// Fenced like every other logger call on this path: an activation-time throw
|
||||
// does not just cost the catalog, it fails the whole row — and on the desktop
|
||||
// a row that did not activate is a boot failure.
|
||||
safely('reporting the missing systemPrompt service', () => ctx.logger?.warn?.(`[${LOG_PREFIX}] no systemPrompt service in this composition; the role catalog will not be advertised`))
|
||||
} else if ((config.catalog ?? 'compact') !== 'off') {
|
||||
safely('registering the role catalog section', () => {
|
||||
const order = Number(systemPrompt.getSectionOrder('TOOL_SUBAGENT'))
|
||||
ctx.effect(() => systemPrompt.section({
|
||||
name: sectionName,
|
||||
order: Number.isFinite(order) ? order + 1 : 2901,
|
||||
text: (context) => {
|
||||
try {
|
||||
const agent = context?.agent
|
||||
if (agent === undefined || agent === null) return ''
|
||||
if (definition === undefined) return ''
|
||||
// Advertise roles only where the delegation tool is actually usable:
|
||||
// a restricted child (or a shadowing registration) must not be told
|
||||
// about roles it cannot reach.
|
||||
if (ctx.tools.get(toolName, context.scope ?? agent) !== definition) return ''
|
||||
if ((config.catalogScope ?? 'main') === 'main' && delegationDepthOf(agent) > 0) return ''
|
||||
// `freshDiagnostics` keeps the loader's per-path standing findings in
|
||||
// step with the delegation path (`lib/tool.js`), so one bad role file
|
||||
// is logged once per loader instead of once per assembly — and logged
|
||||
// again only after the finding cleared (the file healed, a shadow
|
||||
// lifted) and came back.
|
||||
const { roles, diagnostics } = loader.loadSync(agent.session?.header?.cwd, { freshDiagnostics: true })
|
||||
for (const diagnostic of diagnostics) {
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] skipped ${diagnostic.id} (${diagnostic.source}) at ${diagnostic.path}: ${diagnostic.reason}`)
|
||||
}
|
||||
return renderRoleCatalog(roles, { toolName, descriptionMaxLength: config.catalogDescriptionMaxLength })
|
||||
} catch (error) {
|
||||
// Prompt assembly must never fail because role discovery hiccuped.
|
||||
// NOTE: this only covers the provider; the returned text is still
|
||||
// interpolated by the core, which is why role CATALOG fields are
|
||||
// validated to contain no `{{` at load time.
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] role catalog unavailable: ${String(error?.message ?? error)}`)
|
||||
return ''
|
||||
}
|
||||
},
|
||||
}), 'subagent-roles: catalog section')
|
||||
})
|
||||
}
|
||||
|
||||
// ---- child prompt trim --------------------------------------------------
|
||||
// Independent of the catalog: even a deployment that advertises no roles
|
||||
// should not make a child pay for guidance its own policy made unreachable.
|
||||
// The policy comes from the row source created above; on 0.2.1 that is the row
|
||||
// config itself, so a change takes effect when the row re-activates.
|
||||
if (policySource !== undefined) {
|
||||
safely('registering the child prompt trim', () => {
|
||||
ctx.effect(() => {
|
||||
const disposeTrim = registerChildPromptTrim({ ctx, source: policySource })
|
||||
return () => disposeTrim()
|
||||
}, 'subagent-roles: child prompt trim')
|
||||
})
|
||||
}
|
||||
|
||||
// ---- optional diagnostics ----------------------------------------------
|
||||
if (config.enableListTool === true) {
|
||||
const listToolName = config.listToolName ?? 'subagent_roles'
|
||||
safely(`registering the ${listToolName} diagnostic tool`, () => {
|
||||
ctx.effect(() => ctx.tools.register(createRoleListTool({ ctx, config, loader, readBudgetSettings })), 'subagent-roles: list tool')
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Agent Teams role injection (team fork v8, pre-step + fallback + bindings)
|
||||
// v8 adds durable spawn bindings: childId -> {roleId, cwd} persisted to
|
||||
// ~/.dsh/role-inject-bindings.json at install, re-applied on every
|
||||
// agent/created materialization. Without this, a host restart silently
|
||||
// returns old teammates WITHOUT persona and WITHOUT their tool whitelist
|
||||
// (observed 2026-11-16: a doc-writer member woke with the full tool
|
||||
// surface — a privilege escalation worse than death).
|
||||
// Host facts recorded in ~/.dsh/role-inject-diag.log:
|
||||
// * events arrive as SECOND arg of `session/event`: {type,seq,time,data}.
|
||||
// * spawn sequence on the LEAD session: tool/call(name="spawn_teammate",
|
||||
// data.arguments carries {name, description, prompt}) -> subagent/catalog
|
||||
// (data.childId + data.label). The CHILD session emits
|
||||
// subagent/descriptor ... step/start -> system/message (first request
|
||||
// already assembled) -> user/message. Injecting at the child's
|
||||
// user/message is one step too late for the FIRST request, so we register
|
||||
// the role at the lead's tool/call and install at subagent/catalog,
|
||||
// ~270ms before the child assembles its first request.
|
||||
// * tools.restrict() validates against GLOBAL tools; scoped names like
|
||||
// ops_bash are unknown there and the whole call throws. Fallback: parse
|
||||
// the "known global tools:" list from the error, intersect, retry once.
|
||||
// The child user/message `@role:<id>` path remains as a fallback (persona
|
||||
// visible from step 2 onward).
|
||||
safely('registering Agent Teams role injection', () => {
|
||||
const ROLE_MARKER_RE = ROLE_MARKER_PATTERN
|
||||
const diagPath = `${homedir()}/.dsh/role-inject-diag.log`
|
||||
const diag = (msg) => {
|
||||
try { appendFileSync(diagPath, `[${new Date().toISOString()}] ${msg}\n`) } catch { /* best effort */ }
|
||||
}
|
||||
const injectedAgents = new Set()
|
||||
const injectedSessions = new Set()
|
||||
const pendingByLabel = new Map() // label or name -> { roleId, cwd, applied }
|
||||
const pendingMarker = new Map() // sessionId -> roleId
|
||||
const evtCounts = new Map()
|
||||
|
||||
// ---- durable spawn bindings (survive host restarts) ------------------
|
||||
// The persona section and the tool restriction live only in the memory of
|
||||
// the running agent: a host restart that cold-resumes an old teammate
|
||||
// returns it WITHOUT persona and WITHOUT its whitelist (observed 2026-11-16:
|
||||
// a doc-writer member woke with the full tool surface, a privilege
|
||||
// escalation worse than death). Persist childId -> {roleId, cwd} at
|
||||
// install time and re-apply when the agent materializes (agent/created
|
||||
// fires for every cold resume), so a revived member is the SAME member.
|
||||
const bindingsPath = `${homedir()}/.dsh/role-inject-bindings.json`
|
||||
let bindings = new Map()
|
||||
const normId = (id) => (typeof id === 'string' ? id.replace(/^session-/, '') : id)
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(bindingsPath, 'utf8'))
|
||||
bindings = new Map(Object.entries(raw))
|
||||
diag(`loaded ${bindings.size} spawn bindings`)
|
||||
} catch (error) {
|
||||
diag(`no usable bindings file (${String(error?.message ?? error).slice(0, 80)}); starting fresh`)
|
||||
}
|
||||
let persistTimer = null
|
||||
const persistBindings = () => {
|
||||
// debounce: a spawn writes catalog + message markers in quick succession
|
||||
if (persistTimer !== null) clearTimeout(persistTimer)
|
||||
persistTimer = setTimeout(() => {
|
||||
persistTimer = null
|
||||
try {
|
||||
writeFileSync(bindingsPath, `${JSON.stringify(Object.fromEntries(bindings), null, 1)}\n`)
|
||||
} catch (error) {
|
||||
diag(`bindings persist failed: ${String(error?.message ?? error)}`)
|
||||
}
|
||||
}, 500)
|
||||
if (typeof persistTimer?.unref === 'function') persistTimer.unref()
|
||||
}
|
||||
|
||||
const textOfContainer = (value) => {
|
||||
if (typeof value === 'string') return value
|
||||
if (Array.isArray(value)) {
|
||||
for (const part of value) {
|
||||
if (part === null || typeof part !== 'object') continue
|
||||
if (typeof part.text === 'string' && (part.type === 'text' || part.type === undefined)) return part.text
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const deepText = (value, depth) => {
|
||||
if (value === null || value === undefined || depth > 3) return undefined
|
||||
if (typeof value === 'string') return value
|
||||
if (Array.isArray(value)) return textOfContainer(value)
|
||||
const direct = textOfContainer(value.content) ?? textOfContainer(value.parts)
|
||||
?? (typeof value.text === 'string' ? value.text : undefined)
|
||||
if (direct !== undefined) return direct
|
||||
return deepText(value.message, depth + 1) ?? deepText(value.data, depth + 1)
|
||||
}
|
||||
|
||||
const roleIdFromText = (text) => {
|
||||
if (typeof text !== 'string') return undefined
|
||||
const firstLine = text.slice(0, 200).split('\n', 1)[0].trim()
|
||||
const m = ROLE_MARKER_RE.exec(firstLine)
|
||||
return m === null ? undefined : m[1]
|
||||
}
|
||||
|
||||
const findAgentBySession = (sessionId) => {
|
||||
try {
|
||||
const agents = ctx.get('agents')
|
||||
const list = typeof agents?.list === 'function' ? agents.list() : []
|
||||
for (const a of list) {
|
||||
if (a?.id === sessionId || a?.session?.header?.id === sessionId || a?.session?.id === sessionId) return a
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return undefined
|
||||
}
|
||||
|
||||
const applyToolPolicy = (tools, filter) => {
|
||||
if (filter === undefined) return
|
||||
const attempt = (f) => { try { tools.restrict(f); return true } catch { return false } }
|
||||
if (attempt(filter)) return
|
||||
let reduced = filter
|
||||
try {
|
||||
const msg = (() => { try { tools.restrict(filter) } catch (e) { return String(e?.message ?? e) } return '' })()
|
||||
const m = /known global tools: ([\s\S]+)$/.exec(msg)
|
||||
if (m === null) { diag(`tool policy skipped (unparseable error): ${msg.slice(0, 160)}`); return }
|
||||
const known = new Set(m[1].split(',').map((s) => s.trim()).filter(Boolean))
|
||||
if (Array.isArray(filter)) reduced = filter.filter((n) => known.has(n))
|
||||
else if (Array.isArray(filter.allow)) reduced = { ...filter, allow: filter.allow.filter((n) => known.has(n)) }
|
||||
else if (Array.isArray(filter.allowedTools)) reduced = { ...filter, allowedTools: filter.allowedTools.filter((n) => known.has(n)) }
|
||||
else { diag(`tool policy skipped (unknown filter shape keys=${Object.keys(filter).join(',')})`); return }
|
||||
} catch (error) {
|
||||
diag(`tool policy reduce threw: ${String(error?.message ?? error)}`)
|
||||
return
|
||||
}
|
||||
if (attempt(reduced)) diag(`tool policy applied via reduced list`)
|
||||
else diag(`tool policy still failed after reduce`)
|
||||
}
|
||||
|
||||
const installRoleOn = (agent, roleId, cwd) => {
|
||||
if (agent === undefined) return false
|
||||
if (injectedAgents.has(agent.id)) return true
|
||||
const sysPrompt = agent?.ctx?.systemPrompt
|
||||
if (sysPrompt === undefined || typeof sysPrompt.section !== 'function') {
|
||||
diag(`install skipped: no systemPrompt.section on agent ${String(agent?.id)}`)
|
||||
return false
|
||||
}
|
||||
const { roles } = loader.loadSync(cwd, { freshDiagnostics: false })
|
||||
const role = roles.find((r) => r.id === roleId)
|
||||
if (role === undefined || role.persona === undefined) {
|
||||
diag(`role "${roleId}" not found (cwd=${String(cwd)})`)
|
||||
return false
|
||||
}
|
||||
const order = Number(sysPrompt.getSectionOrder?.('DEPLOYMENT_PERSONA_PREFIX'))
|
||||
sysPrompt.section({
|
||||
name: 'deployment:persona-prefix',
|
||||
order: Number.isFinite(order) ? order : 0,
|
||||
text: role.persona,
|
||||
})
|
||||
applyToolPolicy(agent?.ctx?.tools, role.toolFilter)
|
||||
injectedAgents.add(agent.id)
|
||||
const sid = agent?.session?.header?.id ?? agent?.session?.id
|
||||
if (typeof sid === 'string') injectedSessions.add(sid)
|
||||
diag(`injected role "${roleId}" (${role.persona.length} chars) into agent ${String(agent?.id)} (pre=${evtCounts.get(sid) === undefined ? '?' : 'x'})`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (typeof ctx.on !== 'function') { diag('ctx.on unavailable at apply time'); return }
|
||||
|
||||
ctx.on('session/event', (obj, evt) => {
|
||||
try {
|
||||
const sessionId = obj?.header?.id ?? obj?.id ?? obj?.sessionId
|
||||
if (typeof sessionId !== 'string') return
|
||||
const type = evt?.type
|
||||
const n = (evtCounts.get(sessionId) ?? 0) + 1
|
||||
evtCounts.set(sessionId, n)
|
||||
|
||||
// A) lead-side early capture: spawn_teammate tool call
|
||||
if (type === 'tool/call' && evt?.data?.name === 'spawn_teammate') {
|
||||
const rawArgs = evt?.data?.arguments
|
||||
const args = typeof rawArgs === 'string' ? (() => { try { return JSON.parse(rawArgs) } catch { return undefined } })() : rawArgs
|
||||
const roleId = roleIdFromText(deepText(args?.prompt, 0))
|
||||
if (roleId !== undefined) {
|
||||
const cwd = obj?.header?.cwd
|
||||
const entry = { roleId, cwd, applied: false }
|
||||
if (typeof args?.description === 'string') pendingByLabel.set(`d:${args.description}`, entry)
|
||||
if (typeof args?.name === 'string') pendingByLabel.set(`n:${args.name}`, entry)
|
||||
diag(`spawn captured: role=${roleId} name=${String(args?.name)} desc=${String(args?.description)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// A2) catalog event resolves the childId -> install before first request
|
||||
if (type === 'subagent/catalog') {
|
||||
const childId = evt?.data?.childId
|
||||
const label = evt?.data?.label
|
||||
const entry = (typeof label === 'string' ? pendingByLabel.get(`d:${label}`) : undefined)
|
||||
?? (typeof label === 'string' ? pendingByLabel.get(`n:${label}`) : undefined)
|
||||
diag(`catalog: label=${String(label)} childId=${String(childId)} matched=${entry !== undefined}`)
|
||||
if (entry !== undefined && !entry.applied && typeof childId === 'string') {
|
||||
let child
|
||||
try { child = ctx.get('agents')?.get?.(childId) } catch { child = undefined }
|
||||
if (child === undefined) child = findAgentBySession(`session-${childId}`)
|
||||
if (child === undefined) diag(`catalog: child ${childId} not live yet (marker path will catch up)`)
|
||||
else {
|
||||
entry.applied = true
|
||||
if (installRoleOn(child, entry.roleId, child?.session?.header?.cwd ?? entry.cwd)) {
|
||||
bindings.set(normId(childId), { roleId: entry.roleId, cwd: child?.session?.header?.cwd ?? entry.cwd })
|
||||
persistBindings()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// B) child user/message marker path (fallback, step 2 onward)
|
||||
if (!injectedSessions.has(sessionId)) {
|
||||
const text = deepText(evt?.data, 0)
|
||||
const roleId = roleIdFromText(text)
|
||||
if (roleId !== undefined) {
|
||||
pendingMarker.set(sessionId, roleId)
|
||||
const agent = findAgentBySession(sessionId)
|
||||
if (agent !== undefined) {
|
||||
pendingMarker.delete(sessionId)
|
||||
const cwd = agent?.session?.header?.cwd ?? obj?.header?.cwd
|
||||
if (installRoleOn(agent, roleId, cwd)) { bindings.set(normId(sessionId), { roleId, cwd }); persistBindings() }
|
||||
}
|
||||
}
|
||||
} else if (pendingMarker.has(sessionId)) {
|
||||
const agent = findAgentBySession(sessionId)
|
||||
if (agent !== undefined) {
|
||||
const roleId = pendingMarker.get(sessionId)
|
||||
pendingMarker.delete(sessionId)
|
||||
const cwd = agent?.session?.header?.cwd
|
||||
if (installRoleOn(agent, roleId, cwd)) { bindings.set(normId(sessionId), { roleId, cwd }); persistBindings() }
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
diag(`session/event handler threw: ${String(error?.message ?? error)}`)
|
||||
}
|
||||
})
|
||||
|
||||
// Restore path: a cold-resumed (or post-restart woken) member materializes
|
||||
// as a fresh agent object with no memory of prior injection. If we bound
|
||||
// this child id at spawn time, re-apply persona + tool restriction, so a
|
||||
// revived member is the same member — not a persona-less, whitelist-less
|
||||
// agent with the full tool surface.
|
||||
ctx.on('agent/created', ({ agent }) => {
|
||||
try {
|
||||
if (agent === undefined || injectedAgents.has(agent.id)) return
|
||||
const keys = [normId(agent.id), normId(agent?.session?.header?.id), normId(agent?.session?.id)]
|
||||
let binding
|
||||
for (const key of keys) {
|
||||
if (typeof key === 'string' && bindings.has(key)) { binding = bindings.get(key); break }
|
||||
}
|
||||
if (binding === undefined) return
|
||||
if (installRoleOn(agent, binding.roleId, binding.cwd)) {
|
||||
diag(`restored role "${binding.roleId}" on materialization of ${String(agent.id)}`)
|
||||
}
|
||||
} catch (error) {
|
||||
diag(`bindings restore threw: ${String(error?.message ?? error)}`)
|
||||
}
|
||||
})
|
||||
|
||||
diag('event-path injection v8 registered (spawn-capture + tool-restrict fallback + durable bindings restore)')
|
||||
|
||||
// Remedy for members that predate the bindings file: re-inject by sending
|
||||
// them a first-line @role marker, then record the binding. Lead-only; the
|
||||
// member ends up with its own workspace-relative role, same as a fresh
|
||||
// spawn would get.
|
||||
if (typeof ctx.tools?.register === 'function') {
|
||||
safely('registering team_member_rebind', () => {
|
||||
const tool = {
|
||||
name: 'team_member_rebind',
|
||||
description: 'Lead-only remedy for teammates that existed before durable role bindings: re-inject a role persona + tool policy into a live member and record its binding so a later host restart restores it. Use after confirming (via team-ledger diagnostics) that a member lost its persona/whitelist.',
|
||||
parameters: {
|
||||
target: { type: 'string', required: true, description: 'Teammate name from list_agents.' },
|
||||
roleId: { type: 'string', description: 'Role id to bind; defaults to the role recorded for this member if any, else requires the argument.' },
|
||||
},
|
||||
output: {
|
||||
schema: { type: 'object', additionalProperties: true },
|
||||
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v) }],
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const caller = exec?.agent
|
||||
let membership
|
||||
try {
|
||||
membership = ctx.get('agentTeams')?.tryMembership?.(caller) ?? ctx.agentTeams?.tryMembership?.(caller)
|
||||
} catch { membership = undefined }
|
||||
if (membership?.role !== 'lead') return { ok: false, code: 'E_LEAD_ONLY', message: 'only the Lead rebinds members' }
|
||||
const name = String(args?.target ?? '').trim()
|
||||
let members
|
||||
try {
|
||||
members = (ctx.get('agentTeams') ?? ctx.agentTeams).listMembers(caller)
|
||||
} catch (error) {
|
||||
return { ok: false, code: 'E_ROSTER', message: String(error?.message ?? error) }
|
||||
}
|
||||
const member = (members ?? []).find((m) => m?.name === name)
|
||||
if (member === undefined || typeof member.id !== 'string') {
|
||||
return { ok: false, code: 'E_NOT_FOUND', message: `no member named "${name}"` }
|
||||
}
|
||||
const roleId = typeof args?.roleId === 'string' && args.roleId !== ''
|
||||
? args.roleId
|
||||
: bindings.get(normId(member.id))?.roleId
|
||||
if (roleId === undefined) return { ok: false, code: 'E_NO_ROLE', message: 'no recorded role for this member; pass roleId' }
|
||||
const cwd = caller?.session?.header?.cwd
|
||||
const target = findAgentBySession(member.id) ?? findAgentBySession(`session-${member.id}`)
|
||||
let injected = false
|
||||
if (target !== undefined) injected = installRoleOn(target, roleId, cwd)
|
||||
// Always (re)record the binding: even when the agent is not resident
|
||||
// yet, the next materialization will restore it from the file.
|
||||
bindings.set(normId(member.id), { roleId, cwd })
|
||||
persistBindings()
|
||||
diag(`rebind: member=${name} role=${roleId} live=${target !== undefined} injected=${injected}`)
|
||||
return { ok: true, target: name, roleId, live: target !== undefined, injected }
|
||||
},
|
||||
}
|
||||
ctx.effect(() => ctx.tools.register(tool), 'subagent-roles: team_member_rebind tool')
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Tool-policy normalization for ONE delegation.
|
||||
*
|
||||
* A role declares a tool policy (`tools` shorthand or `toolFilter`). Before the
|
||||
* child is published the entries are expanded against the delegating agent's
|
||||
* CURRENTLY VISIBLE tool names, because the child's `tools.restrict()` rejects
|
||||
* an unknown name by throwing inside the child's creation window — an MCP
|
||||
* server that has not finished registering yet would otherwise turn every
|
||||
* delegation into a hard failure.
|
||||
*
|
||||
* Glob entries (`*`, `?`) expand to the concrete matches; literal entries that
|
||||
* are not visible are reported so the caller can warn (`onMissingTool: 'drop'`)
|
||||
* or refuse (`'error'`). An `allow` list that expands to nothing is passed
|
||||
* through as an explicit empty allow list — fail closed, never silently widen.
|
||||
*/
|
||||
|
||||
/** Whether a policy entry is a glob rather than a literal tool name. */
|
||||
export function isGlobPattern(entry) {
|
||||
return entry.includes('*') || entry.includes('?')
|
||||
}
|
||||
|
||||
/**
|
||||
* Names the registry can expose but `tools.restrict()` refuses to accept.
|
||||
* `run_code` is the PTC presentation transport: `schemas()` lists it, while
|
||||
* `restrict()` throws on it by name.
|
||||
*/
|
||||
const UNRESTRICTABLE_TOOL_NAMES = new Set(['run_code'])
|
||||
|
||||
/**
|
||||
* Whether a visible tool name must be kept out of every role policy.
|
||||
* @param name - tool name from the registry view.
|
||||
* @returns whether `tools.restrict()` would reject it outright.
|
||||
*/
|
||||
export function isUnrestrictableToolName(name) {
|
||||
return UNRESTRICTABLE_TOOL_NAMES.has(name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the tool names the core complained about, so one delegation can drop
|
||||
* them and retry instead of failing with an error the model cannot act on.
|
||||
* @param error - the thrown value from `subagents.start` / `restrict()`.
|
||||
* @returns the offending names, deduplicated (empty when unrelated).
|
||||
*/
|
||||
export function parseUnrestrictableToolNames(error) {
|
||||
const text = String(error?.message ?? error ?? '')
|
||||
const names = []
|
||||
const unknown = /names unknown global tools? ((?:"[^"]+"(?:,\s*)?)+)/.exec(text)
|
||||
if (unknown !== null) for (const match of unknown[1].matchAll(/"([^"]+)"/g)) names.push(match[1])
|
||||
const reserved = /cannot name reserved PTC mode presentation transport "([^"]+)"/.exec(text)
|
||||
if (reserved !== null) names.push(reserved[1])
|
||||
return [...new Set(names)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a normalized filter without the named entries. An explicit `allow` list
|
||||
* is preserved even when it becomes empty (that still means "no tools").
|
||||
* @param filter - normalized filter.
|
||||
* @param names - names to remove.
|
||||
* @returns the reduced filter, or undefined when nothing effective remains.
|
||||
*/
|
||||
export function dropToolFilterNames(filter, names) {
|
||||
const drop = new Set(names)
|
||||
const next = {}
|
||||
if (filter?.allow !== undefined) next.allow = filter.allow.filter((name) => !drop.has(name))
|
||||
if (filter?.deny !== undefined) {
|
||||
const deny = filter.deny.filter((name) => !drop.has(name))
|
||||
if (deny.length > 0) next.deny = deny
|
||||
}
|
||||
if (next.allow === undefined && next.deny === undefined) return undefined
|
||||
return next
|
||||
}
|
||||
|
||||
function escapeRegExp(character) {
|
||||
return character.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile one glob entry into a whole-name regular expression.
|
||||
* @param pattern - glob text.
|
||||
* @returns the compiled matcher.
|
||||
*/
|
||||
export function globToRegExp(pattern) {
|
||||
let source = '^'
|
||||
for (const character of pattern) {
|
||||
if (character === '*') source += '.*'
|
||||
else if (character === '?') source += '.'
|
||||
else source += escapeRegExp(character)
|
||||
}
|
||||
return new RegExp(`${source}$`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand one role tool policy against the visible tool names.
|
||||
* @param filter - `{ allow?, deny? }` as declared by the role.
|
||||
* @param visibleNames - tool names visible to the delegating agent.
|
||||
* @param options - `onMissing`: `drop` (default) or `error`.
|
||||
* @returns `{ filter?, missing, unmatched, dropped }`; `filter` is undefined
|
||||
* when nothing effective remains.
|
||||
* @throws when `onMissing` is `error` and any entry could not be resolved.
|
||||
*/
|
||||
export function expandToolFilter(filter, visibleNames, options = {}) {
|
||||
const visible = visibleNames instanceof Set ? visibleNames : new Set(visibleNames ?? [])
|
||||
const missing = []
|
||||
const unmatched = []
|
||||
const dropped = []
|
||||
const expand = (entries) => {
|
||||
const names = []
|
||||
for (const entry of entries ?? []) {
|
||||
if (!isGlobPattern(entry)) {
|
||||
if (visible.has(entry)) {
|
||||
if (!names.includes(entry)) names.push(entry)
|
||||
} else {
|
||||
missing.push(entry)
|
||||
dropped.push(entry)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const matcher = globToRegExp(entry)
|
||||
const matches = [...visible].filter((name) => matcher.test(name)).sort()
|
||||
if (matches.length === 0) {
|
||||
unmatched.push(entry)
|
||||
dropped.push(entry)
|
||||
continue
|
||||
}
|
||||
for (const name of matches) if (!names.includes(name)) names.push(name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
const hasAllow = filter?.allow !== undefined
|
||||
const hasDeny = filter?.deny !== undefined
|
||||
const expanded = {}
|
||||
if (hasAllow) expanded.allow = expand(filter.allow)
|
||||
if (hasDeny) {
|
||||
const deny = expand(filter.deny)
|
||||
if (deny.length > 0) expanded.deny = deny
|
||||
}
|
||||
if (options.onMissing === 'error' && (missing.length > 0 || unmatched.length > 0)) {
|
||||
const known = [...visible].sort().join(', ') || '(none)'
|
||||
const problems = [...missing.map((name) => `"${name}"`), ...unmatched.map((name) => `"${name}" (glob matched nothing)`)]
|
||||
throw new Error(`subagent-roles: tool policy names unavailable tool${problems.length > 1 ? 's' : ''} ${problems.join(', ')}; visible tools: ${known}`)
|
||||
}
|
||||
if (expanded.allow === undefined && expanded.deny === undefined) return { missing, unmatched, dropped }
|
||||
return { filter: expanded, missing, unmatched, dropped }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sum the schema characters of the named tools, for budget diagnostics.
|
||||
* @param schemaCharsByName - tool name to serialized-schema length.
|
||||
* @param names - the names to sum.
|
||||
* @returns the total character count.
|
||||
*/
|
||||
export function sumSchemaChars(schemaCharsByName, names) {
|
||||
let total = 0
|
||||
for (const name of names) total += schemaCharsByName[name] ?? 0
|
||||
return total
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
/**
|
||||
* Role discovery: two roots, one file form.
|
||||
*
|
||||
* <projectRoot>/.dsh/roles/<id>.md project roles (win on id collision)
|
||||
* ~/.dsh/roles/<id>.md global roles
|
||||
*
|
||||
* `<projectRoot>` is the nearest ancestor of the session cwd carrying a
|
||||
* project-root marker (`.git` by default); without one the cwd itself is the
|
||||
* project root.
|
||||
*
|
||||
* Discovery is SYNCHRONOUS on purpose: the system-prompt section provider that
|
||||
* renders the role catalog is called synchronously during assembly, so the
|
||||
* catalog path cannot await filesystem work. Results are cached per absolute
|
||||
* path and invalidated by `mtimeMs`, so a step re-reads only files that
|
||||
* changed. Nothing here throws: a malformed file becomes a diagnostic and is
|
||||
* skipped, because throwing inside prompt assembly would fail every turn.
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { basename, extname, join, resolve } from 'node:path'
|
||||
import { parse as parseYaml } from 'yaml'
|
||||
|
||||
/** Role-id grammar; also the file-stem grammar. */
|
||||
const ROLE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
/** Project-relative role directory (the only one). */
|
||||
const PROJECT_ROLE_DIR = ['.dsh', 'roles']
|
||||
/**
|
||||
* Prompt variables a role persona may reference by default — exactly the three
|
||||
* `dsh-agent-loop` registers. A deployment that registers more can extend this
|
||||
* through the row's `personaVariables`.
|
||||
*/
|
||||
export const PERSONA_VARIABLES = ['cwd', 'model', 'provider']
|
||||
/**
|
||||
* Accepted `maxToolCallsScope` values. `delegation` 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.
|
||||
*/
|
||||
export const TOOL_CALL_SCOPES = ['delegation', 'session']
|
||||
/** Accepted `onToolCallBudget` postures. */
|
||||
export const TOOL_CALL_BUDGET_MODES = ['interrupt', 'wrap-up', 'off']
|
||||
/** Frontmatter keys this format accepts; anything else is a typo. */
|
||||
const ROLE_FRONTMATTER_KEYS = [
|
||||
'name',
|
||||
'displayName',
|
||||
'description',
|
||||
'whenToUse',
|
||||
'provider',
|
||||
'model',
|
||||
'reasoningEffort',
|
||||
'tools',
|
||||
'toolFilter',
|
||||
'maxToolCalls',
|
||||
'maxToolCallsScope',
|
||||
'onToolCallBudget',
|
||||
'graceToolCalls',
|
||||
]
|
||||
/**
|
||||
* The core's own rules, copied verbatim from `@deepseek-ai/dsh-system-prompt`
|
||||
* (`VARIABLE_NAME` / `GROUP_AT`): variable names are lowercase and the
|
||||
* reference must be one complete simple group — no trimming, no whitespace.
|
||||
*/
|
||||
const CORE_VARIABLE_NAME = /^[a-z][a-z0-9_]*$/
|
||||
const CORE_GROUP_AT = /^\{\{([^{}]*)\}\}/
|
||||
const DEFAULT_MAX_BODY_BYTES = 65536
|
||||
/**
|
||||
* Extra bytes a role file may spend on YAML frontmatter, on top of
|
||||
* `maxBodyBytes`, before the READ itself is refused. The persona limit is
|
||||
* measured on the body only, so a plain `size > maxBodyBytes` check would reject
|
||||
* legitimate files; this allowance is far larger than any real frontmatter.
|
||||
*/
|
||||
const FRONTMATTER_READ_ALLOWANCE_BYTES = 65536
|
||||
/** How long a resolved project root is trusted before re-walking the tree. */
|
||||
const PROJECT_ROOT_TTL_MS = 5000
|
||||
/**
|
||||
* Upper bound on every discovery cache. Discovery runs inside prompt assembly
|
||||
* for the whole life of a host process, and each cache is keyed by an absolute
|
||||
* path, so without a bound they would grow with every project, cwd, and role file
|
||||
* the process ever saw. Eviction only costs a re-stat or a re-read.
|
||||
*/
|
||||
const MAX_CACHE_ENTRIES = 512
|
||||
|
||||
/** Insert into a bounded Map, evicting the oldest entry first. */
|
||||
function rememberInMap(map, key, value, limit = MAX_CACHE_ENTRIES) {
|
||||
if (!map.has(key) && map.size >= limit) {
|
||||
for (const oldest of map.keys()) {
|
||||
map.delete(oldest)
|
||||
break
|
||||
}
|
||||
}
|
||||
map.set(key, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the harness home holding the global role directory.
|
||||
* @param configured - the row's `dshHome`, when set.
|
||||
* @param env - environment (injectable for tests).
|
||||
* @returns an absolute path.
|
||||
*/
|
||||
function resolveDshHome(configured, env = process.env) {
|
||||
const fromEnv = env?.DSH_HOME
|
||||
const raw = configured !== undefined && configured !== null && configured !== ''
|
||||
? configured
|
||||
: typeof fromEnv === 'string' && fromEnv.trim().length > 0
|
||||
? fromEnv
|
||||
: join(homedir(), '.dsh')
|
||||
return resolve(raw)
|
||||
}
|
||||
|
||||
/**
|
||||
* Split one role document into frontmatter text and persona body.
|
||||
* EOLs are normalized to `\n`; the body is everything after the closing
|
||||
* delimiter with no leading newline and trailing content preserved.
|
||||
* @param raw - the file text.
|
||||
* @returns the frontmatter text (undefined without a block) and the body.
|
||||
*/
|
||||
export function splitRoleDocument(raw) {
|
||||
const text = String(raw).replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
|
||||
const lines = text.split('\n')
|
||||
if (lines[0]?.trimEnd() !== '---') return { frontmatter: undefined, body: text }
|
||||
let end = -1
|
||||
for (let index = 1; index < lines.length; index += 1) {
|
||||
if (lines[index].trimEnd() === '---') {
|
||||
end = index
|
||||
break
|
||||
}
|
||||
}
|
||||
if (end < 0) return { frontmatter: undefined, body: text }
|
||||
return {
|
||||
frontmatter: lines.slice(1, end).join('\n'),
|
||||
body: lines.slice(end + 1).join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the first persona `{{variable}}` reference the CORE would reject, or
|
||||
* undefined when every reference is allowed.
|
||||
*
|
||||
* This mirrors `dsh-system-prompt`'s scanner exactly rather than approximating
|
||||
* it: interpolate() runs AFTER a section provider returns, so a reference this
|
||||
* check lets through becomes a thrown error on every turn instead of a
|
||||
* contained plugin failure.
|
||||
* @param text - the persona body.
|
||||
* @param allowed - the variable names the deployment registers.
|
||||
* @returns the offending reference name, or undefined.
|
||||
*/
|
||||
export function findUnsupportedPersonaVariable(text, allowed = PERSONA_VARIABLES) {
|
||||
if (typeof text !== 'string' || text.length === 0) return undefined
|
||||
let last = 0
|
||||
for (let open = text.indexOf('{{'); open >= 0; open = text.indexOf('{{', last)) {
|
||||
const group = CORE_GROUP_AT.exec(text.slice(open))
|
||||
if (group === null) {
|
||||
// A lone `{{` without any later `}}` is literal prose for the core…
|
||||
if (text.indexOf('}}', open + 2) >= 0) return text.slice(open + 2, text.indexOf('}}', open + 2))
|
||||
// …and scanning continues past it, exactly like the core does.
|
||||
last = open + 2
|
||||
continue
|
||||
}
|
||||
const name = group[0].slice(2, -2)
|
||||
if (!CORE_VARIABLE_NAME.test(name)) return name
|
||||
if (!allowed.includes(name)) return name
|
||||
last = open + group[0].length
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Whether catalog text carries a `{{` at all (it is rendered through interpolation). */
|
||||
function hasVariableSyntax(text) {
|
||||
return typeof text === 'string' && text.includes('{{')
|
||||
}
|
||||
|
||||
function nonEmptyString(value) {
|
||||
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
|
||||
}
|
||||
|
||||
function normalizeNameList(value, field) {
|
||||
if (!Array.isArray(value)) return { error: `${field} must be an array of tool names` }
|
||||
const names = []
|
||||
for (const entry of value) {
|
||||
const name = nonEmptyString(entry)
|
||||
if (name === undefined) return { error: `${field} entries must be non-empty strings` }
|
||||
if (!names.includes(name)) names.push(name)
|
||||
}
|
||||
return { names }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one tool-call budget count: an integer `>= 0`, where `0` means
|
||||
* unlimited. YAML yields `8.5` or `-1` for a plausible-looking typo, and a
|
||||
* fractional limit would make "the limit+1-th call" unrepresentable.
|
||||
* @param value - the parsed frontmatter value.
|
||||
* @param field - the key name, for the message.
|
||||
* @returns the count, or an error string.
|
||||
*/
|
||||
function normalizeBudgetCount(value, field) {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
|
||||
return { error: `\`${field}\` must be an integer >= 0 (\`0\` means unlimited)` }
|
||||
}
|
||||
return { count: value }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one enum-valued frontmatter key against its accepted vocabulary.
|
||||
* @param value - the parsed frontmatter value.
|
||||
* @param field - the key name, for the message.
|
||||
* @param allowed - the accepted values.
|
||||
* @returns the value, or an error string.
|
||||
*/
|
||||
function normalizeEnumValue(value, field, allowed) {
|
||||
const text = nonEmptyString(value)
|
||||
if (text === undefined || !allowed.includes(text)) {
|
||||
return { error: `\`${field}\` must be one of ${allowed.join(', ')}` }
|
||||
}
|
||||
return { value: text }
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and normalize the `toolFilter` shape (including the `tools`
|
||||
* allow-list shorthand).
|
||||
*
|
||||
* An EXPLICITLY declared `allow` is always preserved, even when empty: the core
|
||||
* accepts `{ allow: [] }` and reads it as "hide every inherited tool", so
|
||||
* dropping it (which would leave a bare `deny` and hand the child everything
|
||||
* else) is a silent fail-open. Only a declaration with nothing effective —
|
||||
* `{}` or a lone empty `deny` — is refused.
|
||||
* @param value - parsed frontmatter.
|
||||
* @returns the normalized filter, or an error string.
|
||||
*/
|
||||
export function normalizeRoleToolFilter(value) {
|
||||
const hasTools = value.tools !== undefined
|
||||
const hasFilter = value.toolFilter !== undefined
|
||||
if (hasTools && hasFilter) return { error: 'declare either `tools` or `toolFilter`, not both' }
|
||||
if (hasTools) {
|
||||
const list = normalizeNameList(value.tools, 'tools')
|
||||
if (list.error !== undefined) return { error: list.error }
|
||||
// `tools: []` is legal and means "no inherited tool at all".
|
||||
return { filter: { allow: list.names } }
|
||||
}
|
||||
if (!hasFilter) return {}
|
||||
const raw = value.toolFilter
|
||||
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return { error: '`toolFilter` must be an object with optional `allow` and/or `deny` arrays' }
|
||||
}
|
||||
for (const key of Object.keys(raw)) {
|
||||
if (key !== 'allow' && key !== 'deny') return { error: `\`toolFilter.${key}\` is not supported (use allow/deny)` }
|
||||
}
|
||||
const filter = {}
|
||||
if (raw.allow !== undefined) {
|
||||
const list = normalizeNameList(raw.allow, 'toolFilter.allow')
|
||||
if (list.error !== undefined) return { error: list.error }
|
||||
filter.allow = list.names
|
||||
}
|
||||
if (raw.deny !== undefined) {
|
||||
const list = normalizeNameList(raw.deny, 'toolFilter.deny')
|
||||
if (list.error !== undefined) return { error: list.error }
|
||||
if (list.names.length > 0) filter.deny = list.names
|
||||
}
|
||||
if (filter.allow === undefined && filter.deny === undefined) {
|
||||
return { error: '`toolFilter` has no usable entries; omit the field to grant all tools, or set `allow: []` to grant none' }
|
||||
}
|
||||
return { filter }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse and validate one role document.
|
||||
* @param id - the role id (the file stem).
|
||||
* @param raw - the file text.
|
||||
* @param options - `maxBodyBytes` guard and the `personaVariables` allow list.
|
||||
* @returns `{ role }` on success or `{ error }` with a human-readable reason.
|
||||
*/
|
||||
export function parseRoleDocument(id, raw, options = {}) {
|
||||
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES
|
||||
// Only names the core's own grammar accepts are honoured: an entry the core
|
||||
// would reject must not be able to turn into a per-turn interpolation throw.
|
||||
const personaVariables = (Array.isArray(options.personaVariables) && options.personaVariables.length > 0
|
||||
? options.personaVariables
|
||||
: PERSONA_VARIABLES
|
||||
).filter((name) => typeof name === 'string' && CORE_VARIABLE_NAME.test(name))
|
||||
if (!ROLE_ID_PATTERN.test(id)) {
|
||||
return { error: `role id "${id}" is not kebab-case (lowercase letters, digits, single hyphens)` }
|
||||
}
|
||||
const { frontmatter, body } = splitRoleDocument(raw)
|
||||
let value = {}
|
||||
if (frontmatter !== undefined && frontmatter.trim().length > 0) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = parseYaml(frontmatter)
|
||||
} catch (error) {
|
||||
return { error: `frontmatter is not valid YAML: ${String(error?.message ?? error)}` }
|
||||
}
|
||||
if (parsed === null || parsed === undefined) value = {}
|
||||
else if (typeof parsed !== 'object' || Array.isArray(parsed)) return { error: 'frontmatter must be a YAML mapping' }
|
||||
else value = parsed
|
||||
}
|
||||
// Reject typos instead of silently ignoring them: a misspelled `tools` key
|
||||
// would otherwise grant the child every inherited tool.
|
||||
const unknownKeys = Object.keys(value).filter((key) => !ROLE_FRONTMATTER_KEYS.includes(key))
|
||||
if (unknownKeys.length > 0) {
|
||||
return { error: `unknown frontmatter key${unknownKeys.length > 1 ? 's' : ''} ${unknownKeys.map((key) => `\`${key}\``).join(', ')}; supported: ${ROLE_FRONTMATTER_KEYS.join(', ')}` }
|
||||
}
|
||||
if (Buffer.byteLength(body, 'utf8') > maxBodyBytes) {
|
||||
return { error: `persona body is ${Buffer.byteLength(body, 'utf8')} bytes, over the ${maxBodyBytes}-byte limit (raise maxBodyBytes to allow it)` }
|
||||
}
|
||||
if (value.name !== undefined) {
|
||||
const declared = nonEmptyString(value.name)
|
||||
if (declared === undefined) return { error: '`name` must be a non-empty string when set' }
|
||||
if (declared !== id) {
|
||||
return { error: `\`name: ${declared}\` must equal the file id "${id}" or be omitted (the file name is the role id)` }
|
||||
}
|
||||
}
|
||||
const description = nonEmptyString(value.description)
|
||||
if (description === undefined) return { error: '`description` is required and must be non-empty' }
|
||||
const displayName = value.displayName === undefined ? undefined : nonEmptyString(value.displayName)
|
||||
if (value.displayName !== undefined && displayName === undefined) {
|
||||
return { error: '`displayName` must be a non-empty string when set' }
|
||||
}
|
||||
const whenToUse = value.whenToUse === undefined ? undefined : nonEmptyString(value.whenToUse)
|
||||
if (value.whenToUse !== undefined && whenToUse === undefined) {
|
||||
return { error: '`whenToUse` must be a non-empty string when set' }
|
||||
}
|
||||
// Catalog text reaches the model through the SAME strict interpolation as the
|
||||
// persona, but it is assembled OUTSIDE this plugin's try/catch — an unknown
|
||||
// reference there would throw on every turn of every agent that sees the
|
||||
// catalog. Any `{{` is therefore refused, including the silently-substituted
|
||||
// registered ones (a description must not leak {{cwd}}).
|
||||
for (const [field, text] of [['description', description], ['displayName', displayName], ['whenToUse', whenToUse]]) {
|
||||
if (hasVariableSyntax(text)) {
|
||||
return { error: `\`${field}\` must not contain \`{{\` (catalog text is interpolated strictly; write plain text)` }
|
||||
}
|
||||
}
|
||||
const route = {}
|
||||
for (const field of ['provider', 'model', 'reasoningEffort']) {
|
||||
if (value[field] === undefined) continue
|
||||
const text = nonEmptyString(value[field])
|
||||
if (text === undefined) return { error: `\`${field}\` must be a non-empty string when set` }
|
||||
route[field] = text
|
||||
}
|
||||
// A route is a pair: a lone provider/model is merged over the parent's other
|
||||
// half by the core, silently producing a route nobody declared.
|
||||
if ((route.provider === undefined) !== (route.model === undefined)) {
|
||||
return { error: '`provider` and `model` must be set together (or both omitted to inherit the parent route)' }
|
||||
}
|
||||
const filterResult = normalizeRoleToolFilter(value)
|
||||
if (filterResult.error !== undefined) return { error: filterResult.error }
|
||||
// The tool-call budget. Counts are validated as integers so "the call after
|
||||
// the limit" is always representable, and the enums are closed so a typo
|
||||
// (`wrapup`) cannot silently disable the guard a role file asked for.
|
||||
const budget = {}
|
||||
for (const field of ['maxToolCalls', 'graceToolCalls']) {
|
||||
if (value[field] === undefined) continue
|
||||
const count = normalizeBudgetCount(value[field], field)
|
||||
if (count.error !== undefined) return { error: count.error }
|
||||
budget[field] = count.count
|
||||
}
|
||||
const budgetEnums = [['maxToolCallsScope', TOOL_CALL_SCOPES], ['onToolCallBudget', TOOL_CALL_BUDGET_MODES]]
|
||||
for (const [field, allowed] of budgetEnums) {
|
||||
if (value[field] === undefined) continue
|
||||
const entry = normalizeEnumValue(value[field], field, allowed)
|
||||
if (entry.error !== undefined) return { error: entry.error }
|
||||
budget[field] = entry.value
|
||||
}
|
||||
const badVariable = findUnsupportedPersonaVariable(body, personaVariables)
|
||||
if (badVariable !== undefined) {
|
||||
return { error: `persona references {{${badVariable}}}; only ${personaVariables.map((name) => `{{${name}}}`).join(', ')} are available (no spaces inside the braces)` }
|
||||
}
|
||||
const persona = body.trim().length > 0 ? body : undefined
|
||||
return {
|
||||
role: {
|
||||
id,
|
||||
displayName: displayName ?? id,
|
||||
description,
|
||||
...(whenToUse !== undefined ? { whenToUse } : {}),
|
||||
...route,
|
||||
...budget,
|
||||
...(filterResult.filter !== undefined ? { toolFilter: filterResult.filter } : {}),
|
||||
...(persona !== undefined ? { persona } : {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a cached role loader. One loader per plugin instance; the cache is
|
||||
* keyed by absolute path and invalidated by `mtimeMs`.
|
||||
* @param options - resolved discovery config.
|
||||
* @returns the loader.
|
||||
*/
|
||||
export function createRoleLoader(options = {}) {
|
||||
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES
|
||||
const personaVariables = Array.isArray(options.personaVariables) ? options.personaVariables : undefined
|
||||
const cacheEntries = Number.isSafeInteger(options.cacheEntries) && options.cacheEntries > 0
|
||||
? options.cacheEntries
|
||||
: MAX_CACHE_ENTRIES
|
||||
const projectRootTtlMs = typeof options.projectRootTtlMs === 'number' ? options.projectRootTtlMs : PROJECT_ROOT_TTL_MS
|
||||
const markers = Array.isArray(options.projectRootMarkers) && options.projectRootMarkers.length > 0
|
||||
? options.projectRootMarkers
|
||||
: ['.git']
|
||||
const dshHome = resolveDshHome(options.dshHome)
|
||||
const fileCache = new Map()
|
||||
const projectRootCache = new Map()
|
||||
const dirCache = new Map()
|
||||
/**
|
||||
* The diagnostics a per-step read has already surfaced, keyed by role ROOT and
|
||||
* then by the exact role path.
|
||||
*
|
||||
* Two levels, both load-bearing. Inside one root the key is the exact absolute
|
||||
* path and the value is the set of that path's standing reasons, so healing one
|
||||
* file clears one small entry instead of walking every reported identity (C).
|
||||
* Across roots the key is the root, so the global root is shared by every cwd —
|
||||
* one log line per loader, not one per session — while one project's assembly
|
||||
* can never forget another project's findings.
|
||||
*/
|
||||
const reportedByRoot = new Map()
|
||||
|
||||
/**
|
||||
* Nearest ancestor carrying a project-root marker (or the cwd itself).
|
||||
*
|
||||
* The answer is cached with a TTL because the tree can change under a live
|
||||
* session (`git init` in a project that had no marker) and a permanent cache
|
||||
* would keep serving the old root for the rest of the process.
|
||||
*/
|
||||
function projectRootFor(cwd) {
|
||||
if (typeof cwd !== 'string' || cwd.length === 0) return undefined
|
||||
const start = resolve(cwd)
|
||||
const now = Date.now()
|
||||
const cached = projectRootCache.get(start)
|
||||
if (cached !== undefined && now - cached.at < projectRootTtlMs) return cached.root
|
||||
let current = start
|
||||
let found = start
|
||||
for (;;) {
|
||||
let hit = false
|
||||
for (const marker of markers) {
|
||||
if (existsSync(join(current, marker))) {
|
||||
hit = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (hit) {
|
||||
found = current
|
||||
break
|
||||
}
|
||||
const parent = resolve(current, '..')
|
||||
if (parent === current) break
|
||||
current = parent
|
||||
}
|
||||
rememberInMap(projectRootCache, start, { root: found, at: now }, cacheEntries)
|
||||
return found
|
||||
}
|
||||
|
||||
function loadRecord(path, id, source) {
|
||||
let stats
|
||||
try {
|
||||
stats = statSync(path)
|
||||
} catch (error) {
|
||||
return { error: `cannot stat role file: ${String(error?.code ?? error)}` }
|
||||
}
|
||||
// A symlinked role file is supported, but it must resolve to a REGULAR file.
|
||||
// `statSync` follows the link, so a link to a FIFO, a socket, or a character
|
||||
// device lands here as a non-regular file — and `readFileSync` on one blocks
|
||||
// forever (`/dev/zero`: reads without end) *synchronously, inside prompt
|
||||
// assembly*, which no signal or timeout can interrupt. Refuse it by type.
|
||||
if (!stats.isFile()) {
|
||||
return { error: `role path is not a regular file (${stats.isDirectory() ? 'directory' : 'special file'})` }
|
||||
}
|
||||
const cached = fileCache.get(path)
|
||||
// Size joins mtime so a same-millisecond rewrite is still noticed.
|
||||
if (cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) return cached.record
|
||||
// Bound the READ, not merely the parsed body: the size is already known here,
|
||||
// and letting `readFileSync` pull in a multi-gigabyte file would allocate it
|
||||
// all before `maxBodyBytes` is ever consulted.
|
||||
if (stats.size > maxBodyBytes + FRONTMATTER_READ_ALLOWANCE_BYTES) {
|
||||
return { error: `role file is ${stats.size} bytes, over the ${maxBodyBytes}-byte persona limit plus ${FRONTMATTER_READ_ALLOWANCE_BYTES} bytes of frontmatter (raise maxBodyBytes or shrink the file)` }
|
||||
}
|
||||
let raw
|
||||
try {
|
||||
raw = readFileSync(path, 'utf8')
|
||||
} catch (error) {
|
||||
return { error: `cannot read role file: ${String(error?.code ?? error)}` }
|
||||
}
|
||||
const parsed = parseRoleDocument(id, raw, { maxBodyBytes, personaVariables })
|
||||
if (parsed.error !== undefined) {
|
||||
// Failures are deliberately NOT cached: fixing a file must take effect
|
||||
// even when its mtime did not move.
|
||||
return { error: parsed.error }
|
||||
}
|
||||
const record = { role: { ...parsed.role, path, source } }
|
||||
rememberInMap(fileCache, path, { mtimeMs: stats.mtimeMs, size: stats.size, record }, cacheEntries)
|
||||
return record
|
||||
}
|
||||
|
||||
/** List one role directory, cached by the directory's own mtime. */
|
||||
function listRoleFiles(root) {
|
||||
let stats
|
||||
try {
|
||||
stats = statSync(root.path)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const cached = dirCache.get(root.path)
|
||||
if (cached !== undefined && cached.mtimeMs === stats.mtimeMs) return cached.files
|
||||
let entries
|
||||
try {
|
||||
entries = readdirSync(root.path, { withFileTypes: true })
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const files = entries
|
||||
// A symlinked role file counts: the stats below follow the link.
|
||||
.filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && extname(entry.name) === '.md')
|
||||
.map((entry) => entry.name)
|
||||
.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))
|
||||
rememberInMap(dirCache, root.path, { mtimeMs: stats.mtimeMs, files }, cacheEntries)
|
||||
return files
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the roots for one session cwd, lowest precedence last.
|
||||
* @param cwd - the session working directory (may be undefined).
|
||||
* @returns ordered roots.
|
||||
*/
|
||||
function rootsFor(cwd) {
|
||||
const roots = []
|
||||
const projectRoot = projectRootFor(cwd)
|
||||
const globalPath = join(dshHome, 'roles')
|
||||
if (projectRoot !== undefined) {
|
||||
const projectPath = join(projectRoot, ...PROJECT_ROLE_DIR)
|
||||
roots.push({ source: 'project', path: projectPath })
|
||||
// A repository rooted at the harness home would otherwise be scanned
|
||||
// twice, reporting every global role as shadowed by itself.
|
||||
if (resolve(projectPath) === resolve(globalPath)) return roots
|
||||
}
|
||||
roots.push({ source: 'global', path: globalPath })
|
||||
return roots
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the merged role catalog for one cwd. Never throws.
|
||||
* @param cwd - the session working directory.
|
||||
* @param options - `freshDiagnostics` returns only the diagnostics that were NOT
|
||||
* standing in the previous read of the same root (for per-step logging); the
|
||||
* default returns every current diagnostic on every read.
|
||||
* @returns `{ roles, diagnostics, roots }` with project roles winning on id.
|
||||
*/
|
||||
function loadSync(cwd, options = {}) {
|
||||
const roles = []
|
||||
const byId = new Set()
|
||||
const diagnostics = []
|
||||
const roots = rootsFor(cwd)
|
||||
// The default read is the diagnostic tool's FULL inventory. Only the per-step
|
||||
// flag turns on the comparison below, so a skipped file is still listed in
|
||||
// full every time the `subagent_roles` tool asks (E).
|
||||
const fresh = options.freshDiagnostics === true
|
||||
for (const root of roots) {
|
||||
const files = listRoleFiles(root)
|
||||
let reported
|
||||
if (fresh) {
|
||||
reported = reportedByRoot.get(root.path)
|
||||
if (reported === undefined) {
|
||||
reported = new Map()
|
||||
rememberInMap(reportedByRoot, root.path, reported, cacheEntries)
|
||||
}
|
||||
}
|
||||
// Paths this assembly actually looked at. Only a fresh read needs it: it is
|
||||
// how a file that vanished entirely is told apart from one that healed.
|
||||
const seen = fresh ? new Set() : undefined
|
||||
for (const file of files) {
|
||||
const id = basename(file, '.md')
|
||||
const path = join(root.path, file)
|
||||
const reasons = []
|
||||
const record = loadRecord(path, id, root.source)
|
||||
if (record.error !== undefined) {
|
||||
reasons.push(record.error)
|
||||
} else if (byId.has(id)) {
|
||||
reasons.push('shadowed by a higher-precedence role of the same id')
|
||||
} else {
|
||||
byId.add(id)
|
||||
roles.push(record.role)
|
||||
}
|
||||
if (!fresh) {
|
||||
for (const reason of reasons) diagnostics.push({ id, path, source: root.source, reason })
|
||||
continue
|
||||
}
|
||||
seen.add(path)
|
||||
// Compare against THIS path's reasons from the previous fresh read of the
|
||||
// same root — a per-identity difference, never a monotonic set. A reason
|
||||
// the previous read did not stand for is new: the first observation, a
|
||||
// changed cause, or the same cause after the read stopped standing for it
|
||||
// (the file healed, or the shadow that produced it lifted) and it came
|
||||
// back. The old "report once, remember forever" set swallowed that last
|
||||
// case — the shadowed-role recurrence this comparison exists to fix (D).
|
||||
const previous = reported.get(path)
|
||||
for (const reason of reasons) {
|
||||
if (previous?.has(reason) !== true) diagnostics.push({ id, path, source: root.source, reason })
|
||||
}
|
||||
// REPLACE, never merge. A cause that stopped being this file's cause must
|
||||
// not linger in the set, or switching back to it would stay silent (D).
|
||||
if (reasons.length === 0) reported.delete(path)
|
||||
else reported.set(path, new Set(reasons))
|
||||
}
|
||||
if (!fresh) continue
|
||||
// A path that stood for a diagnostic last time but was not scanned at all
|
||||
// now — the file was deleted or renamed away — left the assembly without
|
||||
// being observed clean. Forget it, so recreating it broken is reported
|
||||
// again (D). Only THIS root's diagnosed paths are walked, so the cost stays
|
||||
// proportional to this root's findings, not to everything ever reported.
|
||||
for (const path of reported.keys()) {
|
||||
if (!seen.has(path)) reported.delete(path)
|
||||
}
|
||||
}
|
||||
return { roles, diagnostics, roots }
|
||||
}
|
||||
|
||||
return { loadSync, rootsFor, projectRootFor, dshHome }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Route resolution for one role delegation.
|
||||
*
|
||||
* The role FILE is the only route source (the tool exposes no per-call
|
||||
* provider/model overrides). When the official `subagent-model-selection`
|
||||
* section is enabled with an authorized list, a role route outside it is
|
||||
* dropped so the child inherits the parent's model — never silently swapped
|
||||
* for a different authorized route. The role's `reasoningEffort` rides only
|
||||
* with an admitted route: it belongs to that model's vocabulary.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Whether a provider/model pair is admitted by an authorized route list.
|
||||
* An absent or empty list admits everything; with a list, only an exact pair
|
||||
* is admitted (a partial route cannot be).
|
||||
* @param route - `{ provider?, model? }`.
|
||||
* @param allowedRoutes - the authorized list, if any.
|
||||
* @returns whether the route is admitted.
|
||||
*/
|
||||
export function isRouteAllowed(route, allowedRoutes) {
|
||||
if (allowedRoutes === undefined || allowedRoutes.length === 0) return true
|
||||
if (route.provider === undefined || route.model === undefined) return false
|
||||
return allowedRoutes.some((entry) => entry.provider === route.provider && entry.model === route.model)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the child's AgentOptions from one role.
|
||||
*
|
||||
* The role's `reasoningEffort` rides only with an admitted route OR when the
|
||||
* role declares no route at all: an effort is part of the model vocabulary it
|
||||
* was chosen for, so a route dropped by the authorized-list constraint takes
|
||||
* its effort with it.
|
||||
* @param input - the role and the authorized route list.
|
||||
* @returns `{ agentOptions?, layer, warnings }`.
|
||||
*/
|
||||
export function resolveRoleRoute(input) {
|
||||
const { role, allowedRoutes } = input
|
||||
const warnings = []
|
||||
const provider = role?.provider
|
||||
const model = role?.model
|
||||
let effort = role?.reasoningEffort
|
||||
const routeDeclared = provider !== undefined || model !== undefined
|
||||
let admitted = routeDeclared
|
||||
if (routeDeclared && !isRouteAllowed({ provider, model }, allowedRoutes)) {
|
||||
admitted = false
|
||||
const described = provider !== undefined && model !== undefined ? `${provider}/${model}` : String(provider ?? model)
|
||||
warnings.push(`subagent-roles: role "${role?.id ?? 'unknown'}" binds LLM route ${described} which is not in the authorized model list (subagent-model-selection.allowedModels); the route and its reasoning effort were dropped and the subagent inherits the parent model`)
|
||||
effort = undefined
|
||||
}
|
||||
const agentOptions = {
|
||||
...(admitted && provider !== undefined ? { provider } : {}),
|
||||
...(admitted && model !== undefined ? { model } : {}),
|
||||
...(effort !== undefined ? { reasoningEffort: effort } : {}),
|
||||
}
|
||||
const defined = Object.keys(agentOptions).length > 0
|
||||
return {
|
||||
...(defined ? { agentOptions } : {}),
|
||||
layer: admitted && routeDeclared ? 'role' : 'inherit',
|
||||
/**
|
||||
* A route the role DID bind but the authorized list rejected. It must never
|
||||
* be quietly replaced by a provider's own route defaults: the list said no.
|
||||
*/
|
||||
dropped: routeDeclared && !admitted,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Retunable row policy: trim rules and the tool-call budget.
|
||||
*
|
||||
* DSH 0.2.1 removed plugin-registered settings namespaces (`settings.register`),
|
||||
* so there is no user layer to watch: the ROW CONFIG is the whole policy and the
|
||||
* plugin-manager config page edits exactly that row. The readers below keep the
|
||||
* same shape the rest of the plugin already consumes, which is why the switch is
|
||||
* a deletion rather than a rewrite.
|
||||
*
|
||||
* `SettingsSchema` survives as the single declaration of the retunable subset:
|
||||
* the row Config is the storage, and tests pin the config page's field list
|
||||
* against this schema so a knob cannot silently fall out of the GUI.
|
||||
*/
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { TOOL_CALL_BUDGET_MODES } from './roles.js'
|
||||
import { LOG_PREFIX } from './tool.js'
|
||||
import { DEFAULT_CHILD_NAMES } from './trim.js'
|
||||
|
||||
/** The three trim postures, shared by the row config and the settings schema. */
|
||||
export const TRIM_MODES = Object.freeze(['off', 'tools', 'full'])
|
||||
|
||||
/** Settings schema for one row (mirrors the retunable subset of the row config). */
|
||||
export const SettingsSchema = z.object({
|
||||
childPromptTrim: z.union([...TRIM_MODES]).default('full'),
|
||||
childPromptTrimNames: z.array(z.string()).default([...DEFAULT_CHILD_NAMES]),
|
||||
defaultMaxToolCalls: z.natural().default(0),
|
||||
maxToolCallsHardCap: z.natural().default(0),
|
||||
onToolCallBudget: z.union([...TOOL_CALL_BUDGET_MODES]).default('wrap-up'),
|
||||
graceToolCalls: z.natural().default(1),
|
||||
})
|
||||
|
||||
/**
|
||||
* The settings namespace (and Settings card key) for one row.
|
||||
*
|
||||
* Namespaces are lowercase-hyphenated, so a renamed tool — the way a profile
|
||||
* mounts a second row — is slugged rather than used verbatim. The default row
|
||||
* keeps the stable `subagent-roles` name the browser half binds to.
|
||||
* @param toolName - the configured delegation tool name.
|
||||
* @returns the namespace for this row.
|
||||
*/
|
||||
export function settingsNamespaceFor(toolName) {
|
||||
const name = toolName ?? 'subagent_role'
|
||||
if (name === 'subagent_role') return 'subagent-roles'
|
||||
const slug = String(name).toLowerCase().replaceAll(/[^a-z0-9]+/g, '-').replaceAll(/^-+|-+$/g, '')
|
||||
return slug.length === 0 ? 'subagent-roles' : `subagent-roles-${slug}`
|
||||
}
|
||||
|
||||
/** Normalize one resolved settings/config section into a trim policy. */
|
||||
export function trimPolicyFrom(values) {
|
||||
const mode = TRIM_MODES.includes(values?.childPromptTrim) ? values.childPromptTrim : 'full'
|
||||
const names = Array.isArray(values?.childPromptTrimNames)
|
||||
? values.childPromptTrimNames.filter((name) => typeof name === 'string')
|
||||
: [...DEFAULT_CHILD_NAMES]
|
||||
return { mode, dropNames: new Set(names) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one resolved settings/config section into the budget defaults a role
|
||||
* file may omit.
|
||||
*
|
||||
* The output uses the DELEGATION-facing names (`maxToolCalls`), while the input
|
||||
* uses the config/schema names (`defaultMaxToolCalls`): the settings key is the
|
||||
* row's default, and calling it `maxToolCalls` next to a role file's own
|
||||
* `maxToolCalls` would be ambiguous about which one wins.
|
||||
* @param values - the resolved settings section (or the row config as `base`).
|
||||
* @returns the normalized defaults.
|
||||
*/
|
||||
export function budgetDefaultsFrom(values) {
|
||||
const count = (value, fallback) => (Number.isSafeInteger(value) && value >= 0 ? value : fallback)
|
||||
return {
|
||||
maxToolCalls: count(values?.defaultMaxToolCalls, 0),
|
||||
maxToolCallsHardCap: count(values?.maxToolCallsHardCap, 0),
|
||||
onToolCallBudget: TOOL_CALL_BUDGET_MODES.includes(values?.onToolCallBudget) ? values.onToolCallBudget : 'wrap-up',
|
||||
graceToolCalls: count(values?.graceToolCalls, 1),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the policy source a row reads.
|
||||
*
|
||||
* In 0.2.1 the row config is the only storage: the plugin manager edits the
|
||||
* config schema, and a change restarts the row, so there is no watch to keep.
|
||||
* The returned shape is unchanged for the rest of the plugin.
|
||||
* @param options - the plugin `ctx` and the row `config`.
|
||||
* @returns `read()` for the trim policy, `readBudgetDefaults()` for the budget,
|
||||
* and a no-op disposer kept for the caller's effect.
|
||||
*/
|
||||
export function createTrimPolicySource(options) {
|
||||
const { ctx, config } = options
|
||||
const base = {
|
||||
childPromptTrim: config.childPromptTrim ?? 'full',
|
||||
childPromptTrimNames: [...(config.childPromptTrimNames ?? DEFAULT_CHILD_NAMES)],
|
||||
defaultMaxToolCalls: config.defaultMaxToolCalls ?? 0,
|
||||
maxToolCallsHardCap: config.maxToolCallsHardCap ?? 0,
|
||||
onToolCallBudget: config.onToolCallBudget ?? 'wrap-up',
|
||||
graceToolCalls: config.graceToolCalls ?? 1,
|
||||
}
|
||||
const current = { trim: trimPolicyFrom(base), budget: budgetDefaultsFrom(base) }
|
||||
ctx.logger?.info?.(`[${LOG_PREFIX}] trim and tool-call budget follow the plugin row config; edit them from the Plugins page`)
|
||||
|
||||
return {
|
||||
/** The trim policy to apply to the next assembly. */
|
||||
read: () => current.trim,
|
||||
/** The budget defaults to apply to the next delegation. */
|
||||
readBudgetDefaults: () => current.budget,
|
||||
/** Nothing to detach: the row config owns the values. */
|
||||
dispose: () => {},
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Child-prompt trimming.
|
||||
*
|
||||
* Every mounted tool plugin contributes one guidance section to the system
|
||||
* prompt, and the core only makes SOME of them scope-aware (`dsh-tool-fs`,
|
||||
* `dsh-tool-fs-search`, `dsh-tool-web`, `dsh-file-reference-local`); the rest —
|
||||
* `tool:goal`, `tool:ralph`, `tool:jobs`, `tool:workflow`, `app:web-surface`,
|
||||
* `harness:source`, `ui:deliverable-file-references` — render in EVERY scope.
|
||||
* A role that hides a tool therefore still pays for its guidance inside the
|
||||
* child, and a child keeps reading the Web GUI, harness-checkout, and
|
||||
* deliverable instructions it can never act on.
|
||||
*
|
||||
* This module registers ONE host-plane `system-prompt/assemble` listener. The
|
||||
* scope-filtered dispatch of that waterfall admits a listener owned by an
|
||||
* enclosing scope for every descendant scope's assembly (`@deepseek-ai/dsh-scope`),
|
||||
* so a host-plane plugin sees each subagent assembly and the returned assembly
|
||||
* is authoritative — trimming here changes the child's real prompt.
|
||||
*
|
||||
* Three rules, decided per assembly:
|
||||
* - `tool:<name>` guidance for a tool that is registered but NOT visible in
|
||||
* that scope (the root-cause rule: dead guidance is dead weight);
|
||||
* - group guidance (`tool:jobs`, `tool:goal`) whose section name is a label
|
||||
* rather than a tool name, dropped only when EVERY tool its own text names
|
||||
* is invisible there;
|
||||
* - in `full` mode (the default), named prompt parts no child can act on —
|
||||
* matched against sections and contexts alike.
|
||||
*/
|
||||
import { delegationDepthOf } from '@deepseek-ai/dsh-subagent'
|
||||
import { LOG_PREFIX } from './tool.js'
|
||||
|
||||
/**
|
||||
* Prompt parts a subagent never acts on, dropped by name in `full` mode.
|
||||
*
|
||||
* Registered without a scope guard by `dsh-app-boot` (`harness:source`),
|
||||
* `dsh-web-app` (`app:web-surface`), `dsh-client-ui-deliverables`
|
||||
* (`ui:deliverable-file-references`), and `dsh-file-reference-local`
|
||||
* (`context:file-reference`).
|
||||
*
|
||||
* ONE list, matched against sections AND contexts, because the kind is a core
|
||||
* implementation detail that moves: `context:file-reference` is a SECTION in the
|
||||
* installed core despite its name (verified live — a contexts-only list let it
|
||||
* through). Name matching is version-sensitive on purpose: a renamed part is
|
||||
* simply not trimmed, which is the safe direction.
|
||||
*/
|
||||
export const DEFAULT_CHILD_NAMES = Object.freeze([
|
||||
'harness:source',
|
||||
'app:web-surface',
|
||||
'ui:deliverable-file-references',
|
||||
'context:file-reference',
|
||||
])
|
||||
|
||||
/** Bound on remembered child sessions, mirroring the discovery cache bound. */
|
||||
const REPORTED_LIMIT = 512
|
||||
|
||||
/** Insertion-ordered, size-bounded set used to report one line per child. */
|
||||
function boundedSet(limit) {
|
||||
const set = new Set()
|
||||
return {
|
||||
add(value) {
|
||||
if (set.has(value)) return false
|
||||
set.add(value)
|
||||
if (set.size > limit) set.delete(set.values().next().value)
|
||||
return true
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Whole-word test per tool name, compiled once. Bounded like every other cache. */
|
||||
const TOOL_PATTERNS = new Map()
|
||||
|
||||
/** The compiled whole-word pattern for one tool name. */
|
||||
function patternFor(name) {
|
||||
let pattern = TOOL_PATTERNS.get(name)
|
||||
if (pattern === undefined) {
|
||||
const escaped = name.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
pattern = new RegExp(`\\b${escaped}\\b`)
|
||||
TOOL_PATTERNS.set(name, pattern)
|
||||
if (TOOL_PATTERNS.size > REPORTED_LIMIT) TOOL_PATTERNS.delete(TOOL_PATTERNS.keys().next().value)
|
||||
}
|
||||
return pattern
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one section text mentions a tool name as a WHOLE word.
|
||||
*
|
||||
* A plain `includes` is not good enough: `'already'.includes('read')` is true,
|
||||
* which would make the group-label rule treat an unrelated sentence as naming
|
||||
* the `read` tool and keep guidance it should drop.
|
||||
* @param text - the section text.
|
||||
* @param name - a registered tool name.
|
||||
* @returns whether the name appears as a whole word.
|
||||
*/
|
||||
export function mentionsTool(text, name) {
|
||||
return patternFor(name).test(text)
|
||||
}
|
||||
|
||||
/** The registry's known tool names (the global view), or undefined when unreadable. */
|
||||
export function knownToolNames(ctx) {
|
||||
try {
|
||||
const schemas = ctx.tools.schemas()
|
||||
return Array.isArray(schemas)
|
||||
? new Set(schemas.map((schema) => schema?.name).filter((name) => typeof name === 'string'))
|
||||
: undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Visible tool names for one scope, or undefined when the registry cannot answer. */
|
||||
export function visibleToolNames(ctx, agent) {
|
||||
try {
|
||||
const schemas = ctx.tools.schemas(agent)
|
||||
return Array.isArray(schemas)
|
||||
? new Set(schemas.map((schema) => schema?.name).filter((name) => typeof name === 'string'))
|
||||
: undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool a `tool:<name>` section name claims, or undefined for another section. */
|
||||
function claimedTool(sectionName) {
|
||||
return sectionName.startsWith('tool:') ? sectionName.slice('tool:'.length) : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Character count for one prompt part, treating absent text as empty.
|
||||
*
|
||||
* A section or context without a string `text` used to throw on `.length`, and
|
||||
* the outer catch then skipped trimming the WHOLE assembly for that turn. Counting
|
||||
* it as 0 keeps the degradation local and identical in meaning: no content-based
|
||||
* rule can fire for that part and nothing is counted as saved, while every other
|
||||
* part is still trimmed. It is a no-trim, never an error.
|
||||
* @param text - the part's text, possibly missing on a hand-built assembly.
|
||||
* @returns the length, or 0 when there is no string to measure.
|
||||
*/
|
||||
function textLength(text) {
|
||||
return typeof text === 'string' ? text.length : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the trim rules to one assembly.
|
||||
*
|
||||
* Pure: it returns the surviving sections and contexts plus a report, and never
|
||||
* mutates its input. A registry that could not be read (`known`/`visible`
|
||||
* undefined) disables the tool rules instead of guessing a tool away — an
|
||||
* unreadable registry must never cost the child its guidance.
|
||||
* @param assembly - `sections` and `contexts` of one assembly.
|
||||
* @param policy - `mode` (`tools` or `full`), the known and visible tool-name
|
||||
* sets, and the prompt-part names `full` mode drops.
|
||||
* @returns the surviving parts and the dropped names with the characters saved.
|
||||
*/
|
||||
export function trimChildPrompt(assembly, policy) {
|
||||
const sections = Array.isArray(assembly?.sections) ? assembly.sections : []
|
||||
const contexts = Array.isArray(assembly?.contexts) ? assembly.contexts : []
|
||||
const mode = policy?.mode ?? 'full'
|
||||
// `off` means OFF: the switch exists to stop touching a child's prompt, so it
|
||||
// must not fall through to the tool rules (it silently behaved like `tools`
|
||||
// before this guard existed).
|
||||
if (mode === 'off') {
|
||||
return { sections, contexts, droppedSections: [], droppedContexts: [], saved: 0, changed: false }
|
||||
}
|
||||
const known = policy?.known
|
||||
const visible = policy?.visible
|
||||
const canJudgeTools = known !== undefined && visible !== undefined
|
||||
const invisible = (name) => canJudgeTools && known.has(name) && !visible.has(name)
|
||||
const droppedSections = []
|
||||
const droppedContexts = []
|
||||
let saved = 0
|
||||
|
||||
const survivor = (section) => {
|
||||
const tool = claimedTool(section.name)
|
||||
let drop = false
|
||||
if (tool !== undefined && canJudgeTools) {
|
||||
if (invisible(tool)) {
|
||||
// R1 — per-tool guidance for a registered tool this scope cannot call.
|
||||
drop = true
|
||||
} else if (!known.has(tool) && textLength(section.text) > 0) {
|
||||
// R1b — a group label: drop only when every tool it names is invisible.
|
||||
const named = [...known].filter((name) => mentionsTool(section.text, name))
|
||||
drop = named.length > 0 && named.every((name) => !visible.has(name))
|
||||
}
|
||||
}
|
||||
if (!drop && mode === 'full') {
|
||||
drop = policy.dropNames?.has(section.name) === true
|
||||
}
|
||||
if (!drop) return true
|
||||
// An already-empty (or non-string) section costs nothing; report only real removals.
|
||||
const length = textLength(section.text)
|
||||
if (length > 0) {
|
||||
droppedSections.push(`${section.name}(${length})`)
|
||||
saved += length
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const survivors = sections.filter(survivor)
|
||||
const survivingContexts = mode === 'full'
|
||||
? contexts.filter((entry) => {
|
||||
if (policy.dropNames?.has(entry.name) !== true) return true
|
||||
const length = textLength(entry.text)
|
||||
if (length > 0) {
|
||||
droppedContexts.push(`${entry.name}(${length})`)
|
||||
saved += length
|
||||
}
|
||||
return false
|
||||
})
|
||||
: contexts
|
||||
|
||||
return {
|
||||
sections: survivors,
|
||||
contexts: survivingContexts,
|
||||
droppedSections,
|
||||
droppedContexts,
|
||||
saved,
|
||||
changed: survivors.length !== sections.length || survivingContexts.length !== contexts.length,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the child-prompt trim on a plugin context.
|
||||
*
|
||||
* Trimming applies to subagent assemblies only: a top-level agent is the one
|
||||
* talking to the user, so its prompt is left exactly as the deployment composed
|
||||
* it. A failure inside the listener is logged and the assembly passes through
|
||||
* untouched — prompt assembly must never fail because a trim hiccuped.
|
||||
* @param options - the plugin `ctx` and the live `source` the policy is read
|
||||
* from on each assembly (the host settings namespace when one is served, the
|
||||
* row config otherwise), so a Settings edit applies to the next child turn.
|
||||
* @returns the exact disposer that removes the listener.
|
||||
*/
|
||||
export function registerChildPromptTrim(options) {
|
||||
const { ctx, source } = options
|
||||
const reported = boundedSet(REPORTED_LIMIT)
|
||||
|
||||
return ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
||||
const resolved = await next()
|
||||
try {
|
||||
const agent = context?.agent
|
||||
if (agent === undefined || agent === null) return resolved
|
||||
if (delegationDepthOf(agent) <= 0) return resolved
|
||||
const policy = source.read()
|
||||
const result = trimChildPrompt(resolved, {
|
||||
mode: policy.mode,
|
||||
known: knownToolNames(ctx),
|
||||
visible: visibleToolNames(ctx, agent),
|
||||
dropNames: policy.dropNames,
|
||||
})
|
||||
if (result.changed) {
|
||||
resolved.sections = result.sections
|
||||
resolved.contexts = result.contexts
|
||||
}
|
||||
if (result.saved === 0) return resolved
|
||||
const detail = `-${result.saved} chars (${[...result.droppedSections, ...result.droppedContexts].join(', ')})`
|
||||
// One line per child, not per turn: a long child re-assembles every step.
|
||||
const sessionId = agent.session?.header?.id ?? agent.session?.header?.parentSession ?? '(unknown)'
|
||||
if (reported.add(String(sessionId))) {
|
||||
ctx.logger?.info?.(`[${LOG_PREFIX}] child prompt trimmed: ${detail}`)
|
||||
} else {
|
||||
ctx.logger?.debug?.(`[${LOG_PREFIX}] child prompt trimmed: ${detail}`)
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] child prompt trim skipped: ${String(error?.message ?? error)}`)
|
||||
}
|
||||
return resolved
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "dsh-plugin-subagent-roles",
|
||||
"version": "0.5.2-team-fork",
|
||||
"description": "File-defined subagent roles for DeepSeek Harness with Agent Teams integration: role files, catalog, tool filtering, tool-call budget, and automatic persona injection for teammates via @role:<id> marker in spawn_teammate prompt.",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"exports": {
|
||||
".": "./lib/index.js",
|
||||
"./client": "./lib/client.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"scripts",
|
||||
"examples",
|
||||
"cordis.patch.yml",
|
||||
"README.md",
|
||||
"README.zh.md",
|
||||
"CHANGELOG.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"lint": "for f in lib/*.js scripts/*.mjs test/*.js; do node --check \"$f\" || exit 1; done"
|
||||
},
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "^3.18.2",
|
||||
"yaml": "^2.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.5",
|
||||
"@deepseek-ai/dsh-llm": "^0.2.1-rc.1",
|
||||
"@deepseek-ai/dsh-subagent": "^0.2.1-rc.1",
|
||||
"@deepseek-ai/dsh-tools": "^0.2.1-rc.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-ui-theme": "0.2.1-rc.2",
|
||||
"@deepseek-ai/dsh-llm": "0.2.1-rc.2",
|
||||
"@deepseek-ai/dsh-session": "0.2.1-rc.2",
|
||||
"@deepseek-ai/dsh-subagent": "0.2.1-rc.2",
|
||||
"@deepseek-ai/dsh-tool-subagent": "0.2.1-rc.2",
|
||||
"@deepseek-ai/dsh-tools": "0.2.1-rc.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20",
|
||||
"dsh": "^0.2.1-rc.1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/troytse/dsh-plugin-subagent-roles.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/troytse/dsh-plugin-subagent-roles/issues"
|
||||
},
|
||||
"homepage": "https://github.com/troytse/dsh-plugin-subagent-roles",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"deepseek-harness",
|
||||
"cordis",
|
||||
"plugin",
|
||||
"subagent",
|
||||
"roles"
|
||||
],
|
||||
"license": "MIT"
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Print the sys+tools budget of ONE session log, plus which role plugin owns
|
||||
* the delegation tool. Read-only: it decompresses the session log and reports.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/inspect-session-budget.mjs <session-dir>
|
||||
* node scripts/inspect-session-budget.mjs --project <project-dir> [--newest]
|
||||
*
|
||||
* `--project` picks the newest session directory under
|
||||
* ~/.dsh/sessions/<slug-of-project-dir>/.
|
||||
*
|
||||
* Read-only: it never writes. Requires Node >= 22.15 for the multi-frame zstd
|
||||
* decoder (`node:zlib` gained zstd around then); the plugin itself needs >= 20.
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { zstdDecompressSync } from 'node:zlib'
|
||||
|
||||
function sessionRootFor(projectDir) {
|
||||
const slug = `--${projectDir.replace(/^\/+|\/+$/g, '').replaceAll('/', '-')}--`
|
||||
return join(homedir(), '.dsh', 'sessions', slug)
|
||||
}
|
||||
|
||||
function newestSessionDir(root) {
|
||||
const entries = readdirSync(root)
|
||||
.map((name) => join(root, name))
|
||||
.filter((path) => {
|
||||
try {
|
||||
return statSync(path).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
if (entries.length === 0) throw new Error(`no session directories under ${root}`)
|
||||
return entries.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the byte ranges of every complete Zstandard frame. Session logs are
|
||||
* appended frame by frame, and Node's one-shot decoder only reads the first,
|
||||
* so the ranges are scanned here (same frame-header walk the host uses).
|
||||
*/
|
||||
function scanZstdFrames(buffer) {
|
||||
const frames = []
|
||||
let offset = 0
|
||||
while (offset < buffer.length) {
|
||||
const start = offset
|
||||
if (buffer.length - offset < 4) break
|
||||
if (buffer.readUInt32LE(offset) !== 0xfd2fb528) break
|
||||
offset += 4
|
||||
if (offset === buffer.length) break
|
||||
const descriptor = buffer.readUInt8(offset)
|
||||
offset += 1
|
||||
const contentSizeFlag = descriptor >>> 6
|
||||
const singleSegment = (descriptor & 32) !== 0
|
||||
const checksum = (descriptor & 4) !== 0
|
||||
const dictionaryFlag = descriptor & 3
|
||||
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
|
||||
const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
|
||||
offset += (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
|
||||
let complete = true
|
||||
for (;;) {
|
||||
if (buffer.length - offset < 3) {
|
||||
complete = false
|
||||
break
|
||||
}
|
||||
const blockHeader = buffer.readUIntLE(offset, 3)
|
||||
offset += 3
|
||||
const lastBlock = (blockHeader & 1) !== 0
|
||||
const blockType = (blockHeader >>> 1) & 3
|
||||
const blockSize = blockHeader >>> 3
|
||||
offset += blockType === 1 ? 1 : blockSize
|
||||
if (buffer.length - offset < 0) {
|
||||
complete = false
|
||||
break
|
||||
}
|
||||
if (lastBlock) break
|
||||
}
|
||||
if (!complete) break
|
||||
if (checksum) offset += 4
|
||||
frames.push({ start, end: offset })
|
||||
}
|
||||
return frames
|
||||
}
|
||||
|
||||
/** Session logs are appended as concatenated zstd frames; decode every frame. */
|
||||
async function readLog(sessionDir) {
|
||||
const path = join(sessionDir, 'session.v3.jsonl.zstd')
|
||||
const raw = readFileSync(path)
|
||||
let text
|
||||
if (raw.subarray(0, 4).toString('hex') === '28b52ffd') {
|
||||
const frames = scanZstdFrames(raw)
|
||||
text = frames.map((frame) => zstdDecompressSync(raw.subarray(frame.start, frame.end)).toString('utf8')).join('')
|
||||
} else {
|
||||
text = raw.toString('utf8')
|
||||
}
|
||||
return text.split('\n').filter(Boolean).map((line) => JSON.parse(line))
|
||||
}
|
||||
|
||||
function textOf(node) {
|
||||
if (node === null || typeof node !== 'object') return undefined
|
||||
if (node.type === 'text' && typeof node.text === 'string') return node.text
|
||||
for (const value of Object.values(node)) {
|
||||
const found = textOf(value)
|
||||
if (found !== undefined) return found
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
/**
|
||||
* Read one flag's value, refusing a missing one. A flag whose value is absent —
|
||||
* or is itself the next flag — used to flow through as `undefined`, which threw
|
||||
* a bare TypeError for `--project` and silently searched for the literal string
|
||||
* "undefined" for `--grep`.
|
||||
*/
|
||||
function flagValue(flag) {
|
||||
const at = argv.indexOf(flag)
|
||||
if (at < 0) return undefined
|
||||
const value = argv[at + 1]
|
||||
if (value === undefined || value.startsWith('--')) {
|
||||
console.error(`${flag} requires a value`)
|
||||
process.exit(2)
|
||||
}
|
||||
return value
|
||||
}
|
||||
let sessionDir
|
||||
const projectDir = flagValue('--project')
|
||||
if (projectDir !== undefined) {
|
||||
sessionDir = newestSessionDir(sessionRootFor(projectDir))
|
||||
} else if (argv[0] !== undefined && !argv[0].startsWith('--')) {
|
||||
sessionDir = argv[0]
|
||||
} else {
|
||||
console.error('usage: inspect-session-budget.mjs <session-dir> | --project <project-dir>')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const events = await readLog(sessionDir)
|
||||
const header = [...events].reverse().find((event) => event.type === 'request/header')
|
||||
const system = [...events].reverse().find((event) => event.type === 'system/message')
|
||||
const descriptor = events.find((event) => event.type === 'subagent/descriptor')
|
||||
const meta = events.find((event) => event.type === 'session')
|
||||
|
||||
console.log(`session : ${sessionDir}`)
|
||||
if (meta?.data?.cwd !== undefined) console.log(`cwd : ${meta.data.cwd}`)
|
||||
if (descriptor !== undefined) console.log(`subagent : provider=${descriptor.data.provider} mode=${descriptor.data.mode} label=${JSON.stringify(descriptor.data.label)}`)
|
||||
|
||||
const systemText = system === undefined ? undefined : textOf(system.data?.message ?? system.data)
|
||||
if (systemText !== undefined) {
|
||||
console.log(`system prompt: ${systemText.length} chars`)
|
||||
const catalog = systemText.includes('Roles come from role files')
|
||||
console.log(`role catalog : ${catalog ? 'present' : 'absent'}`)
|
||||
const needle = flagValue('--grep')
|
||||
if (needle !== undefined) {
|
||||
const at = systemText.indexOf(needle)
|
||||
console.log(`contains ${JSON.stringify(needle)}: ${at >= 0 ? 'YES' : 'no'}`)
|
||||
if (at >= 0) console.log(` …${systemText.slice(Math.max(0, at - 60), at + needle.length + 60).replaceAll('\n', ' / ')}…`)
|
||||
}
|
||||
if (systemText.includes('Check the [exit code: N] marker')) console.log('bash guidance: present')
|
||||
if (systemText.includes('Use the read tool — not shell commands like cat')) console.log('read guidance: present')
|
||||
}
|
||||
|
||||
const tools = header?.data?.header?.tools ?? []
|
||||
const sizes = tools
|
||||
.map((tool) => ({ name: tool.name, chars: JSON.stringify(tool).length }))
|
||||
.sort((left, right) => right.chars - left.chars)
|
||||
const total = sizes.reduce((sum, entry) => sum + entry.chars, 0)
|
||||
console.log(`tools : ${tools.length} (${total} schema chars)`)
|
||||
if (argv.includes('--all')) {
|
||||
console.log(` ${sizes.map((entry) => `${entry.name}(${entry.chars})`).join(', ')}`)
|
||||
}
|
||||
const role = tools.find((tool) => tool.name === 'subagent_role')
|
||||
if (role !== undefined) {
|
||||
// Matches BOTH of this plugin's wordings (a fork transport drops the
|
||||
// "self-contained" clause) while still rejecting the official `subagent`
|
||||
// tool, which says "to a subagent" rather than "to a role defined by a role file".
|
||||
const owner = /^Delegate a (?:self-contained )?task to a role defined by a role file/.test(String(role.description))
|
||||
? 'this plugin'
|
||||
: 'another registration of the same name'
|
||||
console.log(`subagent_role: ${JSON.stringify(role).length} chars — ${owner}`)
|
||||
}
|
||||
console.log('largest tools:')
|
||||
for (const entry of sizes.slice(0, 8)) console.log(` ${String(entry.chars).padStart(6)} ${entry.name}`)
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 采集算法专家
|
||||
description: 专注 App/algo/ 层:ADC 语义取数、全周傅氏相量、测频、保护判据的设计与实现。熟悉 TPAFE5160 原子快照、TIM3 节拍、adc_input_poll 消费模型。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 构建与门禁验证
|
||||
description: 执行 Keil 构建、pre-commit 门禁、CI 本地自查,诊断构建失败和门禁报错。熟悉 52 个钩子的触发面与口径、keil-build/serial-boot-test skill、ci_local.py 流程。
|
||||
tools: [read, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 代码审查员
|
||||
description: 审查改动的正确性、安全性与规范合规,按严重级别给出结论。熟悉本项目编码规范、分层边界、内存约束和常见陷阱。
|
||||
tools: [read, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 技术文档写手
|
||||
description: 编写和维护项目技术文档,确保文档符合写作规范、链接有效、计数准确。熟悉 docs/ 结构、doc-links/task-table/mem-numbers/generated-fresh 门禁、文档规范。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 网络协议专家
|
||||
description: 专注 CH395F SPI 以太网、netTask socket 栈、IEC 60870-5-104 上行、FTP 服务、SNTP 对时。熟悉单连接 socket 生命周期、netMsgQueue 串行模型、CH395F 中断读清约束。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 存储文件系统专家
|
||||
description: 专注 GD5F SPI NAND、dhara FTL、FatFs 文件系统、FTP 文件服务、日志记录。熟悉 FatFs 两条台架实证陷阱、NAND 坏块管理、卷自愈逻辑。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: 测试工程师
|
||||
description: 编写和维护主机侧单测、板级测试套件,验证改动的正确性。熟悉 test/host/ 结构、run_unit_test.py、board-test-suite skill、测试配置互斥约束。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
displayName: UI/LVGL 专家
|
||||
description: 专注 LVGL 160x160 单色菜单、uiTask、PC 模拟器、UI 自动化回归。熟悉 I1 palette 头越界陷阱、白底白字整屏纯白实证坑、菜单树生成器与黄金参考。
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status]
|
||||
tools: [read, edit, write, grep, glob, ops_bash, ops_inspect_local_file, ops_discover_tools, present, todo_write, send_message, list_agents, read_image, skill, create_skill, job_list, job_output, job_kill, working_directory, team_task_get, team_task_list, team_task_update, get_goal, update_goal, mnemon_recall, mnemon_remember, mnemon_document_search, session_search, session_event_search, web_search, web_fetch, schedule_create, schedule_list, create_goal, compress, decompress, search_context, acp_status, team_gate_open, team_gate_submit, team_gate_accept, team_gate_reject, team_gate_close, team_gate_list]
|
||||
maxToolCalls: 3000
|
||||
onToolCallBudget: wrap-up
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user