Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

policy-map.ts

83 lines2.7 KB

1/**
2 * Map a portable {@link SandboxPolicy} onto Claude Code CLI permission flags.
3 *
4 * This is a best-effort, coarse mapping (the CLI's permission model is
5 * tool-level + a permission mode, not arbitrary command globs):
6 *
7 * - `default` decision → `--permission-mode`:
8 * `'allow'` → `bypassPermissions`, `'acceptEdits'`-ish `'ask'` → `acceptEdits`,
9 * `'deny'` → `default` (in `-p` mode, prompts are auto-denied).
10 * - `capabilities.fileWrite === 'deny'` → disallow `Write`,`Edit`,`MultiEdit`.
11 * - `capabilities.network === 'deny'` → disallow `WebFetch`,`WebSearch`.
12 * - `commands.deny` that name a bare built-in tool (e.g. `Bash`) are added to
13 * `--disallowedTools`; fine-grained command-glob enforcement is left to the
14 * MCP permission-prompt tool (interactive approvals).
15 *
16 * Returns the permission mode plus tool allow/deny additions; the adapter
17 * merges these with its own config.
18 */
19import type { PolicyDecision, SandboxPolicy } from '@tanstack/ai-sandbox'
20import type { ClaudeCodePermissionMode } from './text'
21​
22export interface ClaudePolicyFlags {
23 permissionMode?: ClaudeCodePermissionMode
24 allowedTools: Array<string>
25 disallowedTools: Array<string>
27​
28const WRITE_TOOLS = ['Write', 'Edit', 'MultiEdit']
29const NETWORK_TOOLS = ['WebFetch', 'WebSearch']
30const BUILTIN_TOOL_NAMES = new Set([
31 'Bash',
32 'Read',
33 'Write',
34 'Edit',
35 'MultiEdit',
36 'Glob',
37 'Grep',
38 'WebFetch',
39 'WebSearch',
40 'NotebookEdit',
41 'Task',
42])
43​
44function modeFor(decision: PolicyDecision): ClaudeCodePermissionMode {
45 switch (decision) {
46 case 'allow':
47 return 'bypassPermissions'
48 case 'ask':
49 return 'acceptEdits'
50 case 'deny':
51 return 'default'
52 }
54​
55export function mapPolicyToClaudeFlags(
56 policy: SandboxPolicy | undefined,
57): ClaudePolicyFlags {
58 const allowedTools: Array<string> = []
59 const disallowedTools: Array<string> = []
60 if (!policy) return { allowedTools, disallowedTools }
61​
62 if (policy.capabilities?.fileWrite === 'deny')
63 disallowedTools.push(...WRITE_TOOLS)
64 if (policy.capabilities?.network === 'deny')
65 disallowedTools.push(...NETWORK_TOOLS)
66​
67 // Tool-name-level command rules map directly; everything else is left to the
68 // permission-prompt tool.
69 for (const pattern of policy.commands?.deny ?? []) {
70 if (BUILTIN_TOOL_NAMES.has(pattern)) disallowedTools.push(pattern)
71 }
72 for (const pattern of policy.commands?.allow ?? []) {
73 if (BUILTIN_TOOL_NAMES.has(pattern)) allowedTools.push(pattern)
74 }
75​
76 const result: ClaudePolicyFlags = {
77 allowedTools: [...new Set(allowedTools)],
78 disallowedTools: [...new Set(disallowedTools)],
79 }
80 if (policy.default !== undefined)
81 result.permissionMode = modeFor(policy.default)
82 return result