engine.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /**
  2. * Permission Engine — checker registry/dispatcher plus the legacy rollback reducer.
  3. *
  4. * With `policyOwner: 'core'`, the engine invokes the registered checker and
  5. * delegates the final verdict to Permission Core. The explicit `engine`
  6. * rollback path retains the three-step flow from permission_design.md §4.1:
  7. *
  8. * Step 1: Reject check (hard block, unaffected by bypass mode)
  9. * Step 2: Allow check (fast path)
  10. * Step 3: Fallback (passthrough → ask)
  11. *
  12. * Both paths delegate tool-specific permission logic to registered
  13. * {@link ToolPermissionChecker} implementations (e.g. bash, file-system).
  14. *
  15. * Reference: permission_design.md §4
  16. */
  17. import { logger, backgroundCtx } from './host-utils.js';
  18. import { matchesMcpServerRuntimeName } from './mcp-runtime-name.js';
  19. import type {
  20. PermissionBehavior,
  21. PermissionDecision,
  22. PermissionRule,
  23. ToolCheckResult,
  24. } from './types.js';
  25. import type { ToolPermissionContext } from './context.js';
  26. import {
  27. getContentRulesForTool,
  28. hasWholeToolRule,
  29. isBypassMode,
  30. isInteractiveTool,
  31. } from './context.js';
  32. import { decideUnknownToolPathCapabilities } from './tools/path-capability.js';
  33. import { reducePermissionDecision, type PermissionCheckOptions } from './permission-core.js';
  34. export type { ToolCheckResult } from './types.js';
  35. // ---------------------------------------------------------------------------
  36. // Tool permission checker interface
  37. // ---------------------------------------------------------------------------
  38. /**
  39. * Interface that tool-specific permission checkers must implement.
  40. *
  41. * Registered via {@link PermissionEngine.registerToolPermissionChecker}.
  42. */
  43. export interface ToolPermissionChecker {
  44. /**
  45. * Check whether the tool invocation is permitted.
  46. *
  47. * @param toolName - The registered name of the tool (e.g. "bash", "edit")
  48. * @param input - The parsed input arguments for the tool invocation
  49. * @param context - The current permission context
  50. * @returns - The check result, or `undefined` to indicate passthrough
  51. */
  52. checkPermissions(
  53. toolName: string,
  54. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tool input shapes vary per tool
  55. input: Record<string, any>,
  56. context: ToolPermissionContext,
  57. ): ToolCheckResult | undefined;
  58. }
  59. // ---------------------------------------------------------------------------
  60. // Rule matching helpers (content-specific rules)
  61. // ---------------------------------------------------------------------------
  62. /**
  63. * Parse a rule string `toolName(ruleContent)` into its components.
  64. * Used only for MCP server-level matching.
  65. */
  66. function matchesMcpServerRule(toolName: string, rule: PermissionRule): boolean {
  67. const ruleToolName = rule.ruleValue.toolName;
  68. return !rule.ruleValue.ruleContent && matchesMcpServerRuntimeName(toolName, ruleToolName);
  69. }
  70. /**
  71. * Check if any content-specific ask rule matches the given input.
  72. *
  73. * Content-specific ask rules are bypass-immune (§4.2 point 3).
  74. */
  75. function matchesContentAskRule(
  76. toolName: string,
  77. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- input shape varies per tool
  78. input: Record<string, any>,
  79. ctx: ToolPermissionContext,
  80. ): PermissionRule | undefined {
  81. const contentAskRules = getContentRulesForTool(ctx, toolName, 'ask');
  82. for (const rule of contentAskRules) {
  83. // Content rules have ruleContent defined (guaranteed by getContentRulesForTool)
  84. // The engine performs a simple substring/equality check here.
  85. // Tool-specific matching (wildcard, prefix) is handled by tool checkers.
  86. const { ruleContent } = rule.ruleValue;
  87. if (!ruleContent) continue;
  88. // Extract the relevant input field for matching
  89. const inputContent = extractToolInputContent(toolName, input);
  90. if (inputContent && inputContent.includes(ruleContent)) {
  91. return rule;
  92. }
  93. }
  94. return undefined;
  95. }
  96. /**
  97. * Extract the primary content string from a tool input for rule matching.
  98. */
  99. function extractToolInputContent(
  100. toolName: string,
  101. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tool input shapes vary
  102. input: Record<string, any>,
  103. ): string | undefined {
  104. switch (toolName) {
  105. case 'bash':
  106. return typeof input.command === 'string' ? input.command : undefined;
  107. case 'edit':
  108. case 'write':
  109. case 'read':
  110. case 'glob':
  111. return typeof input.filePath === 'string'
  112. ? input.filePath
  113. : typeof input.path === 'string'
  114. ? input.path
  115. : typeof input.pattern === 'string'
  116. ? input.pattern
  117. : undefined;
  118. default:
  119. // For other tools, try common field names
  120. return typeof input.command === 'string'
  121. ? input.command
  122. : typeof input.url === 'string'
  123. ? input.url
  124. : undefined;
  125. }
  126. }
  127. // ---------------------------------------------------------------------------
  128. // PermissionEngine
  129. // ---------------------------------------------------------------------------
  130. /**
  131. * Tool-checker registry with selectable Core and legacy Engine policy paths.
  132. *
  133. * Usage:
  134. * ```ts
  135. * const engine = new PermissionEngine()
  136. * engine.registerToolPermissionChecker('bash', bashChecker)
  137. * engine.registerToolPermissionChecker('edit', fsChecker)
  138. *
  139. * const decision = engine.checkPermission('bash', { command: 'git status' }, ctx)
  140. * // => { behavior: 'allow', reason: { type: 'rule', rule: ... } }
  141. * ```
  142. */
  143. export class PermissionEngine {
  144. private readonly checkers = new Map<string, ToolPermissionChecker>();
  145. /**
  146. * Register a tool-specific permission checker.
  147. *
  148. * @param toolName - Tool name (e.g. "bash", "edit", "write")
  149. * @param checker - The checker implementation
  150. */
  151. registerToolPermissionChecker(toolName: string, checker: ToolPermissionChecker): void {
  152. const ctx = backgroundCtx();
  153. this.checkers.set(toolName, checker);
  154. logger.debug(ctx, `Registered tool permission checker: toolName=${toolName}`);
  155. }
  156. /**
  157. * Unregister a tool-specific permission checker.
  158. */
  159. unregisterToolPermissionChecker(toolName: string): void {
  160. const ctx = backgroundCtx();
  161. this.checkers.delete(toolName);
  162. logger.debug(ctx, `Unregistered tool permission checker: toolName=${toolName}`);
  163. }
  164. /**
  165. * Check permission for a tool invocation.
  166. *
  167. * The `engine` rollback path implements the three-step decision flow from §4.1.
  168. * The `core` path dispatches the checker once and calls the Core reducer.
  169. *
  170. * **Step 1 — Reject check** (hard block, bypass-immune):
  171. * 1a. Whole tool in deny rules → DENY
  172. * 1b. Whole tool in ask rules → ASK (sandbox exception)
  173. * 1c. Call tool.checkPermissions (tool-specific check)
  174. * 1d. Tool returns deny → DENY
  175. * 1e. requiresUserInteraction → ASK
  176. * 1f. Content-specific ask rule → ASK (bypass-immune)
  177. * 1g. Safety check → ASK (unless bypass mode applies)
  178. *
  179. * **Step 2 — Allow check** (fast path):
  180. * 2a. bypassPermissions mode → ALLOW
  181. * 2b. Whole tool in allow rules → ALLOW
  182. *
  183. * **Step 3 — Fallback**:
  184. * passthrough → ask
  185. */
  186. checkPermission(
  187. toolName: string,
  188. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tool input shapes vary per tool
  189. input: Record<string, any>,
  190. context: ToolPermissionContext,
  191. options: PermissionCheckOptions = {},
  192. ): PermissionDecision {
  193. const policyOwner = options.policyOwner ?? 'engine';
  194. if (policyOwner !== 'engine' && policyOwner !== 'core') {
  195. throw new Error(`Unknown permission policy owner: ${String(policyOwner)}`);
  196. }
  197. if (policyOwner === 'core')
  198. return this.checkPermissionWithCore(toolName, input, context, options);
  199. return this.checkPermissionWithEngine(toolName, input, context, options);
  200. }
  201. private checkPermissionWithCore(
  202. toolName: string,
  203. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tool input shapes vary per tool
  204. input: Record<string, any>,
  205. context: ToolPermissionContext,
  206. options: PermissionCheckOptions,
  207. ): PermissionDecision {
  208. const ctx = backgroundCtx();
  209. const checker = this.checkers.get(toolName);
  210. let checkerResult: ToolCheckResult | undefined;
  211. let checkerError: string | undefined;
  212. try {
  213. checkerResult = checker
  214. ? checker.checkPermissions(toolName, input, context)
  215. : decideUnknownToolPathCapabilities(toolName, input, context);
  216. } catch (err) {
  217. checkerError = (err as Error).message;
  218. logger.error(
  219. ctx,
  220. `Tool permission checker threw an error: toolName=${toolName} error=${checkerError}`,
  221. );
  222. }
  223. this.notifyCheckerDecision(options, Boolean(checker), checkerResult, Boolean(checkerError));
  224. return reducePermissionDecision({
  225. toolName,
  226. input,
  227. context,
  228. checkerRegistered: Boolean(checker),
  229. ...(checkerResult ? { checkerResult } : {}),
  230. ...(checkerError ? { checkerError } : {}),
  231. });
  232. }
  233. private checkPermissionWithEngine(
  234. toolName: string,
  235. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tool input shapes vary per tool
  236. input: Record<string, any>,
  237. context: ToolPermissionContext,
  238. options: PermissionCheckOptions,
  239. ): PermissionDecision {
  240. const ctx = backgroundCtx();
  241. logger.debug(ctx, `Checking permission: toolName=${toolName} mode=${context.mode}`);
  242. // -----------------------------------------------------------------------
  243. // Step 1: Reject check (hard block, bypass-immune)
  244. // -----------------------------------------------------------------------
  245. // 1a. Whole tool in deny rules?
  246. const denyRule = hasWholeToolRule(context, toolName, 'deny');
  247. if (denyRule) {
  248. logger.debug(ctx, `Step 1a: Tool denied by whole-tool deny rule: toolName=${toolName}`);
  249. return { behavior: 'deny', reason: { type: 'rule', rule: denyRule } };
  250. }
  251. // Also check MCP server-level deny rules
  252. const mcpDenyRule = this.findMcpServerRule(toolName, context, 'deny');
  253. if (mcpDenyRule) {
  254. logger.debug(ctx, `Step 1a: Tool denied by MCP server deny rule: toolName=${toolName}`);
  255. return { behavior: 'deny', reason: { type: 'rule', rule: mcpDenyRule } };
  256. }
  257. // Resolve the local checker before broad ask rules. A command/content
  258. // deny is narrower than a whole-tool or MCP ask and therefore must win.
  259. // Checker failures remain ASK; an existing explicit ask rule still owns
  260. // the user-facing reason in that case, matching the previous behavior.
  261. const checker = this.checkers.get(toolName);
  262. let toolCheckResult: ToolCheckResult | undefined;
  263. let checkerError: string | undefined;
  264. try {
  265. toolCheckResult = checker
  266. ? checker.checkPermissions(toolName, input, context)
  267. : decideUnknownToolPathCapabilities(toolName, input, context);
  268. } catch (err) {
  269. checkerError = (err as Error).message;
  270. logger.error(
  271. ctx,
  272. `Tool permission checker threw an error: toolName=${toolName} error=${checkerError}`,
  273. );
  274. }
  275. this.notifyCheckerDecision(options, Boolean(checker), toolCheckResult, Boolean(checkerError));
  276. if (toolCheckResult?.behavior === 'deny') {
  277. logger.debug(ctx, `Step 1d: Tool checker returned deny: toolName=${toolName}`);
  278. return { behavior: 'deny', reason: toolCheckResult.reason };
  279. }
  280. // 1b. Whole tool in ask rules? → ASK (sandbox exception)
  281. const askRule = hasWholeToolRule(context, toolName, 'ask');
  282. if (askRule) {
  283. // Sandbox exception: bash tool + sandbox enabled + autoAllowBashIfSandboxed
  284. if (toolName === 'bash' && context.sandboxEnabled && context.autoAllowBashIfSandboxed) {
  285. logger.debug(ctx, `Step 1b: Bash ask rule bypassed by sandbox: toolName=${toolName}`);
  286. // Don't return ASK — let it fall through to further checks
  287. } else {
  288. logger.debug(
  289. ctx,
  290. `Step 1b: Tool requires ask by whole-tool ask rule: toolName=${toolName}`,
  291. );
  292. return {
  293. behavior: 'ask',
  294. reason: { type: 'rule', rule: askRule },
  295. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  296. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  297. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  298. rewrittenInput: toolCheckResult?.rewrittenInput,
  299. };
  300. }
  301. }
  302. // Also check MCP server-level ask rules
  303. const mcpAskRule = this.findMcpServerRule(toolName, context, 'ask');
  304. if (mcpAskRule) {
  305. logger.debug(ctx, `Step 1b: Tool requires ask by MCP server ask rule: toolName=${toolName}`);
  306. return {
  307. behavior: 'ask',
  308. reason: { type: 'rule', rule: mcpAskRule },
  309. ruleContents: this.resolveRuleContents(toolName, input),
  310. candidateScopes: this.resolveCandidateScopes(undefined),
  311. };
  312. }
  313. if (checkerError) {
  314. return {
  315. behavior: 'ask',
  316. reason: {
  317. type: 'safetyCheck',
  318. description: `Tool checker error: ${checkerError}`,
  319. },
  320. ruleContents: this.resolveRuleContents(toolName, input),
  321. };
  322. }
  323. // 1e. requiresUserInteraction? → ASK
  324. if (isInteractiveTool(context, toolName)) {
  325. logger.debug(ctx, `Step 1e: Tool requires user interaction: toolName=${toolName}`);
  326. return {
  327. behavior: 'ask',
  328. reason: {
  329. type: 'safetyCheck',
  330. description: `Tool "${toolName}" requires user interaction`,
  331. },
  332. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  333. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  334. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  335. };
  336. }
  337. // 1f. Content-specific ask rule? → ASK (bypass-immune)
  338. if (toolCheckResult && toolCheckResult.behavior === 'ask' && toolCheckResult.bypassImmune) {
  339. logger.debug(ctx, `Step 1f: Tool checker returned bypass-immune ask: toolName=${toolName}`);
  340. return {
  341. behavior: 'ask',
  342. reason: toolCheckResult.reason,
  343. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  344. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  345. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  346. bypassImmune: true,
  347. skipAutoClassifier: toolCheckResult.skipAutoClassifier,
  348. };
  349. }
  350. const contentAskMatch = matchesContentAskRule(toolName, input, context);
  351. if (contentAskMatch) {
  352. logger.debug(
  353. ctx,
  354. `Step 1f: Content-specific ask rule matched: toolName=${toolName} ruleContent=${contentAskMatch.ruleValue.ruleContent}`,
  355. );
  356. return {
  357. behavior: 'ask',
  358. reason: { type: 'rule', rule: contentAskMatch },
  359. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  360. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  361. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  362. rewrittenInput: toolCheckResult?.rewrittenInput,
  363. };
  364. }
  365. // 1g. Safety check? → ASK in normal modes.
  366. // Bypass mode may override approvable safety checks unless the checker
  367. // explicitly marked them as bypass-immune above.
  368. if (
  369. toolCheckResult &&
  370. toolCheckResult.behavior === 'ask' &&
  371. toolCheckResult.reason.type === 'safetyCheck' &&
  372. !isBypassMode(context)
  373. ) {
  374. logger.debug(ctx, `Step 1g: Safety check triggered: toolName=${toolName}`);
  375. return {
  376. behavior: 'ask',
  377. reason: toolCheckResult.reason,
  378. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  379. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  380. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  381. rewrittenInput: toolCheckResult?.rewrittenInput,
  382. skipAutoClassifier: toolCheckResult.skipAutoClassifier,
  383. };
  384. }
  385. // 1h. Tool checker requested ASK for a non-safety reason. Preserve the
  386. // tool-specific reason and flags in normal modes; bypassPermissions may
  387. // still override these non-immune asks below.
  388. if (toolCheckResult && toolCheckResult.behavior === 'ask' && !isBypassMode(context)) {
  389. logger.debug(ctx, `Step 1h: Tool checker returned ask: toolName=${toolName}`);
  390. return {
  391. behavior: 'ask',
  392. reason: toolCheckResult.reason,
  393. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  394. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  395. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  396. rewrittenInput: toolCheckResult?.rewrittenInput,
  397. skipAutoClassifier: toolCheckResult.skipAutoClassifier,
  398. };
  399. }
  400. // -----------------------------------------------------------------------
  401. // Step 2: Allow check (fast path)
  402. // -----------------------------------------------------------------------
  403. // 2a. bypassPermissions mode? → ALLOW
  404. if (isBypassMode(context)) {
  405. logger.debug(ctx, `Step 2a: Bypass mode active, allowing: toolName=${toolName}`);
  406. return {
  407. behavior: 'allow',
  408. reason: { type: 'mode', mode: 'bypassPermissions' },
  409. rewrittenInput: toolCheckResult?.rewrittenInput,
  410. };
  411. }
  412. // 2b. Whole tool in allow rules? → ALLOW
  413. const allowRule = hasWholeToolRule(context, toolName, 'allow');
  414. if (allowRule) {
  415. logger.debug(ctx, `Step 2b: Tool allowed by whole-tool allow rule: toolName=${toolName}`);
  416. return {
  417. behavior: 'allow',
  418. reason: { type: 'rule', rule: allowRule },
  419. rewrittenInput: toolCheckResult?.rewrittenInput,
  420. };
  421. }
  422. // Also check MCP server-level allow rules
  423. const mcpAllowRule = this.findMcpServerRule(toolName, context, 'allow');
  424. if (mcpAllowRule) {
  425. logger.debug(ctx, `Step 2b: Tool allowed by MCP server allow rule: toolName=${toolName}`);
  426. return {
  427. behavior: 'allow',
  428. reason: { type: 'rule', rule: mcpAllowRule },
  429. rewrittenInput: toolCheckResult?.rewrittenInput,
  430. };
  431. }
  432. // If the tool checker returned allow, use it
  433. if (toolCheckResult && toolCheckResult.behavior === 'allow') {
  434. logger.debug(ctx, `Step 2: Tool checker returned allow: toolName=${toolName}`);
  435. return {
  436. behavior: 'allow',
  437. reason: toolCheckResult.reason,
  438. rewrittenInput: toolCheckResult.rewrittenInput,
  439. };
  440. }
  441. // -----------------------------------------------------------------------
  442. // Step 3: Fallback
  443. // -----------------------------------------------------------------------
  444. // If no checker is registered for this tool and no generic path-bearing
  445. // fallback matched, default to allow.
  446. if (!checker) {
  447. logger.debug(ctx, `Step 3: No checker registered, allowing by default: toolName=${toolName}`);
  448. return {
  449. behavior: 'allow',
  450. reason: {
  451. type: 'safetyCheck',
  452. description: `No permission checker registered for tool "${toolName}", allowing by default`,
  453. },
  454. };
  455. }
  456. // A checker exists but returned passthrough/undefined — fall back to ask.
  457. logger.debug(
  458. ctx,
  459. `Step 3: Checker returned passthrough, falling back to ask: toolName=${toolName}`,
  460. );
  461. return {
  462. behavior: 'ask',
  463. reason: {
  464. type: 'safetyCheck',
  465. description: `No permission rule matched for tool "${toolName}"`,
  466. category: 'noMatchingPermissionRule',
  467. },
  468. ruleContents: this.resolveRuleContents(toolName, input, toolCheckResult),
  469. ruleMatchers: this.resolveRuleMatchers(toolCheckResult),
  470. candidateScopes: this.resolveCandidateScopes(toolCheckResult),
  471. rewrittenInput: toolCheckResult?.rewrittenInput,
  472. };
  473. }
  474. // -------------------------------------------------------------------------
  475. // Private helpers
  476. // -------------------------------------------------------------------------
  477. private notifyCheckerDecision(
  478. options: PermissionCheckOptions,
  479. checkerRegistered: boolean,
  480. result: ToolCheckResult | undefined,
  481. checkerFailed: boolean,
  482. ): void {
  483. try {
  484. options.onCheckerDecision?.({
  485. checkerRegistered,
  486. checkerBehavior: checkerFailed ? 'error' : (result?.behavior ?? 'none'),
  487. ...(result ? { reasonType: result.reason.type } : {}),
  488. ...(result ? { reason: result.reason } : {}),
  489. rewriteApplied: Boolean(result?.rewrittenInput),
  490. ruleCount: result?.ruleContents?.length ?? 0,
  491. skipAutoClassifier: result?.skipAutoClassifier === true,
  492. });
  493. } catch {
  494. // Observability must never alter the permission verdict.
  495. }
  496. }
  497. /**
  498. * Find an MCP server-level rule that matches a tool name.
  499. *
  500. * For example, rule with toolName "mcp__myserver" will match
  501. * tool "mcp__myserver__sometool".
  502. */
  503. private findMcpServerRule(
  504. toolName: string,
  505. ctx: ToolPermissionContext,
  506. behavior: PermissionBehavior,
  507. ): PermissionRule | undefined {
  508. const bgCtx = backgroundCtx();
  509. if (!toolName.startsWith('mcp__')) return undefined;
  510. return ctx.rules.find(
  511. (r) =>
  512. r.ruleBehavior === behavior &&
  513. !r.ruleValue.ruleContent &&
  514. matchesMcpServerRule(toolName, r),
  515. );
  516. }
  517. /**
  518. * Resolve ruleContents for an 'ask' decision.
  519. * Priority: checker result > extractToolInputContent fallback.
  520. */
  521. private resolveRuleContents(
  522. toolName: string,
  523. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  524. input: Record<string, any>,
  525. checkerResult?: ToolCheckResult,
  526. ): string[] | undefined {
  527. const ctx = backgroundCtx();
  528. if (checkerResult?.ruleContents?.length) {
  529. return checkerResult.ruleContents;
  530. }
  531. const content = extractToolInputContent(toolName, input);
  532. return content ? [content] : undefined;
  533. }
  534. /**
  535. * Companion to `resolveRuleContents` for the structured multi-scope
  536. * shape. Only forwards `candidateScopes` from the tool checker when
  537. * the checker also supplied a matching `ruleContents` — i.e. the
  538. * checker owns both fields and their `candidates[0].ruleContent`
  539. * strings are known to align with the flat `ruleContents[i]` entries
  540. * by construction. Falls back to `undefined` in the synthesized
  541. * `extractToolInputContent` branch because that path does not have
  542. * structured scope alternatives to offer (a single wrapping rule is
  543. * emitted with no widening choices).
  544. *
  545. * See {@link PermissionDecision.candidateScopes} for the contract
  546. * the two fields must jointly satisfy on the wire.
  547. */
  548. private resolveCandidateScopes(
  549. checkerResult?: ToolCheckResult,
  550. ): PermissionDecision['candidateScopes'] {
  551. if (!checkerResult?.ruleContents?.length) return undefined;
  552. if (!checkerResult.candidateScopes || checkerResult.candidateScopes.length === 0) {
  553. return undefined;
  554. }
  555. return checkerResult.candidateScopes;
  556. }
  557. private resolveRuleMatchers(checkerResult?: ToolCheckResult): PermissionDecision['ruleMatchers'] {
  558. if (!checkerResult?.ruleContents?.length) return undefined;
  559. return checkerResult.ruleMatchers?.length === checkerResult.ruleContents.length
  560. ? checkerResult.ruleMatchers
  561. : undefined;
  562. }
  563. }