/** * `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: `/.dsh/roles/.md` (project) * and `~/.dsh/roles/.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 { partitionToolFilter, restrictableNameSet } from './policy.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:` convention: this is a global (host-plane) section that must * never collide with the scoped `tool:` 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:` 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 */ } } // 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() // ---- 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 } /** * 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 } } // 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 '' })() 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 } 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) => { 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 { 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 { ok: false, reason: `role not found at cwd=${String(cwd)}` } } const order = Number(sysPrompt.getSectionOrder?.('DEPLOYMENT_PERSONA_PREFIX')) sysPrompt.section({ name: 'deployment:persona-prefix', order: Number.isFinite(order) ? order : 0, text: role.persona, }) // 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.set(sid, roleId) diag(`injected role "${roleId}" (${role.persona.length} chars) into agent ${String(agent?.id)} (pre=${evtCounts.get(sid) === undefined ? '?' : 'x'})`) return { ok: true, reason: 'injected' } } 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) 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) { 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') }) } }) }