Files
STM32F4-Base/.dsh/plugins/dsh-plugin-subagent-roles/lib/policy.js
T
wandering1 1b740e07b3 fix(dsh): 角色工具白名单先分区再 restrict,实现文档迁入插件目录
缺陷:dsh-ops 把 ops_* 注册在 agent 自己的作用域层
(inheritable:false),全局层名册里没有这些名字。角色白名单
一旦命中 ops_*,首次 restrict 就抛错,整份策略应用失败,成员
工具面完全不设防——四个专精角色此前实际没拿到过白名单。

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

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

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

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

文档:实现说明从 docs/环境与部署 迁入插件自带 docs/(内容全部
是本插件内部实现,按知识各归其位原则);AGENTS.md 与 docs
索引同步改指向,全仓 doc-links 与 mermaid 门禁绿。
2026-11-16 16:42:59 +08:00

235 lines
9.9 KiB
JavaScript

/**
* 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)]
}
/**
* Read the set of names `tools.restrict()` will actually accept in one scope.
*
* The core only restricts INHERITED GLOBAL tools: a tool registered on the
* agent's own scope layer (the `ops_*` family, for instance) is visible to that
* agent but unknown to `restrict()`, which throws on it. That distinction is
* invisible from `schemas()` alone, so a role whitelist that lists such a name
* always loses its first `restrict()` call to an exception and silently
* degrades through the reactive "drop what the error named" path.
*
* @param tools - the tools service (or a scoped view of it).
* @param scope - the viewing scope (the agent).
* @returns the restrictable names, or undefined when the registry cannot say.
*/
export function restrictableNameSet(tools, scope) {
try {
const view = typeof tools?.view === 'function' ? tools.view(scope) : undefined
const names = view?.restrictableNames
return names instanceof Set ? names : undefined
} catch {
return undefined
}
}
/**
* Split a filter into the part `restrict()` accepts and the parts it cannot.
*
* Three buckets, because the three causes need three different responses:
* `scopeLocal` names are visible but owned by the agent's own layer, so they
* stay visible whether or not the policy names them — omitting them is lossless
* and it is what keeps `restrict()` from throwing; `unresolved` names are
* neither restrictable nor visible AT THIS INSTANT and are a role-file error
* only when the name is genuinely absent (see the caveat below);
* `unenforceable` names were asked to be DENIED but cannot be, which is a real
* capability gap the caller must report rather than swallow.
*
* CAVEAT on `unresolved`: a scope-local tool registered LAZILY — after this
* scope is composed, or behind a `when` admission — is indistinguishable here
* from a typo, because both are absent from the registry view at this instant.
* Callers must therefore word the finding as "not visible now", never as "this
* deployment does not register it": the latter is a claim this function cannot
* support, and asserting it turns a timing artifact into a false role-file bug.
*
* @param filter - normalized `{ allow?, deny? }`.
* @param options - `restrictableNames` and `visibleNames` sets.
* @returns `{ filter?, scopeLocal, unresolved, unenforceable }`; `filter` is the
* original filter untouched when `restrictableNames` is unavailable (never
* fail open by guessing which names the core would reject).
*/
export function partitionToolFilter(filter, options = {}) {
const restrictable = options.restrictableNames instanceof Set ? options.restrictableNames : undefined
const visible = options.visibleNames instanceof Set ? options.visibleNames : undefined
const scopeLocal = []
const unresolved = []
const unenforceable = []
if (restrictable === undefined) return { filter, scopeLocal, unresolved, unenforceable }
const classify = (name, bucket) => {
if (restrictable.has(name)) return true
if (visible !== undefined && !visible.has(name)) unresolved.push(name)
else bucket.push(name)
return false
}
const kept = {}
// An `allow` that survives as an EMPTY list must be kept, not dropped: an
// empty allow means "no tools" (fail closed), while omitting the key means
// "no restriction at all" (fail open). A role whose whitelist happens to be
// entirely scope-local names must not silently escalate to the full surface.
if (filter?.allow !== undefined) kept.allow = filter.allow.filter((name) => classify(name, scopeLocal))
if (filter?.deny !== undefined) {
const deny = filter.deny.filter((name) => classify(name, unenforceable))
if (deny.length > 0) kept.deny = deny
}
if (kept.allow === undefined && kept.deny === undefined) {
return { filter: undefined, scopeLocal, unresolved, unenforceable }
}
return { filter: kept, scopeLocal, unresolved, unenforceable }
}
/**
* Copy a normalized filter without the named entries. An explicit `allow` list
* is preserved even when it becomes empty (that still means "no tools").
* @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
}