Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(security): per-agent immutable permission contexts and argv-lane approval

Salman Qureshif486c4a7e72c
diff --git a/src/capabilities/permission-context.test.ts b/src/capabilities/permission-context.test.ts
new file mode 100644
index 00000000..6e49f50c
--- /dev/null
+++ b/src/capabilities/permission-context.test.ts
@@ -0,0 +1,182 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+
+// permissions.yaml lives under MERCURY_HOME, resolved at import time.
+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-ctx-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const { PermissionManager } = await import('./permissions.js');
+const { makeContext, deriveChildContext, isSubsetContext, withChanges } = await import('./permission-context.js');
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+const tick = (ms = 5) => new Promise((r) => setTimeout(r, ms));
+
+function manager(ask = vi.fn().mockResolvedValue('no')) {
+ const pm = new PermissionManager();
+ const shell = pm.getManifest().capabilities.shell;
+ shell.enabled = true;
+ shell.blocked = [];
+ shell.cwdOnly = false;
+ pm.onAsk(ask);
+ return { pm, ask };
+}
+
+describe('PermissionContext values', () => {
+ it('contexts are deeply frozen', () => {
+ const ctx = makeContext({ scopes: [{ path: '/w', read: true, write: true }], allowedTools: ['read_file'] });
+ expect(Object.isFrozen(ctx)).toBe(true);
+ expect(Object.isFrozen(ctx.scopes)).toBe(true);
+ expect(Object.isFrozen(ctx.scopes[0])).toBe(true);
+ expect(Object.isFrozen(ctx.allowedTools)).toBe(true);
+ expect(() => { (ctx as any).autoApprove = true; }).toThrow();
+ });
+
+ it('withChanges returns a new context and leaves the original untouched', () => {
+ const a = makeContext();
+ const b = withChanges(a, { autoApprove: true });
+ expect(a.autoApprove).toBe(false);
+ expect(b.autoApprove).toBe(true);
+ expect(b.autoApproveOrigin).toBe('session');
+ });
+});
+
+describe('deriveChildContext: child ⊆ parent', () => {
+ it('intersects allowedTools with the parent', () => {
+ const parent = makeContext({ allowedTools: ['read_file', 'list_dir'] });
+ const child = deriveChildContext(parent, { allowedTools: ['read_file', 'run_command'] });
+ expect(child.allowedTools).toEqual(['read_file']);
+ expect(isSubsetContext(child, parent)).toBe(true);
+ // A child that asks for nothing inherits the parent's restriction, not "unrestricted".
+ expect(deriveChildContext(parent).allowedTools).toEqual(['read_file', 'list_dir']);
+ });
+
+ it('keeps only requested scopes the parent covers', () => {
+ const parent = makeContext({ scopes: [{ path: '/work', read: true, write: false }] });
+ const child = deriveChildContext(parent, {
+ scopes: [
+ { path: '/work/sub', read: true, write: false },
+ { path: '/work/sub', read: true, write: true },
+ { path: '/etc', read: true, write: false },
+ ],
+ });
+ expect(child.scopes).toEqual([{ path: '/work/sub', read: true, write: false }]);
+ expect(isSubsetContext(child, parent)).toBe(true);
+ });
+
+ it('inherits a user-chosen session Allow All but never an internal turn grant', () => {
+ const session = makeContext({ autoApprove: true, autoApproveOrigin: 'session' });
+ expect(deriveChildContext(session).autoApprove).toBe(true);
+ const turn = makeContext({ autoApprove: true, autoApproveOrigin: 'turn' });
+ expect(deriveChildContext(turn).autoApprove).toBe(false);
+ });
+
+ it('never inherits skill elevation', () => {
+ const parent = makeContext({ elevated: ['run_command'] });
+ expect(deriveChildContext(parent).elevated).toEqual([]);
+ });
+
+ it('isSubsetContext rejects widening', () => {
+ const parent = makeContext({ allowedTools: ['read_file'] });
+ expect(isSubsetContext(makeContext({}), parent)).toBe(false);
+ expect(isSubsetContext(makeContext({ allowedTools: ['read_file'], autoApprove: true }), parent)).toBe(false);
+ });
+});
+
+describe('AsyncLocalStorage isolation', () => {
+ it('two concurrent agents each resolve their own context across awaits', async () => {
+ const { pm } = manager();
+ const a = makeContext({ channelType: 'telegram', channelId: 'A', autoApprove: true });
+ const b = makeContext({ channelType: 'web', channelId: 'B', senderRole: 'member' });
+
+ const seen: string[] = [];
+ const agent = (ctx: typeof a, label: string) => pm.withContext(ctx, async () => {
+ for (let i = 0; i < 3; i++) {
+ await tick(i % 2 ? 1 : 7);
+ const c = pm.currentContext();
+ seen.push(`${label}:${c.channelId}:${pm.isAutoApproveAll()}:${pm.getCurrentSenderRole() ?? '-'}`);
+ }
+ });
+ await Promise.all([agent(a, 'a'), agent(b, 'b')]);
+
+ expect(seen.filter((s) => s.startsWith('a:')).every((s) => s === 'a:A:true:-')).toBe(true);
+ expect(seen.filter((s) => s.startsWith('b:')).every((s) => s === 'b:B:false:member')).toBe(true);
+ // Outside any agent the root context is untouched.
+ expect(pm.currentContext().channelId).toBe('cli');
+ expect(pm.isAutoApproveAll()).toBe(false);
+ });
+
+ it('a grant inside one agent (scope, elevation, allow-all) stays in that agent', async () => {
+ const { pm } = manager();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ const other = pm.withContext(makeContext({ channelId: 'other' }), async () => {
+ await gate;
+ return { auto: pm.isAutoApproveAll(), elevated: pm.isShellElevated(), scopes: pm.currentContext().scopes.length };
+ });
+ await pm.withContext(makeContext({ channelId: 'granted' }), async () => {
+ pm.setAutoApproveAll(true);
+ pm.elevateForSkill(['run_command']);
+ pm.addTempScope('/', true, true);
+ await tick();
+ expect(pm.isAutoApproveAll()).toBe(true);
+ expect(pm.isShellElevated()).toBe(true);
+ });
+ release();
+ expect(await other).toEqual({ auto: false, elevated: false, scopes: 0 });
+ expect(pm.isAutoApproveAll()).toBe(false);
+ expect(pm.isShellElevated()).toBe(false);
+ });
+
+ it('contexts are per PermissionManager (a bot manager never reads a sub-agent cell)', async () => {
+ const { pm } = manager();
+ const { pm: botPm } = manager();
+ botPm.setCurrentContext('bot', 'worker');
+ await pm.withContext(makeContext({ channelType: 'telegram', channelId: 'chat' }), async () => {
+ await tick();
+ expect(botPm.getCurrentChannelType()).toBe('bot');
+ expect(pm.getCurrentChannelType()).toBe('telegram');
+ });
+ });
+
+ it('a turn grant changes the root context only, and endTurnGrant keeps the session', async () => {
+ const { pm, ask } = manager();
+ pm.setCurrentContext('cli', 'cli');
+ const child = pm.withContext(deriveChildContext(pm.currentContext()), async () => {
+ await tick(10);
+ return pm.checkShellCommand('rm -rf build');
+ });
+ pm.setCurrentContext('internal', 'internal');
+ pm.beginTurnGrant({ scopes: [{ path: '/', read: true, write: true }] });
+ expect(pm.isAutoApproveAll()).toBe(true);
+ // Child spawned during the turn: no allow-all.
+ expect(deriveChildContext(pm.currentContext()).autoApprove).toBe(false);
+ await expect(child).resolves.toMatchObject({ allowed: false });
+ expect(ask).toHaveBeenCalledWith('Run command: rm -rf build');
+ pm.endTurnGrant();
+ expect(pm.isAutoApproveAll()).toBe(false);
+ expect(pm.currentContext().scopes).toEqual([]);
+
+ // A user's session Allow All survives an internal turn ending.
+ pm.setAutoApproveAll(true);
+ pm.beginTurnGrant();
+ pm.endTurnGrant();
+ expect(pm.isAutoApproveAll()).toBe(true);
+ });
+
+ it('requestApproval on the internal channel approves only under allow-all', async () => {
+ const { pm } = manager();
+ pm.setCurrentContext('internal', 'internal');
+ await expect(pm.requestApproval('x')).resolves.toBe(false);
+ pm.beginTurnGrant();
+ await expect(pm.requestApproval('x')).resolves.toBe(true);
+ await expect(pm.withContext(deriveChildContext(pm.currentContext()), () => pm.requestApproval('x'))).resolves.toBe(false);
+ pm.endTurnGrant();
+ });
+});
diff --git a/src/capabilities/permission-context.ts b/src/capabilities/permission-context.ts
new file mode 100644
index 00000000..901ea46d
--- /dev/null
+++ b/src/capabilities/permission-context.ts
@@ -0,0 +1,155 @@
+/**
+ * Immutable per-agent permission contexts (ROADMAP P2.2, ADR-016).
+ *
+ * Before this, channel, sender role, allow-all, skill elevation and session
+ * scopes were mutable fields on the single PermissionManager shared by the
+ * main agent and every sub-agent. An internal (scheduled) turn switched
+ * allow-all on for its duration, and a delegated worker whose tool call
+ * landed inside that window inherited it (#75/#99 residual).
+ *
+ * Now each agent's view is a frozen `PermissionContext`. Sub-agents run
+ * inside `AsyncLocalStorage` with a context derived from their parent's at
+ * spawn time (child ⊆ parent), so any tool they invoke — however deep in
+ * the AI SDK's promise chain — reads their own context, never the main
+ * agent's current one.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { resolve, sep } from 'node:path';
+import { homedir } from 'node:os';
+
+export interface ContextScope {
+ readonly path: string;
+ readonly read: boolean;
+ readonly write: boolean;
+ readonly execute?: boolean;
+}
+
+export interface PermissionContext {
+ readonly channelType: string;
+ readonly channelId: string;
+ readonly senderRole: 'admin' | 'member' | undefined;
+ /** Allow-all: approved-scope actions and non-blocked commands run without prompts. */
+ readonly autoApprove: boolean;
+ /**
+ * Where allow-all came from. `session`: the user chose Allow All (CLI
+ * /permissions, Telegram/Signal button) — inherited by children. `turn`:
+ * the grant of one internal (scheduled/background) turn — never inherited.
+ */
+ readonly autoApproveOrigin: 'session' | 'turn' | null;
+ /** Tool allowlist; `undefined` = unrestricted. */
+ readonly allowedTools: readonly string[] | undefined;
+ /** Session/turn scopes on top of the persisted manifest scopes. */
+ readonly scopes: readonly ContextScope[];
+ /** Skill elevation grants (`run_command`, `fs_read`, `fs_write`) — never inherited. */
+ readonly elevated: readonly string[];
+}
+
+function freezeScopes(scopes: readonly ContextScope[]): readonly ContextScope[] {
+ return Object.freeze(scopes.map((s) => Object.freeze({ ...s })));
+}
+
+export function makeContext(fields: Partial<PermissionContext> = {}): PermissionContext {
+ return Object.freeze({
+ channelType: fields.channelType ?? 'cli',
+ channelId: fields.channelId ?? 'cli',
+ senderRole: fields.senderRole,
+ autoApprove: fields.autoApprove ?? false,
+ autoApproveOrigin: fields.autoApprove ? (fields.autoApproveOrigin ?? 'session') : null,
+ allowedTools: fields.allowedTools ? Object.freeze([...fields.allowedTools]) : undefined,
+ scopes: freezeScopes(fields.scopes ?? []),
+ elevated: Object.freeze([...(fields.elevated ?? [])]),
+ });
+}
+
+/** A new frozen context = `base` with `patch` applied. */
+export function withChanges(base: PermissionContext, patch: Partial<PermissionContext>): PermissionContext {
+ const merged = { ...base, ...patch };
+ if (patch.autoApprove === false) merged.autoApproveOrigin = null;
+ if (patch.autoApprove === true && !patch.autoApproveOrigin) merged.autoApproveOrigin = base.autoApproveOrigin ?? 'session';
+ return makeContext(merged);
+}
+
+function expand(path: string): string {
+ return resolve(path.replace(/^~/, homedir()));
+}
+
+function covers(parent: ContextScope, child: ContextScope): boolean {
+ const p = expand(parent.path);
+ const c = expand(child.path);
+ const inside = c === p || c.startsWith(p.endsWith(sep) ? p : p + sep);
+ return inside
+ && (!child.read || parent.read)
+ && (!child.write || parent.write)
+ && (!child.execute || parent.execute === true);
+}
+
+export interface ChildContextRequest {
+ channelType?: string;
+ channelId?: string;
+ allowedTools?: readonly string[];
+ /** Requested scopes; each must be covered by one of the parent's. Defaults to the parent's. */
+ scopes?: readonly ContextScope[];
+}
+
+/**
+ * Derive a child's context. The child is a subset of the parent on every
+ * privilege axis:
+ * - allow-all only when the parent's is a user-chosen session grant (an
+ * internal turn's grant stays with that turn);
+ * - allowedTools = parent ∩ requested;
+ * - scopes = requested scopes the parent covers (default: parent's);
+ * - no skill elevation.
+ * Channel identity is a routing attribute (where prompts go), not a privilege.
+ */
+export function deriveChildContext(parent: PermissionContext, req: ChildContextRequest = {}): PermissionContext {
+ let allowedTools: readonly string[] | undefined;
+ if (parent.allowedTools && req.allowedTools && req.allowedTools.length > 0) {
+ const p = new Set(parent.allowedTools);
+ allowedTools = req.allowedTools.filter((t) => p.has(t));
+ } else if (req.allowedTools && req.allowedTools.length > 0) {
+ allowedTools = req.allowedTools;
+ } else {
+ allowedTools = parent.allowedTools;
+ }
+ const scopes = req.scopes
+ ? req.scopes.filter((s) => parent.scopes.some((p) => covers(p, s)))
+ : parent.scopes;
+ const inheritAllow = parent.autoApprove && parent.autoApproveOrigin === 'session';
+ return makeContext({
+ channelType: req.channelType ?? parent.channelType,
+ channelId: req.channelId ?? parent.channelId,
+ senderRole: parent.senderRole,
+ autoApprove: inheritAllow,
+ autoApproveOrigin: inheritAllow ? 'session' : null,
+ allowedTools,
+ scopes,
+ elevated: [],
+ });
+}
+
+/** True when `child` grants nothing `parent` does not (used by tests and assertions). */
+export function isSubsetContext(child: PermissionContext, parent: PermissionContext): boolean {
+ if (child.autoApprove && !parent.autoApprove) return false;
+ if (parent.allowedTools) {
+ if (!child.allowedTools) return false;
+ if (child.allowedTools.some((t) => !parent.allowedTools!.includes(t))) return false;
+ }
+ if (child.scopes.some((s) => !parent.scopes.some((p) => covers(p, s)))) return false;
+ if (child.elevated.some((e) => !parent.elevated.includes(e))) return false;
+ if (child.senderRole === 'admin' && parent.senderRole === 'member') return false;
+ return true;
+}
+
+/**
+ * The cell an agent's async tree carries. `owner` ties it to one
+ * PermissionManager (bots have their own) so a bot dispatched from inside a
+ * sub-agent never reads that sub-agent's context. `ctx` is replaced (never
+ * mutated) when the agent itself is granted something mid-run, e.g. the
+ * user answers "yes" to a scope request.
+ */
+export interface ContextCell {
+ readonly owner: object;
+ ctx: PermissionContext;
+}
+
+export const permissionContextStore = new AsyncLocalStorage<ContextCell>();
diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.ts
index b8fdfc90..8f7c891a 100644
--- a/src/capabilities/permissions.test.ts
+++ b/src/capabilities/permissions.test.ts
@@ -481,6 +481,9 @@ describe('safe-read classifier: residual side-effect flags (table)', () => {
const ask = vi.fn().mockResolvedValue('no');
permissions.onAsk(ask);
permissions.setCurrentContext('web', 'cloud-request-1');
+ // Verdicts must not depend on which tools the CI host has installed
+ // (tree/rg are often absent from the pinned system dirs).
+ permissions.setBinaryResolver((p) => `/usr/bin/${p}`);
return { permissions, ask };
}
@@ -542,3 +545,68 @@ describe('safe-read classifier: residual side-effect flags (table)', () => {
expect(ask).not.toHaveBeenCalled();
});
});
+
+describe('argv lane (ADR-016)', () => {
+ function makePermissions(installed: (p: string) => string | undefined = (p) => `/usr/bin/${p}`) {
+ const permissions = new PermissionManager();
+ const manifest = permissions.getManifest();
+ manifest.capabilities.shell.enabled = true;
+ manifest.capabilities.shell.blocked = [];
+ const ask = vi.fn().mockResolvedValue('no');
+ permissions.onAsk(ask);
+ permissions.setCurrentContext('web', 'cloud-request-1');
+ permissions.setBinaryResolver(installed);
+ return { permissions, ask };
+ }
+
+ it('auto-approves through the argv lane and says so', async () => {
+ const { permissions, ask } = makePermissions();
+ for (const cmd of ['ls', 'git status', 'git branch', 'pwd', 'cat "README.md"', 'grep -rn "a b" src']) {
+ await expect(permissions.checkShellCommand(cmd)).resolves.toMatchObject({ allowed: true, lane: 'argv' });
+ }
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('sends pipelines and chains of read-only commands to the approval lane', async () => {
+ const { permissions, ask } = makePermissions();
+ ask.mockResolvedValue('yes');
+ for (const cmd of ['git log | head', 'ls && pwd', 'cat a; cat b']) {
+ await expect(permissions.checkShellCommand(cmd)).resolves.toMatchObject({ allowed: true, lane: 'shell' });
+ }
+ expect(ask).toHaveBeenCalledTimes(3);
+ expect(ask).toHaveBeenCalledWith('Run command: git log | head');
+ });
+
+ it('sees through quoting: a quoted path outside the cwd and readable scopes prompts', async () => {
+ const { permissions, ask } = makePermissions();
+ permissions.getManifest().capabilities.shell.cwdOnly = false;
+ // Only the workspace is readable (independent of the host's permissions.yaml).
+ permissions.getManifest().capabilities.filesystem.scopes = [{ path: process.cwd(), read: true, write: true }];
+ await expect(permissions.checkShellCommand('cat "/etc/passwd"')).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkShellCommand('grep --file="/etc/shadow" x')).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkShellCommand("cat 'sub/../../outside.txt'")).resolves.toMatchObject({ allowed: false });
+ expect(ask).toHaveBeenCalledTimes(3);
+ });
+
+ it('an allowlisted program missing from the pinned PATH goes to the approval lane (#103)', async () => {
+ const { permissions, ask } = makePermissions(() => undefined);
+ await expect(permissions.checkShellCommand('rg -n pattern src')).resolves.toMatchObject({ allowed: false });
+ expect(ask).toHaveBeenCalledWith('Run command: rg -n pattern src');
+ });
+
+ it('checks paths against the tool cwd when given', async () => {
+ const { permissions, ask } = makePermissions();
+ permissions.getManifest().capabilities.shell.cwdOnly = false;
+ permissions.getManifest().capabilities.filesystem.scopes = [];
+ await expect(permissions.checkShellCommand('cat ../x.txt', { cwd: '/work/project/sub' })).resolves.toMatchObject({ allowed: false });
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+
+ it('allow-all still approves anything not hard-blocked, through the approval lane', async () => {
+ const { permissions, ask } = makePermissions();
+ permissions.setCurrentContext('cli', 'cli');
+ permissions.setAutoApproveAll(true);
+ await expect(permissions.checkShellCommand('npm test | tee out.txt')).resolves.toMatchObject({ allowed: true, lane: 'shell' });
+ expect(ask).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 957c5931..4af51c51 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -5,6 +5,35 @@ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { getMercuryHome } from '../utils/config.js';
import { logger } from '../utils/logger.js';
import { BLOCKED_COMMANDS } from './shell/blocklist.js';
+import {
+ evaluateArgvPolicy,
+ pinnedBinary,
+ IN_PROCESS_BUILTINS,
+ type BinaryResolver,
+} from './shell/argv-lane.js';
+import {
+ makeContext,
+ withChanges,
+ permissionContextStore,
+ type PermissionContext,
+ type ContextScope,
+} from './permission-context.js';
+
+export type { PermissionContext } from './permission-context.js';
+
+/** Result of a shell permission check. */
+export interface ShellCheckResult {
+ allowed: boolean;
+ reason?: string;
+ needsApproval: boolean;
+ /**
+ * `argv`: auto-approved through the argv lane — the caller must execute
+ * it with execFile (see planArgvExecution), never a shell. `shell`:
+ * approved through the approval lane (prompt, allow-all, elevation, bot
+ * grant) — the exact string the user saw may run through a shell.
+ */
+ lane?: 'argv' | 'shell';
+}
/**
* Command-pattern glob → anchored, case-insensitive RegExp. `*` matches any
@@ -312,10 +341,16 @@ export class PermissionManager {
private manifest: PermissionsManifest;
private readonly cwd: string;
private askHandler?: (prompt: string) => Promise<string>;
- private autoApproveAll = false;
- private elevatedCommands: Set<string> = new Set();
- private currentChannelType: string = 'cli';
- private currentChannelId: string = 'cli';
+ /**
+ * The main agent's (root) context: replaced, never mutated, by the
+ * legacy setters below. Sub-agents never read it while they run — they
+ * carry their own context through AsyncLocalStorage (`withContext`).
+ */
+ private session: PermissionContext = makeContext();
+ /** Grant of the internal turn in progress (agent.ts), layered over `session`. */
+ private turnGrant: { scopes: ContextScope[] } | null = null;
+ private rootCache: PermissionContext | null = null;
+ private binaryResolver: BinaryResolver = pinnedBinary;
private approvedCommandsByContext = new Map<string, Set<string>>();
private approvedWritesByContext = new Map<string, Set<string>>();
/** Hard-linked files the user answered "always" for, per interaction context. */
@@ -326,9 +361,6 @@ export class PermissionManager {
* everything else denies. Never combined with autoApproveAll.
*/
private failClosed = false;
- private currentSenderRole: 'admin' | 'member' | undefined;
-
- private tempScopes: FileScope[] = [];
/**
* Bot-scoped shell allow-list (fail-closed runtimes): patterns the bot's
@@ -366,25 +398,108 @@ export class PermissionManager {
return this.failClosed;
}
+ // ─── Permission context (ADR-016) ─────────────────────────────────────────
+
+ /**
+ * The context of the agent whose code is running: a sub-agent's own
+ * context inside `withContext`, otherwise the main agent's root context
+ * (session plus any internal-turn grant).
+ */
+ currentContext(): PermissionContext {
+ const cell = permissionContextStore.getStore();
+ if (cell && cell.owner === this) return cell.ctx;
+ return this.rootContext();
+ }
+
+ private rootContext(): PermissionContext {
+ if (this.rootCache) return this.rootCache;
+ let ctx = this.session;
+ if (this.turnGrant) {
+ ctx = withChanges(ctx, {
+ autoApprove: true,
+ autoApproveOrigin: ctx.autoApprove ? ctx.autoApproveOrigin : 'turn',
+ scopes: [...ctx.scopes, ...this.turnGrant.scopes],
+ });
+ }
+ this.rootCache = ctx;
+ return ctx;
+ }
+
+ private ctx(): PermissionContext {
+ return this.currentContext();
+ }
+
+ /**
+ * Replace the calling agent's context: its ALS cell when it is a
+ * sub-agent, otherwise the root session. The patch is computed from that
+ * base (never from the merged root, so a turn grant is not baked into
+ * the session).
+ */
+ private updateContext(patch: (base: PermissionContext) => Partial<PermissionContext>): void {
+ const cell = permissionContextStore.getStore();
+ if (cell && cell.owner === this) {
+ cell.ctx = withChanges(cell.ctx, patch(cell.ctx));
+ return;
+ }
+ this.session = withChanges(this.session, patch(this.session));
+ this.rootCache = null;
+ }
+
+ /**
+ * Run `fn` (and everything it awaits or schedules) under `ctx`. Used for
+ * sub-agents; their tools resolve permissions against `ctx` even while
+ * the main agent's root context changes concurrently.
+ */
+ withContext<T>(ctx: PermissionContext, fn: () => T): T {
+ return permissionContextStore.run({ owner: this, ctx: Object.isFrozen(ctx) ? ctx : makeContext(ctx) }, fn);
+ }
+
+ /**
+ * Start the grant of one internal (scheduled/background) turn on the
+ * root context: allow-all plus `scopes`, origin `turn`. Not visible to
+ * sub-agents already running, and not inherited by ones spawned during
+ * the turn. `endTurnGrant()` removes it and leaves the session (e.g. a
+ * user's Allow All) untouched.
+ */
+ beginTurnGrant(grant: { scopes?: Array<{ path: string; read: boolean; write: boolean }> } = {}): void {
+ this.turnGrant = { scopes: (grant.scopes ?? []).map((s) => ({ ...s, path: resolve(s.path) })) };
+ this.rootCache = null;
+ }
+
+ endTurnGrant(): void {
+ this.turnGrant = null;
+ this.rootCache = null;
+ }
+
+ /** Test hook: resolve argv-lane binaries with `resolver` instead of the pinned table. */
+ setBinaryResolver(resolver: BinaryResolver): void {
+ this.binaryResolver = resolver;
+ }
+
+ // ─── Legacy setters (shims over the context) ──────────────────────────────
+
setCurrentChannelType(type: string): void {
- this.currentChannelType = type;
+ this.updateContext(() => ({ channelType: type }));
}
setCurrentContext(type: string, id: string): void {
- this.currentChannelType = type;
- this.currentChannelId = id;
+ this.updateContext(() => ({ channelType: type, channelId: id }));
}
getCurrentChannelType(): string {
- return this.currentChannelType;
+ return this.ctx().channelType;
+ }
+
+ getCurrentChannelId(): string {
+ return this.ctx().channelId;
}
setCurrentSenderRole(role: 'admin' | 'member' | undefined): void {
- this.currentSenderRole = role;
+ this.updateContext(() => ({ senderRole: role }));
}
getCurrentSenderRole(): 'admin' | 'member' | undefined {
- return this.currentSenderRole;
+ return this.ctx().senderRole;
}
onAsk(handler: (prompt: string) => Promise<string>): void {
@@ -392,24 +507,29 @@ export class PermissionManager {
}
async requestApproval(prompt: string): Promise<boolean> {
- if (this.currentChannelType === 'internal') return true;
+ const ctx = this.ctx();
+ // No one can answer on the internal channel: only an allow-all context
+ // (the internal turn's own grant) approves; a child of it does not.
+ if (ctx.channelType === 'internal') return ctx.autoApprove;
if (!this.askHandler) return false;
const result = await this.askHandler(prompt);
return result === 'yes' || result === 'always';
}
+ /** Session-level Allow All (user choice). Inside a sub-agent it only changes that sub-agent. */
setAutoApproveAll(value: boolean): void {
- this.autoApproveAll = value;
+ this.updateContext(() => ({ autoApprove: value, autoApproveOrigin: value ? 'session' : null }));
}
isAutoApproveAll(): boolean {
- return this.autoApproveAll;
+ return this.ctx().autoApprove;
}
private isGlobalAutoApproveActive(): boolean {
// Web/Cloud grants are resolved per session by WebChannel; a Local CLI
// allow-all setting must never silently elevate remote requests.
- return this.autoApproveAll && this.currentChannelType !== 'web';
+ const ctx = this.ctx();
+ return ctx.autoApprove && ctx.channelType !== 'web';
}
elevateForSkill(allowedTools: string[]): void {
@@ -422,28 +542,28 @@ export class PermissionManager {
logger.info({ allowedTools }, 'Skill elevation ignored in fail-closed mode (granted scopes rule)');
return;
}
- if (allowedTools.includes('run_command')) {
- this.elevatedCommands.add('run_command');
- }
- if (allowedTools.includes('read_file') || allowedTools.includes('list_dir')) {
- this.elevatedCommands.add('fs_read');
- }
+ const grants: string[] = [];
+ if (allowedTools.includes('run_command')) grants.push('run_command');
+ if (allowedTools.includes('read_file') || allowedTools.includes('list_dir')) grants.push('fs_read');
if (allowedTools.includes('write_file') || allowedTools.includes('create_file') || allowedTools.includes('delete_file')) {
- this.elevatedCommands.add('fs_write');
+ grants.push('fs_write');
}
+ if (grants.length === 0) return;
+ // Elevation lands on the calling agent's own context only.
+ this.updateContext((base) => ({ elevated: [...new Set([...base.elevated, ...grants])] }));
}
clearElevation(): void {
- this.elevatedCommands.clear();
+ if (this.ctx().elevated.length === 0) return;
+ this.updateContext(() => ({ elevated: [] }));
}
isElevated(tool: string): boolean {
- if (this.elevatedCommands.has(tool)) return true;
- return false;
+ return this.ctx().elevated.includes(tool);
}
isShellElevated(): boolean {
- return this.elevatedCommands.has('run_command');
+ return this.isElevated('run_command');
}
private load(): PermissionsManifest {
@@ -503,7 +623,7 @@ export class PermissionManager {
// Skill elevation is an explicit "read anywhere" grant, so neither the
// scope checks nor the alias prompt apply — but the caller still gets the
// canonical path and identity so the open is verified like any other.
- if (this.elevatedCommands.has('fs_read')) {
+ if (this.isElevated('fs_read')) {
return this.describeRead(canonical).result;
}
@@ -519,7 +639,7 @@ export class PermissionManager {
// the user for the target when a prompt is possible, otherwise deny —
// the model is told the canonical path so it can request that scope.
const reason = `Permission denied: read of ${path} resolves outside the approved scopes (${canonical})`;
- if (!this.failClosed && !this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {
+ if (!this.failClosed && !this.isGlobalAutoApproveActive() && this.askHandler && this.ctx().channelType !== 'internal') {
const granted = await this.requestScopeExternal(canonical, 'read');
if (!granted.allowed) return { allowed: false, reason, code: 'symlink-escape', canonical };
} else {
@@ -563,11 +683,12 @@ export class PermissionManager {
const nlink = described.nlink;
if (nlink === undefined || nlink <= 1 || this.isGlobalAutoApproveActive()) return described.result;
- const approvedAliases = this.approvedHardlinkReadsByContext.get(this.currentChannelId);
+ const channelId = this.ctx().channelId;
+ const approvedAliases = this.approvedHardlinkReadsByContext.get(channelId);
if (approvedAliases?.has(canonical)) return described.result;
const reason = `Permission denied for read access to ${path}: the file has ${nlink} hard links and may alias a file outside the approved scopes`;
- if (this.failClosed || !this.askHandler || this.currentChannelType === 'internal') {
+ if (this.failClosed || !this.askHandler || this.ctx().channelType === 'internal') {
return { allowed: false, reason, code: 'hardlink', canonical };
}
const response = await this.askHandler(
@@ -576,7 +697,7 @@ export class PermissionManager {
if (response === 'always') {
const approved = approvedAliases ?? new Set<string>();
approved.add(canonical);
- this.approvedHardlinkReadsByContext.set(this.currentChannelId, approved);
+ this.approvedHardlinkReadsByContext.set(channelId, approved);
return described.result;
}
if (response === 'yes') return described.result;
@@ -598,10 +719,10 @@ export class PermissionManager {
}
private async checkScopedAccess(path: string, mode: 'read' | 'write'): Promise<FsAccessResult> {
- if (mode === 'read' && this.elevatedCommands.has('fs_read')) {
+ if (mode === 'read' && this.isElevated('fs_read')) {
return { allowed: true };
}
- if (mode === 'write' && this.elevatedCommands.has('fs_write')) {
+ if (mode === 'write' && this.isElevated('fs_write')) {
return { allowed: true };
}
@@ -634,7 +755,9 @@ export class PermissionManager {
}
// Write access: in auto-approve-all mode, allow if scope covers it
- const contextWriteApproved = this.approvedWritesByContext.get(this.currentChannelId)?.has(resolved) === true;
+ const channelId = this.ctx().channelId;
+ const channelType = this.ctx().channelType;
+ const contextWriteApproved = this.approvedWritesByContext.get(channelId)?.has(resolved) === true;
if (mode === 'write' && (this.isGlobalAutoApproveActive() || contextWriteApproved)) {
if (scope && scope.write) return { allowed: true };
if (tempScope && tempScope.write) return { allowed: true };
@@ -650,16 +773,16 @@ export class PermissionManager {
}
// Write access in ask-me mode: ALWAYS prompt the user, even if scope exists
- if (mode === 'write' && !this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {
+ if (mode === 'write' && !this.isGlobalAutoApproveActive() && this.askHandler && channelType !== 'internal') {
const scopeAllows = (scope && scope.write) || (tempScope && tempScope.write);
if (scopeAllows) {
// Scope allows it, but user wants to confirm — prompt with file path
const result = await this.askHandler(`Write to file: ${resolved}`);
if (result === 'yes') return { allowed: true };
if (result === 'always') {
- const approved = this.approvedWritesByContext.get(this.currentChannelId) ?? new Set<string>();
+ const approved = this.approvedWritesByContext.get(channelId) ?? new Set<string>();
approved.add(resolved);
- this.approvedWritesByContext.set(this.currentChannelId, approved);
+ this.approvedWritesByContext.set(channelId, approved);
return { allowed: true };
}
return { allowed: false, reason: `User denied write to ${path}` };
@@ -676,37 +799,37 @@ export class PermissionManager {
return { allowed: false, reason: `Permission denied: ${mode} access to ${path}` };
}
- if (!this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {
+ if (!this.isGlobalAutoApproveActive() && this.askHandler && channelType !== 'internal') {
return this.requestScopeExternal(path, mode);
}
return { allowed: false, reason: `Permission denied for ${mode} access to ${path}` };
}
- // Read-only commands that never need approval even in ask-me mode
- private static readonly SAFE_READ_COMMANDS = new Set([
- 'ls', 'cat', 'pwd', 'which', 'echo', 'head', 'tail', 'wc', 'find', 'grep', 'rg',
- 'ps', 'df', 'du', 'uname', 'dir', 'type', 'cd', 'where', 'tree', 'findstr',
- 'tasklist', 'systeminfo', 'git', // git read commands are filtered by pattern below
- ]);
-
- private static readonly SAFE_READ_PATTERNS = [
- 'ls *', 'cat *', 'pwd', 'which *', 'echo *', 'head *', 'tail *', 'wc *',
- 'find *', 'grep *', 'rg *', 'ps *', 'df *', 'du *', 'uname *',
- 'dir *', 'type *', 'cd *', 'where *', 'tree *', 'findstr *',
- 'tasklist *', 'systeminfo *',
- 'git status *', 'git diff *', 'git log *', 'git branch *',
- ];
-
- async checkShellCommand(command: string): Promise<{ allowed: boolean; reason?: string; needsApproval: boolean }> {
+ /**
+ * Shell permission check. Two lanes (ADR-016):
+ *
+ * - **argv lane** (no prompt): the command tokenises into argv with no
+ * shell syntax, `argv[0]` is allowlisted, its flags pass the per-command
+ * policy, and every path argument stays inside the cwd or a readable
+ * scope. The caller executes it with execFile from the pinned PATH.
+ * - **approval lane**: everything else, including pipelines and chains.
+ * The user sees the exact string; once approved it may use a shell.
+ *
+ * Hard blocks win over both, and Allow All / skill elevation / an
+ * "always" answer / a bot allow-list grant approve through the approval
+ * lane without prompting.
+ */
+ async checkShellCommand(command: string, options: { cwd?: string } = {}): Promise<ShellCheckResult> {
const shell = this.manifest.capabilities.shell;
if (!shell.enabled) {
return { allowed: false, reason: 'Shell capability is disabled', needsApproval: false };
}
const trimmed = command.trim();
- const baseCmd = trimmed.split(/\s+/)[0];
const segments = splitShellSegments(trimmed);
+ const ctx = this.ctx();
+ const cwd = options.cwd ?? this.cwd;
// Always block dangerous commands — check each segment so an
// auto-approved base command can't launder a chained destructive one
@@ -721,17 +844,17 @@ export class PermissionManager {
if (this.isGlobalAutoApproveActive()) {
logger.info({ cmd: trimmed }, 'Shell command auto-approved (Local allow-all mode)');
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
if (this.isShellElevated()) {
logger.info({ cmd: trimmed }, 'Shell command auto-approved (skill elevation)');
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
- if (this.approvedCommandsByContext.get(this.currentChannelId)?.has(trimmed)) {
+ if (this.approvedCommandsByContext.get(ctx.channelId)?.has(trimmed)) {
logger.info({ cmd: trimmed }, 'Shell command auto-approved for this interaction context');
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
if (shell.cwdOnly) {
@@ -753,8 +876,8 @@ export class PermissionManager {
// broad pattern like "cat *" can never launder a path outside granted
// scopes; needsApproval wins (the same pattern in both lists means
// deny); a bare "*" is rejected at grant time — allow-all is an
- // interactive-mode concept, not a bot grant. Safe-read commands stay
- // fully covered by the allSegmentsSafeRead lane below.
+ // interactive-mode concept, not a bot grant. Read-only commands stay
+ // covered by the argv lane below.
if (this.failClosed && this.botShellAllowList && this.botShellAllowList.length > 0) {
const needsApprovalList = shell.needsApproval ?? [];
const botList = this.botShellAllowList;
@@ -766,19 +889,15 @@ export class PermissionManager {
);
if (allSegmentsApproved) {
logger.info({ cmd: trimmed }, 'Shell command auto-approved (bot allow-list)');
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
}
- // In ask-me mode: only auto-approve when EVERY segment is a safe read.
- // Matching the full trimmed string would let `cat foo; rm -rf ~` slip
- // through because `cat *` matches the entire concatenation.
- const allSegmentsSafeRead = segments.length > 0 && segments.every((segment) =>
- this.isSafeReadSegment(segment)
- );
- if (allSegmentsSafeRead) {
- logger.info({ cmd: trimmed, segments: segments.length }, 'Shell command auto-approved (safe read-only)');
- return { allowed: true, needsApproval: false };
+ // Argv lane: the only path to a prompt-free approval in Ask Me mode.
+ const argvLane = this.classifyArgvLane(trimmed, cwd);
+ if (argvLane.ok) {
+ logger.info({ cmd: trimmed }, 'Shell command auto-approved (argv lane)');
+ return { allowed: true, needsApproval: false, lane: 'argv' };
}
// Fail-closed execute grants (bots): an explicitly granted execute scope
@@ -790,21 +909,21 @@ export class PermissionManager {
const pathTokens = segments.flatMap(s => this.extractPathTokens(s));
if (pathTokens.length > 0 && pathTokens.every(t => this.isExecuteScoped(t))) {
logger.info({ cmd: trimmed, paths: pathTokens.length }, 'Shell command allowed by execute scope');
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
}
- // All non-safe commands require user approval in ask-me mode
- if (this.askHandler && this.currentChannelType !== 'internal') {
+ // Approval lane: the user sees the exact string.
+ if (this.askHandler && ctx.channelType !== 'internal') {
const result = await this.askHandler(`Run command: ${trimmed}`);
if (result === 'yes') {
- return { allowed: true, needsApproval: false };
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
if (result === 'always') {
- const approved = this.approvedCommandsByContext.get(this.currentChannelId) ?? new Set<string>();
+ const approved = this.approvedCommandsByContext.get(ctx.channelId) ?? new Set<string>();
approved.add(trimmed);
- this.approvedCommandsByContext.set(this.currentChannelId, approved);
- return { allowed: true, needsApproval: false };
+ this.approvedCommandsByContext.set(ctx.channelId, approved);
+ return { allowed: true, needsApproval: false, lane: 'shell' };
}
return { allowed: false, reason: `User denied: ${trimmed}`, needsApproval: false };
}
@@ -813,56 +932,40 @@ export class PermissionManager {
}
/**
- * Per-command flags that turn a "read-only" command into a write or an
- * exec. Each entry is matched against the segment's command word, then its
- * flag pattern against the whole segment. Flags are anchored at a token
- * start and must end at whitespace, `=` or end-of-segment, so `-fprint0`
- * and `-fls` cannot hide behind a `\b` that stops at the digit (#71 family).
+ * Argv-lane classification: policy (tokenizer, allowlist, flag policy),
+ * binary availability in the pinned PATH, and a path gate over the
+ * tokenised arguments (after quote removal, so `cat "/etc/passwd"` is
+ * seen as the absolute path it is).
*/
- private static readonly SIDE_EFFECT_FLAGS: ReadonlyArray<{ command: RegExp; flags: RegExp }> = [
- // find: -exec/-execdir/-ok/-okdir run commands; -delete deletes;
- // -fprint/-fprint0/-fprintf/-fls write attacker-chosen files;
- // -files0-from dereferences a path list the literal-path gate never saw.
- { command: /^find(?:\s|$)/, flags: /(?:^|\s)-(?:delete|exec|execdir|ok|okdir|fprintf|fprint0|fprint|fls|files0-from)(?=\s|=|$)/ },
- // tree -o FILE / --output FILE writes the listing to a file.
- { command: /^tree(?:\s|$)/, flags: /(?:^|\s)(?:-[A-Za-z]*o[A-Za-z]*|--output)(?=\s|=|$)/ },
- // curl: -o/-O (also inside a cluster such as -sSLo), --output,
- // --remote-name(-all), -J/--remote-header-name, --output-dir write files.
- { command: /^curl(?:\s|$)/, flags: /(?:^|\s)(?:-[A-Za-z]*[oOJ][A-Za-z]*|--output|--output-dir|--remote-name|--remote-name-all|--remote-header-name|--create-dirs)(?=\s|=|$)/ },
- // wget: -O/--output-document, -o/--output-file, -a/--append-output,
- // -P/--directory-prefix all choose where it writes.
- { command: /^wget(?:\s|$)/, flags: /(?:^|\s)(?:-[A-Za-z]*[oOaP][A-Za-z]*|--output-document|--output-file|--append-output|--directory-prefix)(?=\s|=|$)/ },
- // git log/diff: --output writes the result to a file; --ext-diff runs the
- // configured external diff program; --no-index diffs arbitrary paths.
- { command: /^git\s+(?:log|diff|status|branch)(?:\s|$)/, flags: /(?:^|\s)(?:--output|--ext-diff|--no-index)(?=\s|=|$)/ },
- // rg --pre CMD pipes every file through an arbitrary preprocessor.
- { command: /^rg(?:\s|$)/, flags: /(?:^|\s)--pre(?=\s|=|$)/ },
- ];
-
- private isSafeReadSegment(segment: string): boolean {
- // Redirection turns otherwise read-only commands such as cat/echo into writes.
- if (/\d*(?:>{1,2}|<{1,2})|&>/.test(segment)) return false;
- // Command-specific write/exec flags (find -exec, curl -o, rg --pre, …).
- for (const rule of PermissionManager.SIDE_EFFECT_FLAGS) {
- if (rule.command.test(segment) && rule.flags.test(segment)) return false;
+ classifyArgvLane(command: string, cwd: string = this.cwd): { ok: true; argv: string[] } | { ok: false; reason: string } {
+ const verdict = evaluateArgvPolicy(command);
+ if (!verdict.ok) return verdict;
+ const argv = verdict.argv;
+ if (!IN_PROCESS_BUILTINS.has(argv[0]) && !this.binaryResolver(argv[0])) {
+ return { ok: false, reason: `${argv[0]} is not installed in the pinned system PATH` };
}
- // File-list indirection in any safe-read command (wc/du/sort/…): the
- // paths live inside the referenced file, invisible to the literal-path
- // gate, so the read can escape the approved scopes.
- if (/(?:^|\s)--files0-from(?:=|\s|$)/.test(segment)) return false;
- // Shell expansion runs after this check, so a "safe read" can still
- // resolve outside the workspace (`head $HOME/secret`, CVE-2026-28463) or
- // disclose environment values (`echo $TOKEN`). Require approval for any
- // segment that relies on variable expansion or a home shorthand.
- // ANSI-C quoting ($'\x2f...') also expands post-check — caught by the same class.
- if (/\$[{(0-9A-Za-z_']|`/.test(segment)) return false;
- if (/(?:^|\s)~[A-Za-z0-9_-]*(?:\/|$)/.test(segment)) return false;
- const branchArgs = segment.match(/^git\s+branch(?:\s+(.*))?$/)?.[1]?.trim();
- if (branchArgs && (
- !branchArgs.startsWith('-')
- || /(?:^|\s)(?:-[dDmMcC]\b|--(?:delete|move|copy|edit-description|set-upstream-to|unset-upstream|track)\b)/.test(branchArgs)
- )) return false;
- return PermissionManager.SAFE_READ_PATTERNS.some((pattern) => this.matchPattern(segment, pattern));
+ for (const arg of argv.slice(1)) {
+ for (const candidate of this.argvPathCandidates(arg)) {
+ const resolved = resolve(cwd, candidate.replace(/^~/, homedir()));
+ if (resolved === cwd || resolved.startsWith(cwd.endsWith(sep) ? cwd : cwd + sep)) continue;
+ if (this.isLexicallyReadable(resolved)) continue;
+ return { ok: false, reason: `path ${candidate} is outside the working directory and readable scopes` };
+ }
+ }
+ return { ok: true, argv };
+ }
+
+ /** Path-like parts of one argv element: the element itself and an `--opt=value` value. */
+ private argvPathCandidates(arg: string): string[] {
+ const parts = [arg];
+ const eq = arg.indexOf('=');
+ if (arg.startsWith('-') && eq > 0) parts.push(arg.slice(eq + 1));
+ return parts.filter((p) =>
+ p.startsWith('/')
+ || /^[A-Za-z]:[\\/]/.test(p)
+ || p.startsWith('\\\\')
+ || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(p),
+ );
}
isGitReadAllowed(): boolean {
@@ -929,14 +1032,18 @@ export class PermissionManager {
return { allowed: false, reason: `Permission denied for ${mode} access to ${path}` };
}
+ /**
+ * Session-only scope on the calling agent's context (the main agent's
+ * session, or a sub-agent's own context — never shared with siblings).
+ */
addTempScope(path: string, read: boolean, write: boolean): void {
const resolved = resolve(path);
- this.tempScopes.push({ path: resolved, read, write });
+ this.updateContext((base) => ({ scopes: [...base.scopes, { path: resolved, read, write }] }));
logger.info({ path: resolved, read, write }, 'Temp permission scope added (session only)');
}
- private findTempScope(resolvedPath: string): FileScope | undefined {
- for (const scope of this.tempScopes) {
+ private findTempScope(resolvedPath: string): ContextScope | undefined {
+ for (const scope of this.ctx().scopes) {
const scopeResolved = resolve(scope.path.replace(/^~/, homedir()));
if (resolvedPath === scopeResolved || resolvedPath.startsWith(scopeResolved + sep)) {
return scope;
@@ -966,7 +1073,7 @@ export class PermissionManager {
* directory (macOS `/tmp` → `/private/tmp`) still covers its own files.
*/
private isWithinScope(canonicalPath: string, mode: 'read' | 'write'): boolean {
- const granting = [...this.manifest.capabilities.filesystem.scopes, ...this.tempScopes].filter(
+ const granting = [...this.manifest.capabilities.filesystem.scopes, ...this.ctx().scopes].filter(
(scope) => (mode === 'write' ? scope.write : scope.read),
);
for (const scope of granting) {
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 75bdb1cf..ecc8fb84 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -88,8 +88,6 @@ export class CapabilityRegistry {
private userMemory?: UserMemoryStore;
private sendFileHandler?: (filePath: string, channel?: string) => Promise<void>;
private sendMessageHandler?: (content: string) => Promise<void>;
- private currentChannelId = 'cli';
- private currentChannelType = 'cli';
private chatCommandContext?: ChatCommandContext;
private currentCwd = process.cwd();
private researchModeGetter: (() => boolean) | null = null;
@@ -130,14 +128,18 @@ export class CapabilityRegistry {
return this.chatCommandContext;
}
+ /**
+ * Channel of the calling agent. Stored in its permission context, so a
+ * sub-agent (running under its own context) never overwrites the main
+ * agent's channel, and its prompts route to its own source channel.
+ */
setChannelContext(channelId: string, channelType: string): void {
- this.currentChannelId = channelId;
- this.currentChannelType = channelType;
this.permissions.setCurrentContext(channelType, channelId);
}
getChannelContext(): { channelId: string; channelType: string } {
- return { channelId: this.currentChannelId, channelType: this.currentChannelType };
+ const ctx = this.permissions.currentContext();
+ return { channelId: ctx.channelId, channelType: ctx.channelType };
}
getCwd(): string {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index c59a5f46..7b979ab9 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -2945,8 +2945,9 @@ export class Agent {
const isInternal = msg.channelType === 'internal';
if (isInternal) {
- this.capabilities.permissions.setAutoApproveAll(true);
- this.capabilities.permissions.addTempScope('/', true, true);
+ // Turn-scoped grant on the root context only (ADR-016): running
+ // sub-agents keep their own context and new ones do not inherit it.
+ this.capabilities.permissions.beginTurnGrant({ scopes: [{ path: '/', read: true, write: true }] });
}
try {
@@ -5144,7 +5145,7 @@ export class Agent {
if (ch instanceof CLIChannel) ch.clearLiveActivity();
}
if (isInternal) {
- this.capabilities.permissions.setAutoApproveAll(false);
+ this.capabilities.permissions.endTurnGrant();
}
this.capabilities.permissions.clearElevation();
}
diff --git a/src/core/sub-agent-approval.test.ts b/src/core/sub-agent-approval.test.ts
index afc7bc6d..c98b63e0 100644
--- a/src/core/sub-agent-approval.test.ts
+++ b/src/core/sub-agent-approval.test.ts
@@ -143,7 +143,55 @@ describe('delegated sub-agent shell commands go through the parent\'s approval f
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');
+ it('#75/#99 residual: a chat child\'s rm -rf that lands inside a concurrent internal allow-all turn still prompts (P2.2)', async () => {
+ // The child's first model call waits until the main agent is inside an
+ // internal turn, then asks for `rm -rf build`.
+ let release!: () => void;
+ const gate = new Promise<void>((r) => { release = r; });
+ let calls = 0;
+ const model = new MockLanguageModelV3({
+ doGenerate: async (): Promise<LanguageModelV3GenerateResult> => {
+ calls++;
+ if (calls === 1) {
+ await gate;
+ return {
+ content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'run_command', input: JSON.stringify({ command: 'rm -rf build' }) }],
+ finishReason: { unified: 'tool-calls', raw: 'tool_use' },
+ usage,
+ warnings: [],
+ };
+ }
+ return { content: [{ type: 'text', text: 'done' }], finishReason: { unified: 'stop', raw: 'end_turn' }, usage, warnings: [] };
+ },
+ });
+ const ask = vi.fn().mockResolvedValue('no');
+ const { agent, registry } = makeChild({ model, ask });
+ const permissions = registry.permissions;
+
+ const running = agent.run();
+
+ // Main agent: an internal (scheduled) turn starts while the child runs —
+ // exactly what agent.ts handleMessage does for msg.channelType 'internal'.
+ registry.setChannelContext('internal', 'internal');
+ permissions.beginTurnGrant({ scopes: [{ path: '/', read: true, write: true }] });
+ try {
+ // The window is real for the main agent: it may run the command unprompted…
+ await expect(permissions.checkShellCommand('rm -rf build')).resolves.toMatchObject({ allowed: true });
+ expect(ask).not.toHaveBeenCalled();
+
+ // …but the child's call, landing inside that window, still prompts.
+ release();
+ const result = await running;
+ 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');
+ // The child never clobbered the main agent's channel.
+ expect(registry.getChannelContext()).toEqual({ channelId: 'internal', channelType: 'internal' });
+ } finally {
+ permissions.endTurnGrant();
+ }
+ });
});
describe('sub-agent tool surface and prompt (#74)', () => {
diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.ts
index 689b0378..e81cf90a 100644
--- a/src/core/sub-agent.ts
+++ b/src/core/sub-agent.ts
@@ -16,7 +16,8 @@ import { createDelegateTaskTool, createListAgentsTool, createStopAgentTool } fro
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 { resolveChildTools, childMayUse } from '../utils/tool-filter.js';
+import { resolveChildTools, childMayUse, filterToolsByAllowlist } from '../utils/tool-filter.js';
+import { deriveChildContext, type PermissionContext } from '../capabilities/permission-context.js';
import { logger } from '../utils/logger.js';
export type ProgressCallback = (agentId: string, progress: string) => void;
@@ -121,7 +122,46 @@ export class SubAgent {
this.onPostComment = cb;
}
+ private permissionContext?: PermissionContext;
+
+ /**
+ * This agent's frozen permission context: the one the supervisor derived
+ * at spawn time, or (when constructed directly) one derived now from the
+ * current context. Child ⊆ parent; see permission-context.ts.
+ */
+ getPermissionContext(): PermissionContext | undefined {
+ if (this.permissionContext) return this.permissionContext;
+ if (this.config.permissionContext) {
+ this.permissionContext = this.config.permissionContext;
+ } else {
+ const permissions = this.capabilities.permissions as any;
+ if (typeof permissions?.currentContext !== 'function') return undefined;
+ this.permissionContext = deriveChildContext(permissions.currentContext(), {
+ channelType: this.config.sourceChannelType || 'internal',
+ channelId: this.config.sourceChannelId || 'internal',
+ allowedTools: this.config.allowedTools,
+ });
+ }
+ return this.permissionContext;
+ }
+
+ /**
+ * Run the task under this agent's own permission context. Every tool it
+ * invokes — through any depth of the AI SDK's promise chain — resolves
+ * permissions against that context via AsyncLocalStorage, so a concurrent
+ * change to the main agent's context (an internal turn's allow-all) never
+ * reaches it (#75/#99 residual).
+ */
async run(): Promise<SubAgentResult> {
+ const ctx = this.getPermissionContext();
+ const permissions = this.capabilities.permissions as any;
+ if (ctx && typeof permissions?.withContext === 'function') {
+ return permissions.withContext(ctx, () => this.runInContext());
+ }
+ return this.runInContext();
+ }
+
+ private async runInContext(): Promise<SubAgentResult> {
this.status = 'running';
this.startTime = Date.now();
@@ -175,10 +215,8 @@ export class SubAgent {
this.capabilities.setCwd(this.config.workingDirectory);
}
- this.capabilities.setChannelContext(
- this.config.sourceChannelId || 'internal',
- this.config.sourceChannelType || 'internal',
- );
+ // Channel routing comes from this agent's permission context (set in
+ // run()); the shared registry's main-agent channel is left alone.
try {
const provider = this.providers.getDefault();
@@ -502,16 +540,21 @@ export class SubAgent {
* the shared registry instance carries the main agent's authority (#74).
*/
private resolveTools() {
- const tools = resolveChildTools(this.capabilities.getTools(), this.config.allowedTools);
+ let tools = resolveChildTools(this.capabilities.getTools(), this.config.allowedTools);
+ // The context's allowlist is the parent's ∩ this agent's: a grandchild
+ // can never be granted a tool its parent did not have.
+ const ctxTools = this.getPermissionContext()?.allowedTools;
+ if (ctxTools) tools = filterToolsByAllowlist(tools, ctxTools);
+ const ctxAllows = (name: string) => !ctxTools || ctxTools.includes(name);
if (this.supervisor) {
const scoped = { callerId: this.config.id };
- if (childMayUse('delegate_task', this.config.allowedTools)) {
+ if (childMayUse('delegate_task', this.config.allowedTools) && ctxAllows('delegate_task')) {
tools.delegate_task = createDelegateTaskTool(this.supervisor, this.capabilities, scoped);
}
- if (childMayUse('list_agents', this.config.allowedTools)) {
+ if (childMayUse('list_agents', this.config.allowedTools) && ctxAllows('list_agents')) {
tools.list_agents = createListAgentsTool(this.supervisor, scoped);
}
- if (childMayUse('stop_agent', this.config.allowedTools)) {
+ if (childMayUse('stop_agent', this.config.allowedTools) && ctxAllows('stop_agent')) {
tools.stop_agent = createStopAgentTool(this.supervisor, scoped);
}
}
@@ -564,13 +607,14 @@ export class SubAgent {
const permissions = this.capabilities.permissions;
const readable: string[] = [];
const writable: string[] = [];
- for (const scope of permissions.getManifest().capabilities.filesystem.scopes) {
+ for (const scope of [...permissions.getManifest().capabilities.filesystem.scopes, ...(this.getPermissionContext()?.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()) {
+ const ctx = this.getPermissionContext();
+ if (ctx ? ctx.autoApprove : 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.');
diff --git a/src/core/supervisor-context.test.ts b/src/core/supervisor-context.test.ts
new file mode 100644
index 00000000..adc2f15e
--- /dev/null
+++ b/src/core/supervisor-context.test.ts
@@ -0,0 +1,100 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+import { MockLanguageModelV3 } from 'ai/test';
+
+// The task board and permissions.yaml live under MERCURY_HOME.
+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-supctx-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const { SubAgentSupervisor } = await import('./supervisor.js');
+const { PermissionManager } = await import('../capabilities/permissions.js');
+const { makeContext, isSubsetContext } = await import('../capabilities/permission-context.js');
+
+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(permissions: InstanceType<typeof PermissionManager>) {
+ 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,
+ } as any,
+ tokenBudget: { getStatusText: () => '', getUsagePercentage: () => 0, recordUsage() {}, getRemaining: () => 1_000_000 } as any,
+ channels: {} as any,
+ });
+ return supervisor;
+}
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 30));
+
+describe('SubAgentSupervisor permission contexts (ADR-016)', () => {
+ const supervisors: InstanceType<typeof SubAgentSupervisor>[] = [];
+ afterAll(async () => {
+ for (const s of supervisors) await s.haltAll();
+ await settle();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it('snapshots the spawning agent\'s context at spawn time, as a subset', async () => {
+ const permissions = new PermissionManager();
+ const supervisor = makeSupervisor(permissions);
+ supervisors.push(supervisor);
+ supervisor.setMaxConcurrent(10);
+
+ const parent = makeContext({ channelType: 'telegram', channelId: 'chat-1', allowedTools: ['read_file', 'run_command'] });
+ const id = await permissions.withContext(parent, () => supervisor.spawn({
+ task: 'child', allowedTools: ['run_command', 'write_file'], sourceChannelType: 'telegram', sourceChannelId: 'chat-1',
+ }));
+ const ctx = (supervisor as any).agentConfigs.get(id).permissionContext;
+ expect(ctx.allowedTools).toEqual(['run_command']);
+ expect(ctx.channelId).toBe('chat-1');
+ expect(isSubsetContext(ctx, parent)).toBe(true);
+ });
+
+ it('a queued agent keeps the context it was spawned with, not the root context when it starts', async () => {
+ const permissions = new PermissionManager();
+ const supervisor = makeSupervisor(permissions);
+ supervisors.push(supervisor);
+ supervisor.setMaxConcurrent(1);
+
+ await supervisor.spawn({ task: 'occupies the only slot' });
+ const queuedId = await supervisor.spawn({ task: 'queued', sourceChannelType: 'cli', sourceChannelId: 'cli' });
+ const queued = (supervisor as any).waitQueue.find((c: any) => c.id === queuedId);
+ expect(queued.permissionContext.autoApprove).toBe(false);
+
+ // The main agent then enters an internal allow-all turn; the queued
+ // config's frozen context is unaffected.
+ permissions.beginTurnGrant({ scopes: [{ path: '/', read: true, write: true }] });
+ expect(permissions.isAutoApproveAll()).toBe(true);
+ expect(queued.permissionContext.autoApprove).toBe(false);
+ expect(queued.permissionContext.scopes).toEqual([]);
+ expect(Object.isFrozen(queued.permissionContext)).toBe(true);
+ permissions.endTurnGrant();
+ });
+});
diff --git a/src/core/supervisor.ts b/src/core/supervisor.ts
index b5ec250a..d623ada4 100644
--- a/src/core/supervisor.ts
+++ b/src/core/supervisor.ts
@@ -12,6 +12,8 @@ import { FileLockManager } from './file-lock.js';
import { TaskBoard } from './task-board.js';
import { ResourceManager } from './resource-manager.js';
import { logger } from '../utils/logger.js';
+import { deriveChildContext, type PermissionContext } from '../capabilities/permission-context.js';
+import type { PermissionManager } from '../capabilities/permissions.js';
/** Bounded auto-resumes after a step-budget pause before reporting honestly. */
const MAX_SUBAGENT_STEP_RESUMES = 3;
@@ -122,7 +124,14 @@ export class SubAgentSupervisor {
async spawn(config: Omit<SubAgentConfig, 'id'>): Promise<string> {
const id = this.taskBoard.nextId();
- const fullConfig: SubAgentConfig = { ...config, id };
+ // Snapshot the spawning agent's permission context NOW (spawn runs inside
+ // the caller's async context): a queued agent that starts later must not
+ // pick up whatever the main agent's context is at that moment.
+ const fullConfig: SubAgentConfig = {
+ ...config,
+ id,
+ permissionContext: config.permissionContext ?? this.childPermissionContext(config),
+ };
this.parents.set(id, config.parentId);
if (!this.resourceManager.canSpawn()) {
@@ -177,6 +186,16 @@ export class SubAgentSupervisor {
return id;
}
+ private childPermissionContext(config: Omit<SubAgentConfig, 'id'>): PermissionContext | undefined {
+ const permissions = this.capabilities.permissions as Partial<PermissionManager> | undefined;
+ if (typeof permissions?.currentContext !== 'function') return undefined;
+ return deriveChildContext(permissions.currentContext(), {
+ channelType: config.sourceChannelType,
+ channelId: config.sourceChannelId,
+ allowedTools: config.allowedTools,
+ });
+ }
+
private startAgentInBackground(config: SubAgentConfig): void {
this.agentConfigs.set(config.id, config);
const subAgent = new SubAgent(config, {
diff --git a/src/types/agent.ts b/src/types/agent.ts
index 8c4bac6d..11e06085 100644
--- a/src/types/agent.ts
+++ b/src/types/agent.ts
@@ -61,6 +61,13 @@ export interface SubAgentConfig {
* descendants (#74).
*/
parentId?: string;
+ /**
+ * Frozen permission context, derived from the spawning agent's context at
+ * spawn time (child ⊆ parent; ADR-016). The sub-agent runs under it via
+ * AsyncLocalStorage. Absent only for agents constructed directly (tests),
+ * which derive one from the current context when they start.
+ */
+ permissionContext?: import('../capabilities/permission-context.js').PermissionContext;
}
export interface SubAgentResult {