Files
STM32F4-Base/.dsh/plugins/dsh-plugin-subagent-roles/lib/index.js
T
wandering1 9e538d2809
CI / 静态门禁 (pre-commit) (push) Failing after 43s
CI / 主机侧单测 (MSVC) (push) Failing after 24s
feat(dsh): 门禁账本插件接入 + 角色绑定跨重启还原
二、门禁与唤醒(新插件 dsh-plugin-team-ledger 0.2.0)
宿主 Agent Teams 缺两块能力,补在独立仓
D:/Code/AI/dsh-plugin-team-ledger:

- 状态存放:<工作区>/.dsh/team/gate.jsonl 追加账本,记验收
  清单、实测证据、认领历史,跨重启存活;canonical JSON +
  fsync,坏尾行截断恢复。
- 唤醒模型:门禁推进后按事件计划唤醒下一责任人,借活体
  Lead 作 caller 走宿主 sendMessage;无定时器;30 分钟滑动
  窗口限 4 次防复活风暴。
- 验收独立性由机器强制:执行人/历史认领者不能 accept,
  checklist 逐项 passed=true 缺一不可。
- team_member_revive(Lead 专用):成员模型路由死亡后的
  复活通道——可换 provider/model,再经 subagents.sendMessage
  冷恢复唤醒,绕过宿主 roster 的 phase=active 门禁。

二、角色绑定跨重启还原(roles fork 0.5.2)
persona 与工具白名单只有运行中 agent 的内存态,宿主重启后
冷恢复的成员既无 persona 也无白名单——实测出现 doc-writer
成员带全量工具面(qq_*/ImageGen),属静默权限放大。改为
注入成功时持久化 childId -> {roleId, cwd} 到
~/.dsh/role-inject-bindings.json,并在 agent/created 时重放。
追加 team_member_rebind 补绑定,覆盖 0.5.2 之前已存在的成员。

三、配套
- .dsh/roles 八个角色白名单加入门禁工具;AGENTS.md 委派策略
  补门禁/复活/重绑三套操作口径。
- docs/环境与部署/子Agent角色自动注入实现说明.md 新增
  §5.1,记录绑定机制、存量成员缺口与「成员自省不可全信」的
  台架教训。
2026-11-16 00:42:51 +08:00

540 lines
28 KiB
JavaScript

/**
* `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')
})
}
})
}