feat(dsh): 门禁账本插件接入 + 角色绑定跨重启还原
CI / 静态门禁 (pre-commit) (push) Failing after 43s
CI / 主机侧单测 (MSVC) (push) Failing after 24s

二、门禁与唤醒(新插件 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:
2026-11-16 00:42:51 +08:00
parent 384ad5a80d
commit 9e538d2809
31 changed files with 5616 additions and 12 deletions
@@ -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
})
}