fix(dsh): 角色工具白名单先分区再 restrict,实现文档迁入插件目录
缺陷:dsh-ops 把 ops_* 注册在 agent 自己的作用域层
(inheritable:false),全局层名册里没有这些名字。角色白名单
一旦命中 ops_*,首次 restrict 就抛错,整份策略应用失败,成员
工具面完全不设防——四个专精角色此前实际没拿到过白名单。
修复:白名单改走「先分区、再 restrict」两步——作用域层名字由
分区器摘除交策略层,全局层一次性交 restrict。三条路径(初始
注入 / 降级重试 / rebind 重放)共用同一个分区器,行为逐字一致。
两条刻意设计:
- 白名单全被分区掉时 allow 集合为空,必须显式发 {"allow":[]}
(fail closed;省略即不限制,会静默放开全部工具)
- 未向任何提供方注册的名字报 not visible yet and not
restrictable,不得误报成「未注册」——注册时机问题不能把
将来能用的名字从白名单里丢掉
真机验收(宿主重启后取证):目标角色 doc-writer 走
applied in one pass (allow=35),白名单 43 项 = 4 作用域层 +
4 不可解析 + 35 进限制,与 diag 逐行自洽;成员工具面
qq_*/workbuddy_*/ImageGen 全部不可见;persona 逐字注入。
能力边界报备(未修,文档已写明):ops_discover_tools 可激活
写侧作用域工具绕过白名单——白名单是初始可见面裁剪,不是安全
边界;要封锁写权限须连它一起排除。
文档:实现说明从 docs/环境与部署 迁入插件自带 docs/(内容全部
是本插件内部实现,按知识各归其位原则);AGENTS.md 与 docs
索引同步改指向,全仓 doc-links 与 mermaid 门禁绿。
This commit is contained in:
@@ -23,6 +23,7 @@ import { createToolCallBudgetMonitor } from './budget.js'
|
||||
import { Config } from './config.js'
|
||||
import { renderRoleCatalog } from './catalog.js'
|
||||
import { createRoleLoader } from './roles.js'
|
||||
import { partitionToolFilter, restrictableNameSet } from './policy.js'
|
||||
import { createTrimPolicySource } from './settings.js'
|
||||
import { registerChildPromptTrim } from './trim.js'
|
||||
import { LOG_PREFIX, createRoleListTool, createRoleTool } from './tool.js'
|
||||
@@ -256,8 +257,13 @@ export function apply(ctx, config = {}) {
|
||||
const diag = (msg) => {
|
||||
try { appendFileSync(diagPath, `[${new Date().toISOString()}] ${msg}\n`) } catch { /* best effort */ }
|
||||
}
|
||||
const injectedAgents = new Set()
|
||||
const injectedSessions = new Set()
|
||||
// agentId -> roleId of the LAST SUCCESSFUL injection. A Set is not enough:
|
||||
// an early "already injected" short-circuit keyed on *attempts* is what made
|
||||
// a failed install (role file missing) look installed forever, so a later
|
||||
// call with a correct cwd silently returned true without injecting anything.
|
||||
// Keyed by agentId AND sessionId so a re-materialized agent is retried.
|
||||
const injectedAgents = new Map()
|
||||
const injectedSessions = new Map()
|
||||
const pendingByLabel = new Map() // label or name -> { roleId, cwd, applied }
|
||||
const pendingMarker = new Map() // sessionId -> roleId
|
||||
const evtCounts = new Map()
|
||||
@@ -334,10 +340,53 @@ export function apply(ctx, config = {}) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const applyToolPolicy = (tools, filter) => {
|
||||
/**
|
||||
* The names one agent's scope can actually see, for the partition's
|
||||
* unresolved-vs-scope-local distinction. Undefined (not an empty set) when the
|
||||
* registry cannot answer, so a failure never looks like "nothing visible".
|
||||
*/
|
||||
const visibleNameSet = (tools, agent) => {
|
||||
try {
|
||||
const view = typeof tools?.view === 'function' ? tools.view(agent) : undefined
|
||||
const visible = view?.visible
|
||||
return visible instanceof Map ? new Set(visible.keys()) : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const applyToolPolicy = (tools, filter, context = {}) => {
|
||||
if (filter === undefined) return
|
||||
const attempt = (f) => { try { tools.restrict(f); return true } catch { return false } }
|
||||
if (attempt(filter)) return
|
||||
// Split off names `restrict()` cannot accept BEFORE the first attempt, so
|
||||
// the policy lands cleanly instead of degrading through a thrown
|
||||
// exception. Without this every role whitelist that mentions a
|
||||
// scope-local tool (the `ops_*` family lives on the agent's own layer)
|
||||
// paid a guaranteed exception per injection and the diag could only ever
|
||||
// say "applied via reduced list" — indistinguishable from a real failure.
|
||||
const partition = partitionToolFilter(filter, context)
|
||||
if (partition.scopeLocal.length > 0 || partition.unresolved.length > 0 || partition.unenforceable.length > 0) {
|
||||
const role = context.roleId === undefined ? '' : ` for role "${context.roleId}"`
|
||||
if (partition.scopeLocal.length > 0) diag(`tool policy${role}: omitted ${partition.scopeLocal.length} scope-local name(s) (visible either way): ${partition.scopeLocal.join(',')}`)
|
||||
// "not visible yet", never "not registered": a lazily registered
|
||||
// scope-local tool looks identical to a typo at this instant.
|
||||
if (partition.unresolved.length > 0) diag(`tool policy${role}: ${partition.unresolved.length} name(s) not visible yet and not restrictable, so left out of the enforced policy: ${partition.unresolved.join(',')}`)
|
||||
if (partition.unenforceable.length > 0) diag(`tool policy${role}: cannot deny ${partition.unenforceable.length} scope-local tool(s), they stay visible: ${partition.unenforceable.join(',')}`)
|
||||
}
|
||||
const planned = partition.filter
|
||||
if (planned === undefined) {
|
||||
// Nothing enforceable survived (e.g. a `deny` list made entirely of
|
||||
// scope-local names). Restricting with the original filter would throw
|
||||
// and re-enter the reactive path, so stop here and say why.
|
||||
diag(`tool policy${context.roleId === undefined ? '' : ` for role "${context.roleId}"`}: no enforceable entry remains; the child keeps its inherited surface`)
|
||||
return
|
||||
}
|
||||
if (attempt(planned)) {
|
||||
// The clean path now leaves a record too: a silent success is what made
|
||||
// "did the whitelist actually bind?" unanswerable from the log alone.
|
||||
diag(`tool policy applied in one pass${context.roleId === undefined ? '' : ` for role "${context.roleId}"`} (allow=${planned?.allow?.length ?? 'n/a'}${planned?.deny === undefined ? '' : `, deny=${planned.deny.length}`})`)
|
||||
return
|
||||
}
|
||||
let reduced = filter
|
||||
try {
|
||||
const msg = (() => { try { tools.restrict(filter) } catch (e) { return String(e?.message ?? e) } return '' })()
|
||||
@@ -352,23 +401,44 @@ export function apply(ctx, config = {}) {
|
||||
diag(`tool policy reduce threw: ${String(error?.message ?? error)}`)
|
||||
return
|
||||
}
|
||||
if (attempt(reduced)) diag(`tool policy applied via reduced list`)
|
||||
const allowOf = (f) => (Array.isArray(f) ? f : (f?.allow ?? f?.allowedTools))
|
||||
const before = allowOf(filter) ?? []
|
||||
const after = new Set(allowOf(reduced) ?? [])
|
||||
const dropped = before.filter((n) => !after.has(n))
|
||||
if (attempt(reduced)) diag(`tool policy applied via reduced list (dropped ${dropped.length}: ${dropped.join(',') || 'none'})`)
|
||||
else diag(`tool policy still failed after reduce`)
|
||||
}
|
||||
|
||||
const installRoleOn = (agent, roleId, cwd) => {
|
||||
if (agent === undefined) return false
|
||||
if (injectedAgents.has(agent.id)) return true
|
||||
const result = tryInstallRoleOn(agent, roleId, cwd)
|
||||
if (!result.ok) {
|
||||
// Negative record: without it, "no binding in the file" cannot be told
|
||||
// apart from "binding written and then failed", so verification step 2
|
||||
// could never prove a negative. Keyed the same way as a real binding.
|
||||
const sessionId = agent?.id !== undefined ? normId(agent.id) : undefined
|
||||
if (typeof sessionId === 'string' && !bindings.has(sessionId)) {
|
||||
diag(`install FAILED for role "${roleId}" on agent ${String(agent?.id)}: ${result.reason}`)
|
||||
}
|
||||
}
|
||||
return result.ok
|
||||
}
|
||||
|
||||
const tryInstallRoleOn = (agent, roleId, cwd) => {
|
||||
if (agent === undefined) return { ok: false, reason: 'agent undefined' }
|
||||
// Only a SUCCESSFUL install for THIS role counts as done. A different
|
||||
// role, or a previous attempt that failed to find its file, must be
|
||||
// retried — otherwise one bad cwd poisons the agent for its lifetime.
|
||||
if (injectedAgents.get(agent.id) === roleId) return { ok: true, reason: 'already' }
|
||||
const sysPrompt = agent?.ctx?.systemPrompt
|
||||
if (sysPrompt === undefined || typeof sysPrompt.section !== 'function') {
|
||||
diag(`install skipped: no systemPrompt.section on agent ${String(agent?.id)}`)
|
||||
return false
|
||||
return { ok: false, reason: 'no systemPrompt.section' }
|
||||
}
|
||||
const { roles } = loader.loadSync(cwd, { freshDiagnostics: false })
|
||||
const role = roles.find((r) => r.id === roleId)
|
||||
if (role === undefined || role.persona === undefined) {
|
||||
diag(`role "${roleId}" not found (cwd=${String(cwd)})`)
|
||||
return false
|
||||
return { ok: false, reason: `role not found at cwd=${String(cwd)}` }
|
||||
}
|
||||
const order = Number(sysPrompt.getSectionOrder?.('DEPLOYMENT_PERSONA_PREFIX'))
|
||||
sysPrompt.section({
|
||||
@@ -376,12 +446,20 @@ export function apply(ctx, config = {}) {
|
||||
order: Number.isFinite(order) ? order : 0,
|
||||
text: role.persona,
|
||||
})
|
||||
applyToolPolicy(agent?.ctx?.tools, role.toolFilter)
|
||||
injectedAgents.add(agent.id)
|
||||
// Hand the partition its two facts: which names the child's scope can
|
||||
// restrict, and which ones it can see at all. Both come from the child's
|
||||
// own registry view, never from the parent's — the whole point is that
|
||||
// the two views differ.
|
||||
applyToolPolicy(agent?.ctx?.tools, role.toolFilter, {
|
||||
roleId,
|
||||
restrictableNames: restrictableNameSet(agent?.ctx?.tools, agent),
|
||||
visibleNames: visibleNameSet(agent?.ctx?.tools, agent),
|
||||
})
|
||||
injectedAgents.set(agent.id, roleId)
|
||||
const sid = agent?.session?.header?.id ?? agent?.session?.id
|
||||
if (typeof sid === 'string') injectedSessions.add(sid)
|
||||
if (typeof sid === 'string') injectedSessions.set(sid, roleId)
|
||||
diag(`injected role "${roleId}" (${role.persona.length} chars) into agent ${String(agent?.id)} (pre=${evtCounts.get(sid) === undefined ? '?' : 'x'})`)
|
||||
return true
|
||||
return { ok: true, reason: 'injected' }
|
||||
}
|
||||
|
||||
if (typeof ctx.on !== 'function') { diag('ctx.on unavailable at apply time'); return }
|
||||
@@ -464,7 +542,13 @@ export function apply(ctx, config = {}) {
|
||||
// agent with the full tool surface.
|
||||
ctx.on('agent/created', ({ agent }) => {
|
||||
try {
|
||||
if (agent === undefined || injectedAgents.has(agent.id)) return
|
||||
if (agent === undefined) return
|
||||
// Skip only when THIS role already landed on this agent instance.
|
||||
if (injectedAgents.get(agent.id) !== undefined) {
|
||||
const already = injectedAgents.get(agent.id)
|
||||
diag(`restore skipped: role "${already}" already present on ${String(agent.id)}`)
|
||||
return
|
||||
}
|
||||
const keys = [normId(agent.id), normId(agent?.session?.header?.id), normId(agent?.session?.id)]
|
||||
let binding
|
||||
for (const key of keys) {
|
||||
|
||||
@@ -51,6 +51,84 @@ export function parseUnrestrictableToolNames(error) {
|
||||
return [...new Set(names)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the set of names `tools.restrict()` will actually accept in one scope.
|
||||
*
|
||||
* The core only restricts INHERITED GLOBAL tools: a tool registered on the
|
||||
* agent's own scope layer (the `ops_*` family, for instance) is visible to that
|
||||
* agent but unknown to `restrict()`, which throws on it. That distinction is
|
||||
* invisible from `schemas()` alone, so a role whitelist that lists such a name
|
||||
* always loses its first `restrict()` call to an exception and silently
|
||||
* degrades through the reactive "drop what the error named" path.
|
||||
*
|
||||
* @param tools - the tools service (or a scoped view of it).
|
||||
* @param scope - the viewing scope (the agent).
|
||||
* @returns the restrictable names, or undefined when the registry cannot say.
|
||||
*/
|
||||
export function restrictableNameSet(tools, scope) {
|
||||
try {
|
||||
const view = typeof tools?.view === 'function' ? tools.view(scope) : undefined
|
||||
const names = view?.restrictableNames
|
||||
return names instanceof Set ? names : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a filter into the part `restrict()` accepts and the parts it cannot.
|
||||
*
|
||||
* Three buckets, because the three causes need three different responses:
|
||||
* `scopeLocal` names are visible but owned by the agent's own layer, so they
|
||||
* stay visible whether or not the policy names them — omitting them is lossless
|
||||
* and it is what keeps `restrict()` from throwing; `unresolved` names are
|
||||
* neither restrictable nor visible AT THIS INSTANT and are a role-file error
|
||||
* only when the name is genuinely absent (see the caveat below);
|
||||
* `unenforceable` names were asked to be DENIED but cannot be, which is a real
|
||||
* capability gap the caller must report rather than swallow.
|
||||
*
|
||||
* CAVEAT on `unresolved`: a scope-local tool registered LAZILY — after this
|
||||
* scope is composed, or behind a `when` admission — is indistinguishable here
|
||||
* from a typo, because both are absent from the registry view at this instant.
|
||||
* Callers must therefore word the finding as "not visible now", never as "this
|
||||
* deployment does not register it": the latter is a claim this function cannot
|
||||
* support, and asserting it turns a timing artifact into a false role-file bug.
|
||||
*
|
||||
* @param filter - normalized `{ allow?, deny? }`.
|
||||
* @param options - `restrictableNames` and `visibleNames` sets.
|
||||
* @returns `{ filter?, scopeLocal, unresolved, unenforceable }`; `filter` is the
|
||||
* original filter untouched when `restrictableNames` is unavailable (never
|
||||
* fail open by guessing which names the core would reject).
|
||||
*/
|
||||
export function partitionToolFilter(filter, options = {}) {
|
||||
const restrictable = options.restrictableNames instanceof Set ? options.restrictableNames : undefined
|
||||
const visible = options.visibleNames instanceof Set ? options.visibleNames : undefined
|
||||
const scopeLocal = []
|
||||
const unresolved = []
|
||||
const unenforceable = []
|
||||
if (restrictable === undefined) return { filter, scopeLocal, unresolved, unenforceable }
|
||||
const classify = (name, bucket) => {
|
||||
if (restrictable.has(name)) return true
|
||||
if (visible !== undefined && !visible.has(name)) unresolved.push(name)
|
||||
else bucket.push(name)
|
||||
return false
|
||||
}
|
||||
const kept = {}
|
||||
// An `allow` that survives as an EMPTY list must be kept, not dropped: an
|
||||
// empty allow means "no tools" (fail closed), while omitting the key means
|
||||
// "no restriction at all" (fail open). A role whose whitelist happens to be
|
||||
// entirely scope-local names must not silently escalate to the full surface.
|
||||
if (filter?.allow !== undefined) kept.allow = filter.allow.filter((name) => classify(name, scopeLocal))
|
||||
if (filter?.deny !== undefined) {
|
||||
const deny = filter.deny.filter((name) => classify(name, unenforceable))
|
||||
if (deny.length > 0) kept.deny = deny
|
||||
}
|
||||
if (kept.allow === undefined && kept.deny === undefined) {
|
||||
return { filter: undefined, scopeLocal, unresolved, unenforceable }
|
||||
}
|
||||
return { filter: kept, scopeLocal, unresolved, unenforceable }
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a normalized filter without the named entries. An explicit `allow` list
|
||||
* is preserved even when it becomes empty (that still means "no tools").
|
||||
|
||||
@@ -21,6 +21,8 @@ import {
|
||||
expandToolFilter,
|
||||
isUnrestrictableToolName,
|
||||
parseUnrestrictableToolNames,
|
||||
partitionToolFilter,
|
||||
restrictableNameSet,
|
||||
sumSchemaChars,
|
||||
} from './policy.js'
|
||||
import { resolveRoleRoute } from './route.js'
|
||||
@@ -56,8 +58,25 @@ function visibleToolSchemas(ctx, agent) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialized-schema length per tool name, for budget diagnostics. */
|
||||
function schemaCharsByName(schemas) {
|
||||
/**
|
||||
* The names one agent's scope can see, for the partition's unresolved-vs-scope-local
|
||||
* distinction. Undefined (not an empty set) when the registry cannot answer, so
|
||||
* a failure never looks like "nothing is visible".
|
||||
* @param tools - the tools service.
|
||||
* @param agent - the viewing agent scope.
|
||||
* @returns the visible names, or undefined.
|
||||
*/
|
||||
function visibleNameSet(tools, agent) {
|
||||
try {
|
||||
const view = typeof tools?.view === 'function' ? tools.view(agent) : undefined
|
||||
const visible = view?.visible
|
||||
return visible instanceof Map ? new Set(visible.keys()) : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialized-schema length per tool name, for budget diagnostics. */function schemaCharsByName(schemas) {
|
||||
const map = {}
|
||||
for (const schema of schemas) {
|
||||
if (schema === null || typeof schema !== 'object' || typeof schema.name !== 'string') continue
|
||||
@@ -814,8 +833,17 @@ export function createRoleTool(options) {
|
||||
}
|
||||
const tools = child?.ctx?.tools
|
||||
if (composition.toolFilter !== undefined && typeof tools?.restrict === 'function') {
|
||||
// Partition against the CHILD's own view: the caller already partitioned
|
||||
// against the delegating agent's view, but the two scopes need not expose
|
||||
// the same restrictable set. Doing it here too means the normal path never
|
||||
// depends on catching an exception.
|
||||
const partition = partitionToolFilter(composition.toolFilter, {
|
||||
restrictableNames: restrictableNameSet(tools, child),
|
||||
visibleNames: visibleNameSet(tools, child),
|
||||
})
|
||||
const planned = partition.filter ?? composition.toolFilter
|
||||
try {
|
||||
tools.restrict(composition.toolFilter)
|
||||
tools.restrict(planned)
|
||||
} catch (error) {
|
||||
// A tool registered on the delegating agent's own layer is visible to the
|
||||
// parent but unknown to the child's scope. Drop exactly those names and
|
||||
@@ -824,7 +852,7 @@ export function createRoleTool(options) {
|
||||
// original failure is kept and surfaces from `startDelegation`.
|
||||
if (composition.onMissing === 'error') throw error
|
||||
const names = parseUnrestrictableToolNames(error)
|
||||
const next = names.length === 0 ? undefined : dropToolFilterNames(composition.toolFilter, names)
|
||||
const next = names.length === 0 ? undefined : dropToolFilterNames(planned, names)
|
||||
if (next === undefined) throw error
|
||||
tools.restrict(next)
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] the child's scope cannot restrict ${names.map((name) => `"${name}"`).join(', ')}; they were dropped from the role's tool policy`)
|
||||
@@ -965,6 +993,31 @@ export function createRoleTool(options) {
|
||||
warnings.push(message)
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] ${message}`)
|
||||
}
|
||||
// Split off the names `restrict()` cannot accept BEFORE handing the
|
||||
// filter to the child, so the policy lands on the first attempt instead
|
||||
// of degrading through a thrown exception. A scope-local name (the
|
||||
// `ops_*` family is registered on the agent's own layer) stays visible
|
||||
// regardless, so dropping it from `allow` costs nothing; a denied one
|
||||
// cannot be enforced at all and is reported instead of silently kept.
|
||||
const partition = partitionToolFilter(toolFilter, {
|
||||
restrictableNames: restrictableNameSet(ctx.tools, agent),
|
||||
visibleNames,
|
||||
})
|
||||
toolFilter = partition.filter
|
||||
if (partition.scopeLocal.length > 0) {
|
||||
ctx.logger?.info?.(`[${LOG_PREFIX}] role "${role.id}": ${partition.scopeLocal.length} scope-local tool(s) omitted from the enforced policy (they stay visible either way): ${partition.scopeLocal.join(', ')}`)
|
||||
}
|
||||
if (partition.unresolved.length > 0) {
|
||||
// Wording matters: at composition time a lazily registered tool and a
|
||||
// typo are indistinguishable, so this reports what was observed (not
|
||||
// visible yet) rather than what would be a role-file bug.
|
||||
ctx.logger?.info?.(`[${LOG_PREFIX}] role "${role.id}": ${partition.unresolved.length} name(s) not visible yet at composition time: ${partition.unresolved.join(', ')}`)
|
||||
}
|
||||
if (partition.unenforceable.length > 0) {
|
||||
const message = `${ERROR_PREFIX} role "${role.id}" denies tool(s) it cannot restrict; they stay visible to the child: ${partition.unenforceable.join(', ')}`
|
||||
warnings.push(message)
|
||||
ctx.logger?.warn?.(`[${LOG_PREFIX}] ${message}`)
|
||||
}
|
||||
if (toolFilter?.allow?.length === 0) {
|
||||
const message = `${ERROR_PREFIX} role "${role.id}" allows no currently available tool; the child will see an empty tool set`
|
||||
warnings.push(message)
|
||||
@@ -1277,6 +1330,17 @@ export function createRoleListTool(options) {
|
||||
lines.push(` budget: ${sumSchemaChars(chars, filter.allow)} of ${totalVisible} visible tool-schema chars`)
|
||||
}
|
||||
if (expansion.dropped.length > 0) lines.push(` unavailable: ${expansion.dropped.join(', ')}`)
|
||||
// What the child's own scope can enforce differs from what this scope
|
||||
// can see: scope-local tools are visible here but not restrictable
|
||||
// there. Show the difference so a role file is not read as binding
|
||||
// names it structurally cannot bind.
|
||||
const partition = partitionToolFilter(expansion.filter, {
|
||||
restrictableNames: agent === undefined ? undefined : restrictableNameSet(ctx.tools, agent),
|
||||
visibleNames: new Set(Object.keys(chars)),
|
||||
})
|
||||
if (partition.scopeLocal.length > 0) lines.push(` not enforceable (scope-local, stays visible): ${partition.scopeLocal.join(', ')}`)
|
||||
if (partition.unresolved.length > 0) lines.push(` not visible at composition time (scope-local or not yet registered): ${partition.unresolved.join(', ')}`)
|
||||
if (partition.unenforceable.length > 0) lines.push(` deny not enforceable (stays visible): ${partition.unenforceable.join(', ')}`)
|
||||
}
|
||||
}
|
||||
if (diagnostics.length > 0) {
|
||||
|
||||
Reference in New Issue
Block a user