@gotgenes/pi-permission-system 17.0.0 → 17.1.1

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +1 -1
  3. package/src/access-intent/access-path.ts +5 -5
  4. package/src/access-intent/bash/bash-path-resolver.ts +535 -0
  5. package/src/access-intent/bash/program.ts +21 -14
  6. package/src/access-intent/bash/token-classification.ts +24 -1
  7. package/src/canonicalize-path.ts +11 -5
  8. package/src/forwarded-permissions/permission-forwarder.ts +11 -1
  9. package/src/forwarding-manager.ts +7 -1
  10. package/src/handlers/before-agent-start.ts +1 -1
  11. package/src/handlers/gates/bash-path-extractor.ts +7 -5
  12. package/src/handlers/gates/external-directory.ts +7 -18
  13. package/src/handlers/gates/path.ts +3 -2
  14. package/src/handlers/gates/skill-read.ts +4 -2
  15. package/src/handlers/gates/tool-call-gate-pipeline.ts +20 -4
  16. package/src/handlers/gates/tool.ts +4 -2
  17. package/src/index.ts +12 -1
  18. package/src/input-normalizer.ts +9 -4
  19. package/src/path-normalizer.ts +100 -0
  20. package/src/path-utils.ts +39 -28
  21. package/src/permission-manager.ts +21 -7
  22. package/src/permission-session.ts +35 -2
  23. package/src/prompting-gateway.ts +3 -0
  24. package/src/rule.ts +8 -6
  25. package/src/skill-prompt-sanitizer.ts +8 -10
  26. package/src/subagent-context.ts +17 -9
  27. package/test/access-intent/access-path.test.ts +73 -24
  28. package/test/access-intent/bash/program.test.ts +131 -65
  29. package/test/access-intent/bash/token-classification.test.ts +75 -0
  30. package/test/bash-external-directory.test.ts +53 -1
  31. package/test/canonicalize-path.test.ts +34 -8
  32. package/test/forwarding-manager.test.ts +7 -1
  33. package/test/handlers/external-directory-symlink-acceptance.test.ts +23 -4
  34. package/test/handlers/gates/bash-command-metamorphic.test.ts +5 -1
  35. package/test/handlers/gates/bash-external-directory.test.ts +5 -1
  36. package/test/handlers/gates/bash-path.test.ts +6 -1
  37. package/test/handlers/gates/external-directory-policy.test.ts +26 -8
  38. package/test/handlers/gates/external-directory.test.ts +8 -1
  39. package/test/handlers/gates/path.test.ts +53 -14
  40. package/test/handlers/gates/skill-read.test.ts +26 -13
  41. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +2 -1
  42. package/test/handlers/gates/tool.test.ts +13 -1
  43. package/test/helpers/gate-fixtures.ts +10 -0
  44. package/test/helpers/session-fixtures.ts +3 -0
  45. package/test/input-normalizer.test.ts +104 -39
  46. package/test/path-normalizer.test.ts +166 -0
  47. package/test/path-utils.test.ts +130 -51
  48. package/test/permission-forwarder.test.ts +1 -0
  49. package/test/permission-manager-unified.test.ts +40 -0
  50. package/test/permission-resolver.test.ts +12 -3
  51. package/test/permission-session.test.ts +41 -0
  52. package/test/pi-infrastructure-read.test.ts +27 -4
  53. package/test/prompting-gateway.test.ts +1 -0
  54. package/test/rule.test.ts +88 -42
  55. package/test/session-rules.test.ts +21 -4
  56. package/test/skill-prompt-sanitizer.test.ts +37 -16
  57. package/test/subagent-context.test.ts +77 -31
  58. package/test/synthesize.test.ts +13 -11
  59. package/src/access-intent/bash/cwd-projection.ts +0 -500
@@ -1,13 +1,19 @@
1
1
  /**
2
2
  * Pure, synchronous token-classification helpers for bash path extraction.
3
3
  *
4
- * Exports two classifiers consumed by `cwd-projection.ts`:
4
+ * Exports two classifiers consumed by `bash-path-resolver.ts`:
5
5
  * - `classifyTokenAsPathCandidate` — strict gate for the external-directory guard.
6
6
  * - `classifyTokenAsRuleCandidate` — broader gate for cross-cutting `path` rules.
7
7
  *
8
8
  * Both classifiers share the private `rejectNonPathToken` predicate that captures
9
9
  * the seven rejection cases common to both (the production clone this module was
10
10
  * extracted to eliminate).
11
+ *
12
+ * Both classifiers recognize Windows drive-letter absolute paths (`C:/…`, `C:\…`)
13
+ * unconditionally on all platforms. On POSIX the token resolves as a real in-CWD
14
+ * relative path and is gated by the `path` surface; on Windows the `PathNormalizer`
15
+ * routes it through the absolute-path branch. Shape recognition is platform-independent
16
+ * string matching; the platform-sensitive absoluteness decision belongs to `PathNormalizer`.
11
17
  */
12
18
 
13
19
  // ── Public classifiers ─────────────────────────────────────────────────────
@@ -19,6 +25,7 @@
19
25
  * - Absolute paths (starting with `/`)
20
26
  * - Home-relative paths (starting with `~/`)
21
27
  * - Parent-traversal paths (containing `..`)
28
+ * - Windows drive-letter absolute paths (`C:/…` or `C:\…`)
22
29
  *
23
30
  * Returns the raw token string if it qualifies, or `null` to skip.
24
31
  */
@@ -28,6 +35,7 @@ export function classifyTokenAsPathCandidate(token: string): string | null {
28
35
  if (token.startsWith("/")) return token;
29
36
  if (token.startsWith("~/")) return token;
30
37
  if (token.includes("..")) return token;
38
+ if (WINDOWS_DRIVE_PATH_PATTERN.test(token)) return token;
31
39
 
32
40
  return null;
33
41
  }
@@ -38,8 +46,13 @@ export function classifyTokenAsPathCandidate(token: string): string | null {
38
46
  * Accepts the same shapes as `classifyTokenAsPathCandidate`, plus:
39
47
  * - Dot-files and `./`-relative paths (starting with `.`)
40
48
  * - Any relative path containing `/` (e.g. `src/foo.ts`)
49
+ * - Windows drive-letter absolute paths (`C:/…` or `C:\…`)
41
50
  *
42
51
  * The `~/foo` case is covered by `includes("/")` — no separate `~/` branch needed.
52
+ * The forward-slash drive form (`C:/…`) is also caught by `includes("/")`, but the
53
+ * explicit `WINDOWS_DRIVE_PATH_PATTERN` branch makes both separator forms first-class
54
+ * and order-independent, and covers the backslash-only form (`D:\…`) which `includes("/")`
55
+ * cannot reach.
43
56
  *
44
57
  * Does NOT require the strict "must start with `/` or `~/` or contain `..`"
45
58
  * gate that the external-directory classifier uses.
@@ -52,12 +65,22 @@ export function classifyTokenAsRuleCandidate(token: string): string | null {
52
65
  if (token.startsWith(".")) return token;
53
66
  if (token.includes("/")) return token; // covers ~/ paths and all relative paths with /
54
67
  if (token.includes("..")) return token; // bare ".." (no slash)
68
+ if (WINDOWS_DRIVE_PATH_PATTERN.test(token)) return token; // backslash-only drive form
55
69
 
56
70
  return null;
57
71
  }
58
72
 
59
73
  // ── Private rejection predicate ────────────────────────────────────────────
60
74
 
75
+ /**
76
+ * Windows drive-letter absolute path: a single ASCII letter, a colon, then a
77
+ * separator (`/` or `\`). Matches `C:/…` and `C:\…` but not drive-relative
78
+ * `C:foo` (no separator) or multi-letter schemes (`https:`, `mailto:`).
79
+ * Single-letter schemes with `//` (e.g. `c://x`) are already rejected by
80
+ * `URL_PATTERN` before this pattern is tested.
81
+ */
82
+ const WINDOWS_DRIVE_PATH_PATTERN = /^[a-zA-Z]:[/\\]/;
83
+
61
84
  /**
62
85
  * URL pattern to skip tokens that look like URLs rather than paths.
63
86
  */
@@ -1,5 +1,5 @@
1
1
  import { realpathSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { posix as posixPath, win32 as winPath } from "node:path";
3
3
 
4
4
  /**
5
5
  * Resolve symlinks in an absolute path, best-effort.
@@ -11,16 +11,22 @@ import { join } from "node:path";
11
11
  * encountered (e.g. `EACCES`, `ELOOP`), so callers fall back to lexical
12
12
  * containment for paths that cannot be resolved.
13
13
  */
14
- export function canonicalizePath(absolutePath: string): string {
14
+ export function canonicalizePath(
15
+ absolutePath: string,
16
+ platform: NodeJS.Platform,
17
+ ): string {
15
18
  if (!absolutePath) return absolutePath;
16
19
 
17
- const parts = absolutePath.split("/").filter(Boolean);
20
+ const impl = platform === "win32" ? winPath : posixPath;
21
+ const root = impl.parse(absolutePath).root;
22
+ const rest = absolutePath.slice(root.length);
23
+ const parts = rest.split(impl.sep).filter(Boolean);
18
24
  for (let i = parts.length; i >= 0; i--) {
19
- const candidate = "/" + parts.slice(0, i).join("/");
25
+ const candidate = root + parts.slice(0, i).join(impl.sep);
20
26
  try {
21
27
  const real = realpathSync(candidate);
22
28
  const tail = parts.slice(i);
23
- return tail.length === 0 ? real : join(real, ...tail);
29
+ return tail.length === 0 ? real : impl.join(real, ...tail);
24
30
  } catch (error) {
25
31
  const code = (error as NodeJS.ErrnoException).code;
26
32
  if (code !== "ENOENT" && code !== "ENOTDIR") return absolutePath;
@@ -77,6 +77,8 @@ export interface ForwarderContext {
77
77
  export interface PermissionForwarderDeps {
78
78
  forwardingDir: string;
79
79
  subagentSessionsDir: string;
80
+ /** Host platform, injected from the composition root, for subagent-context path detection. */
81
+ platform: NodeJS.Platform;
80
82
  /** In-process subagent session registry for detection and forwarding target resolution. */
81
83
  registry?: SubagentSessionRegistry;
82
84
  /** Event bus used for UI prompt broadcasts. */
@@ -185,6 +187,7 @@ export interface InboxProcessor {
185
187
  export class PermissionForwarder implements ApprovalRequester, InboxProcessor {
186
188
  private readonly forwardingDir: string;
187
189
  private readonly subagentSessionsDir: string;
190
+ private readonly platform: NodeJS.Platform;
188
191
  private readonly registry: SubagentSessionRegistry | undefined;
189
192
  private readonly events: PermissionEventBus | undefined;
190
193
  private readonly logger: DebugReviewLogger;
@@ -199,6 +202,7 @@ export class PermissionForwarder implements ApprovalRequester, InboxProcessor {
199
202
  constructor(deps: PermissionForwarderDeps) {
200
203
  this.forwardingDir = deps.forwardingDir;
201
204
  this.subagentSessionsDir = deps.subagentSessionsDir;
205
+ this.platform = deps.platform;
202
206
  this.registry = deps.registry;
203
207
  this.events = deps.events;
204
208
  this.logger = deps.logger;
@@ -228,7 +232,12 @@ export class PermissionForwarder implements ApprovalRequester, InboxProcessor {
228
232
  }
229
233
 
230
234
  if (
231
- !isSubagentExecutionContext(ctx, this.subagentSessionsDir, this.registry)
235
+ !isSubagentExecutionContext(
236
+ ctx,
237
+ this.subagentSessionsDir,
238
+ this.platform,
239
+ this.registry,
240
+ )
232
241
  ) {
233
242
  return Promise.resolve({ approved: false, state: "denied" });
234
243
  }
@@ -307,6 +316,7 @@ export class PermissionForwarder implements ApprovalRequester, InboxProcessor {
307
316
  isSubagent: isSubagentExecutionContext(
308
317
  ctx,
309
318
  this.subagentSessionsDir,
319
+ this.platform,
310
320
  this.registry,
311
321
  ),
312
322
  currentSessionId: requesterSessionId,
@@ -30,6 +30,7 @@ export class ForwardingManager {
30
30
  constructor(
31
31
  private readonly subagentSessionsDir: string,
32
32
  private readonly forwarder: InboxProcessor,
33
+ private readonly platform: NodeJS.Platform,
33
34
  private readonly registry?: SubagentSessionRegistry,
34
35
  ) {}
35
36
 
@@ -42,7 +43,12 @@ export class ForwardingManager {
42
43
  start(ctx: ExtensionContext): void {
43
44
  if (
44
45
  !ctx.hasUI ||
45
- isSubagentExecutionContext(ctx, this.subagentSessionsDir, this.registry)
46
+ isSubagentExecutionContext(
47
+ ctx,
48
+ this.subagentSessionsDir,
49
+ this.platform,
50
+ this.registry,
51
+ )
46
52
  ) {
47
53
  this.stop();
48
54
  return;
@@ -84,7 +84,7 @@ export class AgentPrepHandler {
84
84
  toolPromptResult.prompt,
85
85
  this.resolver,
86
86
  agentName,
87
- ctx.cwd,
87
+ this.session.getPathNormalizer(),
88
88
  );
89
89
  this.session.setActiveSkillEntries(skillPromptResult.entries);
90
90
  return skillPromptResult.prompt !== event.systemPrompt
@@ -1,21 +1,23 @@
1
1
  import { BashProgram } from "#src/access-intent/bash/program";
2
+ import type { PathNormalizer } from "#src/path-normalizer";
2
3
 
3
4
  /**
4
- * Extract paths from a bash command string that resolve outside CWD.
5
+ * Extract paths from a bash command that resolve outside CWD.
5
6
  *
6
- * Thin facade over {@link BashProgram.externalPaths}; parses the command and
7
+ * Thin facade over {@link BashProgram.externalPaths}; parses the command
8
+ * through the injected {@link PathNormalizer} (platform + cwd baked in) and
7
9
  * returns the cd-aware external paths in their lexical (as-typed) string form.
8
10
  * See `BashProgram` for the parsing and resolution semantics.
9
11
  *
10
12
  * Returns `string[]` (not `AccessPath[]`) so the large projection-correctness
11
13
  * test suite in `bash-external-directory.test.ts` can assert path values
12
- * without migrating every call site.
14
+ * without migrating to the `AccessPath` accessors.
13
15
  */
14
16
  export async function extractExternalPathsFromBashCommand(
15
17
  command: string,
16
- cwd: string,
18
+ normalizer: PathNormalizer,
17
19
  ): Promise<string[]> {
18
- return (await BashProgram.parse(command, cwd))
20
+ return (await BashProgram.parse(command, normalizer))
19
21
  .externalPaths()
20
22
  .map((p) => p.value());
21
23
  }
@@ -1,10 +1,5 @@
1
- import { AccessPath } from "#src/access-intent/access-path";
2
- import {
3
- getToolInputPath,
4
- isPathOutsideWorkingDirectory,
5
- isPiInfrastructureRead,
6
- normalizePathForComparison,
7
- } from "#src/path-utils";
1
+ import type { PathNormalizer } from "#src/path-normalizer";
2
+ import { getToolInputPath } from "#src/path-utils";
8
3
  import type { ScopedPermissionResolver } from "#src/permission-resolver";
9
4
  import { SessionApproval } from "#src/session-approval";
10
5
  import { deriveApprovalPattern } from "#src/session-rules";
@@ -26,6 +21,7 @@ export function describeExternalDirectoryGate(
26
21
  tcc: ToolCallContext,
27
22
  infraDirs: string[],
28
23
  resolver: ScopedPermissionResolver,
24
+ normalizer: PathNormalizer,
29
25
  extractors?: ToolAccessExtractorLookup,
30
26
  ): GateResult {
31
27
  const externalDirectoryPath = getToolInputPath(
@@ -35,22 +31,17 @@ export function describeExternalDirectoryGate(
35
31
  );
36
32
  if (!externalDirectoryPath) return null;
37
33
 
38
- if (!isPathOutsideWorkingDirectory(externalDirectoryPath, tcc.cwd)) {
34
+ if (!normalizer.isOutsideWorkingDirectory(externalDirectoryPath)) {
39
35
  return null;
40
36
  }
41
37
 
42
38
  // The boundary decision (above) and the infrastructure-read containment
43
39
  // check (below) use the canonical, symlink-resolved path; pattern matching
44
40
  // uses the typed and resolved aliases (#418).
45
- const accessPath = AccessPath.forPath(externalDirectoryPath, {
46
- cwd: tcc.cwd,
47
- });
48
- const canonicalExtPath = accessPath.boundaryValue();
41
+ const accessPath = normalizer.forPath(externalDirectoryPath);
49
42
 
50
43
  // ── Pi infrastructure read bypass ──────────────────────────────────────
51
- if (
52
- isPiInfrastructureRead(tcc.toolName, canonicalExtPath, infraDirs, tcc.cwd)
53
- ) {
44
+ if (normalizer.isInfrastructureRead(tcc.toolName, accessPath, infraDirs)) {
54
45
  return {
55
46
  action: "allow",
56
47
  log: {
@@ -89,9 +80,7 @@ export function describeExternalDirectoryGate(
89
80
  resolver,
90
81
  tcc.agentName ?? undefined,
91
82
  );
92
- const pattern = deriveApprovalPattern(
93
- normalizePathForComparison(externalDirectoryPath, tcc.cwd),
94
- );
83
+ const pattern = deriveApprovalPattern(accessPath.value());
95
84
 
96
85
  return {
97
86
  surface: "external_directory",
@@ -1,4 +1,4 @@
1
- import { AccessPath } from "#src/access-intent/access-path";
1
+ import type { PathNormalizer } from "#src/path-normalizer";
2
2
  import { getToolInputPath } from "#src/path-utils";
3
3
  import type { ScopedPermissionResolver } from "#src/permission-resolver";
4
4
  import { SessionApproval } from "#src/session-approval";
@@ -18,6 +18,7 @@ import type { ToolCallContext } from "./types";
18
18
  export function describePathGate(
19
19
  tcc: ToolCallContext,
20
20
  resolver: ScopedPermissionResolver,
21
+ normalizer: PathNormalizer,
21
22
  extractors?: ToolAccessExtractorLookup,
22
23
  ): GateResult {
23
24
  const filePath = getToolInputPath(tcc.toolName, tcc.input, extractors);
@@ -26,7 +27,7 @@ export function describePathGate(
26
27
  // Emit an access-path intent so the resolver matches the lexical aliases
27
28
  // *and* the canonical (symlink-resolved) form, the same set
28
29
  // `external_directory` matches (#418, #486).
29
- const accessPath = AccessPath.forPath(filePath, { cwd: tcc.cwd });
30
+ const accessPath = normalizer.forPath(filePath);
30
31
  const check = resolver.resolve({
31
32
  kind: "access-path",
32
33
  surface: "path",
@@ -1,4 +1,4 @@
1
- import { normalizePathForComparison } from "#src/path-utils";
1
+ import type { PathNormalizer } from "#src/path-normalizer";
2
2
  import { formatSkillPathAskPrompt } from "#src/permission-prompts";
3
3
  import type { SkillPromptEntry } from "#src/skill-prompt-sanitizer";
4
4
  import { findSkillPathMatch } from "#src/skill-prompt-sanitizer";
@@ -15,6 +15,7 @@ import type { ToolCallContext } from "./types";
15
15
  */
16
16
  export function describeSkillReadGate(
17
17
  tcc: ToolCallContext,
18
+ normalizer: PathNormalizer,
18
19
  getActiveSkillEntries: () => SkillPromptEntry[],
19
20
  ): GateDescriptor | null {
20
21
  const activeSkillEntries = getActiveSkillEntries();
@@ -29,10 +30,11 @@ export function describeSkillReadGate(
29
30
  return null;
30
31
  }
31
32
 
32
- const normalizedReadPath = normalizePathForComparison(path, tcc.cwd);
33
+ const normalizedReadPath = normalizer.comparableValue(path);
33
34
  const matchedSkill = findSkillPathMatch(
34
35
  normalizedReadPath,
35
36
  activeSkillEntries,
37
+ normalizer,
36
38
  );
37
39
 
38
40
  if (!matchedSkill) {
@@ -1,4 +1,5 @@
1
1
  import { BashProgram } from "#src/access-intent/bash/program";
2
+ import type { PathNormalizer } from "#src/path-normalizer";
2
3
  import type { ScopedPermissionResolver } from "#src/permission-resolver";
3
4
  import type { SkillPromptEntry } from "#src/skill-prompt-sanitizer";
4
5
  import type { ToolAccessExtractorLookup } from "#src/tool-access-extractor-registry";
@@ -36,6 +37,10 @@ export interface ToolCallGateInputs {
36
37
  getInfrastructureReadDirs(): string[];
37
38
  /** Resolved tool-preview formatter options from the current config. */
38
39
  getToolPreviewLimits(): ToolPreviewFormatterOptions;
40
+ /** The session's path normalizer (platform + cwd baked in). */
41
+ getPathNormalizer(): PathNormalizer;
42
+ /** The host platform injected at the composition root. */
43
+ getPlatform(): NodeJS.Platform;
39
44
  }
40
45
 
41
46
  /**
@@ -64,9 +69,10 @@ export class ToolCallGatePipeline {
64
69
  // Parse the bash command exactly once per evaluate; the three bash gates
65
70
  // share this single BashProgram instead of each re-parsing (#308).
66
71
  const command = getNonEmptyString(toRecord(tcc.input).command);
72
+ const normalizer = this.inputs.getPathNormalizer();
67
73
  const bashProgram =
68
74
  tcc.toolName === "bash" && command
69
- ? await BashProgram.parse(command, tcc.cwd)
75
+ ? await BashProgram.parse(command, normalizer)
70
76
  : null;
71
77
 
72
78
  const formatter = new ToolPreviewFormatter(
@@ -75,16 +81,21 @@ export class ToolCallGatePipeline {
75
81
  );
76
82
 
77
83
  const infraDirs = this.inputs.getInfrastructureReadDirs();
84
+ const platform = this.inputs.getPlatform();
78
85
 
79
86
  const gateProducers: Array<() => GateResult | Promise<GateResult>> = [
80
87
  () =>
81
- describeSkillReadGate(tcc, () => this.inputs.getActiveSkillEntries()),
82
- () => describePathGate(tcc, this.resolver, this.customExtractors),
88
+ describeSkillReadGate(tcc, normalizer, () =>
89
+ this.inputs.getActiveSkillEntries(),
90
+ ),
91
+ () =>
92
+ describePathGate(tcc, this.resolver, normalizer, this.customExtractors),
83
93
  () =>
84
94
  describeExternalDirectoryGate(
85
95
  tcc,
86
96
  infraDirs,
87
97
  this.resolver,
98
+ normalizer,
88
99
  this.customExtractors,
89
100
  ),
90
101
  () => describeBashExternalDirectoryGate(tcc, bashProgram, this.resolver),
@@ -108,7 +119,12 @@ export class ToolCallGatePipeline {
108
119
  input: tcc.input,
109
120
  agentName: tcc.agentName ?? undefined,
110
121
  });
111
- const toolDescriptor = describeToolGate(tcc, toolCheck, formatter);
122
+ const toolDescriptor = describeToolGate(
123
+ tcc,
124
+ toolCheck,
125
+ formatter,
126
+ platform,
127
+ );
112
128
  toolDescriptor.preCheck = toolCheck;
113
129
  return toolDescriptor;
114
130
  },
@@ -23,12 +23,13 @@ import type { ToolCallContext } from "./types";
23
23
  function deriveSuggestionValue(
24
24
  tcc: ToolCallContext,
25
25
  check: PermissionCheckResult,
26
+ platform: NodeJS.Platform,
26
27
  ): string {
27
28
  if (tcc.toolName === "bash") return check.command ?? "";
28
29
  if (tcc.toolName === "mcp") return check.target ?? "mcp";
29
30
  const path = getPathBearingToolPath(tcc.toolName, tcc.input);
30
31
  if (path === null) return "*";
31
- return normalizePathForComparison(path, tcc.cwd);
32
+ return normalizePathForComparison(path, tcc.cwd, platform);
32
33
  }
33
34
 
34
35
  /**
@@ -41,6 +42,7 @@ export function describeToolGate(
41
42
  tcc: ToolCallContext,
42
43
  check: PermissionCheckResult,
43
44
  formatter: ToolPreviewFormatter,
45
+ platform: NodeJS.Platform,
44
46
  ): GateDescriptor {
45
47
  const permissionLogContext = formatter.getPermissionLogContext(
46
48
  check,
@@ -51,7 +53,7 @@ export function describeToolGate(
51
53
  // Compute session approval suggestion for the "for this session" option.
52
54
  const suggestion = suggestSessionPattern(
53
55
  tcc.toolName,
54
- deriveSuggestionValue(tcc, check),
56
+ deriveSuggestionValue(tcc, check, platform),
55
57
  );
56
58
 
57
59
  const askMessage = formatAskPrompt(
package/src/index.ts CHANGED
@@ -42,7 +42,14 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
42
42
  // getPackageDir() is Pi's own install dir; auto-allow it for read-only tools
43
43
  // so the agent can read Pi's bundled docs/examples regardless of layout.
44
44
  const paths = computeExtensionPaths(agentDir, getPackageDir());
45
- const permissionManager = new PermissionManager({ agentDir });
45
+ // The single process.platform read for the whole extension; injected into the
46
+ // session (PathNormalizer) and, later, rule evaluation. Interior modules must
47
+ // not read process.platform (enforced by the eslint guard scoped to src/).
48
+ const hostPlatform = process.platform;
49
+ const permissionManager = new PermissionManager({
50
+ agentDir,
51
+ platform: hostPlatform,
52
+ });
46
53
  const sessionRules = new SessionRules();
47
54
  const subagentRegistry = getSubagentSessionRegistry();
48
55
  const formatterRegistry = new ToolInputFormatterRegistry();
@@ -73,6 +80,7 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
73
80
  const forwardingDeps: PermissionForwarderDeps = {
74
81
  forwardingDir: paths.forwardingDir,
75
82
  subagentSessionsDir: paths.subagentSessionsDir,
83
+ platform: hostPlatform,
76
84
  registry: subagentRegistry,
77
85
  events: pi.events,
78
86
  logger,
@@ -91,6 +99,7 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
91
99
  const gateway = new PromptingGateway({
92
100
  config: configStore,
93
101
  subagentSessionsDir: paths.subagentSessionsDir,
102
+ platform: hostPlatform,
94
103
  registry: subagentRegistry,
95
104
  prompter,
96
105
  });
@@ -100,12 +109,14 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
100
109
  new ForwardingManager(
101
110
  paths.subagentSessionsDir,
102
111
  forwarder,
112
+ hostPlatform,
103
113
  subagentRegistry,
104
114
  ),
105
115
  permissionManager,
106
116
  sessionRules,
107
117
  configStore,
108
118
  gateway,
119
+ hostPlatform,
109
120
  );
110
121
 
111
122
  // refresh() must run after `session` is assigned: a debug-write IO failure
@@ -66,13 +66,14 @@ export function normalizeInput(
66
66
  toolName: string,
67
67
  input: unknown,
68
68
  configuredMcpServerNames: readonly string[],
69
+ platform: NodeJS.Platform,
69
70
  cwd?: string,
70
71
  ): NormalizedInput {
71
72
  // --- Special surfaces (path, external_directory) ---
72
73
  if (SPECIAL_PERMISSION_KEYS.has(toolName)) {
73
74
  return {
74
75
  surface: toolName,
75
- values: normalizePathSurfaceValues(input, cwd),
76
+ values: normalizePathSurfaceValues(input, platform, cwd),
76
77
  resultExtras: {},
77
78
  };
78
79
  }
@@ -123,7 +124,7 @@ export function normalizeInput(
123
124
  if (PATH_BEARING_TOOLS.has(toolName)) {
124
125
  return {
125
126
  surface: toolName,
126
- values: normalizePathSurfaceValues(input, cwd),
127
+ values: normalizePathSurfaceValues(input, platform, cwd),
127
128
  resultExtras: {},
128
129
  };
129
130
  }
@@ -149,9 +150,13 @@ export function normalizeInput(
149
150
  * Only `input.path` is read — policy values are never sourced from any other
150
151
  * (potentially attacker-controlled) field on the raw tool input.
151
152
  */
152
- function normalizePathSurfaceValues(input: unknown, cwd?: string): string[] {
153
+ function normalizePathSurfaceValues(
154
+ input: unknown,
155
+ platform: NodeJS.Platform,
156
+ cwd?: string,
157
+ ): string[] {
153
158
  const path = getNonEmptyString(toRecord(input).path);
154
159
  if (path === null) return ["*"];
155
- const values = getPathPolicyValues(path, cwd ? { cwd } : {});
160
+ const values = getPathPolicyValues(path, cwd ? { cwd } : {}, platform);
156
161
  return values.length > 0 ? values : ["*"];
157
162
  }
@@ -0,0 +1,100 @@
1
+ import { posix as posixPath, win32 as winPath } from "node:path";
2
+
3
+ import { AccessPath } from "./access-intent/access-path";
4
+ import {
5
+ isPathOutsideWorkingDirectory,
6
+ isPathWithinDirectory,
7
+ isPiInfrastructureRead,
8
+ normalizePathForComparison,
9
+ } from "./path-utils";
10
+
11
+ /**
12
+ * Path-interpretation collaborator, constructed once at the session edge with
13
+ * the two ambient inputs — the host `platform` and the session `cwd` — baked
14
+ * in, and handed raw path tokens thereafter.
15
+ *
16
+ * The bash path pipeline and the per-tool/external-directory gates ask this
17
+ * object the platform-dependent questions ("is this path absolute *under our
18
+ * platform*?", "resolve this `cd` offset *against our cwd*") and receive
19
+ * prepared {@link AccessPath} values, instead of reading `process.platform`
20
+ * ambiently or threading `cwd` through every call. Internally it selects the
21
+ * `win32`/`posix` path flavor once and delegates to the platform-parameterized
22
+ * `path-utils` / `AccessPath` primitives.
23
+ */
24
+ export class PathNormalizer {
25
+ private readonly impl: typeof posixPath;
26
+
27
+ constructor(
28
+ private readonly platform: NodeJS.Platform,
29
+ private readonly cwd: string,
30
+ ) {
31
+ this.impl = platform === "win32" ? winPath : posixPath;
32
+ }
33
+
34
+ /** Build an AccessPath for a token, resolved against `resolveBase` (default cwd). */
35
+ forPath(pathValue: string, options?: { resolveBase?: string }): AccessPath {
36
+ return AccessPath.forPath(pathValue, {
37
+ cwd: this.cwd,
38
+ resolveBase: options?.resolveBase,
39
+ platform: this.platform,
40
+ });
41
+ }
42
+
43
+ /** Build a literal-only AccessPath (unknown base after a non-literal `cd`). */
44
+ forLiteral(literal: string): AccessPath {
45
+ return AccessPath.forLiteral(literal);
46
+ }
47
+
48
+ /** Platform-aware absoluteness (`win32` vs `posix` rules). */
49
+ isAbsolute(pathValue: string): boolean {
50
+ return this.impl.isAbsolute(pathValue);
51
+ }
52
+
53
+ /** Resolve a `cd`-folded offset against the baked cwd (platform-aware). */
54
+ resolveBase(offset: string): string {
55
+ return this.impl.resolve(this.cwd, offset);
56
+ }
57
+
58
+ /** Join a `cd` offset with a relative target (platform-aware), for cd-folding. */
59
+ joinBase(offset: string, target: string): string {
60
+ return this.impl.join(offset, target);
61
+ }
62
+
63
+ /** Containment of `pathValue` within `directory` (platform-aware). */
64
+ isWithinDirectory(pathValue: string, directory: string): boolean {
65
+ return isPathWithinDirectory(pathValue, directory, this.platform);
66
+ }
67
+
68
+ /** Canonical (symlink-resolved) outside-cwd test against the baked cwd. */
69
+ isOutsideWorkingDirectory(pathValue: string): boolean {
70
+ return isPathOutsideWorkingDirectory(pathValue, this.cwd, this.platform);
71
+ }
72
+
73
+ /**
74
+ * Lexical (not symlink-resolved) comparison value, resolved against the baked
75
+ * cwd. Mirrors the as-typed absolute form used for skill-prompt matching;
76
+ * touches no filesystem, unlike {@link forPath}'s canonical alias.
77
+ */
78
+ comparableValue(pathValue: string): string {
79
+ return normalizePathForComparison(pathValue, this.cwd, this.platform);
80
+ }
81
+
82
+ /**
83
+ * Pi infrastructure-read containment for a read-only tool, decided against
84
+ * the canonical (symlink-resolved) path and the baked cwd/platform. Takes the
85
+ * already-built {@link AccessPath} so the caller does not re-resolve it.
86
+ */
87
+ isInfrastructureRead(
88
+ toolName: string,
89
+ accessPath: AccessPath,
90
+ infraDirs: readonly string[],
91
+ ): boolean {
92
+ return isPiInfrastructureRead(
93
+ toolName,
94
+ accessPath.boundaryValue(),
95
+ infraDirs,
96
+ this.cwd,
97
+ this.platform,
98
+ );
99
+ }
100
+ }