Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(security): sub-agent lineage — orchestration tools opt-in and confined to descendants (#74)
Salman Qureshi1469d1d8ebbb
diff --git a/src/capabilities/subagents/delegate-task.ts b/src/capabilities/subagents/delegate-task.tsindex 6aeec3d8..936e3393 100644--- a/src/capabilities/subagents/delegate-task.ts+++ b/src/capabilities/subagents/delegate-task.ts@@ -3,20 +3,22 @@ import { z } from 'zod';import { zodSchema } from 'ai';import type { SubAgentSupervisor } from '../../core/supervisor.js';import type { CapabilityRegistry } from '../registry.js';+import type { SubAgentToolOptions } from './stop-agent.js';import { logger } from '../../utils/logger.js';-export function createDelegateTaskTool(supervisor: SubAgentSupervisor, capabilities: CapabilityRegistry) {+export function createDelegateTaskTool(supervisor: SubAgentSupervisor, capabilities: CapabilityRegistry, options: SubAgentToolOptions = {}) {+ const { callerId } = options;return tool({description: 'Delegate a task to a sub-agent worker. Use this for complex, multi-step tasks that can run in parallel. The sub-agent works independently — you will be notified when it completes. You can continue handling other messages while sub-agents work.',inputSchema: zodSchema(z.object({task: z.string().describe('Clear description of the task for the sub-agent to complete'),workingDirectory: z.string().optional().describe('Working directory for the sub-agent (defaults to current directory)'),priority: z.enum(['low', 'normal', 'high']).optional().describe('Task priority (default: normal)'),- allowedTools: z.array(z.string()).optional().describe('Optional list of tool names this sub-agent is allowed to use. If not specified, all tools are available.'),+ allowedTools: z.array(z.string()).optional().describe('Optional list of tool names this sub-agent is allowed to use. If not specified, every tool except delegate_task, list_agents and stop_agent is available; name those explicitly to grant them.'),})),execute: async ({ task, workingDirectory, priority, allowedTools }) => {try {- logger.info({ task: task.slice(0, 50) }, 'Delegating task to sub-agent');+ logger.info({ task: task.slice(0, 50), parentId: callerId }, 'Delegating task to sub-agent');const { channelId, channelType } = capabilities.getChannelContext();@@ -27,6 +29,9 @@ export function createDelegateTaskTool(supervisor: SubAgentSupervisor, capabilitallowedTools,sourceChannelId: channelId,sourceChannelType: channelType,+ // Lineage: a child spawned by a sub-agent records its parent so+ // list_agents/stop_agent can be confined to that subtree.+ parentId: callerId,});const resourceInfo = supervisor.getResourceUsage();@@ -44,4 +49,4 @@ export function createDelegateTaskTool(supervisor: SubAgentSupervisor, capabilit}},});-}\ No newline at end of file+}diff --git a/src/capabilities/subagents/index.ts b/src/capabilities/subagents/index.tsindex 26eddeb7..96eeafe2 100644--- a/src/capabilities/subagents/index.ts+++ b/src/capabilities/subagents/index.ts@@ -1,3 +1,3 @@export { createDelegateTaskTool } from './delegate-task.js';export { createListAgentsTool } from './list-agents.js';-export { createStopAgentTool } from './stop-agent.js';\ No newline at end of file+export { createStopAgentTool, type SubAgentToolOptions } from './stop-agent.js';\ No newline at end of filediff --git a/src/capabilities/subagents/list-agents.ts b/src/capabilities/subagents/list-agents.tsindex 36524c9d..72bdaf29 100644--- a/src/capabilities/subagents/list-agents.ts+++ b/src/capabilities/subagents/list-agents.ts@@ -2,26 +2,33 @@ import { tool } from 'ai';import { z } from 'zod';import { zodSchema } from 'ai';import type { SubAgentSupervisor } from '../../core/supervisor.js';+import type { SubAgentToolOptions } from './stop-agent.js';-export function createListAgentsTool(supervisor: SubAgentSupervisor) {+export function createListAgentsTool(supervisor: SubAgentSupervisor, options: SubAgentToolOptions = {}) {+ const { callerId } = options;return tool({- description: 'List all active and queued sub-agents with their status, task, and progress. Use this to check what sub-agents are currently working on.',+ description: callerId+ ? 'List the sub-agents you delegated (and their descendants) with their status, task, and progress.'+ : 'List all active and queued sub-agents with their status, task, and progress. Use this to check what sub-agents are currently working on.',inputSchema: zodSchema(z.object({})),execute: async () => {- const agents = supervisor.getActiveAgents();+ // A sub-agent only sees its own descendants; the main agent sees all.+ const agents = supervisor.getActiveAgents(callerId);const resourceInfo = supervisor.getResourceUsage();if (agents.length === 0) {- return `No active sub-agents.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`;+ return callerId+ ? `No agents delegated by you are active.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`+ : `No active sub-agents.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`;}const statusIcons: Record<string, string> = {pending: '\u{1f535}',running: '\u{1f7e2}',paused: '\u{1f7e1}',- completed: '\u2705',- failed: '\u274c',- halted: '\u26d4',+ completed: '✅',+ failed: '❌',+ halted: '⛔',};const lines = [@@ -30,7 +37,7 @@ export function createListAgentsTool(supervisor: SubAgentSupervisor) {];for (const agent of agents) {- const icon = statusIcons[agent.status] || '\u2753';+ const icon = statusIcons[agent.status] || '❓';const taskPreview = agent.task.length > 40 ? agent.task.slice(0, 40) + '...' : agent.task;lines.push(`${icon} **${agent.id}** ${taskPreview}`);if (agent.progress) {@@ -45,4 +52,4 @@ export function createListAgentsTool(supervisor: SubAgentSupervisor) {return lines.join('\n');},});-}\ No newline at end of file+}diff --git a/src/capabilities/subagents/stop-agent.ts b/src/capabilities/subagents/stop-agent.tsindex e7258388..984a0e74 100644--- a/src/capabilities/subagents/stop-agent.ts+++ b/src/capabilities/subagents/stop-agent.ts@@ -4,26 +4,49 @@ import { zodSchema } from 'ai';import type { SubAgentSupervisor } from '../../core/supervisor.js';import { logger } from '../../utils/logger.js';-export function createStopAgentTool(supervisor: SubAgentSupervisor) {+export interface SubAgentToolOptions {+ /**+ * Id of the sub-agent this tool instance belongs to. Undefined means the+ * main agent, which owns the whole tree. A sub-agent's instance may only+ * act on its own descendants (#74).+ */+ callerId?: string;+}++export function createStopAgentTool(supervisor: SubAgentSupervisor, options: SubAgentToolOptions = {}) {+ const { callerId } = options;+ const scopeNote = callerId ? ' Only agents you delegated (and their descendants) can be stopped.' : '';return tool({- description: 'Stop a running or queued sub-agent, or stop all sub-agents. The agent will finish its current tool step before halting.',+ description: `Stop a running or queued sub-agent, or stop all sub-agents. The agent will finish its current tool step before halting.${scopeNote}`,inputSchema: zodSchema(z.object({- agentId: z.string().describe('ID of the sub-agent to stop (e.g. "a1"), or "all" to stop every agent'),+ agentId: z.string().describe(callerId+ ? 'ID of the sub-agent to stop (e.g. "a1"), or "all" to stop every agent you delegated'+ : 'ID of the sub-agent to stop (e.g. "a1"), or "all" to stop every agent'),})),execute: async ({ agentId }) => {try {if (agentId.toLowerCase() === 'all') {- await supervisor.haltAll();- logger.info('All sub-agents halted via stop_agent tool');+ const halted = await supervisor.haltAll(callerId);+ logger.info({ callerId, halted }, 'Sub-agents halted via stop_agent tool');+ if (callerId) {+ return halted.length === 0+ ? 'No agents delegated by you are active.'+ : `Halted ${halted.length} agent${halted.length === 1 ? '' : 's'} you delegated (${halted.join(', ')}). Any agent currently executing a tool step will finish that step before stopping.`;+ }return 'All sub-agents have been halted. Any agents currently executing a tool step will finish that step before stopping.';}- const halted = await supervisor.halt(agentId);+ if (callerId && !supervisor.isDescendant(agentId, callerId)) {+ logger.warn({ callerId, agentId }, 'stop_agent refused: target is not a descendant of the caller');+ return `Agent ${agentId} was not delegated by you, so you cannot stop it. Use list_agents to see the agents you delegated.`;+ }++ const halted = await supervisor.halt(agentId, callerId);if (!halted) {return `No active agent found with ID "${agentId}". Use the list_agents tool to see active agents.`;}- logger.info({ agentId }, 'Sub-agent halted via stop_agent tool');+ logger.info({ agentId, callerId }, 'Sub-agent halted via stop_agent tool');return `Agent ${agentId} halt signal sent. It will finish its current tool step and then stop. File locks will be released automatically.`;} catch (err: any) {logger.error({ err }, 'Failed to stop agent');@@ -31,4 +54,4 @@ export function createStopAgentTool(supervisor: SubAgentSupervisor) {}},});-}\ No newline at end of file+}diff --git a/src/core/sub-agent-approval.test.ts b/src/core/sub-agent-approval.test.tsnew file mode 100644index 00000000..afc7bc6d--- /dev/null+++ b/src/core/sub-agent-approval.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it, afterAll, vi } from 'vitest';+import { existsSync, rmSync, mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { MockLanguageModelV3 } from 'ai/test';+import type { LanguageModelV3GenerateResult, LanguageModelV3Usage } from '@ai-sdk/provider';++// permissions.yaml and the task board live under MERCURY_HOME, resolved at+// import time — point it at a scratch directory before anything loads.+const home = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = mkdtempSync(join(tmpdir(), 'mercury-subagent-'));+ process.env.MERCURY_HOME = dir;+ return dir;+});++const { SubAgent } = await import('./sub-agent.js');+const { CapabilityRegistry } = await import('../capabilities/registry.js');+const { FileLockManager } = await import('./file-lock.js');+const { TaskBoard } = await import('./task-board.js');++const usage: LanguageModelV3Usage = {+ inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },+ outputTokens: { total: 1, text: 1, reasoning: 0 },+};++/** First turn: call run_command with `command`; second turn: say done. */+function commandThenDone(command: string) {+ let calls = 0;+ return new MockLanguageModelV3({+ doGenerate: async (): Promise<LanguageModelV3GenerateResult> => {+ calls++;+ if (calls === 1) {+ return {+ content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'run_command', input: JSON.stringify({ command }) }],+ finishReason: { unified: 'tool-calls', raw: 'tool_use' },+ usage,+ warnings: [],+ };+ }+ return { content: [{ type: 'text', text: 'done' }], finishReason: { unified: 'stop', raw: 'end_turn' }, usage, warnings: [] };+ },+ });+}++function makeChild(opts: { model: MockLanguageModelV3; ask?: (prompt: string) => Promise<string>; channelType?: string; allowedTools?: string[] }) {+ const registry = new CapabilityRegistry({} as any);+ registry.registerAll();+ const manifest = registry.permissions.getManifest();+ manifest.capabilities.shell.enabled = true;+ manifest.capabilities.shell.cwdOnly = false;+ // The parent's state: Ask Me mode, with the parent's approval handler.+ registry.permissions.setAutoApproveAll(false);+ if (opts.ask) registry.permissions.onAsk(opts.ask);+ registry.setChannelContext('cli', 'cli');++ const taskBoard = new TaskBoard();+ const agent = new SubAgent(+ {+ id: 'a1',+ task: 'Do the thing',+ allowedTools: opts.allowedTools,+ sourceChannelId: opts.channelType ?? 'cli',+ sourceChannelType: opts.channelType ?? 'cli',+ },+ {+ agentConfig: { identity: { name: 'Mercury', owner: 'test' } } as any,+ providers: { getDefault: () => ({ name: 'mock', getModel: () => 'mock-model', getModelInstance: () => opts.model }) } as any,+ identity: { getSystemPrompt: () => 'You are a test agent.' } as any,+ shortTerm: {} as any,+ longTerm: {} as any,+ episodic: { record() {} } as any,+ userMemory: null,+ capabilities: registry,+ tokenBudget: { getStatusText: () => '', getUsagePercentage: () => 0, recordUsage() {}, getRemaining: () => 1_000_000 } as any,+ fileLockManager: new FileLockManager(),+ taskBoard,+ },+ );+ taskBoard.create({ agentId: 'a1', task: 'Do the thing', status: 'pending', priority: 'normal', startedAt: Date.now(), filesLocked: [] });+ return { agent, registry };+}++function toolResultText(model: MockLanguageModelV3): string {+ // The second provider call carries the first call's tool result.+ return JSON.stringify(model.doGenerateCalls[1]?.prompt ?? []);+}++describe('delegated sub-agent shell commands go through the parent\'s approval flow (#75, #99)', () => {+ let scratch: string;+ afterAll(() => {+ rmSync(home, { recursive: true, force: true });+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });++ it('a dangerous command from a child reaches the parent\'s approval handler and is refused on "no"', async () => {+ const model = commandThenDone('rm -rf build');+ const ask = vi.fn().mockResolvedValue('no');+ const { agent } = makeChild({ model, ask });++ const result = await agent.run();++ expect(result.status).toBe('completed');+ expect(ask).toHaveBeenCalledTimes(1);+ expect(ask).toHaveBeenCalledWith('Run command: rm -rf build');+ expect(toolResultText(model)).toContain('User denied: rm -rf build');+ });++ it('the command runs only after the parent\'s handler says yes (no auto-approval)', async () => {+ scratch = mkdtempSync(join(tmpdir(), 'mercury-subagent-cmd-'));+ const marker = join(scratch, 'ran.txt');+ const model = commandThenDone(`touch ${marker}`);+ const ask = vi.fn().mockResolvedValue('yes');+ const { agent } = makeChild({ model, ask });++ await agent.run();++ expect(ask).toHaveBeenCalledWith(`Run command: touch ${marker}`);+ expect(existsSync(marker)).toBe(true);+ });++ it('without any approval handler the command is denied, not auto-approved', async () => {+ const model = commandThenDone('rm -rf build');+ const { agent } = makeChild({ model });++ await agent.run();++ expect(toolResultText(model)).toMatch(/requires approval|Permission denied|denied/);+ expect(toolResultText(model)).not.toContain('(no output)');+ });++ it('a child on the internal channel still cannot run an unapproved command', async () => {+ const model = commandThenDone('rm -rf build');+ const ask = vi.fn().mockResolvedValue('yes');+ const { agent } = makeChild({ model, ask, channelType: 'internal' });++ await agent.run();++ // No prompt is possible on the internal channel, so the command is refused.+ expect(ask).not.toHaveBeenCalled();+ expect(toolResultText(model)).toMatch(/requires approval/);+ });++ it.todo('P2.2: a child\'s tool call that lands inside a concurrent internal-channel turn (setAutoApproveAll window in agent.ts) must still prompt — needs the immutable per-agent permission context');+});++describe('sub-agent tool surface and prompt (#74)', () => {+ it('does not receive delegate_task/list_agents/stop_agent unless the parent grants them', () => {+ const model = commandThenDone('true');+ const { agent, registry } = makeChild({ model });+ // Pretend the shared registry exposes the orchestration tools, as it does+ // for the main agent once a supervisor is attached.+ const tools = registry.getTools();+ (tools as any).stop_agent = { description: 'root-bound' };+ (tools as any).list_agents = { description: 'root-bound' };+ (tools as any).delegate_task = { description: 'root-bound' };+ vi.spyOn(registry, 'getTools').mockReturnValue(tools);++ const names = agent.getToolNames();+ expect(names).toContain('run_command');+ expect(names).not.toContain('stop_agent');+ expect(names).not.toContain('list_agents');+ expect(names).not.toContain('delegate_task');+ });++ it('the system prompt no longer claims full permissions and describes the real scopes', () => {+ const model = commandThenDone('true');+ const { agent, registry } = makeChild({ model });+ registry.permissions.getManifest().capabilities.filesystem.scopes = [+ { path: '/work/project', read: true, write: true },+ { path: '/work/docs', read: true, write: false },+ ];+ const prompt: string = (agent as any).buildSystemPrompt();+ expect(prompt).not.toMatch(/full permissions/i);+ expect(prompt).toContain('same permissions as the agent that delegated you');+ expect(prompt).toContain('Writable scopes: /work/project');+ expect(prompt).toContain('Read-only scopes: /work/docs');+ expect(prompt).toMatch(/go to the user for approval/);+ });+});diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.tsindex 45f5b434..689b0378 100644--- a/src/core/sub-agent.ts+++ b/src/core/sub-agent.ts@@ -11,10 +11,12 @@ import type { CapabilityRegistry } from '../capabilities/registry.js';import type { FileLockManager } from './file-lock.js';import type { TaskBoard } from './task-board.js';import type { SaverMode } from './saver-mode.js';+import type { SubAgentSupervisor } from './supervisor.js';+import { createDelegateTaskTool, createListAgentsTool, createStopAgentTool } from '../capabilities/subagents/index.js';import { getHeapStatistics } from 'node:v8';import { memoryGovernorThresholds, memoryGovernorVerdict, CONVERSATION_TOOL_BUDGET_CHARS, TOOL_RESULT_KEEP_RECENT, summarizeToolResult } from './memory-governor.js';import { classifyStreamCompletion } from './stream-completion.js';-import { filterToolsByAllowlist } from '../utils/tool-filter.js';+import { resolveChildTools, childMayUse } from '../utils/tool-filter.js';import { logger } from '../utils/logger.js';export type ProgressCallback = (agentId: string, progress: string) => void;@@ -45,6 +47,7 @@ export class SubAgent {private fileLockManager: FileLockManager;private taskBoard: TaskBoard;private saverMode?: SaverMode;+ private supervisor?: SubAgentSupervisor;private onProgress?: ProgressCallback;private onComplete?: CompletionCallback;@@ -67,6 +70,8 @@ export class SubAgent {fileLockManager: FileLockManager;taskBoard: TaskBoard;saverMode?: SaverMode;+ /** Needed only to hand out lineage-scoped orchestration tools. */+ supervisor?: SubAgentSupervisor;},) {this.config = config;@@ -84,6 +89,7 @@ export class SubAgent {this.fileLockManager = dependencies.fileLockManager;this.taskBoard = dependencies.taskBoard;this.saverMode = dependencies.saverMode;+ this.supervisor = dependencies.supervisor;}getStatus(): SubAgentStatus {@@ -489,11 +495,32 @@ export class SubAgent {/*** Tools handed to the model. `allowedTools` is a real runtime restriction:- * when set, the child never sees tools outside the list even though the- * shared registry would otherwise expose them (e.g. list_agents/stop_agent).+ * when set, the child never sees tools outside the list. The orchestration+ * tools (delegate_task, list_agents, stop_agent) are stripped unless the+ * parent granted them by name, and a granted one is re-bound to THIS+ * agent's id so the supervisor confines it to this agent's descendants —+ * the shared registry instance carries the main agent's authority (#74).*/private resolveTools() {- return filterToolsByAllowlist(this.capabilities.getTools(), this.config.allowedTools);+ const tools = resolveChildTools(this.capabilities.getTools(), this.config.allowedTools);+ if (this.supervisor) {+ const scoped = { callerId: this.config.id };+ if (childMayUse('delegate_task', this.config.allowedTools)) {+ tools.delegate_task = createDelegateTaskTool(this.supervisor, this.capabilities, scoped);+ }+ if (childMayUse('list_agents', this.config.allowedTools)) {+ tools.list_agents = createListAgentsTool(this.supervisor, scoped);+ }+ if (childMayUse('stop_agent', this.config.allowedTools)) {+ tools.stop_agent = createStopAgentTool(this.supervisor, scoped);+ }+ }+ return tools;+ }++ /** Names of the tools this agent actually receives. */+ getToolNames(): string[] {+ return Object.keys(this.resolveTools());}private buildSystemPrompt(): string {@@ -501,7 +528,8 @@ export class SubAgent {prompt += `\n\nYou are a sub-agent (ID: ${this.config.id}) working independently on a specific task.`;prompt += `\nTask: ${this.config.task}`;- prompt += `\nYou have full permissions for this task. Focus only on completing this task efficiently.`;+ prompt += `\n${this.describePermissions()}`;+ prompt += `\nFocus only on completing this task efficiently.`;if (this.config.workingDirectory) {prompt += `\nWorking directory: ${this.config.workingDirectory}`;}@@ -522,12 +550,37 @@ export class SubAgent {prompt += `\n\nEnvironment:\n- Platform: ${process.platform}\n- Working directory: ${this.capabilities.getCwd()}`;- const toolNames = this.capabilities.getToolNames();- const toolsList = this.config.allowedTools- ? toolNames.filter(t => this.config.allowedTools!.includes(t))- : toolNames;- prompt += `\n\nAvailable tools: ${toolsList.join(', ')}`;+ prompt += `\n\nAvailable tools: ${this.getToolNames().join(', ')}`;return prompt;}++ /**+ * An accurate statement of what this agent may do: it runs under the same+ * permission state as the agent that delegated it — the same approved+ * scopes, the same shell approval prompt — never with elevated rights.+ */+ private describePermissions(): string {+ const permissions = this.capabilities.permissions;+ const readable: string[] = [];+ const writable: string[] = [];+ for (const scope of permissions.getManifest().capabilities.filesystem.scopes) {+ if (scope.write) writable.push(scope.path);+ else if (scope.read) readable.push(scope.path);+ }+ const parts: string[] = [];+ parts.push('You run with the same permissions as the agent that delegated you, not more.');+ if (permissions.isAutoApproveAll()) {+ parts.push('This session is in Allow All mode, so approved-scope actions run without prompts.');+ } else {+ parts.push('File writes and non-read-only shell commands go to the user for approval (reads inside approved scopes do not); a denial is final — do not retry it or work around it.');+ }+ if (writable.length > 0) parts.push(`Writable scopes: ${writable.join(', ')}.`);+ if (readable.length > 0) parts.push(`Read-only scopes: ${readable.join(', ')}.`);+ parts.push('Use approve_scope to request a path outside these scopes.');+ if (this.config.allowedTools?.some(t => ['delegate_task', 'list_agents', 'stop_agent'].includes(t))) {+ parts.push('Your delegate_task/list_agents/stop_agent only reach agents you delegated yourself.');+ }+ return parts.join(' ');+ }}diff --git a/src/core/supervisor-lineage.test.ts b/src/core/supervisor-lineage.test.tsnew file mode 100644index 00000000..048a216e--- /dev/null+++ b/src/core/supervisor-lineage.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it, afterAll, beforeAll, vi } from 'vitest';+import { rmSync } from 'node:fs';+import { MockLanguageModelV3 } from 'ai/test';++// The task board and permissions.yaml live under MERCURY_HOME, which the+// modules read at import time — point it at a scratch directory first.+const home = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = mkdtempSync(join(tmpdir(), 'mercury-lineage-'));+ process.env.MERCURY_HOME = dir;+ return dir;+});++const { SubAgentSupervisor } = await import('./supervisor.js');+const { createStopAgentTool, createListAgentsTool } = await import('../capabilities/subagents/index.js');++/** A model that never answers: it rejects only when the agent is aborted. */+function blockingModel() {+ return new MockLanguageModelV3({+ doGenerate: (options) => new Promise((_, reject) => {+ const signal = options.abortSignal;+ const abort = () => reject(signal?.reason ?? new DOMException('aborted', 'AbortError'));+ if (signal?.aborted) return abort();+ signal?.addEventListener('abort', abort, { once: true });+ }),+ });+}++function makeSupervisor() {+ const model = blockingModel();+ const supervisor = new SubAgentSupervisor({+ agentConfig: { identity: { name: 'Mercury', owner: 'test' } } as any,+ providers: { getDefault: () => ({ name: 'mock', getModel: () => 'mock-model', getModelInstance: () => model }) } as any,+ identity: { getSystemPrompt: () => 'You are a test agent.' } as any,+ shortTerm: {} as any,+ longTerm: {} as any,+ episodic: { record() {} } as any,+ userMemory: null,+ capabilities: {+ getCwd: () => process.cwd(),+ setCwd() {},+ setChannelContext() {},+ getTools: () => ({}),+ getToolNames: () => [],+ permissions: {+ clearElevation() {},+ isAutoApproveAll: () => false,+ getManifest: () => ({ capabilities: { filesystem: { scopes: [] } } }),+ },+ } as any,+ tokenBudget: { getStatusText: () => '', getUsagePercentage: () => 0, recordUsage() {}, getRemaining: () => 1_000_000 } as any,+ channels: {} as any,+ });+ supervisor.setMaxConcurrent(10);+ return supervisor;+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 30));++async function run(toolInstance: any, input: any): Promise<string> {+ return toolInstance.execute(input, { toolCallId: 't', messages: [] });+}++describe('SubAgentSupervisor lineage (#74)', () => {+ const supervisors: InstanceType<typeof SubAgentSupervisor>[] = [];+ beforeAll(() => {+ expect(process.env.MERCURY_HOME).toBe(home);+ });+ afterAll(async () => {+ for (const s of supervisors) await s.haltAll();+ await settle();+ rmSync(home, { recursive: true, force: true });+ });++ /** root → a (→ b → c) and root → d; returns the ids. */+ async function tree() {+ const supervisor = makeSupervisor();+ supervisors.push(supervisor);+ const a = await supervisor.spawn({ task: 'a' });+ const b = await supervisor.spawn({ task: 'b', parentId: a });+ const c = await supervisor.spawn({ task: 'c', parentId: b });+ const d = await supervisor.spawn({ task: 'd' });+ return { supervisor, a, b, c, d };+ }++ it('records parentage and answers descendant queries transitively', async () => {+ const { supervisor, a, b, c, d } = await tree();+ expect(supervisor.getParentId(a)).toBeUndefined();+ expect(supervisor.getParentId(b)).toBe(a);+ expect(supervisor.isDescendant(b, a)).toBe(true);+ expect(supervisor.isDescendant(c, a)).toBe(true);+ expect(supervisor.isDescendant(c, b)).toBe(true);+ expect(supervisor.isDescendant(d, a)).toBe(false);+ expect(supervisor.isDescendant(a, b)).toBe(false);+ expect(supervisor.isDescendant(a, a)).toBe(false);+ });++ it('getActiveAgents(owner) lists only the owner\'s descendants; no owner lists everything', async () => {+ const { supervisor, a, b, c, d } = await tree();+ expect(supervisor.getActiveAgents().map(x => x.id).sort()).toEqual([a, b, c, d].sort());+ expect(supervisor.getActiveAgents(a).map(x => x.id).sort()).toEqual([b, c].sort());+ expect(supervisor.getActiveAgents(b).map(x => x.id)).toEqual([c]);+ expect(supervisor.getActiveAgents(d)).toEqual([]);+ });++ it('halt(id, caller) refuses siblings and ancestors, allows descendants', async () => {+ const { supervisor, a, b, c, d } = await tree();+ await expect(supervisor.halt(d, b)).resolves.toBe(false);+ await expect(supervisor.halt(a, b)).resolves.toBe(false);+ await expect(supervisor.halt(b, b)).resolves.toBe(false);+ await settle();+ expect(supervisor.getActiveAgents().map(x => x.id).sort()).toEqual([a, b, c, d].sort());++ await expect(supervisor.halt(c, a)).resolves.toBe(true);+ await settle();+ expect(supervisor.getActiveAgents().map(x => x.id).sort()).toEqual([a, b, d].sort());+ });++ it('haltAll(caller) halts only the caller\'s subtree', async () => {+ const { supervisor, a, b, c, d } = await tree();+ const halted = await supervisor.haltAll(a);+ expect(halted.sort()).toEqual([b, c].sort());+ await settle();+ expect(supervisor.getActiveAgents().map(x => x.id).sort()).toEqual([a, d].sort());+ });++ it('halt also reaches a queued descendant', async () => {+ const supervisor = makeSupervisor();+ supervisors.push(supervisor);+ supervisor.setMaxConcurrent(1);+ const root = await supervisor.spawn({ task: 'root' });+ const child = await supervisor.spawn({ task: 'child', parentId: root });+ expect(supervisor.getActiveAgents(root).map(x => x.id)).toEqual([child]);+ expect(supervisor.getActiveAgents(root)[0].status).toBe('pending');+ await expect(supervisor.halt(child, root)).resolves.toBe(true);+ expect(supervisor.getActiveAgents(root)).toEqual([]);+ expect(supervisor.getTaskBoard().get(child)?.status).toBe('halted');+ });++ it('stop_agent bound to a child cannot stop a sibling, and "all" only halts its own subtree', async () => {+ const { supervisor, a, b, c, d } = await tree();+ const stopAsB = createStopAgentTool(supervisor, { callerId: b });+ await expect(run(stopAsB, { agentId: d })).resolves.toMatch(/was not delegated by you/);+ await expect(run(stopAsB, { agentId: a })).resolves.toMatch(/was not delegated by you/);+ const all = await run(stopAsB, { agentId: 'all' });+ expect(all).toContain(c);+ expect(all).not.toContain(d);+ await settle();+ expect(supervisor.getActiveAgents().map(x => x.id).sort()).toEqual([a, b, d].sort());+ // The main agent's instance (no caller) still halts anything.+ const stopAsMain = createStopAgentTool(supervisor);+ await expect(run(stopAsMain, { agentId: d })).resolves.toMatch(/halt signal sent/);+ });++ it('list_agents bound to a child shows only its descendants', async () => {+ const { supervisor, a, b, c, d } = await tree();+ const listAsA = await run(createListAgentsTool(supervisor, { callerId: a }), {});+ expect(listAsA).toContain(b);+ expect(listAsA).toContain(c);+ expect(listAsA).not.toContain(`**${d}**`);+ const listAsD = await run(createListAgentsTool(supervisor, { callerId: d }), {});+ expect(listAsD).toMatch(/No agents delegated by you/);+ const listAsMain = await run(createListAgentsTool(supervisor), {});+ for (const id of [a, b, c, d]) expect(listAsMain).toContain(`**${id}**`);+ });+});diff --git a/src/core/supervisor.ts b/src/core/supervisor.tsindex b48d6b62..b5ec250a 100644--- a/src/core/supervisor.ts+++ b/src/core/supervisor.ts@@ -48,6 +48,12 @@ export class SubAgentSupervisor {/** Bounded auto-resume counter for step-budget pauses, per agent. */private stepResumeCounts: Map<string, number> = new Map();private pauseResolvers: Map<string, () => void> = new Map();+ /**+ * Lineage: agent id → id of the sub-agent that delegated it (undefined for+ * agents spawned by the main agent or a user command). Kept after an agent+ * finishes so a grandchild's chain still resolves once its parent is gone.+ */+ private parents: Map<string, string | undefined> = new Map();constructor(dependencies: {@@ -117,6 +123,7 @@ export class SubAgentSupervisor {async spawn(config: Omit<SubAgentConfig, 'id'>): Promise<string> {const id = this.taskBoard.nextId();const fullConfig: SubAgentConfig = { ...config, id };+ this.parents.set(id, config.parentId);if (!this.resourceManager.canSpawn()) {logger.info({ task: config.task.slice(0, 50) }, 'No resources available, queuing sub-agent task');@@ -185,6 +192,7 @@ export class SubAgentSupervisor {fileLockManager: this.fileLockManager,taskBoard: this.taskBoard,saverMode: this.saverMode,+ supervisor: this,});this.activeAgents.set(config.id, subAgent);@@ -335,14 +343,44 @@ export class SubAgentSupervisor {}}- async halt(agentId: string): Promise<boolean> {+ /** Id of the sub-agent that delegated `agentId`, if any. */+ getParentId(agentId: string): string | undefined {+ return this.parents.get(agentId);+ }++ /**+ * True when `agentId` sits strictly below `ancestorId` in the delegation+ * tree. The main agent is not an id, so callers representing it pass no+ * ancestor and own everything.+ */+ isDescendant(agentId: string, ancestorId: string): boolean {+ let current = this.parents.get(agentId);+ for (let depth = 0; current !== undefined && depth < 1000; depth++) {+ if (current === ancestorId) return true;+ current = this.parents.get(current);+ }+ return false;+ }++ /**+ * Halt one agent (running or queued). When `callerId` is given, the target+ * must be one of the caller's descendants — a sub-agent can never halt a+ * sibling or an ancestor (#74).+ */+ async halt(agentId: string, callerId?: string): Promise<boolean> {+ if (callerId !== undefined && !this.isDescendant(agentId, callerId)) {+ logger.warn({ agentId, callerId }, 'Cannot halt — agent is not a descendant of the caller');+ return false;+ }+const agent = this.activeAgents.get(agentId);- if (!agent) {+ const queued = this.waitQueue.some(c => c.id === agentId);+ if (!agent && !queued) {logger.warn({ agentId }, 'Cannot halt — agent not found');return false;}- agent.abort();+ agent?.abort();this.waitQueue = this.waitQueue.filter(c => c.id !== agentId);@@ -358,19 +396,35 @@ export class SubAgentSupervisor {return true;}- async haltAll(): Promise<void> {+ /**+ * Halt every agent, or — with `callerId` — only the caller's descendants.+ * Returns the ids that were signalled.+ */+ async haltAll(callerId?: string): Promise<string[]> {+ const owned = (id: string) => callerId === undefined || this.isDescendant(id, callerId);+ const halted: string[] = [];+for (const [agentId, agent] of this.activeAgents.entries()) {+ if (!owned(agentId)) continue;agent.abort();+ halted.push(agentId);}+ const remaining: SubAgentConfig[] = [];for (const config of this.waitQueue) {+ if (!owned(config.id)) {+ remaining.push(config);+ continue;+ }this.taskBoard.update(config.id, {status: 'halted',completedAt: Date.now(),progress: 'Halted while queued',});+ halted.push(config.id);}- this.waitQueue = [];+ this.waitQueue = remaining;+ return halted;}async pause(agentId: string): Promise<boolean> {@@ -403,6 +457,11 @@ export class SubAgentSupervisor {clearTaskBoard(): void {this.fileLockManager.clearAll();this.taskBoard.clear();+ // Only forget lineage for agents that are gone; a live subtree keeps its+ // chain so its stop_agent/list_agents stay confined.+ for (const id of [...this.parents.keys()]) {+ if (!this.activeAgents.has(id) && !this.waitQueue.some(c => c.id === id)) this.parents.delete(id);+ }}getResourceUsage(): ResourceUsage {@@ -413,10 +472,16 @@ export class SubAgentSupervisor {);}- getActiveAgents(): Array<{ id: string; task: string; status: SubAgentStatus; progress?: string }> {+ /**+ * Active and queued agents. With `ownerId`, only that sub-agent's+ * descendants are listed — a child never learns about its siblings.+ */+ getActiveAgents(ownerId?: string): Array<{ id: string; task: string; status: SubAgentStatus; progress?: string }> {const agents: Array<{ id: string; task: string; status: SubAgentStatus; progress?: string }> = [];+ const owned = (id: string) => ownerId === undefined || this.isDescendant(id, ownerId);for (const [id, agent] of this.activeAgents.entries()) {+ if (!owned(id)) continue;const entry = this.taskBoard.get(id);agents.push({id,@@ -427,6 +492,7 @@ export class SubAgentSupervisor {}for (const config of this.waitQueue) {+ if (!owned(config.id)) continue;agents.push({id: config.id,task: config.task,diff --git a/src/types/agent.ts b/src/types/agent.tsindex 06ebee95..8c4bac6d 100644--- a/src/types/agent.ts+++ b/src/types/agent.ts@@ -54,6 +54,13 @@ export interface SubAgentConfig {priority?: SubAgentPriority;sourceChannelId?: string;sourceChannelType?: string;+ /**+ * Id of the sub-agent that spawned this one via `delegate_task`; absent+ * when the main agent (or a user command) spawned it. The supervisor uses+ * it for lineage checks: a sub-agent may only list or stop its own+ * descendants (#74).+ */+ parentId?: string;}export interface SubAgentResult {diff --git a/src/utils/tool-filter.test.ts b/src/utils/tool-filter.test.tsindex 04e7d923..b86e2bb1 100644--- a/src/utils/tool-filter.test.ts+++ b/src/utils/tool-filter.test.ts@@ -1,11 +1,12 @@import { describe, expect, it } from 'vitest';-import { filterToolsByAllowlist } from './tool-filter.js';+import { filterToolsByAllowlist, resolveChildTools, childMayUse, ORCHESTRATION_TOOLS } from './tool-filter.js';const tools = {read_file: 1,write_file: 2,list_agents: 3,stop_agent: 4,+ delegate_task: 5,};describe('filterToolsByAllowlist', () => {@@ -29,3 +30,31 @@ describe('filterToolsByAllowlist', () => {expect(filterToolsByAllowlist(tools, ['read_file', 'does_not_exist'])).toEqual({ read_file: 1 });});});++// #74: a child spawned WITHOUT an allowlist used to inherit stop_agent and+// could halt its siblings. Orchestration tools are opt-in for children.+describe('resolveChildTools (sub-agent default tool set)', () => {+ it('strips delegate_task, list_agents and stop_agent when no allowlist is given', () => {+ expect(resolveChildTools(tools)).toEqual({ read_file: 1, write_file: 2 });+ expect(resolveChildTools(tools, [])).toEqual({ read_file: 1, write_file: 2 });+ });++ it('keeps an orchestration tool only when the allowlist names it', () => {+ expect(resolveChildTools(tools, ['read_file', 'stop_agent'])).toEqual({ read_file: 1, stop_agent: 4 });+ expect(resolveChildTools(tools, ['list_agents'])).toEqual({ list_agents: 3 });+ });++ it('still applies the allowlist to ordinary tools', () => {+ expect(resolveChildTools(tools, ['write_file'])).toEqual({ write_file: 2 });+ });++ it('childMayUse is true only for an explicitly granted orchestration tool', () => {+ for (const name of ORCHESTRATION_TOOLS) {+ expect(childMayUse(name)).toBe(false);+ expect(childMayUse(name, [])).toBe(false);+ expect(childMayUse(name, ['read_file'])).toBe(false);+ expect(childMayUse(name, [name])).toBe(true);+ }+ expect(childMayUse('read_file', ['read_file'])).toBe(false);+ });+});diff --git a/src/utils/tool-filter.ts b/src/utils/tool-filter.tsindex 8a685743..23bd10ce 100644--- a/src/utils/tool-filter.ts+++ b/src/utils/tool-filter.ts@@ -7,3 +7,29 @@ export function filterToolsByAllowlist<T>(all: Record<string, T>, allowed?: readconst allowedSet = new Set(allowed);return Object.fromEntries(Object.entries(all).filter(([name]) => allowedSet.has(name)));}++/**+ * Tools that reach across the agent tree. A child never receives them by+ * default: a worker spawned without an `allowedTools` list used to inherit+ * `stop_agent` and could halt its siblings (#74). The parent must grant them+ * by name, and even then the supervisor restricts them to the caller's own+ * descendants.+ */+export const ORCHESTRATION_TOOLS: readonly string[] = ['delegate_task', 'list_agents', 'stop_agent'];++/**+ * The tool set a sub-agent is handed: the allowlist filter, with the+ * orchestration tools stripped unless the allowlist names them explicitly.+ */+export function resolveChildTools<T>(all: Record<string, T>, allowed?: readonly string[]): Record<string, T> {+ const granted = new Set(allowed ?? []);+ const withoutOrchestration = Object.fromEntries(+ Object.entries(all).filter(([name]) => !ORCHESTRATION_TOOLS.includes(name) || granted.has(name)),+ );+ return filterToolsByAllowlist(withoutOrchestration, allowed);+}++/** True when a child's allowlist explicitly grants the named orchestration tool. */+export function childMayUse(toolName: string, allowed?: readonly string[]): boolean {+ return ORCHESTRATION_TOOLS.includes(toolName) && Array.isArray(allowed) && allowed.includes(toolName);+}