pi-permission-system 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.2.0] - 2026-03-12
9
+
10
+ ### Added
11
+ - `getToolPermission()` method to retrieve tool-level permission state without evaluating command-level rules, useful for tool injection decisions
12
+
13
+ ## [0.1.8] - 2026-03-10
14
+
15
+ ### Changed
16
+ - Refactored pattern compilation to support multiple sources for proper global+agent pattern merging
17
+ - Simplified `wildcard-matcher.ts` by removing unused `wildcardCount` and `literalLength` properties
18
+ - `BashFilter` now accepts pre-compiled patterns via `BashPermissionSource` type
19
+ - Replaced `compilePermissionPatterns` with `compilePermissionPatternsFromSources` for cleaner API
20
+
21
+ ### Fixed
22
+ - Permission pattern priority now correctly implements last-match-wins hierarchy (opencode-style)
23
+ - MCP tool-level deny no longer blocks specific MCP allow patterns
24
+
25
+ ### Tests
26
+ - Updated tests to reflect last-match-wins behavior
27
+ - Added test for specific MCP rules winning over `tools.mcp: deny`
28
+ - Rearranged test pattern declarations for clarity
29
+
8
30
  ## [0.1.7] - 2026-03-10
9
31
 
10
32
  ### Added
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 🔐 pi-permission-system
2
2
 
3
- [![Version](https://img.shields.io/badge/version-0.1.7-blue.svg)](package.json)
3
+ [![Version](https://img.shields.io/badge/version-0.2.0-blue.svg)](package.json)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
5
 
6
6
  Permission enforcement extension for the Pi coding agent that provides centralized, deterministic permission gates for tool, bash, MCP, skill, and special operations.
@@ -181,18 +181,13 @@ Controls built-in tools by exact name (no wildcards):
181
181
 
182
182
  ### `bash`
183
183
 
184
- Command patterns use `*` wildcards and match against the full command string. Patterns are sorted by specificity:
185
-
186
- 1. Fewer wildcards wins
187
- 2. Longer literal text wins
188
- 3. Longer overall pattern wins
184
+ Command patterns use `*` wildcards and match against the full command string. If multiple patterns match, the **last matching rule wins**.
189
185
 
190
186
  ```jsonc
191
187
  {
192
188
  "bash": {
193
- "git status": "allow",
194
- "git diff": "allow",
195
189
  "git *": "ask",
190
+ "git status": "allow",
196
191
  "rm -rf *": "deny"
197
192
  }
198
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-permission-system",
3
- "version": "0.1.7",
3
+ "version": "0.2.0",
4
4
  "description": "Permission enforcement extension for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -7,6 +7,12 @@ import {
7
7
 
8
8
  type CompiledPattern = CompiledWildcardPattern<PermissionState>;
9
9
 
10
+ type BashPermissionSource = BashPermissions | readonly CompiledPattern[];
11
+
12
+ function isCompiledPatternList(value: BashPermissionSource): value is readonly CompiledPattern[] {
13
+ return Array.isArray(value);
14
+ }
15
+
10
16
  export interface BashPermissionCheck {
11
17
  state: PermissionState;
12
18
  matchedPattern?: string;
@@ -17,10 +23,12 @@ export class BashFilter {
17
23
  private readonly compiledPatterns: CompiledPattern[];
18
24
 
19
25
  constructor(
20
- private readonly permissions: BashPermissions,
26
+ permissions: BashPermissionSource,
21
27
  private readonly defaultState: PermissionState,
22
28
  ) {
23
- this.compiledPatterns = compileWildcardPatterns(permissions);
29
+ this.compiledPatterns = isCompiledPatternList(permissions)
30
+ ? [...permissions]
31
+ : compileWildcardPatterns(permissions);
24
32
  }
25
33
 
26
34
  check(command: string): BashPermissionCheck {
package/src/common.ts CHANGED
@@ -1,82 +1,82 @@
1
- import type { PermissionState } from "./types.js";
2
-
3
- export function toRecord(value: unknown): Record<string, unknown> {
4
- if (!value || typeof value !== "object" || Array.isArray(value)) {
5
- return {};
6
- }
7
-
8
- return value as Record<string, unknown>;
9
- }
10
-
11
- export function getNonEmptyString(value: unknown): string | null {
12
- if (typeof value !== "string") {
13
- return null;
14
- }
15
-
16
- const trimmed = value.trim();
17
- return trimmed.length > 0 ? trimmed : null;
18
- }
19
-
20
- export function isPermissionState(value: unknown): value is PermissionState {
21
- return value === "allow" || value === "deny" || value === "ask";
22
- }
23
-
24
- type StackNode = { indent: number; target: Record<string, unknown> };
25
-
26
- export function parseSimpleYamlMap(input: string): Record<string, unknown> {
27
- const root: Record<string, unknown> = {};
28
- const stack: StackNode[] = [{ indent: -1, target: root }];
29
-
30
- const lines = input.split(/\r?\n/);
31
- for (const rawLine of lines) {
32
- if (!rawLine.trim() || rawLine.trimStart().startsWith("#")) {
33
- continue;
34
- }
35
-
36
- const indent = rawLine.length - rawLine.trimStart().length;
37
- const line = rawLine.trim();
38
- const separatorIndex = line.indexOf(":");
39
- if (separatorIndex <= 0) {
40
- continue;
41
- }
42
-
43
- const key = line.slice(0, separatorIndex).trim().replace(/^['"]|['"]$/g, "");
44
- const rawValue = line.slice(separatorIndex + 1).trim();
45
-
46
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
47
- stack.pop();
48
- }
49
-
50
- const current = stack[stack.length - 1].target;
51
-
52
- if (!rawValue) {
53
- const child: Record<string, unknown> = {};
54
- current[key] = child;
55
- stack.push({ indent, target: child });
56
- continue;
57
- }
58
-
59
- let scalar = rawValue;
60
- if ((scalar.startsWith('"') && scalar.endsWith('"')) || (scalar.startsWith("'") && scalar.endsWith("'"))) {
61
- scalar = scalar.slice(1, -1);
62
- }
63
-
64
- current[key] = scalar;
65
- }
66
-
67
- return root;
68
- }
69
-
70
- export function extractFrontmatter(markdown: string): string {
71
- const normalized = markdown.replace(/\r\n/g, "\n");
72
- if (!normalized.startsWith("---\n")) {
73
- return "";
74
- }
75
-
76
- const end = normalized.indexOf("\n---", 4);
77
- if (end === -1) {
78
- return "";
79
- }
80
-
81
- return normalized.slice(4, end);
82
- }
1
+ import type { PermissionState } from "./types.js";
2
+
3
+ export function toRecord(value: unknown): Record<string, unknown> {
4
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5
+ return {};
6
+ }
7
+
8
+ return value as Record<string, unknown>;
9
+ }
10
+
11
+ export function getNonEmptyString(value: unknown): string | null {
12
+ if (typeof value !== "string") {
13
+ return null;
14
+ }
15
+
16
+ const trimmed = value.trim();
17
+ return trimmed.length > 0 ? trimmed : null;
18
+ }
19
+
20
+ export function isPermissionState(value: unknown): value is PermissionState {
21
+ return value === "allow" || value === "deny" || value === "ask";
22
+ }
23
+
24
+ type StackNode = { indent: number; target: Record<string, unknown> };
25
+
26
+ export function parseSimpleYamlMap(input: string): Record<string, unknown> {
27
+ const root: Record<string, unknown> = {};
28
+ const stack: StackNode[] = [{ indent: -1, target: root }];
29
+
30
+ const lines = input.split(/\r?\n/);
31
+ for (const rawLine of lines) {
32
+ if (!rawLine.trim() || rawLine.trimStart().startsWith("#")) {
33
+ continue;
34
+ }
35
+
36
+ const indent = rawLine.length - rawLine.trimStart().length;
37
+ const line = rawLine.trim();
38
+ const separatorIndex = line.indexOf(":");
39
+ if (separatorIndex <= 0) {
40
+ continue;
41
+ }
42
+
43
+ const key = line.slice(0, separatorIndex).trim().replace(/^['"]|['"]$/g, "");
44
+ const rawValue = line.slice(separatorIndex + 1).trim();
45
+
46
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
47
+ stack.pop();
48
+ }
49
+
50
+ const current = stack[stack.length - 1].target;
51
+
52
+ if (!rawValue) {
53
+ const child: Record<string, unknown> = {};
54
+ current[key] = child;
55
+ stack.push({ indent, target: child });
56
+ continue;
57
+ }
58
+
59
+ let scalar = rawValue;
60
+ if ((scalar.startsWith('"') && scalar.endsWith('"')) || (scalar.startsWith("'") && scalar.endsWith("'"))) {
61
+ scalar = scalar.slice(1, -1);
62
+ }
63
+
64
+ current[key] = scalar;
65
+ }
66
+
67
+ return root;
68
+ }
69
+
70
+ export function extractFrontmatter(markdown: string): string {
71
+ const normalized = markdown.replace(/\r\n/g, "\n");
72
+ if (!normalized.startsWith("---\n")) {
73
+ return "";
74
+ }
75
+
76
+ const end = normalized.indexOf("\n---", 4);
77
+ if (end === -1) {
78
+ return "";
79
+ }
80
+
81
+ return normalized.slice(4, end);
82
+ }
package/src/index.ts CHANGED
@@ -844,8 +844,11 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
844
844
  return false;
845
845
  }
846
846
 
847
- const check = permissionManager.checkPermission(toolName, {}, agentName ?? undefined);
848
- return check.state !== "deny";
847
+ // Use tool-level permission check for tool injection decisions
848
+ // This ensures that agent-specific tool deny rules (e.g., bash: deny) are respected
849
+ // before any command-level permissions are considered
850
+ const toolPermission = permissionManager.getToolPermission(toolName, agentName ?? undefined);
851
+ return toolPermission !== "deny";
849
852
  };
850
853
 
851
854
  pi.on("session_start", async (_event, ctx) => {
@@ -13,7 +13,7 @@ import type {
13
13
  PermissionState,
14
14
  } from "./types.js";
15
15
  import {
16
- compileWildcardPatterns,
16
+ compileWildcardPatternEntries,
17
17
  findCompiledWildcardMatch,
18
18
  findCompiledWildcardMatchForNames,
19
19
  type CompiledWildcardPattern,
@@ -367,14 +367,26 @@ type ResolvedPermissions = {
367
367
  bashFilter: BashFilter;
368
368
  };
369
369
 
370
- function compilePermissionPatterns(
371
- permissions: Record<string, PermissionState> | undefined,
370
+ function compilePermissionPatternsFromSources(
371
+ ...sources: Array<Record<string, PermissionState> | undefined>
372
372
  ): CompiledPermissionPatterns {
373
- if (!permissions || Object.keys(permissions).length === 0) {
373
+ const entries: Array<readonly [string, PermissionState]> = [];
374
+
375
+ for (const source of sources) {
376
+ if (!source) {
377
+ continue;
378
+ }
379
+
380
+ for (const entry of Object.entries(source)) {
381
+ entries.push(entry);
382
+ }
383
+ }
384
+
385
+ if (entries.length === 0) {
374
386
  return [];
375
387
  }
376
388
 
377
- return compileWildcardPatterns(permissions);
389
+ return compileWildcardPatternEntries(entries);
378
390
  }
379
391
 
380
392
  function findCompiledPermissionMatch(patterns: CompiledPermissionPatterns, name: string) {
@@ -542,10 +554,10 @@ export class PermissionManager {
542
554
  globalConfig,
543
555
  agentConfig,
544
556
  merged,
545
- compiledSpecial: compilePermissionPatterns(merged.special),
546
- compiledSkills: compilePermissionPatterns(merged.skills),
547
- compiledMcp: compilePermissionPatterns(merged.mcp),
548
- bashFilter: new BashFilter(merged.bash || {}, bashDefault),
557
+ compiledSpecial: compilePermissionPatternsFromSources(globalConfig.special, agentConfig.special),
558
+ compiledSkills: compilePermissionPatternsFromSources(globalConfig.skills, agentConfig.skills),
559
+ compiledMcp: compilePermissionPatternsFromSources(globalConfig.mcp, agentConfig.mcp),
560
+ bashFilter: new BashFilter(compilePermissionPatternsFromSources(globalConfig.bash, agentConfig.bash), bashDefault),
549
561
  };
550
562
 
551
563
  this.resolvedPermissionsCache.set(cacheKey, { stamp, value });
@@ -573,6 +585,59 @@ export class PermissionManager {
573
585
  return value;
574
586
  }
575
587
 
588
+ /**
589
+ * Get the tool-level permission state for a tool, without considering command-level rules.
590
+ * This is used for tool injection decisions where we need to know if a tool is allowed/denied
591
+ * at the tool level before checking specific command permissions.
592
+ *
593
+ * @param toolName - The name of the tool (e.g., "bash", "read", "write")
594
+ * @param agentName - Optional agent name to check agent-specific permissions
595
+ * @returns The permission state for the tool at the tool level
596
+ */
597
+ getToolPermission(toolName: string, agentName?: string): PermissionState {
598
+ const { merged } = this.resolvePermissions(agentName);
599
+ const normalizedToolName = toolName.trim();
600
+
601
+ // Handle special permission keys (doom_loop, external_directory)
602
+ if (SPECIAL_PERMISSION_KEYS.has(normalizedToolName)) {
603
+ return merged.defaultPolicy.special;
604
+ }
605
+
606
+ // Handle skill tool
607
+ if (normalizedToolName === "skill") {
608
+ return merged.defaultPolicy.skills;
609
+ }
610
+
611
+ // For bash tool, return the tool-level permission (not command-level)
612
+ if (normalizedToolName === "bash") {
613
+ return merged.tools?.bash || merged.defaultPolicy.bash;
614
+ }
615
+
616
+ // Handle mcp tool
617
+ if (normalizedToolName === "mcp") {
618
+ return merged.tools?.mcp || merged.defaultPolicy.mcp;
619
+ }
620
+
621
+ // Handle other tool permission names
622
+ if (TOOL_PERMISSION_NAMES.has(normalizedToolName)) {
623
+ return merged.tools?.[normalizedToolName] || merged.defaultPolicy.tools;
624
+ }
625
+
626
+ // For MCP tools (qualified names like "server_tool"), check mcp permissions
627
+ if (normalizedToolName.includes("_")) {
628
+ const mcpMatch = findCompiledPermissionMatch(
629
+ compilePermissionPatternsFromSources(this.loadGlobalConfig().mcp, this.loadAgentPermissions(agentName).mcp),
630
+ normalizedToolName
631
+ );
632
+ if (mcpMatch) {
633
+ return mcpMatch.state;
634
+ }
635
+ }
636
+
637
+ // Default to the tools default policy
638
+ return merged.defaultPolicy.tools;
639
+ }
640
+
576
641
  checkPermission(toolName: string, input: unknown, agentName?: string): PermissionCheckResult {
577
642
  const { agentConfig, merged, compiledSpecial, compiledSkills, compiledMcp, bashFilter } = this.resolvePermissions(agentName);
578
643
  const normalizedToolName = toolName.trim();
@@ -609,19 +674,6 @@ export class PermissionManager {
609
674
  if (normalizedToolName === "bash") {
610
675
  const record = toRecord(input);
611
676
  const command = typeof record.command === "string" ? record.command : "";
612
-
613
- const agentBashToolOverride = agentConfig.tools?.bash;
614
- const hasAgentBashPatterns = Object.keys(agentConfig.bash || {}).length > 0;
615
-
616
- if (agentBashToolOverride && !hasAgentBashPatterns) {
617
- return {
618
- toolName,
619
- state: agentBashToolOverride,
620
- command,
621
- source: "bash",
622
- };
623
- }
624
-
625
677
  const result = bashFilter.check(command);
626
678
 
627
679
  return {
@@ -638,15 +690,6 @@ export class PermissionManager {
638
690
  const fallbackTarget = mcpTargets[0] || "mcp";
639
691
  const toolLevelMcpState = merged.tools?.mcp;
640
692
 
641
- if (toolLevelMcpState === "deny") {
642
- return {
643
- toolName,
644
- state: "deny",
645
- target: fallbackTarget,
646
- source: "tool",
647
- };
648
- }
649
-
650
693
  const mcpMatch = findCompiledPermissionMatchForNames(compiledMcp, mcpTargets);
651
694
  if (mcpMatch) {
652
695
  return {
package/src/test.ts CHANGED
@@ -47,13 +47,13 @@ function runTest(name: string, testFn: () => void): void {
47
47
  console.log(`[PASS] ${name}`);
48
48
  }
49
49
 
50
- runTest("BashFilter wildcard and specificity matching", () => {
50
+ runTest("BashFilter uses opencode-style last-match hierarchy", () => {
51
51
  const filter = new BashFilter(
52
52
  {
53
- "git status": "allow",
54
- "git status *": "ask",
55
- "git *": "deny",
56
53
  "*": "ask",
54
+ "git *": "deny",
55
+ "git status *": "ask",
56
+ "git status": "allow",
57
57
  },
58
58
  "deny",
59
59
  );
@@ -98,7 +98,7 @@ runTest("PermissionManager built-in permission checking", () => {
98
98
  }
99
99
  });
100
100
 
101
- runTest("Agent-specific bash override", () => {
101
+ runTest("Bash patterns stay higher priority than tool-level bash fallback", () => {
102
102
  const { manager, cleanup } = createManager(
103
103
  {
104
104
  defaultPolicy: {
@@ -108,28 +108,31 @@ runTest("Agent-specific bash override", () => {
108
108
  skills: "ask",
109
109
  special: "ask",
110
110
  },
111
- tools: {
112
- bash: "allow",
113
- },
114
111
  bash: {
115
- "echo *": "allow",
112
+ "rm -rf *": "deny",
116
113
  },
117
114
  },
118
115
  {
119
116
  reviewer: `---
120
117
  name: reviewer
121
118
  permission:
122
- bash: deny
119
+ tools:
120
+ bash: allow
123
121
  ---
124
122
  `,
125
123
  },
126
124
  );
127
125
 
128
126
  try {
129
- const result = manager.checkPermission("bash", { command: "echo hello" }, "reviewer");
130
- assert.equal(result.state, "deny");
131
- assert.equal(result.source, "bash");
132
- assert.equal(result.matchedPattern, undefined);
127
+ const denied = manager.checkPermission("bash", { command: "rm -rf build" }, "reviewer");
128
+ assert.equal(denied.state, "deny");
129
+ assert.equal(denied.source, "bash");
130
+ assert.equal(denied.matchedPattern, "rm -rf *");
131
+
132
+ const fallback = manager.checkPermission("bash", { command: "echo hello" }, "reviewer");
133
+ assert.equal(fallback.state, "allow");
134
+ assert.equal(fallback.source, "bash");
135
+ assert.equal(fallback.matchedPattern, undefined);
133
136
  } finally {
134
137
  cleanup();
135
138
  }
@@ -145,9 +148,9 @@ runTest("MCP wildcard matching", () => {
145
148
  special: "ask",
146
149
  },
147
150
  mcp: {
151
+ "*": "deny",
148
152
  "subagent_*": "ask",
149
153
  "subagent_query-*": "allow",
150
- "*": "deny",
151
154
  },
152
155
  });
153
156
 
@@ -179,9 +182,9 @@ runTest("Skill permission matching", () => {
179
182
  special: "ask",
180
183
  },
181
184
  skills: {
182
- "requesting-code-review": "allow",
183
- "web-*": "deny",
184
185
  "*": "ask",
186
+ "web-*": "deny",
187
+ "requesting-code-review": "allow",
185
188
  },
186
189
  });
187
190
 
@@ -214,8 +217,8 @@ runTest("MCP proxy tool infers server-prefixed aliases from configured server na
214
217
  special: "ask",
215
218
  },
216
219
  mcp: {
217
- exa_get_code_context_exa: "allow",
218
220
  "exa_*": "deny",
221
+ exa_get_code_context_exa: "allow",
219
222
  },
220
223
  },
221
224
  {},
@@ -246,8 +249,8 @@ runTest("MCP describe mode normalizes qualified tool names without duplicating s
246
249
  special: "ask",
247
250
  },
248
251
  mcp: {
249
- exa_web_search_exa: "allow",
250
252
  "exa_*": "deny",
253
+ exa_web_search_exa: "allow",
251
254
  },
252
255
  },
253
256
  {},
@@ -365,6 +368,49 @@ permission:
365
368
  }
366
369
  });
367
370
 
371
+ runTest("specific MCP rules still win when tools.mcp is deny", () => {
372
+ const { manager, cleanup } = createManager(
373
+ {
374
+ defaultPolicy: {
375
+ tools: "ask",
376
+ bash: "ask",
377
+ mcp: "ask",
378
+ skills: "ask",
379
+ special: "ask",
380
+ },
381
+ },
382
+ {
383
+ reviewer: `---
384
+ name: reviewer
385
+ permission:
386
+ tools:
387
+ mcp: deny
388
+ mcp:
389
+ exa_web_search_exa: allow
390
+ ---
391
+ `,
392
+ },
393
+ {
394
+ mcpServerNames: ["exa"],
395
+ },
396
+ );
397
+
398
+ try {
399
+ const allowed = manager.checkPermission("mcp", { tool: "web_search_exa" }, "reviewer");
400
+ assert.equal(allowed.state, "allow");
401
+ assert.equal(allowed.source, "mcp");
402
+ assert.equal(allowed.matchedPattern, "exa_web_search_exa");
403
+ assert.equal(allowed.target, "exa_web_search_exa");
404
+
405
+ const fallback = manager.checkPermission("mcp", { tool: "other_exa" }, "reviewer");
406
+ assert.equal(fallback.state, "deny");
407
+ assert.equal(fallback.source, "tool");
408
+ assert.equal(fallback.target, "exa_other_exa");
409
+ } finally {
410
+ cleanup();
411
+ }
412
+ });
413
+
368
414
  runTest("partial agent defaultPolicy overrides preserve global defaults", () => {
369
415
  const { manager, cleanup } = createManager(
370
416
  {
@@ -484,4 +530,70 @@ runTest("Tool registry blocks unregistered tools and handles aliases", () => {
484
530
  assert.equal(missingNameCheck.status, "missing-tool-name");
485
531
  });
486
532
 
533
+ runTest("getToolPermission returns tool-level deny for agent with bash: deny", () => {
534
+ const { manager, cleanup } = createManager(
535
+ {
536
+ defaultPolicy: {
537
+ tools: "ask",
538
+ bash: "ask",
539
+ mcp: "ask",
540
+ skills: "ask",
541
+ special: "ask",
542
+ },
543
+ },
544
+ {
545
+ orchestrator: `---
546
+ name: orchestrator
547
+ permission:
548
+ tools:
549
+ bash: deny
550
+ read: deny
551
+ task: allow
552
+ ---
553
+ `,
554
+ },
555
+ );
556
+
557
+ try {
558
+ // Tool-level check for bash should return deny for orchestrator
559
+ const bashPermission = manager.getToolPermission("bash", "orchestrator");
560
+ assert.equal(bashPermission, "deny");
561
+
562
+ // Tool-level check for task should return allow
563
+ const taskPermission = manager.getToolPermission("task", "orchestrator");
564
+ assert.equal(taskPermission, "allow");
565
+
566
+ // Tool-level check for read should return deny
567
+ const readPermission = manager.getToolPermission("read", "orchestrator");
568
+ assert.equal(readPermission, "deny");
569
+
570
+ // When no agent specified, should fall back to default policy
571
+ const defaultBashPermission = manager.getToolPermission("bash");
572
+ assert.equal(defaultBashPermission, "ask");
573
+
574
+ // Global config tools setting should work
575
+ const { manager: manager2, cleanup: cleanup2 } = createManager({
576
+ defaultPolicy: {
577
+ tools: "deny",
578
+ bash: "ask",
579
+ mcp: "ask",
580
+ skills: "ask",
581
+ special: "ask",
582
+ },
583
+ tools: {
584
+ bash: "allow",
585
+ },
586
+ });
587
+
588
+ try {
589
+ const globalBashPermission = manager2.getToolPermission("bash");
590
+ assert.equal(globalBashPermission, "allow");
591
+ } finally {
592
+ cleanup2();
593
+ }
594
+ } finally {
595
+ cleanup();
596
+ }
597
+ });
598
+
487
599
  console.log("All permission system tests passed.");
@@ -2,8 +2,6 @@ export type CompiledWildcardPattern<TState> = {
2
2
  pattern: string;
3
3
  state: TState;
4
4
  regex: RegExp;
5
- wildcardCount: number;
6
- literalLength: number;
7
5
  };
8
6
 
9
7
  export type WildcardPatternMatch<TState> = {
@@ -26,39 +24,27 @@ export function compileWildcardPattern<TState>(pattern: string, state: TState):
26
24
  pattern,
27
25
  state,
28
26
  regex: new RegExp(`^${escaped}$`),
29
- wildcardCount: (pattern.match(/\*/g) || []).length,
30
- literalLength: pattern.replace(/\*/g, "").length,
31
27
  };
32
28
  }
33
29
 
34
- function compareCompiledPatterns<TState>(
35
- left: CompiledWildcardPattern<TState>,
36
- right: CompiledWildcardPattern<TState>,
37
- ): number {
38
- if (left.wildcardCount !== right.wildcardCount) {
39
- return left.wildcardCount - right.wildcardCount;
40
- }
41
-
42
- if (left.literalLength !== right.literalLength) {
43
- return right.literalLength - left.literalLength;
44
- }
45
-
46
- return right.pattern.length - left.pattern.length;
30
+ export function compileWildcardPatternEntries<TState>(
31
+ entries: Iterable<readonly [string, TState]>,
32
+ ): CompiledWildcardPattern<TState>[] {
33
+ return Array.from(entries, ([pattern, state]) => compileWildcardPattern(pattern, state));
47
34
  }
48
35
 
49
36
  export function compileWildcardPatterns<TState>(
50
37
  patterns: Record<string, TState>,
51
38
  ): CompiledWildcardPattern<TState>[] {
52
- return Object.entries(patterns)
53
- .map(([pattern, state]) => compileWildcardPattern(pattern, state))
54
- .sort(compareCompiledPatterns);
39
+ return compileWildcardPatternEntries(Object.entries(patterns));
55
40
  }
56
41
 
57
42
  export function findCompiledWildcardMatch<TState>(
58
43
  patterns: readonly CompiledWildcardPattern<TState>[],
59
44
  name: string,
60
45
  ): WildcardPatternMatch<TState> | null {
61
- for (const pattern of patterns) {
46
+ for (let index = patterns.length - 1; index >= 0; index -= 1) {
47
+ const pattern = patterns[index];
62
48
  if (pattern.regex.test(name)) {
63
49
  return {
64
50
  state: pattern.state,