SLOPSHOPPER

tool-visibility-controller

Claude Code plugin for per-agent tool visibility — hide and refuse subagents, skills, MCP and built-in tools per loop

guardpromptprocesstimeragents
A shopper browsing a rack in a slop shop
README

tool-visibility-controller

Claude Code plugin for per-agent tool visibility — hide and refuse subagents, skills, MCP and built-in tools per loop.

Add a visibility field to an agent, skill or command's frontmatter: visible-to: { include: [...], exclude: [...] } names the loops (agent types, main for the main chat) that may see and invoke the item, and an agent's agents, skills, mcp and tools blocks limit what its own loop sees. Rules for what you do not own (the main chat, built-in agents, plugin agents and skills, MCP servers, built-in tools) go in tool-visibility-controller.json in ~/.claude/ or a project's .claude/. Each loop's agent listing, skill listing, deferred-tools notice and MCP instructions lose what it may not use, and a spawn, skill or tool call it may not make is refused with a message naming the rule. Definitions and scope files are read lazily on the first policy use and cached until session.start or /reload-plugins; after an edit, run /reload-plugins or start a new session. Reload clears the policy cache and missing-path log suppression after the command finishes or throws, without rerunning or rewriting it or changing its result or error. The next policy use reads the files again; other commands and events retain the cached policy, and a failed load is retried on the next use. Any error is logged and leaves the listing, the call and the spawn as they were, and a diagnostic names the action that went unchecked. A missing definition file is skipped and logged once per path until session.start or /reload-plugins resets that suppression; one that exists but cannot be read is an error.

Install with /plugin install tool-visibility-controller --marketplace rezzminator/tool-visibility-controller (where --marketplace is available). Requires function hooks (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1). Limits: a tool whose schema sits in the prompt's tool list cannot be hidden per loop (its call is refused), and a sub-agent receives the agent listing after its first tool call. Remove it with claude plugin uninstall tool-visibility-controller@tool-visibility-controller. Full documentation: <https://github.com/rezzminator/tool-visibility-controller>

Built and maintained with Professor.

Source 9 files
hooks/tool-visibility-controller.ts 430 lines
1import type { EngineInterface, On, Register } from 'claude-code';
2import { levelRow, MAX_RETAINED_ROWS, pluginLogDir, PluginLogQueue, type Level } from '../src/plugin-log.ts';
3import { BURST_WINDOW_MS, ScreenBurst } from '../src/screen-burst.ts';
4import { AgentTypes } from '../src/agent-types.ts';
5import { hookFailureText, message, missingDefinition, unresolvedLoopText } from '../src/failures.ts';
6import { SpawnCalls } from '../src/spawns.ts';
7import { filterDeferredTools, filterEntries, filterMcpInstructions } from '../src/listings.ts';
8import {
9  ancestorDirs,
10  buildPolicy,
11  decide,
12  denyText,
13  hasRules,
14  isEmpty,
15  MAIN,
16  mcpServer,
17  mergeScopes,
18  normalizeServer,
19  readScopeFile,
20  SCOPE_FILE,
21  type Owned,
22  type Policy,
23  type ScopeFile,
24} from '../src/policy.ts';
25import { readDefinition, SETS, type SetName } from '../src/visibility.ts';
26
27// Thin adapter: every decision lives in src/. A failure is logged with its
28// context, and the listing, the call or the spawn goes on as it was.
29
30/** The attachments that list what a loop can use. */
31const LISTINGS = new Set(['agent_listing_delta', 'skill_listing', 'mcp_instructions_delta', 'deferred_tools_delta']);
32
33/** How deep command subdirectories are read (`a:b:c`). */
34const COMMAND_DEPTH = 3;
35
36type Logger = { queue: PluginLogQueue; session?: string; warning?: string };
37type Pending = { level: Level; event: string; msg: string; hook: string; detail?: Record<string, unknown>; at: number };
38type LogState = { logger?: Promise<Logger>; work: Promise<void>; failing: boolean; pending: Pending[] };
39type Cache = { policy?: Promise<Policy>; missing: Set<string>; types: AgentTypes; spawns: SpawnCalls; log: LogState; logDrain: Promise<void>; burst: ScreenBurst; burstArmed: boolean };
40type Entry = { name: string; kind: string; isLink?: boolean };
41type Read = { name: string; owned: Owned | null };
42
43const PLUGIN = 'tool-visibility-controller';
44
45// The logger's last-resort screen door never interferes with a policy result.
46// Identical lines collapse: a burst shows its first line, then one count.
47function showLines($: EngineInterface, lines: readonly string[]): void {
48  for (const line of lines) {
49    try { $.ui.log(line); } catch {
50      // No other screen door exists when ui.log itself is unavailable.
51    }
52  }
53}
54
55function logFallback($: EngineInterface, cache: Cache, text: string): void {
56  showLines($, cache.burst.offer(text.startsWith(`${PLUGIN}: `) ? text : `${PLUGIN}: ${text}`, Date.now()));
57  if (cache.burstArmed || cache.burst.pending() === 0) return;
58  cache.burstArmed = true;
59  try {
60    $.clock.after(BURST_WINDOW_MS, () => {
61      cache.burstArmed = false;
62      showLines($, cache.burst.drain());
63    });
64  } catch {
65    // Without a timer the count still shows at the next repeat past the window or at session end.
66    cache.burstArmed = false;
67  }
68}
69
70async function loggerOf($: EngineInterface, cache: Cache, state: LogState): Promise<Logger> {
71  state.logger ??= (async () => {
72    const override = await $.env.get('PLUGIN_LOG_DIR');
73    const home = await $.env.get('HOME');
74    const dir = pluginLogDir(override, home, PLUGIN);
75    let session: string | undefined;
76    let warning: string | undefined;
77    try { session = await $.session.id(); } catch (error) {
78      warning = `session id unavailable: ${message(error)}; session omitted`;
79    }
80    return { queue: new PluginLogQueue(dir, PLUGIN, (text) => logFallback($, cache, text)), session, warning };
81  })();
82  try {
83    return await state.logger;
84  } catch (error) {
85    // A rejected initialization can recover on the next event.
86    state.logger = undefined;
87    throw error;
88  }
89}
90
91// Rows wait in state.pending until the logger exists, and in its queue until a write lands: a stalled
92// worker rejects the `$` calls here, and a rejected step keeps what it had not yet handed over.
93// Only the final step (session end or start) gives a row up, with the usual screen fallback.
94async function drainLog($: EngineInterface, cache: Cache, state: LogState, final: boolean): Promise<void> {
95  if (state.pending.length === 0 && (!final || state.logger === undefined)) return;
96  const logger = await loggerOf($, cache, state);
97  let clock: number | undefined;
98  let clockFailed = false;
99  try { clock = await $.clock.now(); } catch (error) {
100    clockFailed = true;
101    if (!state.failing) logFallback($, cache, `plugin log clock: ${message(error)}; local time used`);
102  }
103  if (logger.warning !== undefined) {
104    logger.queue.add(levelRow({ plugin: PLUGIN, level: 'warning', event: 'log-session-unavailable', msg: logger.warning, where: 'hooks/tool-visibility-controller.ts#loggerOf' }, clock ?? Date.now()));
105    logger.warning = undefined;
106  }
107  for (const item of state.pending.splice(0)) {
108    logger.queue.add(levelRow({ plugin: PLUGIN, level: item.level, event: item.event, msg: item.msg, where: `hooks/tool-visibility-controller.ts#${item.hook}`, session: logger.session, detail: item.detail }, clock ?? item.at));
109  }
110  await logger.queue.flush((argv) => $.process.run(argv, { timeoutMs: 5000 }), { retain: !final });
111  state.failing = clockFailed;
112}
113
114function logStepFailed($: EngineInterface, cache: Cache, state: LogState, error: unknown, final: boolean): void {
115  if (!state.failing) logFallback($, cache, `plugin log metadata: ${message(error)}; ${final ? 'rows dropped' : 'rows kept for retry'}`);
116  state.failing = true;
117  if (final) for (const item of state.pending.splice(0)) if (item.level !== 'error') logFallback($, cache, item.msg);
118}
119
120function plog($: EngineInterface, cache: Cache, level: Level, event: string, msg: string, hook: string, detail?: Record<string, unknown>): void {
121  if (level === 'error') logFallback($, cache, msg);
122  const state = cache.log;
123  state.pending.push({ level, event, msg, hook, detail, at: Date.now() });
124  if (state.pending.length > MAX_RETAINED_ROWS) {
125    const oldest = state.pending.shift()!;
126    if (oldest.level !== 'error') logFallback($, cache, oldest.msg);
127  }
128  state.work = state.work.then(() => drainLog($, cache, state, false)).catch((error) => logStepFailed($, cache, state, error, false));
129}
130
131// The last write of a log state, at session end or when a new session replaces it.
132function finishLog($: EngineInterface, cache: Cache, state: LogState): Promise<void> {
133  state.work = state.work.then(() => drainLog($, cache, state, true)).catch((error) => logStepFailed($, cache, state, error, true));
134  return state.work;
135}
136
137function claudeDir(dir: string): string {
138  return `${dir === '/' ? '' : dir}/.claude`;
139}
140
141async function entriesOf($: EngineInterface, cache: Cache, dir: string): Promise<Entry[]> {
142  if (!(await $.fs.exists(dir))) return [];
143  try {
144    return await $.fs.list(dir);
145  } catch (error) {
146    plog($, cache, 'error', 'agent-dir-unlisted', `tool-visibility-controller: listing ${dir} failed: ${message(error)}; the definitions in it are not read`, 'entriesOf', { error: message(error), path: dir });
147    return [];
148  }
149}
150
151// A missing definition is skipped; it must not mask a farther valid one.
152// Other unreadable files still stand for their name with no rule, as before.
153async function readOwned($: EngineInterface, cache: Cache, path: string, set: 'agents' | 'skills', fallback: string, byPath: boolean): Promise<Read | null> {
154  let text: string;
155  try {
156    text = await $.fs.read(path);
157  } catch (error) {
158    if (missingDefinition(error)) {
159      if (!cache.missing.has(path)) {
160        cache.missing.add(path);
161        plog($, cache, 'error', 'agent-def-missing', `tool-visibility-controller: reading ${path} failed: ${message(error)}; definition is skipped; other definitions are still read`, 'readOwned', { error: message(error), path });
162      }
163      return null;
164    }
165    plog($, cache, 'error', 'agent-def-unreadable', `tool-visibility-controller: reading ${path} failed: ${message(error)}; ${fallback} has no visibility rule`, 'readOwned', { error: message(error), path });
166    return { name: fallback, owned: null };
167  }
168  const definition = readDefinition(text, fallback);
169  const name = byPath ? fallback : definition.name;
170  for (const problem of definition.problems) plog($, cache, 'error', 'frontmatter-problem', `tool-visibility-controller: ${path}: ${problem}; that block is ignored`, 'readOwned', { error: problem, path });
171  const visibility = definition.visibility;
172  if (visibility === null) return { name, owned: null };
173  if (set !== 'agents') {
174    for (const viewed of SETS) {
175      if (visibility.sets[viewed] !== undefined) {
176        plog($, cache, 'error', 'frontmatter-problem', `tool-visibility-controller: ${path}: visibility.${viewed} applies only in agent files; it is ignored here`, 'readOwned', { path });
177      }
178    }
179  }
180  return { name, owned: { set, name, path, visibility } };
181}
182
183async function readAgents($: EngineInterface, cache: Cache, dir: string): Promise<Read[]> {
184  const read: Read[] = [];
185  for (const entry of await entriesOf($, cache, dir)) {
186    if (!entry.name.endsWith('.md') || entry.kind === 'dir') continue;
187    const definition = await readOwned($, cache, `${dir}/${entry.name}`, 'agents', entry.name.slice(0, -3), false);
188    if (definition !== null) read.push(definition);
189  }
190  return read;
191}
192
193async function readSkills($: EngineInterface, cache: Cache, dir: string): Promise<Read[]> {
194  const read: Read[] = [];
195  for (const entry of await entriesOf($, cache, dir)) {
196    if (entry.kind === 'file') continue;
197    const path = `${dir}/${entry.name}/SKILL.md`;
198    if (await $.fs.exists(path)) {
199      const definition = await readOwned($, cache, path, 'skills', entry.name, false);
200      if (definition !== null) read.push(definition);
201    }
202  }
203  return read;
204}
205
206// Commands by file, a subdirectory's named `dir:name` as Claude Code lists them.
207async function readCommands($: EngineInterface, cache: Cache, dir: string, prefix: string, depth: number): Promise<Read[]> {
208  const read: Read[] = [];
209  for (const entry of await entriesOf($, cache, dir)) {
210    if (entry.name.endsWith('.md') && entry.kind !== 'dir') {
211      const definition = await readOwned($, cache, `${dir}/${entry.name}`, 'skills', `${prefix}${entry.name.slice(0, -3)}`, true);
212      if (definition !== null) read.push(definition);
213    } else if (depth < COMMAND_DEPTH && (entry.kind === 'dir' || entry.isLink === true)) {
214      read.push(...(await readCommands($, cache, `${dir}/${entry.name}`, `${prefix}${entry.name}:`, depth + 1)));
215    }
216  }
217  return read;
218}
219
220async function readScope($: EngineInterface, cache: Cache, path: string): Promise<ScopeFile | null> {
221  if (!(await $.fs.exists(path))) return null;
222  let text: string;
223  try {
224    text = await $.fs.read(path);
225  } catch (error) {
226    plog($, cache, 'error', 'scope-unreadable', `tool-visibility-controller: reading ${path} failed: ${message(error)}; the file is ignored`, 'readScope', { error: message(error), path });
227    return null;
228  }
229  const { scope, problems } = readScopeFile(text);
230  for (const problem of problems) plog($, cache, 'error', 'scope-problem', `tool-visibility-controller: ${path}: ${problem}; ${scope === null ? 'the file is ignored' : 'that block is ignored'}`, 'readScope', { error: problem, path });
231  return scope;
232}
233
234// The user tier ($CLAUDE_CONFIG_DIR, else ~/.claude), then each project tier
235// from below the home directory (else the filesystem root) down to the session
236// root: the nearest definition of a name wins, and a nearer scope file's key
237// replaces a farther one's.
238async function loadPolicy($: EngineInterface, cache: Cache): Promise<Policy> {
239  const config = await $.env.get('CLAUDE_CONFIG_DIR');
240  const home = await $.env.get('HOME');
241  const tiers: string[] = [];
242  if (config !== undefined && config !== '') tiers.push(config);
243  else if (home !== undefined && home !== '') tiers.push(`${home}/.claude`);
244  else plog($, cache, 'error', 'user-tier-skipped', 'tool-visibility-controller: neither CLAUDE_CONFIG_DIR nor HOME is set; user definitions and scope file are not read', 'loadPolicy');
245  for (const dir of ancestorDirs(await $.session.root(), home)) tiers.push(claudeDir(dir));
246  const agents = new Map<string, Owned | null>();
247  const skills = new Map<string, Owned | null>();
248  const scopes: Array<{ path: string; scope: ScopeFile }> = [];
249  for (const tier of tiers) {
250    for (const { name, owned } of await readAgents($, cache, `${tier}/agents`)) agents.set(name, owned);
251    for (const { name, owned } of await readCommands($, cache, `${tier}/commands`, '', 0)) skills.set(name, owned);
252    for (const { name, owned } of await readSkills($, cache, `${tier}/skills`)) skills.set(name, owned);
253    const path = `${tier}/${SCOPE_FILE}`;
254    const scope = await readScope($, cache, path);
255    if (scope !== null) scopes.push({ path, scope });
256  }
257  const owned = [...agents.values(), ...skills.values()].filter((item): item is Owned => item !== null);
258  return buildPolicy(owned, mergeScopes(scopes));
259}
260
261// Read once until session.start or /reload-plugins; a failed load is retried at the next use.
262async function policyOf($: EngineInterface, cache: Cache): Promise<Policy> {
263  cache.policy ??= loadPolicy($, cache);
264  try {
265    return await cache.policy;
266  } catch (error) {
267    cache.policy = undefined;
268    throw error;
269  }
270}
271
272// The loop's name: MAIN for the main chat, else its agent type, found in the
273// session's agent list or, for an id no row names, announced by SubagentStart
274// or SubagentStop; undefined when neither names the id.
275async function loopType($: EngineInterface, cache: Cache, agentId: string | undefined): Promise<string | undefined> {
276  if (agentId === undefined) return MAIN;
277  return cache.types.of(agentId, () => $.agent.list());
278}
279
280// A loop with no type is reported once, not at every listing and every call:
281// the engine's own forks (compaction, memory) send a listing of each kind.
282// Enforcement is skipped, so this is an error even for an engine-owned fork.
283function logUnresolved($: EngineInterface, cache: Cache, agentId: string | undefined, action: string): void {
284  if (!cache.types.firstMiss(String(agentId))) return;
285  plog($, cache, 'error', 'name-unresolved', unresolvedLoopText(String(agentId), action), 'logUnresolved', { agentId, action });
286}
287
288function hider(policy: Policy, set: SetName, loop: string): (name: string) => boolean {
289  return (name) => !decide(policy, set, loop, name).allowed;
290}
291
292async function rewritten($: EngineInterface, cache: Cache, type: string, text: string, agentId: string | undefined): Promise<string | null> {
293  try {
294    const policy = await policyOf($, cache);
295    if (isEmpty(policy)) return text;
296    const loop = await loopType($, cache, agentId);
297    if (loop === undefined) {
298      logUnresolved($, cache, agentId, `rewriting ${type}`);
299      return text;
300    }
301    if (type === 'agent_listing_delta') return hasRules(policy, 'agents') ? filterEntries(text, hider(policy, 'agents', loop), 'agents') : text;
302    if (type === 'skill_listing') return hasRules(policy, 'skills') ? filterEntries(text, hider(policy, 'skills', loop), 'skills') : text;
303    if (type === 'deferred_tools_delta') {
304      if (!hasRules(policy, 'mcp') && !hasRules(policy, 'tools')) return text;
305      const mcp = hider(policy, 'mcp', loop);
306      const tools = hider(policy, 'tools', loop);
307      return filterDeferredTools(text, (tool) => (mcpServer(tool) === undefined ? tools(tool) : mcp(tool)));
308    }
309    if (!hasRules(policy, 'mcp')) return text;
310    const names = (await $.tool.list()).map((tool) => tool.name);
311    const mcp = hider(policy, 'mcp', loop);
312    return filterMcpInstructions(text, (heading) => {
313      const server = normalizeServer(heading);
314      const own = names.filter((name) => name.startsWith(`mcp__${server}__`));
315      return own.length > 0 && own.every(mcp);
316    });
317  } catch (error) {
318    plog($, cache, 'error', 'rewrite-failed', `tool-visibility-controller: rewriting the ${type} of loop ${agentId ?? MAIN} failed: ${message(error)}; it is left whole`, 'rewritten', { error: message(error) });
319    return text;
320  }
321}
322
323async function checkCall($: EngineInterface, cache: Cache, targets: ReadonlyArray<[SetName, string]>, agentId: string | undefined): Promise<string | undefined> {
324  const what = targets.map(([, item]) => item).join(' / ');
325  try {
326    const policy = await policyOf($, cache);
327    const relevant = targets.filter(([set]) => hasRules(policy, set));
328    if (relevant.length === 0) return undefined;
329    const loop = await loopType($, cache, agentId);
330    if (loop === undefined) {
331      logUnresolved($, cache, agentId, `checking ${what}`);
332      return undefined;
333    }
334    for (const [set, item] of relevant) {
335      const verdict = decide(policy, set, loop, item);
336      if (!verdict.allowed) return denyText(set, item, loop, verdict);
337    }
338    return undefined;
339  } catch (error) {
340    plog($, cache, 'error', 'check-failed', `tool-visibility-controller: checking ${what} from loop ${agentId ?? MAIN} failed: ${message(error)}; it goes through`, 'checkCall', { error: message(error) });
341    return undefined;
342  }
343}
344
345/** What a tool call invokes: the tool itself, and for the Skill tool the skill or command it names. */
346function callTargets(tool: string, skill: unknown): Array<[SetName, string]> {
347  const targets: Array<[SetName, string]> = [[mcpServer(tool) === undefined ? 'tools' : 'mcp', tool]];
348  if (tool === 'Skill' && typeof skill === 'string' && skill.trim() !== '') targets.push(['skills', skill.trim().replace(/^\//, '')]);
349  return targets;
350}
351
352export const register: Register = (on: On) => {
353  const cache: Cache = { missing: new Set(), types: new AgentTypes(), spawns: new SpawnCalls(), log: { work: Promise.resolve(), failing: false, pending: [] }, logDrain: Promise.resolve(), burst: new ScreenBurst(), burstArmed: false };
354
355  on('session.start', async ($, e, next) => {
356    cache.policy = undefined;
357    cache.missing.clear();
358    cache.logDrain = Promise.all([cache.logDrain, finishLog($, cache, cache.log)]).then(() => {});
359    cache.log = { work: Promise.resolve(), failing: false, pending: [] };
360    return next(e);
361  });
362
363  // Unchanged modules get no session.start on reload. Invalidate after core finishes,
364  // even if it fails: a partial reload may already have changed the definitions.
365  on('command.run', { command: 'reload-plugins' }, async ($, e, next) => {
366    try {
367      return await next(e);
368    } finally {
369      cache.policy = undefined;
370      cache.missing.clear();
371    }
372  });
373
374  on('session.end', async ($, e, next) => {
375    await Promise.all([cache.logDrain, finishLog($, cache, cache.log)]);
376    showLines($, cache.burst.drain());
377    return next(e);
378  });
379
380  // A sub-agent's start and stop name its type (a teammate's, its name, so the list wins); a workflow's agents are never in $.agent.list(), so this is their only source.
381  on('classic.SubagentStart', async ($, e, next) => {
382    cache.types.learn(e.agent_id, e.agent_type);
383    return next(e);
384  }).catch(($, e, next) => {
385    plog($, cache, 'error', 'hook-threw', hookFailureText('classic.SubagentStart', next.error, `agent ${e.agent_id}, type ${e.agent_type}`), 'classic.SubagentStart', { kind: next.error.kind, error: next.error.message });
386    return next(e);
387  });
388
389  on('classic.SubagentStop', async ($, e, next) => {
390    cache.types.learn(e.agent_id, e.agent_type);
391    return next(e);
392  }).catch(($, e, next) => {
393    plog($, cache, 'error', 'hook-threw', hookFailureText('classic.SubagentStop', next.error, `agent ${e.agent_id}, type ${e.agent_type}`), 'classic.SubagentStop', { kind: next.error.kind, error: next.error.message });
394    return next(e);
395  });
396
397  on('prompt.attachment', async ($, e, next) => {
398    const result = await next(e);
399    if (!LISTINGS.has(e.type) || result.text === null) return result;
400    const text = await rewritten($, cache, e.type, result.text, e.agentId);
401    return text === result.text ? result : { ...result, text };
402  }).catch(($, e, next) => {
403    plog($, cache, 'error', 'hook-threw', hookFailureText('prompt.attachment', next.error, `listing ${e.type}, loop ${e.agentId ?? MAIN}`), 'prompt.attachment', { kind: next.error.kind, error: next.error.message });
404    return next(e);
405  });
406
407  // A hook that throws or overruns its budget lets the spawn through.
408  // Only a fresh spawn is gated: a resume runs under the loop resuming it, not its parent (see src/spawns.ts).
409  on('agent.spawn', async ($, e, next) => {
410    if (e.workflow === undefined && !cache.spawns.claim(e.tool_use_id)) return next(e);
411    const deny = await checkCall($, cache, [['agents', e.subagentType]], e.parentAgentId);
412    if (deny !== undefined) plog($, cache, 'info', 'denied', deny, 'agent.spawn');
413    return deny === undefined ? next(e) : { deny };
414  }).catch(($, e, next) => {
415    plog($, cache, 'error', 'hook-threw', hookFailureText('agent.spawn', next.error, `agent ${e.subagentType}, loop ${e.parentAgentId ?? MAIN}`), 'agent.spawn', { kind: next.error.kind, error: next.error.message });
416    return next(e);
417  });
418
419  // A hook that throws or overruns its budget lets the call through.
420  on('tool.call', async ($, e, next) => {
421    if (e.tool === 'Agent') cache.spawns.note(e.tool_use_id);
422    const deny = await checkCall($, cache, callTargets(e.tool, (e as { skill?: unknown }).skill), e.agentId);
423    if (deny !== undefined) plog($, cache, 'info', 'denied', deny, 'tool.call');
424    return deny === undefined ? next(e) : { deny };
425  }).catch(($, e, next) => {
426    plog($, cache, 'error', 'hook-threw', hookFailureText('tool.call', next.error, `tool ${e.tool}, loop ${e.agentId ?? MAIN}`), 'tool.call', { kind: next.error.kind, error: next.error.message });
427    return next(e);
428  });
429};
430
src/plugin-log.ts 198 lines
1/** Standalone JSONL plugin logs; the adapter owns all engine API calls. */
2export const PLUGIN_LOG_CAP_BYTES = 20971520;
3export const ROW_MAX_BYTES = 4096;
4
5export type Level = 'error' | 'warning' | 'info';
6export type LevelFields = {
7  plugin: string;
8  level: Level;
9  event: string;
10  msg: string;
11  where: string;
12  session?: string;
13  detail?: Record<string, unknown>;
14};
15export type ProcessResult = { exitCode: number; stdout: string; stderr: string };
16export type ProcessRun = (argv: readonly string[]) => Promise<ProcessResult>;
17/** `retained` rows stay queued for the next flush; it is absent when none do. */
18export type FlushResult = { written: number; dropped: number; retained?: number };
19/** Rows a failing log may hold for retry; past it the oldest are dropped. */
20export const MAX_RETAINED_ROWS = 1000;
21const FILES: Record<Level, string> = { error: 'errors.jsonl', warning: 'warnings.jsonl', info: 'info.jsonl' };
22const bytes = (text: string) => new TextEncoder().encode(text).length;
23
24export function pluginLogDir(override: string | undefined, home: string | undefined, plugin: string): string | undefined {
25  const root = override || home;
26  if (!root) return undefined;
27  const base = root.replace(/\/+$/, '');
28  return override ? `${base}/${plugin}` : `${base}/.local/state/${plugin}/logs`;
29}
30
31/** Keep JSON key order and count UTF-8 bytes, including the newline. */
32export function levelRow(fields: LevelFields, nowMs: number): string {
33  const row = {
34    ts: new Date(nowMs).toISOString(),
35    plugin: fields.plugin,
36    level: fields.level,
37    event: fields.event,
38    msg: fields.msg,
39    where: fields.where,
40    ...(fields.session ? { session: fields.session } : {}),
41    ...(fields.detail === undefined ? {} : { detail: fields.detail }),
42  };
43  const encode = () => `${JSON.stringify(row)}\n`;
44  const original = encode();
45  if (bytes(original) <= ROW_MAX_BYTES) return original;
46  row.detail = { truncated: true, bytes: bytes(original) };
47  // Paths and identifiers can dominate the row, not just its message.
48  row.plugin = Array.from(row.plugin).slice(0, 64).join('');
49  row.event = Array.from(row.event).slice(0, 64).join('');
50  row.where = Array.from(row.where).slice(0, 256).join('');
51  if (row.session) row.session = Array.from(row.session).slice(0, 64).join('');
52  const msg = Array.from(row.msg);
53  let low = 0;
54  let high = msg.length;
55  while (low < high) {
56    const mid = Math.ceil((low + high) / 2);
57    row.msg = msg.slice(0, mid).join('');
58    if (bytes(encode()) <= ROW_MAX_BYTES) low = mid;
59    else high = mid - 1;
60  }
61  row.msg = msg.slice(0, low).join('');
62  return encode();
63}
64
65/** Literal argv only. Rename-aside cap races are deliberately not locked. */
66export const APPEND_SCRIPT = `set -eu
67umask 077
68dir=$1
69plugin=$2
70shift 2
71mkdir -p "$dir"
72# The session fragment is JSON data bounded by levelRow, never shell source.
73cap_file() (
74  if [ ! -f "$dir/$1" ]; then return; fi
75  size=$(wc -c < "$dir/$1")
76  if [ "$size" -gt ${PLUGIN_LOG_CAP_BYTES} ]; then
77    archived_size=$size
78    if [ "$1" != warnings.jsonl ]; then cap_file warnings.jsonl; fi
79    mv -f "$dir/$1" "$dir/$1.1"
80    stamp=$(date -u +%Y-%m-%dT%H:%M:%S.000Z)
81    printf '{"ts":"%s","plugin":"%s","level":"warning","event":"log-capped","msg":"level file moved aside after reaching the cap","where":"src/plugin-log.ts#APPEND_SCRIPT"%s,"detail":{"file":"%s","bytes":%s}}\\n' "$stamp" "$plugin" "$session_fragment" "$1" "$archived_size" >> "$dir/warnings.jsonl"
82  fi
83)
84while [ "$#" -gt 0 ]; do
85  file=$1
86  row=$2
87  session_fragment=$3
88  shift 3
89  case "$file" in errors.jsonl|warnings.jsonl|info.jsonl) ;; *) printf 'invalid plugin log file: %s/%s\\n' "$dir" "$file" >&2; exit 2 ;; esac
90  cap_file "$file"
91  printf '%s' "$row" >> "$dir/$file"
92done`;
93
94export function appendArgv(dir: string, plugin: string, rows: readonly string[]): string[][] {
95  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(plugin)) throw new Error(`invalid plugin log name: ${plugin}`);
96  const commands: string[][] = [];
97  for (let i = 0; i < rows.length; i += 64) {
98    const argv = ['/bin/sh', '-c', APPEND_SCRIPT, 'plugin-log', dir, plugin];
99    for (const row of rows.slice(i, i + 64)) {
100      const parsed = JSON.parse(row) as LevelFields & { ts: string };
101      const level = parsed.level;
102      if (!Object.hasOwn(FILES, level)) throw new Error(`invalid plugin log level: ${String(level)}`);
103      // Reserve the longest filename and a 19-digit filesystem byte count.
104      // Reuse the row truncation rule for pathological session values.
105      const cap = JSON.parse(levelRow({ plugin, level: 'warning', event: 'log-capped', msg: 'level file moved aside after reaching the cap', where: 'src/plugin-log.ts#APPEND_SCRIPT', session: parsed.session, detail: { file: 'warnings.jsonl', bytes: 2 ** 63 } }, Date.parse(parsed.ts))) as LevelFields;
106      const session = cap.session ? `,"session":${JSON.stringify(cap.session)}` : '';
107      argv.push(FILES[level], row, session);
108    }
109    commands.push(argv);
110  }
111  return commands;
112}
113
114/** Each flush drains a snapshot, drops failed batches, and never rejects. */
115export class PluginLogQueue {
116  private rows: string[] = [];
117  private chain: Promise<unknown> = Promise.resolve();
118  private failing = false;
119
120  constructor(private dir: string | undefined, private plugin: string, private notice: (text: string) => void) {}
121
122  add(row: string): void { this.rows.push(row); }
123
124  private show(text: string): void {
125    try { this.notice(text); } catch {
126      // No other screen door exists, and logging must not alter policy.
127    }
128  }
129
130  private dropped(rows: readonly string[]): FlushResult {
131    for (const row of rows) {
132      try {
133        const parsed = JSON.parse(row) as LevelFields;
134        // Errors already reached the screen synchronously in the adapter.
135        if (parsed.level !== 'error') this.show(parsed.msg);
136      } catch (error) {
137        this.show(`plugin log fallback: ${error instanceof Error ? error.message : String(error)}; row: ${row}`);
138      }
139    }
140    return { written: 0, dropped: rows.length };
141  }
142
143  private failure(error: unknown, dropped: number): void {
144    if (this.failing) return;
145    this.failing = true;
146    const cause = error instanceof Error ? error.message : String(error);
147    const text = this.dir === undefined
148      ? 'plugin log off: no PLUGIN_LOG_DIR and no HOME'
149      : `plugin log ${this.dir}: ${cause}; dropped ${dropped} row(s)`;
150    this.show(text);
151  }
152
153  /** With `retain`, a batch a reachable `process.run` failed on waits in front of the queue for the next flush instead of being dropped. */
154  flush(run: ProcessRun | undefined, options: { retain?: boolean } = {}): Promise<FlushResult> {
155    const rows = this.rows.splice(0);
156    const task = this.chain.then(async () => {
157      const result: FlushResult = { written: 0, dropped: 0 };
158      if (rows.length === 0) return result;
159      if (this.dir === undefined) {
160        this.failure('no directory', rows.length);
161        return this.dropped(rows);
162      }
163      let commands: string[][];
164      try { commands = appendArgv(this.dir, this.plugin, rows); } catch (error) {
165        this.failure(error, rows.length);
166        return this.dropped(rows);
167      }
168      let kept: string[] = [];
169      let start = 0;
170      for (const argv of commands) {
171        const count = (argv.length - 6) / 3;
172        const batch = rows.slice(start, start + count);
173        start += count;
174        try {
175          if (!run) throw new Error('process.run is unavailable');
176          const response = await run(argv);
177          if (response.exitCode !== 0) throw new Error(`exit ${response.exitCode}: ${response.stderr.split('\n')[0] || 'append failed'}`);
178          this.failing = false;
179          result.written += count;
180        } catch (error) {
181          this.failure(error, count);
182          if (options.retain && run) kept = kept.concat(batch);
183          else result.dropped += this.dropped(batch).dropped;
184        }
185      }
186      if (kept.length > 0) {
187        const over = Math.max(0, kept.length + this.rows.length - MAX_RETAINED_ROWS);
188        result.dropped += this.dropped(kept.slice(0, over)).dropped;
189        this.rows = kept.slice(over).concat(this.rows);
190        result.retained = kept.length - over;
191      }
192      return result;
193    });
194    this.chain = task;
195    return task;
196  }
197}
198
src/screen-burst.ts 43 lines
1/** Collapses a burst of identical screen lines into the first plus a count. */
2export const BURST_WINDOW_MS = 30000;
3const MAX_RUNS = 200;
4
5type Run = { shownAt: number; suppressed: number };
6const summary = (text: string, suppressed: number) => `${text} (and ${suppressed} more)`;
7
8export class ScreenBurst {
9  private runs = new Map<string, Run>();
10
11  /** The lines to show now: the text when it opens a burst, preceded by the summary of the burst it follows; nothing for a repeat inside the window. */
12  offer(text: string, nowMs: number): string[] {
13    const run = this.runs.get(text);
14    if (run !== undefined && nowMs - run.shownAt < BURST_WINDOW_MS) {
15      run.suppressed += 1;
16      return [];
17    }
18    const shown = run !== undefined && run.suppressed > 0 ? [summary(text, run.suppressed)] : [];
19    this.runs.delete(text);
20    for (const [key, other] of this.runs) {
21      if (other.suppressed === 0 && (nowMs - other.shownAt >= BURST_WINDOW_MS || this.runs.size >= MAX_RUNS)) this.runs.delete(key);
22    }
23    this.runs.set(text, { shownAt: nowMs, suppressed: 0 });
24    return [...shown, text];
25  }
26
27  /** The summary of every burst with suppressed repeats; the next occurrence of each line is shown afresh. */
28  drain(): string[] {
29    const lines = [...this.runs].filter(([, run]) => run.suppressed > 0).map(([text, run]) => summary(text, run.suppressed));
30    this.runs.clear();
31    return lines;
32  }
33
34  /** Repeats suppressed and not yet summarised. */
35  pending(): number {
36    let total = 0;
37    for (const run of this.runs.values()) total += run.suppressed;
38    return total;
39  }
40
41  size(): number { return this.runs.size; }
42}
43
src/agent-types.ts 40 lines
1// Each loop's agent type by id, pure: who a loop is, and which loops were
2// already reported as nobody.
3
4/**
5 * Each agent loop's type by id. The session's agent list comes first, once
6 * per id it names: a teammate's SubagentStart and SubagentStop carry its name
7 * as `agent_type`, not its type. An id no list row names takes the type the
8 * engine announced (SubagentStart, SubagentStop): a workflow's agents are
9 * never in `$.agent.list()`, so the announcement is their only source. An id
10 * neither names is an engine loop (a fork of its own: compaction, memory)
11 * that no rule governs.
12 */
13export class AgentTypes {
14  private readonly listed = new Map<string, string>();
15  private readonly announced = new Map<string, string>();
16  private readonly missed = new Set<string>();
17
18  learn(id: string, type: string): void {
19    if (id && type) this.announced.set(id, type);
20  }
21
22  async of(id: string, list: () => Promise<readonly { id: string; type: string }[]>): Promise<string | undefined> {
23    const known = this.listed.get(id);
24    if (known) return known;
25    const agent = (await list()).find((info) => info.id === id);
26    if (agent?.type) {
27      this.listed.set(id, agent.type);
28      return agent.type;
29    }
30    return this.announced.get(id) ?? agent?.type;
31  }
32
33  /** True the first time an id is reported as resolving to no type, false on every later report: one log line per loop. */
34  firstMiss(id: string): boolean {
35    if (this.missed.has(id)) return false;
36    this.missed.add(id);
37    return true;
38  }
39}
40
src/failures.ts 23 lines
1// Failure classification and diagnostics, pure. Operational failures keep the
2// documented fail-open result; the screen must say what was not checked and why.
3import type { HookFailure } from 'claude-code';
4
5export function message(error: unknown): string {
6  return typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string'
7    ? error.message : String(error);
8}
9
10/** The worker may preserve an errno code or serialize it into the message. */
11export function missingDefinition(error: unknown): boolean {
12  if (typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string') return error.code === 'ENOENT';
13  return /^ENOENT\b/.test(message(error));
14}
15
16export function unresolvedLoopText(agentId: string, action: string): string {
17  return `tool-visibility-controller: loop ${agentId} resolves to no agent type while ${action}; proceeding unchecked: its listings, spawns and tool calls are left whole; restore its agent-list entry or SubagentStart type announcement to resume visibility checks`;
18}
19
20export function hookFailureText(hook: string, failure: Pick<HookFailure, 'kind' | 'message'>, context: string): string {
21  return `${hook} failed; proceeding unchecked (${context}; ${failure.kind}: ${failure.message ?? 'engine supplied no failure message'})`;
22}
23
src/spawns.ts 28 lines
1/**
2 * Tells a fresh spawn from a resume. A fresh spawn is an Agent tool call's own:
3 * its `tool.call` fires first under the same tool_use_id. A resume (a wake when
4 * an agent's children finish, or a message sent to a finished agent) raises
5 * `agent.spawn` outside any Agent tool call, under the loop doing the resuming,
6 * which is not the agent's parent, so gating it by that loop refuses the
7 * agent's own resume and the engine drops the notices it was woken for.
8 */
9export class SpawnCalls {
10  private readonly open = new Set<string>();
11
12  constructor(private readonly cap = 512) {}
13
14  /** Records an Agent tool call about to spawn. */
15  note(toolUseId: string): void {
16    if (toolUseId === '') return;
17    this.open.add(toolUseId);
18    while (this.open.size > this.cap) this.open.delete(this.open.values().next().value as string);
19  }
20
21  /** True once for the spawn of a noted call; a resume, never noted or already spawned, is false. */
22  claim(toolUseId: string | undefined): boolean {
23    if (toolUseId === undefined || !this.open.has(toolUseId)) return false;
24    this.open.delete(toolUseId);
25    return true;
26  }
27}
28
src/listings.ts 114 lines
1// The listing rewrites, pure: each removes what a loop may not see and keeps
2// every other byte, so the same input always gives the same output and the
3// prompt cache holds. Each answers null when nothing it listed is left.
4
5const TOOLS_SUFFIX = /\(Tools: [^()]*\)\s*$/;
6
7/** The name an entry line lists: `- name: description`, `- plugin:name: description`, or a bare `- name`. */
8function entryName(line: string): string | undefined {
9  return /^- (\S+?)(?::\s|:$|$)/.exec(line)?.[1];
10}
11
12/**
13 * The agent or skill listing without the entries `hidden` names. An entry is
14 * its `- name` line and the description lines that follow it, a bullet that
15 * names no entry included: an agent's up to its `(Tools: ...)` suffix, a
16 * skill's up to a blank line or the next entry.
17 */
18export function filterEntries(text: string, hidden: (name: string) => boolean, kind: 'agents' | 'skills'): string | null {
19  const lines = text.split('\n');
20  const kept: string[] = [];
21  let removed = 0;
22  let remaining = 0;
23  for (let i = 0; i < lines.length; i += 1) {
24    const line = lines[i] ?? '';
25    const name = entryName(line);
26    if (name === undefined) {
27      kept.push(line);
28      continue;
29    }
30    if (!hidden(name)) {
31      remaining += 1;
32      kept.push(line);
33      continue;
34    }
35    removed += 1;
36    const spans = kind === 'skills' || (line.startsWith(`- ${name}:`) && !TOOLS_SUFFIX.test(line));
37    if (!spans) continue;
38    if (kind === 'agents') {
39      // An agent's description ends at its Tools suffix, blank lines and all, when one comes before the next entry.
40      let end = i + 1;
41      while (end < lines.length && entryName(lines[end] ?? '') === undefined && !TOOLS_SUFFIX.test(lines[end] ?? '')) end += 1;
42      if (end < lines.length && entryName(lines[end] ?? '') === undefined) {
43        i = end;
44        continue;
45      }
46    }
47    while (i + 1 < lines.length) {
48      const next = lines[i + 1] ?? '';
49      if (next.trim() === '' || entryName(next) !== undefined) break;
50      i += 1;
51      if (kind === 'agents' && TOOLS_SUFFIX.test(next)) break;
52    }
53  }
54  if (removed === 0) return text;
55  return remaining === 0 ? null : kept.join('\n');
56}
57
58/**
59 * The MCP server instructions without the `## <server>` blocks `hidden` names
60 * (the heading as written, the server's configured name).
61 */
62export function filterMcpInstructions(text: string, hidden: (server: string) => boolean): string | null {
63  const lines = text.split('\n');
64  const kept: string[] = [];
65  let removed = 0;
66  let remaining = 0;
67  let dropping = false;
68  let lastDropped = false;
69  for (const line of lines) {
70    const heading = /^## (.+)$/.exec(line)?.[1];
71    if (heading !== undefined) {
72      dropping = hidden(heading);
73      if (dropping) removed += 1;
74      else remaining += 1;
75    }
76    if (!dropping) kept.push(line);
77    lastDropped = dropping;
78  }
79  if (removed === 0) return text;
80  if (remaining === 0) return null;
81  if (lastDropped) {
82    while (kept.length > 0 && kept.at(-1) === '') kept.pop();
83    if (text.endsWith('\n')) kept.push('');
84  }
85  return kept.join('\n');
86}
87
88const TOOL_NAME = /^[A-Za-z0-9_.:-]+$/;
89
90/**
91 * The deferred-tools notice without the tool names `hidden` names. A list is a
92 * paragraph whose first line ends with `:`; one about MCP servers lists server
93 * names and is kept as it is. A list left with no name is dropped whole.
94 */
95export function filterDeferredTools(text: string, hidden: (tool: string) => boolean): string | null {
96  const paragraphs = text.split('\n\n');
97  const kept: string[] = [];
98  let removed = 0;
99  for (const paragraph of paragraphs) {
100    const [header, ...items] = paragraph.split('\n');
101    const toolList = header !== undefined && header.endsWith(':') && !/MCP servers?\b/.test(header);
102    if (!toolList || items.length === 0) {
103      kept.push(paragraph);
104      continue;
105    }
106    const left = items.filter((item) => !(TOOL_NAME.test(item) && hidden(item)));
107    removed += items.length - left.length;
108    if (left.length === items.length) kept.push(paragraph);
109    else if (left.length > 0) kept.push([header, ...left].join('\n'));
110  }
111  if (removed === 0) return text;
112  return kept.some((paragraph) => paragraph.trim() !== '') ? kept.join('\n\n') : null;
113}
114
src/policy.ts 297 lines
1// Who may see and invoke what, pure: name matching, the rules from definitions
2// and scope files, the verdict with the rule that gave it, and the refusal text.
3
4import { SETS, VISIBLE_TO, type Filter, type SetName, type Visibility } from './visibility.ts';
5
6/** The loop name of the main chat, in rules and as a caller. */
7export const MAIN = 'main';
8
9/** The scope file's name, in the user config directory and in each project `.claude/`. */
10export const SCOPE_FILE = 'tool-visibility-controller.json';
11
12/** One rule: its filter, the block that states it, and the file it is in. */
13export type Rule = { block: string; path: string; filter: Filter };
14
15type ItemRule = { pattern: string; exact: boolean; rule: Rule };
16
17/** Every rule in force: per set, the item rules (who may see an item) and, per loop, its viewer rules (what it sees). */
18export type Policy = { items: Record<SetName, ItemRule[]>; loops: Map<string, Partial<Record<SetName, Rule[]>>> };
19
20/** Allowed, or refused by one rule on the item's side (`visible-to`) or the loop's side (a set block). */
21export type Verdict = { allowed: true } | { allowed: false; side: 'item' | 'viewer'; rule: Rule };
22
23/** A scope file as read: viewer blocks per loop, and a `visible-to` per item pattern. */
24export type ScopeFile = { loops: Record<string, Partial<Record<SetName, Filter>>>; items: Record<SetName, Record<string, Filter>> };
25
26/** Scope files merged key by key, the nearest file's key winning. */
27export type Merged = { loops: Map<string, Map<SetName, Rule>>; items: Map<SetName, Map<string, Rule>> };
28
29/** A definition this plugin reads: an agent, or a skill or command, with its `visibility`. */
30export type Owned = { set: 'agents' | 'skills'; name: string; path: string; visibility: Visibility };
31
32const compiled = new Map<string, RegExp>();
33
34/** Whether `value` matches `pattern`, exactly or with `*` standing for any run of characters. */
35export function globMatch(pattern: string, value: string): boolean {
36  if (!pattern.includes('*')) return pattern === value;
37  let re = compiled.get(pattern);
38  if (re === undefined) {
39    re = new RegExp(`^${pattern.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`);
40    compiled.set(pattern, re);
41  }
42  return re.test(value);
43}
44
45/** The server of an MCP tool name `mcp__<server>__<tool>`; undefined for any other tool. */
46export function mcpServer(name: string): string | undefined {
47  return /^mcp__(.+?)__(.+)$/.exec(name)?.[1];
48}
49
50/** A configured server name as Claude Code writes it into tool names: every other character becomes `_`. */
51export function normalizeServer(name: string): string {
52  return name.replace(/[^A-Za-z0-9_*-]/g, '_');
53}
54
55/**
56 * Whether an item pattern matches an item name of `set`. MCP: `server`,
57 * `server/tool` or a full `mcp__server__tool`, `*` anywhere. Skills: the full
58 * name (`plugin:name`) or the bare name after the plugin. Else the name.
59 */
60export function itemMatches(set: SetName, pattern: string, name: string): boolean {
61  if (set === 'mcp') {
62    if (pattern.startsWith('mcp__')) return globMatch(pattern, name);
63    if (mcpServer(name) === undefined) return false;
64    const slash = pattern.indexOf('/');
65    const server = normalizeServer(slash < 0 ? pattern : pattern.slice(0, slash));
66    // A server name may itself hold `__`: try every split of server and tool.
67    for (let at = name.indexOf('__', 5); at > 5 && at + 2 < name.length; at = name.indexOf('__', at + 1)) {
68      if (globMatch(server, name.slice(5, at)) && (slash < 0 || globMatch(pattern.slice(slash + 1), name.slice(at + 2)))) return true;
69    }
70    return false;
71  }
72  if (globMatch(pattern, name)) return true;
73  return set === 'skills' && name.includes(':') && globMatch(pattern, name.slice(name.lastIndexOf(':') + 1));
74}
75
76function admits(filter: Filter, matches: (pattern: string) => boolean): boolean {
77  return (filter.include === undefined || filter.include.some(matches)) && !(filter.exclude ?? []).some(matches);
78}
79
80/** Whether `loop` may see and invoke `item` of `set`; refused, the rule that refused it. */
81export function decide(policy: Policy, set: SetName, loop: string, item: string): Verdict {
82  for (const { pattern, exact, rule } of policy.items[set]) {
83    const applies = exact ? pattern === item : itemMatches(set, pattern, item);
84    if (applies && !admits(rule.filter, (p) => globMatch(p, loop))) return { allowed: false, side: 'item', rule };
85  }
86  for (const rule of policy.loops.get(loop)?.[set] ?? []) {
87    if (!admits(rule.filter, (p) => itemMatches(set, p, item))) return { allowed: false, side: 'viewer', rule };
88  }
89  return { allowed: true };
90}
91
92/** No rule at all: nothing to filter or refuse. */
93export function isEmpty(policy: Policy): boolean {
94  return SETS.every((set) => policy.items[set].length === 0) && policy.loops.size === 0;
95}
96
97/** Whether any rule speaks about `set`. */
98export function hasRules(policy: Policy, set: SetName): boolean {
99  return policy.items[set].length > 0 || [...policy.loops.values()].some((blocks) => (blocks[set]?.length ?? 0) > 0);
100}
101
102const NOUN: Record<SetName, string> = { agents: 'Agent type', skills: 'Skill', mcp: 'MCP tool', tools: 'Tool' };
103const INSTEAD: Record<SetName, string> = {
104  agents: 'choose another agent type',
105  skills: 'do the task without this skill',
106  mcp: 'use another tool',
107  tools: 'use another tool',
108};
109
110function who(loop: string): string {
111  return loop === MAIN ? 'the main chat' : loop;
112}
113
114function joined(names: readonly string[], word: string): string {
115  return names.length < 2 ? (names[0] ?? '') : `${names.slice(0, -1).join(', ')} ${word} ${names.at(-1)}`;
116}
117
118/** The refusal the model reads: the item, the caller, the rule with its file, and what to do instead. */
119export function denyText(set: SetName, item: string, loop: string, verdict: Verdict): string {
120  if (verdict.allowed) return '';
121  const { rule, side } = verdict;
122  const caller = loop === MAIN ? 'the main chat' : `a ${loop} agent`;
123  const matches = side === 'item' ? (p: string) => globMatch(p, loop) : (p: string) => itemMatches(set, p, item);
124  const include = rule.filter.include;
125  const why =
126    include !== undefined && !include.some(matches)
127      ? include.length === 0
128        ? 'admits nothing'
129        : `admits only ${joined(include, 'and')}`
130      : `excludes ${(rule.filter.exclude ?? []).find(matches) ?? item}`;
131  const delegates = side === 'item' && include !== undefined ? include.filter((p) => !p.includes('*')).map(who) : [];
132  const instead = delegates.length > 0 ? `Delegate the task to ${joined(delegates, 'or')}, or ${INSTEAD[set]}.` : `${INSTEAD[set][0]?.toUpperCase()}${INSTEAD[set].slice(1)}.`;
133  return `${NOUN[set]} ${item} is not available to ${caller}: ${rule.block} in ${rule.path} ${why}. ${instead}`;
134}
135
136function isObject(value: unknown): value is Record<string, unknown> {
137  return typeof value === 'object' && value !== null && !Array.isArray(value);
138}
139
140function readFilter(value: unknown, path: string, problems: string[]): Filter | undefined {
141  if (!isObject(value)) {
142    problems.push(`${path} is not an object of include and exclude`);
143    return undefined;
144  }
145  const filter: { include?: string[]; exclude?: string[] } = {};
146  for (const [key, list] of Object.entries(value)) {
147    if (key !== 'include' && key !== 'exclude') {
148      problems.push(`${path} has an unknown key ${JSON.stringify(key)}; use include or exclude`);
149      return undefined;
150    }
151    if (!Array.isArray(list) || list.some((item) => typeof item !== 'string' || item.trim() === '')) {
152      problems.push(`${path}.${key} is not a list of names`);
153      return undefined;
154    }
155    filter[key] = list.map((item: string) => item.trim());
156  }
157  return filter;
158}
159
160function isSet(key: string): key is SetName {
161  return (SETS as readonly string[]).includes(key);
162}
163
164/**
165 * Reads a scope file's text. Invalid JSON reads as null; a malformed block is
166 * named in `problems` and left out, the other blocks kept.
167 */
168export function readScopeFile(text: string): { scope: ScopeFile | null; problems: string[] } {
169  const problems: string[] = [];
170  let json: unknown;
171  try {
172    json = JSON.parse(text);
173  } catch (error) {
174    return { scope: null, problems: [`it is not valid JSON (${error instanceof Error ? error.message : String(error)})`] };
175  }
176  if (!isObject(json)) return { scope: null, problems: ['its top level is not an object of loops and items'] };
177  const scope: ScopeFile = { loops: {}, items: { agents: {}, skills: {}, mcp: {}, tools: {} } };
178  for (const [key, value] of Object.entries(json)) {
179    if (key === 'loops') {
180      if (!isObject(value)) {
181        problems.push('loops is not an object of loop names');
182        continue;
183      }
184      for (const [loop, blocks] of Object.entries(value)) {
185        if (!isObject(blocks)) {
186          problems.push(`loops.${loop} is not an object of agents, skills, mcp and tools`);
187          continue;
188        }
189        const read: Partial<Record<SetName, Filter>> = {};
190        for (const [set, block] of Object.entries(blocks)) {
191          if (!isSet(set)) {
192            problems.push(`loops.${loop} has an unknown key ${JSON.stringify(set)}; use agents, skills, mcp or tools`);
193            continue;
194          }
195          const filter = readFilter(block, `loops.${loop}.${set}`, problems);
196          if (filter !== undefined) read[set] = filter;
197        }
198        if (Object.keys(read).length > 0) scope.loops[loop] = read;
199      }
200    } else if (key === 'items') {
201      if (!isObject(value)) {
202        problems.push('items is not an object of agents, skills, mcp and tools');
203        continue;
204      }
205      for (const [set, patterns] of Object.entries(value)) {
206        if (!isSet(set)) {
207          problems.push(`items has an unknown key ${JSON.stringify(set)}; use agents, skills, mcp or tools`);
208          continue;
209        }
210        if (!isObject(patterns)) {
211          problems.push(`items.${set} is not an object of item patterns`);
212          continue;
213        }
214        for (const [pattern, entry] of Object.entries(patterns)) {
215          const path = `items.${set}.${pattern}`;
216          if (!isObject(entry)) {
217            problems.push(`${path} is not an object holding visible-to`);
218            continue;
219          }
220          const unknown = Object.keys(entry).find((k) => k !== VISIBLE_TO);
221          if (unknown !== undefined) {
222            problems.push(`${path} has an unknown key ${JSON.stringify(unknown)}; use visible-to`);
223            continue;
224          }
225          if (!(VISIBLE_TO in entry)) continue;
226          const filter = readFilter(entry[VISIBLE_TO], `${path}.${VISIBLE_TO}`, problems);
227          if (filter !== undefined) scope.items[set][pattern] = filter;
228        }
229      }
230    } else {
231      problems.push(`it has an unknown key ${JSON.stringify(key)}; use loops or items`);
232    }
233  }
234  return { scope, problems };
235}
236
237/** Scope files given lowest precedence first (user, then project from the root down): a nearer file's key replaces a farther one's. */
238export function mergeScopes(files: ReadonlyArray<{ path: string; scope: ScopeFile }>): Merged {
239  const merged: Merged = { loops: new Map(), items: new Map() };
240  for (const { path, scope } of files) {
241    for (const [loop, blocks] of Object.entries(scope.loops)) {
242      const target = merged.loops.get(loop) ?? new Map<SetName, Rule>();
243      merged.loops.set(loop, target);
244      for (const set of SETS) {
245        const filter = blocks[set];
246        if (filter !== undefined) target.set(set, { block: `loops.${loop}.${set}`, path, filter });
247      }
248    }
249    for (const set of SETS) {
250      const target = merged.items.get(set) ?? new Map<string, Rule>();
251      merged.items.set(set, target);
252      for (const [pattern, filter] of Object.entries(scope.items[set] ?? {})) {
253        target.set(pattern, { block: `items.${set}.${pattern}.${VISIBLE_TO}`, path, filter });
254      }
255    }
256  }
257  return merged;
258}
259
260/**
261 * Every rule in force: each definition's `visible-to` (exact name) and each
262 * agent's own set blocks, then the merged scope files. All apply together.
263 */
264export function buildPolicy(owned: ReadonlyArray<Owned>, merged: Merged): Policy {
265  const policy: Policy = { items: { agents: [], skills: [], mcp: [], tools: [] }, loops: new Map() };
266  const viewer = (loop: string, set: SetName, rule: Rule) => {
267    const blocks = policy.loops.get(loop) ?? {};
268    (blocks[set] ??= []).push(rule);
269    policy.loops.set(loop, blocks);
270  };
271  for (const { set, name, path, visibility } of owned) {
272    if (visibility.visibleTo !== undefined) {
273      policy.items[set].push({ pattern: name, exact: true, rule: { block: `visibility.${VISIBLE_TO}`, path, filter: visibility.visibleTo } });
274    }
275    if (set !== 'agents') continue;
276    for (const viewed of SETS) {
277      const filter = visibility.sets[viewed];
278      if (filter !== undefined) viewer(name, viewed, { block: `visibility.${viewed}`, path, filter });
279    }
280  }
281  for (const [set, patterns] of merged.items) for (const [pattern, rule] of patterns) policy.items[set].push({ pattern, exact: false, rule });
282  for (const [loop, blocks] of merged.loops) for (const [set, rule] of blocks) viewer(loop, set, rule);
283  return policy;
284}
285
286/**
287 * The project directories of a session at `root`, farthest first: `root` and
288 * each directory above it, stopping below `home` (the user tier, never a
289 * project) as Claude Code does, else at the filesystem root.
290 */
291export function ancestorDirs(root: string, home?: string): string[] {
292  const parts = root.split('/').filter((part) => part !== '');
293  const dirs = ['/', ...parts.map((_, i) => `/${parts.slice(0, i + 1).join('/')}`)];
294  const stop = home === undefined ? -1 : dirs.indexOf(`/${home.split('/').filter((part) => part !== '').join('/')}`);
295  return stop < 0 ? dirs : dirs.slice(stop + 1);
296}
297
src/visibility.ts 318 lines
1// Reading the `visibility` field of an agent, skill or command definition's
2// YAML frontmatter, pure. A YAML subset suffices: block and flow mappings,
3// block and flow lists, plain and quoted scalars, comments.
4
5/** A filter over names: `include` keeps only matches, `exclude` drops matches; both, include minus exclude. */
6export type Filter = { include?: readonly string[]; exclude?: readonly string[] };
7
8/** The four sets a loop sees and invokes. */
9export const SETS = ['agents', 'skills', 'mcp', 'tools'] as const;
10export type SetName = (typeof SETS)[number];
11
12/** The `visibility` field: who may see the item (`visible-to`), and what the agent's own loop sees, per set. */
13export type Visibility = { visibleTo?: Filter; sets: Partial<Record<SetName, Filter>> };
14
15/** One definition: its name, its field (null when absent or unreadable), and every problem found in it. */
16export type Definition = { name: string; visibility: Visibility | null; problems: string[] };
17
18/** The frontmatter key and its block names. */
19export const FIELD = 'visibility';
20export const VISIBLE_TO = 'visible-to';
21
22type Value = string | Value[] | ValueMap | null | Broken;
23type ValueMap = Map<string, Value>;
24
25/** A value that could not be read, kept in place of a block so its siblings stand. */
26class Broken {
27  constructor(
28    readonly path: string[],
29    readonly message: string,
30  ) {}
31}
32
33class Malformed extends Error {
34  readonly path: string[] = [];
35}
36
37function stripComment(line: string): string {
38  let quote = '';
39  for (let i = 0; i < line.length; i += 1) {
40    const c = line[i];
41    if (quote !== '') {
42      if (c === quote) quote = '';
43    } else if (c === '"' || c === "'") {
44      quote = c;
45    } else if (c === '#' && (i === 0 || /\s/.test(line[i - 1] ?? ''))) {
46      return line.slice(0, i).trimEnd();
47    }
48  }
49  return line.trimEnd();
50}
51
52function indentOf(line: string): number {
53  return line.length - line.trimStart().length;
54}
55
56function unquote(raw: string): string {
57  const item = raw.trim();
58  if (item.length >= 2 && (item[0] === '"' || item[0] === "'") && item.at(-1) === item[0]) return item.slice(1, -1);
59  return item;
60}
61
62// A flow value (`[a, b]`, `{ k: v }`, or a scalar) read from `text` at `at`.
63function readFlow(text: string, at: { i: number }): Value {
64  const skip = () => {
65    while (at.i < text.length && /\s/.test(text[at.i] ?? '')) at.i += 1;
66  };
67  skip();
68  const c = text[at.i];
69  if (c === '[') {
70    at.i += 1;
71    const items: Value[] = [];
72    skip();
73    if (text[at.i] === ']') {
74      at.i += 1;
75      return items;
76    }
77    for (;;) {
78      skip();
79      if (text[at.i] === ',' || text[at.i] === ']') throw new Malformed('a list has an empty item');
80      items.push(readFlow(text, at));
81      skip();
82      if (text[at.i] === ',') {
83        at.i += 1;
84        skip();
85        if (text[at.i] !== ']') continue;
86      }
87      if (text[at.i] === ']') {
88        at.i += 1;
89        return items;
90      }
91      throw new Malformed('a list is not closed with ]');
92    }
93  }
94  if (c === '{') {
95    at.i += 1;
96    const map: ValueMap = new Map();
97    skip();
98    if (text[at.i] === '}') {
99      at.i += 1;
100      return map;
101    }
102    for (;;) {
103      skip();
104      const colon = text.indexOf(':', at.i);
105      if (colon < 0) throw new Malformed('a mapping entry has no ":"');
106      const key = unquote(text.slice(at.i, colon));
107      if (key === '' || /[[\]{},]/.test(key)) throw new Malformed(`${JSON.stringify(key)} is not a key`);
108      if (map.has(key)) throw new Malformed(`${JSON.stringify(key)} is given twice`);
109      at.i = colon + 1;
110      map.set(key, readFlow(text, at));
111      skip();
112      if (text[at.i] === ',') {
113        at.i += 1;
114        skip();
115        if (text[at.i] !== '}') continue;
116      }
117      if (text[at.i] === '}') {
118        at.i += 1;
119        return map;
120      }
121      throw new Malformed('a mapping is not closed with }');
122    }
123  }
124  if (c === '"' || c === "'") {
125    const end = text.indexOf(c, at.i + 1);
126    if (end < 0) throw new Malformed('a quoted name is not closed');
127    const value = text.slice(at.i + 1, end);
128    at.i = end + 1;
129    return value;
130  }
131  const start = at.i;
132  while (at.i < text.length && !/[,\]}]/.test(text[at.i] ?? '')) at.i += 1;
133  return text.slice(start, at.i).trim();
134}
135
136function parseInline(value: string): Value {
137  const at = { i: 0 };
138  const parsed = readFlow(value, at);
139  if (value.slice(at.i).trim() !== '') {
140    throw new Malformed(value.trimStart().startsWith('[') ? 'a list is not closed with ]' : `${JSON.stringify(value.trim())} has text after its value`);
141  }
142  return parsed;
143}
144
145// A block (mapping or list) from `lines`, every one indented at least as the first.
146// With `isolate`, a key whose value cannot be read holds a Broken in its place.
147function parseBlock(lines: readonly string[], isolate = false): Value {
148  const rows = lines.filter((line) => line.trim() !== '');
149  const first = rows[0];
150  if (first === undefined) return null;
151  const base = indentOf(first);
152  if (first.trimStart().startsWith('- ') || first.trim() === '-') {
153    const items: Value[] = [];
154    for (const row of rows) {
155      if (indentOf(row) !== base) throw new Malformed('a list item is nested');
156      const item = /^\s*-\s*(.*)$/.exec(row)?.[1];
157      if (item === undefined) throw new Malformed('a list mixes items and keys');
158      if (item === '') throw new Malformed('a list has an empty item');
159      items.push(parseInline(item));
160    }
161    return items;
162  }
163  const map: ValueMap = new Map();
164  for (let i = 0; i < rows.length; i += 1) {
165    const row = rows[i] ?? '';
166    if (indentOf(row) !== base) throw new Malformed('a line is indented deeper than its key');
167    const entry = /^\s*("[^"]*"|'[^']*'|[^:\s][^:]*?)\s*:(?:\s+(.*))?$/.exec(row);
168    if (entry === null) throw new Malformed(`${JSON.stringify(row.trim())} is not a key: value line`);
169    const key = unquote(entry[1] ?? '');
170    const inline = entry[2]?.trim() ?? '';
171    const twice = map.has(key);
172    // A flow collection may wrap onto deeper lines: on the key's line, or below it.
173    const wraps = /^[[{]/.test(inline);
174    const child: string[] = [];
175    while ((inline === '' || wraps) && i + 1 < rows.length) {
176      const next = rows[i + 1] ?? '';
177      const deeper = indentOf(next) > base;
178      const sameIndentList = inline === '' && indentOf(next) === base && /^\s*-(\s|$)/.test(next);
179      if (!deeper && !sameIndentList) break;
180      child.push(next);
181      i += 1;
182    }
183    const flow = wraps || /^[[{]/.test(child[0]?.trim() ?? '');
184    try {
185      if (twice) throw new Malformed('it is given twice');
186      map.set(
187        key,
188        flow
189          ? parseInline([inline, ...child.map((line) => line.trim())].join(' '))
190          : inline !== ''
191            ? parseInline(inline)
192            : child.length === 0
193              ? null
194              : parseBlock(child),
195      );
196    } catch (error) {
197      if (!(error instanceof Malformed)) throw error;
198      error.path.unshift(key);
199      if (!isolate) throw error;
200      map.set(key, new Broken(error.path, error.message));
201    }
202  }
203  return map;
204}
205
206function isMap(value: Value): value is ValueMap {
207  return value instanceof Map;
208}
209
210/** A name in a list: non-empty, on one line, without flow punctuation. */
211function isName(value: Value): value is string {
212  return typeof value === 'string' && value.trim() !== '' && !/[[\]{},\n]/.test(value);
213}
214
215// A filter block at `path`, or the reason it is unusable.
216function readFilter(value: Value, path: string, problems: string[]): Filter | undefined {
217  if (value instanceof Broken) {
218    problems.push(`${FIELD}.${value.path.join('.')}: ${value.message}`);
219    return undefined;
220  }
221  if (value === null) {
222    problems.push(`${path} has no value`);
223    return undefined;
224  }
225  if (!isMap(value)) {
226    problems.push(`${path} is not a mapping of include and exclude`);
227    return undefined;
228  }
229  const filter: { include?: string[]; exclude?: string[] } = {};
230  for (const [key, list] of value) {
231    if (key !== 'include' && key !== 'exclude') {
232      problems.push(`${path} has an unknown key ${JSON.stringify(key)}; use include or exclude`);
233      return undefined;
234    }
235    if (!Array.isArray(list)) {
236      problems.push(`${path}.${key} is not a list; write [name, ...]`);
237      return undefined;
238    }
239    const bad = list.find((item) => !isName(item));
240    if (bad !== undefined) {
241      problems.push(`${path}.${key} holds ${JSON.stringify(bad)}, which is not a name`);
242      return undefined;
243    }
244    filter[key] = list.map((item) => (item as string).trim());
245  }
246  return filter;
247}
248
249/** Reads the `visibility` field's value, its problems reported by block path, each bad block left out. */
250export function readVisibility(value: Value | undefined, problems: string[]): Visibility | null {
251  if (value === undefined) return null;
252  if (value === null) {
253    problems.push(`${FIELD} has no value`);
254    return null;
255  }
256  if (value instanceof Broken) {
257    problems.push(`${FIELD}.${value.path.join('.')}: ${value.message}`);
258    return null;
259  }
260  if (!isMap(value)) {
261    problems.push(`${FIELD} is not a mapping of visible-to, agents, skills, mcp and tools`);
262    return null;
263  }
264  const visibility: Visibility = { sets: {} };
265  for (const [key, block] of value) {
266    const path = `${FIELD}.${key}`;
267    if (key === VISIBLE_TO) {
268      const filter = readFilter(block, path, problems);
269      if (filter !== undefined) visibility.visibleTo = filter;
270    } else if ((SETS as readonly string[]).includes(key)) {
271      const filter = readFilter(block, path, problems);
272      if (filter !== undefined) visibility.sets[key as SetName] = filter;
273    } else {
274      problems.push(`${FIELD} has an unknown key ${JSON.stringify(key)}; use visible-to, agents, skills, mcp or tools`);
275    }
276  }
277  return visibility;
278}
279
280/**
281 * Reads one definition's name (frontmatter `name`, else `fallback`) and its
282 * `visibility` field from the YAML frontmatter. A malformed block is named in
283 * `problems` and left out; the other blocks stand.
284 */
285export function readDefinition(text: string, fallback: string): Definition {
286  const lines = text.replace(/^/, '').split(/\r?\n/);
287  if (lines[0]?.trim() !== '---') return { name: fallback, visibility: null, problems: [] };
288  const end = lines.findIndex((line, i) => i > 0 && line.trim() === '---');
289  const front = lines.slice(1, end < 0 ? lines.length : end).map(stripComment);
290  const nameLine = front.find((line) => /^name:/.test(line));
291  const name = nameLine === undefined ? '' : unquote(nameLine.slice('name:'.length));
292  const at = front.findIndex((line) => line.startsWith(`${FIELD}:`));
293  const problems: string[] = [];
294  if (at < 0) return { name: name === '' ? fallback : name, visibility: null, problems };
295  const inline = (front[at] ?? '').slice(FIELD.length + 1).trim();
296  const block: string[] = [];
297  for (const line of front.slice(at + 1)) {
298    if (line.trim() !== '' && indentOf(line) === 0) break;
299    block.push(line);
300  }
301  const rows = block.filter((line) => line.trim() !== '');
302  let value: Value;
303  try {
304    value = /^[[{]/.test(inline || (rows[0]?.trim() ?? ''))
305      ? parseInline([inline, ...rows.map((line) => line.trim())].join(' '))
306      : inline !== ''
307        ? parseInline(inline)
308        : rows.length > 0
309          ? parseBlock(block, true)
310          : null;
311  } catch (error) {
312    if (!(error instanceof Malformed)) throw error;
313    problems.push([FIELD, ...error.path].join('.') + `: ${error.message}`);
314    return { name: name === '' ? fallback : name, visibility: null, problems };
315  }
316  return { name: name === '' ? fallback : name, visibility: readVisibility(value, problems), problems };
317}
318