@j0hanz/filesystem-mcp 2.6.3 → 2.7.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 (148) hide show
  1. package/README.md +28 -19
  2. package/dist/cli-help.d.ts.map +1 -1
  3. package/dist/cli-help.js +5 -2
  4. package/dist/cli-help.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +22 -3
  7. package/dist/cli.js.map +1 -1
  8. package/dist/core/concurrency.d.ts +0 -17
  9. package/dist/core/concurrency.d.ts.map +1 -1
  10. package/dist/core/concurrency.js +53 -47
  11. package/dist/core/concurrency.js.map +1 -1
  12. package/dist/core/config.d.ts +7 -0
  13. package/dist/core/config.d.ts.map +1 -1
  14. package/dist/core/config.js +7 -0
  15. package/dist/core/config.js.map +1 -1
  16. package/dist/core/diff.d.ts +0 -4
  17. package/dist/core/diff.d.ts.map +1 -1
  18. package/dist/core/diff.js +1 -15
  19. package/dist/core/diff.js.map +1 -1
  20. package/dist/core/file-uri.d.ts +9 -9
  21. package/dist/core/file-uri.d.ts.map +1 -1
  22. package/dist/core/file-uri.js +16 -11
  23. package/dist/core/file-uri.js.map +1 -1
  24. package/dist/core/fs.d.ts +1 -1
  25. package/dist/core/fs.d.ts.map +1 -1
  26. package/dist/core/fs.js +65 -56
  27. package/dist/core/fs.js.map +1 -1
  28. package/dist/core/glob.d.ts +6 -0
  29. package/dist/core/glob.d.ts.map +1 -1
  30. package/dist/core/glob.js +80 -13
  31. package/dist/core/glob.js.map +1 -1
  32. package/dist/core/input-required.d.ts +30 -13
  33. package/dist/core/input-required.d.ts.map +1 -1
  34. package/dist/core/input-required.js +35 -10
  35. package/dist/core/input-required.js.map +1 -1
  36. package/dist/core/mime.d.ts +2 -4
  37. package/dist/core/mime.d.ts.map +1 -1
  38. package/dist/core/mime.js +3 -8
  39. package/dist/core/mime.js.map +1 -1
  40. package/dist/core/path-completer.d.ts.map +1 -1
  41. package/dist/core/path-completer.js +7 -4
  42. package/dist/core/path-completer.js.map +1 -1
  43. package/dist/core/path-discovery.d.ts.map +1 -1
  44. package/dist/core/path-discovery.js +2 -2
  45. package/dist/core/path-discovery.js.map +1 -1
  46. package/dist/core/path-utils.d.ts +1 -3
  47. package/dist/core/path-utils.d.ts.map +1 -1
  48. package/dist/core/path-utils.js +0 -3
  49. package/dist/core/path-utils.js.map +1 -1
  50. package/dist/core/path.d.ts +7 -0
  51. package/dist/core/path.d.ts.map +1 -1
  52. package/dist/core/path.js +69 -26
  53. package/dist/core/path.js.map +1 -1
  54. package/dist/core/read.d.ts +1 -0
  55. package/dist/core/read.d.ts.map +1 -1
  56. package/dist/core/read.js +4 -0
  57. package/dist/core/read.js.map +1 -1
  58. package/dist/core/schema.d.ts +0 -80
  59. package/dist/core/schema.d.ts.map +1 -1
  60. package/dist/core/schema.js +0 -89
  61. package/dist/core/schema.js.map +1 -1
  62. package/dist/core/search.d.ts +8 -1
  63. package/dist/core/search.d.ts.map +1 -1
  64. package/dist/core/search.js +191 -101
  65. package/dist/core/search.js.map +1 -1
  66. package/dist/core/store.d.ts +7 -11
  67. package/dist/core/store.d.ts.map +1 -1
  68. package/dist/core/store.js +19 -21
  69. package/dist/core/store.js.map +1 -1
  70. package/dist/core/util.d.ts +17 -0
  71. package/dist/core/util.d.ts.map +1 -1
  72. package/dist/core/util.js +19 -0
  73. package/dist/core/util.js.map +1 -1
  74. package/dist/instructions.js +1 -1
  75. package/dist/instructions.js.map +1 -1
  76. package/dist/resources.d.ts.map +1 -1
  77. package/dist/resources.js +5 -2
  78. package/dist/resources.js.map +1 -1
  79. package/dist/server.d.ts.map +1 -1
  80. package/dist/server.js +8 -1
  81. package/dist/server.js.map +1 -1
  82. package/dist/tools/batch.d.ts +3 -13
  83. package/dist/tools/batch.d.ts.map +1 -1
  84. package/dist/tools/batch.js +11 -27
  85. package/dist/tools/batch.js.map +1 -1
  86. package/dist/tools/create.d.ts.map +1 -1
  87. package/dist/tools/create.js +25 -46
  88. package/dist/tools/create.js.map +1 -1
  89. package/dist/tools/define.d.ts +20 -23
  90. package/dist/tools/define.d.ts.map +1 -1
  91. package/dist/tools/define.js +11 -27
  92. package/dist/tools/define.js.map +1 -1
  93. package/dist/tools/delete.d.ts.map +1 -1
  94. package/dist/tools/delete.js +10 -37
  95. package/dist/tools/delete.js.map +1 -1
  96. package/dist/tools/diff.d.ts.map +1 -1
  97. package/dist/tools/diff.js +2 -13
  98. package/dist/tools/diff.js.map +1 -1
  99. package/dist/tools/edit.d.ts.map +1 -1
  100. package/dist/tools/edit.js +20 -53
  101. package/dist/tools/edit.js.map +1 -1
  102. package/dist/tools/find-files.d.ts.map +1 -1
  103. package/dist/tools/find-files.js +3 -28
  104. package/dist/tools/find-files.js.map +1 -1
  105. package/dist/tools/index.js +1 -1
  106. package/dist/tools/index.js.map +1 -1
  107. package/dist/tools/list-roots.d.ts.map +1 -1
  108. package/dist/tools/list-roots.js +1 -12
  109. package/dist/tools/list-roots.js.map +1 -1
  110. package/dist/tools/list.d.ts.map +1 -1
  111. package/dist/tools/list.js +19 -53
  112. package/dist/tools/list.js.map +1 -1
  113. package/dist/tools/move.d.ts.map +1 -1
  114. package/dist/tools/move.js +54 -37
  115. package/dist/tools/move.js.map +1 -1
  116. package/dist/tools/patch.d.ts.map +1 -1
  117. package/dist/tools/patch.js +4 -24
  118. package/dist/tools/patch.js.map +1 -1
  119. package/dist/tools/progress.d.ts +0 -2
  120. package/dist/tools/progress.d.ts.map +1 -1
  121. package/dist/tools/progress.js +20 -12
  122. package/dist/tools/progress.js.map +1 -1
  123. package/dist/tools/read.d.ts.map +1 -1
  124. package/dist/tools/read.js +29 -116
  125. package/dist/tools/read.js.map +1 -1
  126. package/dist/tools/replace-text.d.ts.map +1 -1
  127. package/dist/tools/replace-text.js +20 -43
  128. package/dist/tools/replace-text.js.map +1 -1
  129. package/dist/tools/search-text.d.ts.map +1 -1
  130. package/dist/tools/search-text.js +24 -78
  131. package/dist/tools/search-text.js.map +1 -1
  132. package/dist/tools/stat.d.ts.map +1 -1
  133. package/dist/tools/stat.js +5 -19
  134. package/dist/tools/stat.js.map +1 -1
  135. package/dist/transport/http-policy.d.ts.map +1 -1
  136. package/dist/transport/http-policy.js +1 -0
  137. package/dist/transport/http-policy.js.map +1 -1
  138. package/dist/transport/http.d.ts.map +1 -1
  139. package/dist/transport/http.js +16 -27
  140. package/dist/transport/http.js.map +1 -1
  141. package/dist/transport/shared.d.ts +3 -1
  142. package/dist/transport/shared.d.ts.map +1 -1
  143. package/dist/transport/shared.js +14 -1
  144. package/dist/transport/shared.js.map +1 -1
  145. package/dist/transport/stdio.d.ts.map +1 -1
  146. package/dist/transport/stdio.js +18 -3
  147. package/dist/transport/stdio.js.map +1 -1
  148. package/package.json +3 -3
package/dist/core/glob.js CHANGED
@@ -4,8 +4,10 @@ import ignore from 'ignore';
4
4
  import { processInParallel } from "./concurrency.js";
5
5
  import { formatUnknownErrorMessage } from "./errors.js";
6
6
  import { Logger } from "./observability.js";
7
- import { isWindowsDriveRelativePath, toPosixPath } from "./path-utils.js";
7
+ import { isPathInsideDirectory, isWindowsDriveRelativePath, toPosixPath } from "./path-utils.js";
8
8
  import { MIB } from "./util.js";
9
+ /** `..` bounded on both sides by a separator, a brace delimiter, or the pattern edge. */
10
+ const TRAVERSAL_DOTDOT_RE = /(?:^|[/\\{,])\.\.(?=[/\\},]|$)/u;
9
11
  export function isSafeGlobSyntax(pattern) {
10
12
  if (!pattern || pattern.trim().length === 0) {
11
13
  return false;
@@ -16,10 +18,11 @@ export function isSafeGlobSyntax(pattern) {
16
18
  if (isWindowsDriveRelativePath(pattern)) {
17
19
  return false;
18
20
  }
19
- // Covers every engine-specific traversal form too — `{a,..}` and `[..]` both
20
- // contain '..', so they are rejected here. Keep this check whole-string: the
21
- // per-form guards that used to follow it were unreachable because of it.
22
- if (pattern.includes('..')) {
21
+ // Only a whole `..` — a path segment, or one alternative of a `{a,..}`
22
+ // brace set — can traverse. `..` inside a segment (`[...slug]`, `v1..2.md`,
23
+ // `[..]`) is a literal name or a character class, and PathGuard re-checks
24
+ // containment on every resolved entry regardless.
25
+ if (TRAVERSAL_DOTDOT_RE.test(pattern)) {
23
26
  return false;
24
27
  }
25
28
  return true;
@@ -49,13 +52,56 @@ async function loadGitignoreFiles(root, gitignorePaths, manager, signal) {
49
52
  }
50
53
  }, GLOB_BATCH_CONCURRENCY, signal);
51
54
  }
55
+ /**
56
+ * Load `.gitignore` from each ancestor of `root` up to and including `ceiling`,
57
+ * farthest first. A rule set that ignores `root` itself is skipped: the caller
58
+ * named that directory on purpose, and applying the rule would empty the walk.
59
+ */
60
+ async function loadAncestorGitignores(root, ceiling, manager, signal) {
61
+ const normalizedCeiling = resolve(ceiling);
62
+ const chain = [];
63
+ for (let dir = dirname(resolve(root));; dir = dirname(dir)) {
64
+ if (!isPathInsideDirectory(normalizedCeiling, dir))
65
+ break;
66
+ chain.push(dir);
67
+ if ((isPathInsideDirectory(dir, normalizedCeiling) &&
68
+ isPathInsideDirectory(normalizedCeiling, dir)) ||
69
+ dirname(dir) === dir) {
70
+ break;
71
+ }
72
+ }
73
+ for (const dir of chain.reverse()) {
74
+ signal?.throwIfAborted();
75
+ const file = join(dir, '.gitignore');
76
+ try {
77
+ const info = await lstat(file);
78
+ if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES)
79
+ continue;
80
+ const matcher = ignore().add(await fsReadFile(file, { encoding: 'utf-8', signal }));
81
+ const prefix = toPosixPath(relative(dir, root));
82
+ if (matcher.test(`${prefix}/`).ignored)
83
+ continue;
84
+ manager.addAncestorMatcher(prefix, matcher);
85
+ }
86
+ catch (error) {
87
+ if (error instanceof Error && error.name === 'AbortError')
88
+ throw error;
89
+ // ENOENT is the normal case (no .gitignore at this level); anything else is not worth a warning per walk
90
+ }
91
+ }
92
+ }
52
93
  class GitignoreManager {
53
94
  matchers = new Map();
95
+ /** Rules from directories above the walk root, farthest first; `prefix` re-bases a walk-relative path to that directory. */
96
+ ancestors = [];
54
97
  addMatcher(dir, matcher) {
55
98
  this.matchers.set(dir, matcher);
56
99
  }
100
+ addAncestorMatcher(prefix, matcher) {
101
+ this.ancestors.push({ prefix, matcher });
102
+ }
57
103
  /** `null` when no `.gitignore` was found, so callers skip the filter entirely. */
58
- static async load(root, signal, maxDepth) {
104
+ static async load(root, signal, maxDepth, ignoreCeiling) {
59
105
  const manager = new GitignoreManager();
60
106
  try {
61
107
  const gitignorePaths = [];
@@ -64,6 +110,8 @@ class GitignoreManager {
64
110
  // Skip what the walk itself skips, and stop one level past its depth
65
111
  // bound: a .gitignore at depth d only affects entries at depth >= d.
66
112
  exclude: (entry) => {
113
+ if (signal?.aborted)
114
+ return true;
67
115
  const name = basename(entry);
68
116
  if (name === '.hg' || name === '.svn' || DEFAULT_EXCLUDED_NAMES.has(name))
69
117
  return true;
@@ -76,13 +124,16 @@ class GitignoreManager {
76
124
  gitignorePaths.push(match);
77
125
  }
78
126
  await loadGitignoreFiles(root, gitignorePaths, manager, signal);
127
+ if (ignoreCeiling !== undefined) {
128
+ await loadAncestorGitignores(root, ignoreCeiling, manager, signal);
129
+ }
79
130
  }
80
131
  catch (error) {
81
132
  if (error instanceof Error && error.name === 'AbortError')
82
133
  throw error;
83
134
  Logger.warn(`Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`);
84
135
  }
85
- return manager.matchers.size === 0 ? null : manager;
136
+ return manager.matchers.size === 0 && manager.ancestors.length === 0 ? null : manager;
86
137
  }
87
138
  isIgnored(relativePath, isDirectory) {
88
139
  const normalized = toPosixPath(relativePath);
@@ -111,6 +162,13 @@ class GitignoreManager {
111
162
  : `${posixPath}/`
112
163
  : posixPath;
113
164
  let ignored = false;
165
+ for (const { prefix, matcher } of this.ancestors) {
166
+ const res = matcher.test(`${prefix}/${pathToCheck}`);
167
+ if (res.ignored)
168
+ ignored = true;
169
+ if (res.unignored)
170
+ ignored = false;
171
+ }
114
172
  // Check root level
115
173
  const rootMatcher = this.matchers.get('');
116
174
  if (rootMatcher) {
@@ -246,8 +304,8 @@ function* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles) {
246
304
  return;
247
305
  yield { path: absolutePath, dirent: match };
248
306
  }
249
- function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth) {
250
- if (!skipIgnored && maxDepth === undefined)
307
+ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal) {
308
+ if (!skipIgnored && maxDepth === undefined && signal === undefined)
251
309
  return undefined;
252
310
  // fs.glob can hand the predicate a dirent whose parentPath is "." — the walk
253
311
  // root, not the process cwd — when it re-visits a directory under `**` whose
@@ -261,6 +319,10 @@ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth) {
261
319
  (gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));
262
320
  return {
263
321
  prune: (match) => {
322
+ // fs.glob takes no signal and calls this for every entry it visits, so
323
+ // pruning everything is the only way to stop a walk that yields nothing.
324
+ if (signal?.aborted)
325
+ return true;
264
326
  const posixRel = relativeOf(match);
265
327
  const isDir = match.isDirectory();
266
328
  if (excluded(posixRel, isDir))
@@ -275,7 +337,7 @@ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth) {
275
337
  isExcluded: (match) => excluded(relativeOf(match), match.isDirectory()),
276
338
  };
277
339
  }
278
- async function* processGlobPattern(pattern, plan, seen, onlyFiles, filter) {
340
+ async function* processGlobPattern(pattern, plan, seen, onlyFiles, filter, signal) {
279
341
  const { cwd, maxDepth, suppressErrors } = plan;
280
342
  let iterable;
281
343
  try {
@@ -292,6 +354,8 @@ async function* processGlobPattern(pattern, plan, seen, onlyFiles, filter) {
292
354
  }
293
355
  try {
294
356
  for await (const match of iterable) {
357
+ if (signal?.aborted)
358
+ break;
295
359
  // A function `exclude` only prunes descent in fs.glob — it still yields
296
360
  // the rejected dirent itself, and any rejected entry below the top level.
297
361
  // Re-apply the ignore rules (not the depth bound) to drop those.
@@ -305,17 +369,20 @@ async function* processGlobPattern(pattern, plan, seen, onlyFiles, filter) {
305
369
  throw error;
306
370
  Logger.warn(`globEntries: suppressed mid-walk error for pattern "${pattern}": ${formatUnknownErrorMessage(error)}`);
307
371
  }
372
+ // A pruned walk ends like a finished one. Say it was cut short, so no caller
373
+ // reads "the walk ended" as "the whole tree was seen".
374
+ signal?.throwIfAborted();
308
375
  }
309
376
  export async function* globEntries(options) {
310
377
  const gitignoreMatcher = options.skipIgnored
311
- ? await GitignoreManager.load(options.cwd, options.signal, options.maxDepth)
378
+ ? await GitignoreManager.load(options.cwd, options.signal, options.maxDepth, options.ignoreCeiling)
312
379
  : null;
313
380
  const plan = normalizeGlobOptions(options);
314
381
  const seen = new Set();
315
382
  const onlyFiles = options.onlyFiles ?? true;
316
- const filter = createWalkFilter(plan.cwd, options.skipIgnored ?? false, gitignoreMatcher, plan.maxDepth);
383
+ const filter = createWalkFilter(plan.cwd, options.skipIgnored ?? false, gitignoreMatcher, plan.maxDepth, options.signal);
317
384
  for (const pattern of plan.patterns) {
318
- yield* processGlobPattern(pattern, plan, seen, onlyFiles, filter);
385
+ yield* processGlobPattern(pattern, plan, seen, onlyFiles, filter, options.signal);
319
386
  }
320
387
  }
321
388
  /** Names a `skipIgnored` walk never enters or yields, at any depth. */
@@ -1 +1 @@
1
- {"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGnF,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,MAA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ACX,OAAO;IACP,OAAO;IACP,SAAS;IACT,aAAa;IACb,QAAQ;IACR,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,KAAK;IACL,KAAK;IACL,OAAO;IACP,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;CACZ,CAAC,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile, lstat } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.ts';\nimport { formatUnknownErrorMessage } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport type { DirentLike } from './path-utils.ts';\nimport { isWindowsDriveRelativePath, toPosixPath } from './path-utils.ts';\nimport { MIB } from './util.ts';\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n if (isAbsolute(pattern)) {\n return false;\n }\n if (isWindowsDriveRelativePath(pattern)) {\n return false;\n }\n // Covers every engine-specific traversal form too — `{a,..}` and `[..]` both\n // contain '..', so they are rejected here. Keep this check whole-string: the\n // per-form guards that used to follow it were unreachable because of it.\n if (pattern.includes('..')) {\n return false;\n }\n return true;\n}\n\n/** A .gitignore past this size is not a .gitignore; skip it rather than read it. */\nconst MAX_GITIGNORE_BYTES = MIB;\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n // lstat, not stat: a symlinked .gitignore may point at a device, a\n // FIFO or a huge file outside the root. Only a plain, small file is a\n // rule set worth reading.\n const info = await lstat(absPath);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) return;\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\nclass GitignoreManager {\n private matchers = new Map<string, Ignore>();\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n /** `null` when no `.gitignore` was found, so callers skip the filter entirely. */\n static async load(\n root: string,\n signal?: AbortSignal,\n maxDepth?: number,\n ): Promise<GitignoreManager | null> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n const gitignoreEntries = fsGlob('**/.gitignore', {\n cwd: root,\n // Skip what the walk itself skips, and stop one level past its depth\n // bound: a .gitignore at depth d only affects entries at depth >= d.\n exclude: (entry: string) => {\n const name = basename(entry);\n if (name === '.hg' || name === '.svn' || DEFAULT_EXCLUDED_NAMES.has(name)) return true;\n return maxDepth !== undefined && toPosixPath(entry).split('/').length - 1 > maxDepth;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager.matchers.size === 0 ? null : manager;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkPath(currentDir, true)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return this.checkPath(normalized, isDirectory);\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n /** Skip what a walk should not surface: DEFAULT_EXCLUDED_NAMES and .gitignore. */\n skipIgnored?: boolean;\n /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */\n signal?: AbortSignal;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nconst DOT_CHAR_CODE = 46;\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n if (original && original.charCodeAt(0) !== DOT_CHAR_CODE) {\n const newSegments = [...segments];\n newSegments[idx] = `.${original}`;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere.\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const addDotFile = afterGlobstar.length > 0 && afterGlobstar.charCodeAt(0) !== DOT_CHAR_CODE;\n if (addDotFile) patterns.add(`${prefix}**/.${afterGlobstar}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const absolutePath = resolve(cwd, match.parentPath, match.name);\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\ninterface WalkFilter {\n /** Given to fs.glob: true stops descent into a directory. */\n prune: (match: GlobDirentLike) => boolean;\n /** Re-applied to yielded entries: the ignore rules only, never the depth bound. */\n isExcluded: (match: GlobDirentLike) => boolean;\n}\n\nfunction createWalkFilter(\n cwd: string,\n skipIgnored: boolean,\n gitignoreMatcher: GitignoreManager | null,\n maxDepth: number | undefined,\n): WalkFilter | undefined {\n if (!skipIgnored && maxDepth === undefined) return undefined;\n\n // fs.glob can hand the predicate a dirent whose parentPath is \".\" — the walk\n // root, not the process cwd — when it re-visits a directory under `**` whose\n // name also exists in the process cwd. Resolving against `cwd` names the\n // entry the dirent describes; `join` would resolve it against the process.\n const relativeOf = (match: GlobDirentLike): string =>\n toPosixPath(relative(cwd, resolve(cwd, match.parentPath, match.name)));\n // Every default exclude is a bare name that applies at any depth, so a Set\n // lookup per segment replaces compiling dozens of globs per entry.\n const excluded = (posixRel: string, isDir: boolean): boolean =>\n skipIgnored &&\n (posixRel.split('/').some((segment) => DEFAULT_EXCLUDED_NAMES.has(segment)) ||\n (gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));\n\n return {\n prune: (match) => {\n const posixRel = relativeOf(match);\n const isDir = match.isDirectory();\n if (excluded(posixRel, isDir)) return true;\n // Stop descent one level past the depth bound. Pruning a directory *at*\n // the bound would drop it where fs.glob treats it as top-level, so prune\n // its children instead; processDirentMatch drops that extra level.\n if (maxDepth === undefined || !isDir) return false;\n return posixRel.split('/').length - 1 > maxDepth;\n },\n isExcluded: (match) => excluded(relativeOf(match), match.isDirectory()),\n };\n}\n\nasync function* processGlobPattern(\n pattern: string,\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n filter: WalkFilter | undefined,\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob(pattern, {\n cwd,\n ...(filter ? { exclude: filter.prune } : {}),\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n // A function `exclude` only prunes descent in fs.glob — it still yields\n // the rejected dirent itself, and any rejected entry below the top level.\n // Re-apply the ignore rules (not the depth bound) to drop those.\n if (filter?.isExcluded(match)) continue;\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${pattern}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n const gitignoreMatcher = options.skipIgnored\n ? await GitignoreManager.load(options.cwd, options.signal, options.maxDepth)\n : null;\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const filter = createWalkFilter(\n plan.cwd,\n options.skipIgnored ?? false,\n gitignoreMatcher,\n plan.maxDepth,\n );\n\n for (const pattern of plan.patterns) {\n yield* processGlobPattern(pattern, plan, seen, onlyFiles, filter);\n }\n}\n\n/** Names a `skipIgnored` walk never enters or yields, at any depth. */\nconst DEFAULT_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n '.git',\n '.vscode',\n '.idea',\n '.DS_Store',\n '.next',\n '.nuxt',\n '.output',\n '.svelte-kit',\n '.cache',\n '.yarn',\n 'jspm_packages',\n 'bower_components',\n 'out',\n 'tmp',\n '.temp',\n 'npm-debug.log',\n 'yarn-debug.log',\n 'yarn-error.log',\n 'Thumbs.db',\n]);\n"]}
1
+ {"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGnF,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EAAE,GAAG,EAAE,MAAM,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N,OAAO;IACP,UAAU;IACV,MAAM;IACN,SAAS;IACT,OAAO;IACP,WAAW;IACX,OAAO;IACP,OAAO;IACP,SAAS;IACT,aAAa;IACb,QAAQ;IACR,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,KAAK;IACL,KAAK;IACL,OAAO;IACP,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;CACZ,CAAC,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile, lstat } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.ts';\nimport { formatUnknownErrorMessage } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport type { DirentLike } from './path-utils.ts';\nimport { isPathInsideDirectory, isWindowsDriveRelativePath, toPosixPath } from './path-utils.ts';\nimport { MIB } from './util.ts';\n\n/** `..` bounded on both sides by a separator, a brace delimiter, or the pattern edge. */\nconst TRAVERSAL_DOTDOT_RE = /(?:^|[/\\\\{,])\\.\\.(?=[/\\\\},]|$)/u;\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n if (isAbsolute(pattern)) {\n return false;\n }\n if (isWindowsDriveRelativePath(pattern)) {\n return false;\n }\n // Only a whole `..` — a path segment, or one alternative of a `{a,..}`\n // brace set — can traverse. `..` inside a segment (`[...slug]`, `v1..2.md`,\n // `[..]`) is a literal name or a character class, and PathGuard re-checks\n // containment on every resolved entry regardless.\n if (TRAVERSAL_DOTDOT_RE.test(pattern)) {\n return false;\n }\n return true;\n}\n\n/** A .gitignore past this size is not a .gitignore; skip it rather than read it. */\nconst MAX_GITIGNORE_BYTES = MIB;\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n // lstat, not stat: a symlinked .gitignore may point at a device, a\n // FIFO or a huge file outside the root. Only a plain, small file is a\n // rule set worth reading.\n const info = await lstat(absPath);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) return;\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\n/**\n * Load `.gitignore` from each ancestor of `root` up to and including `ceiling`,\n * farthest first. A rule set that ignores `root` itself is skipped: the caller\n * named that directory on purpose, and applying the rule would empty the walk.\n */\nasync function loadAncestorGitignores(\n root: string,\n ceiling: string,\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n const normalizedCeiling = resolve(ceiling);\n const chain: string[] = [];\n for (let dir = dirname(resolve(root)); ; dir = dirname(dir)) {\n if (!isPathInsideDirectory(normalizedCeiling, dir)) break;\n chain.push(dir);\n if (\n (isPathInsideDirectory(dir, normalizedCeiling) &&\n isPathInsideDirectory(normalizedCeiling, dir)) ||\n dirname(dir) === dir\n ) {\n break;\n }\n }\n for (const dir of chain.reverse()) {\n signal?.throwIfAborted();\n const file = join(dir, '.gitignore');\n try {\n const info = await lstat(file);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) continue;\n const matcher = ignore().add(await fsReadFile(file, { encoding: 'utf-8', signal }));\n const prefix = toPosixPath(relative(dir, root));\n if (matcher.test(`${prefix}/`).ignored) continue;\n manager.addAncestorMatcher(prefix, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n // ENOENT is the normal case (no .gitignore at this level); anything else is not worth a warning per walk\n }\n }\n}\n\nclass GitignoreManager {\n private matchers = new Map<string, Ignore>();\n /** Rules from directories above the walk root, farthest first; `prefix` re-bases a walk-relative path to that directory. */\n private ancestors: { prefix: string; matcher: Ignore }[] = [];\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n addAncestorMatcher(prefix: string, matcher: Ignore): void {\n this.ancestors.push({ prefix, matcher });\n }\n\n /** `null` when no `.gitignore` was found, so callers skip the filter entirely. */\n static async load(\n root: string,\n signal?: AbortSignal,\n maxDepth?: number,\n ignoreCeiling?: string,\n ): Promise<GitignoreManager | null> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n const gitignoreEntries = fsGlob('**/.gitignore', {\n cwd: root,\n // Skip what the walk itself skips, and stop one level past its depth\n // bound: a .gitignore at depth d only affects entries at depth >= d.\n exclude: (entry: string) => {\n if (signal?.aborted) return true;\n const name = basename(entry);\n if (name === '.hg' || name === '.svn' || DEFAULT_EXCLUDED_NAMES.has(name)) return true;\n return maxDepth !== undefined && toPosixPath(entry).split('/').length - 1 > maxDepth;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n if (ignoreCeiling !== undefined) {\n await loadAncestorGitignores(root, ignoreCeiling, manager, signal);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager.matchers.size === 0 && manager.ancestors.length === 0 ? null : manager;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkPath(currentDir, true)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return this.checkPath(normalized, isDirectory);\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n for (const { prefix, matcher } of this.ancestors) {\n const res = matcher.test(`${prefix}/${pathToCheck}`);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n /** Skip what a walk should not surface: DEFAULT_EXCLUDED_NAMES and .gitignore. */\n skipIgnored?: boolean;\n /**\n * Topmost directory whose `.gitignore` may apply to this walk — the allowed\n * root containing `cwd`. Ancestors of `cwd` up to and including it are\n * consulted; nothing above it is ever read. Ignored without `skipIgnored`.\n */\n ignoreCeiling?: string;\n /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */\n signal?: AbortSignal;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nconst DOT_CHAR_CODE = 46;\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n if (original && original.charCodeAt(0) !== DOT_CHAR_CODE) {\n const newSegments = [...segments];\n newSegments[idx] = `.${original}`;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere.\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const addDotFile = afterGlobstar.length > 0 && afterGlobstar.charCodeAt(0) !== DOT_CHAR_CODE;\n if (addDotFile) patterns.add(`${prefix}**/.${afterGlobstar}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const absolutePath = resolve(cwd, match.parentPath, match.name);\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\ninterface WalkFilter {\n /** Given to fs.glob: true stops descent into a directory. */\n prune: (match: GlobDirentLike) => boolean;\n /** Re-applied to yielded entries: the ignore rules only, never the depth bound. */\n isExcluded: (match: GlobDirentLike) => boolean;\n}\n\nfunction createWalkFilter(\n cwd: string,\n skipIgnored: boolean,\n gitignoreMatcher: GitignoreManager | null,\n maxDepth: number | undefined,\n signal: AbortSignal | undefined,\n): WalkFilter | undefined {\n if (!skipIgnored && maxDepth === undefined && signal === undefined) return undefined;\n\n // fs.glob can hand the predicate a dirent whose parentPath is \".\" — the walk\n // root, not the process cwd — when it re-visits a directory under `**` whose\n // name also exists in the process cwd. Resolving against `cwd` names the\n // entry the dirent describes; `join` would resolve it against the process.\n const relativeOf = (match: GlobDirentLike): string =>\n toPosixPath(relative(cwd, resolve(cwd, match.parentPath, match.name)));\n // Every default exclude is a bare name that applies at any depth, so a Set\n // lookup per segment replaces compiling dozens of globs per entry.\n const excluded = (posixRel: string, isDir: boolean): boolean =>\n skipIgnored &&\n (posixRel.split('/').some((segment) => DEFAULT_EXCLUDED_NAMES.has(segment)) ||\n (gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));\n\n return {\n prune: (match) => {\n // fs.glob takes no signal and calls this for every entry it visits, so\n // pruning everything is the only way to stop a walk that yields nothing.\n if (signal?.aborted) return true;\n const posixRel = relativeOf(match);\n const isDir = match.isDirectory();\n if (excluded(posixRel, isDir)) return true;\n // Stop descent one level past the depth bound. Pruning a directory *at*\n // the bound would drop it where fs.glob treats it as top-level, so prune\n // its children instead; processDirentMatch drops that extra level.\n if (maxDepth === undefined || !isDir) return false;\n return posixRel.split('/').length - 1 > maxDepth;\n },\n isExcluded: (match) => excluded(relativeOf(match), match.isDirectory()),\n };\n}\n\nasync function* processGlobPattern(\n pattern: string,\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n filter: WalkFilter | undefined,\n signal: AbortSignal | undefined,\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob(pattern, {\n cwd,\n ...(filter ? { exclude: filter.prune } : {}),\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n if (signal?.aborted) break;\n // A function `exclude` only prunes descent in fs.glob — it still yields\n // the rejected dirent itself, and any rejected entry below the top level.\n // Re-apply the ignore rules (not the depth bound) to drop those.\n if (filter?.isExcluded(match)) continue;\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${pattern}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n // A pruned walk ends like a finished one. Say it was cut short, so no caller\n // reads \"the walk ended\" as \"the whole tree was seen\".\n signal?.throwIfAborted();\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n const gitignoreMatcher = options.skipIgnored\n ? await GitignoreManager.load(\n options.cwd,\n options.signal,\n options.maxDepth,\n options.ignoreCeiling,\n )\n : null;\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const filter = createWalkFilter(\n plan.cwd,\n options.skipIgnored ?? false,\n gitignoreMatcher,\n plan.maxDepth,\n options.signal,\n );\n\n for (const pattern of plan.patterns) {\n yield* processGlobPattern(pattern, plan, seen, onlyFiles, filter, options.signal);\n }\n}\n\n/** Names a `skipIgnored` walk never enters or yields, at any depth. */\nconst DEFAULT_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n '.git',\n '.vscode',\n '.idea',\n '.DS_Store',\n '.next',\n '.nuxt',\n '.output',\n '.svelte-kit',\n '.cache',\n '.yarn',\n 'jspm_packages',\n 'bower_components',\n 'out',\n 'tmp',\n '.temp',\n 'npm-debug.log',\n 'yarn-debug.log',\n 'yarn-error.log',\n 'Thumbs.db',\n]);\n"]}
@@ -10,6 +10,27 @@ type PendingOp = 'delete' | 'move' | 'copy' | 'create' | 'grant';
10
10
  export interface PendingState {
11
11
  readonly op: PendingOp;
12
12
  readonly paths: readonly string[];
13
+ /**
14
+ * Set on the state of a round minted because the previous round's answer
15
+ * was dropped by the SDK (`droppedInputResponseKeys`). Sealed in the HMAC
16
+ * payload, so a client cannot clear it: the re-issue happens once.
17
+ */
18
+ readonly reissued?: true;
19
+ }
20
+ /** The per-round confirmation context; `ToolCtx` satisfies it structurally. */
21
+ export interface PendingCtx {
22
+ readonly requestState?: (() => PendingState | undefined) | undefined;
23
+ /**
24
+ * What the client declared it can do, or `undefined` when this connection
25
+ * cannot say. Only positively-absent form support short-circuits; see
26
+ * {@link assertCanElicit}.
27
+ */
28
+ readonly clientCapabilities?: ClientCapabilities | undefined;
29
+ /** `ctx.mcpReq.droppedInputResponseKeys` for this round; see `ToolCtx`. */
30
+ readonly droppedInputResponseKeys?: readonly string[] | undefined;
31
+ readonly inputResponses?: Record<string, unknown> | undefined;
32
+ /** The live handler context; the codec binds the minted state to its method and caller. */
33
+ readonly serverCtx: ServerContext;
13
34
  }
14
35
  /** One embedded form-mode confirmation, keyed within the call. */
15
36
  export interface PendingInput {
@@ -54,23 +75,15 @@ export declare function buildInputRequired(pending: PendingState, inputs: readon
54
75
  * matching same-op retry so the caller proceeds.
55
76
  *
56
77
  * One home for the R9 binding check means a future fix cannot miss two of three
57
- * sites. The caller supplies `buildInputs` so only the prompt text varies.
78
+ * sites. The caller passes the round's `PendingCtx` and supplies `buildInputs`
79
+ * so only the prompt text varies.
58
80
  */
59
81
  interface PendingRoundTripOpts {
60
82
  readonly op: PendingOp;
61
83
  readonly pending: readonly string[];
62
- readonly requestState: (() => PendingState | undefined) | undefined;
63
- /**
64
- * What the client declared it can do, or `undefined` when this connection
65
- * cannot say. Only a positively-absent `elicitation` short-circuits; see
66
- * {@link assertCanElicit}.
67
- */
68
- readonly clientCapabilities?: ClientCapabilities | undefined;
69
84
  readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];
70
- /** The live handler context; the codec binds the minted state to its method and caller. */
71
- readonly serverCtx: ServerContext;
72
85
  }
73
- export declare function pendingRoundTrip(opts: PendingRoundTripOpts): Promise<InputRequiredResult | undefined>;
86
+ export declare function pendingRoundTrip(ctx: PendingCtx, opts: PendingRoundTripOpts): Promise<InputRequiredResult | undefined>;
74
87
  /**
75
88
  * Round-trip key for `pendingSorted[index]` — the single home of the
76
89
  * `confirm_${i}` convention. The build side mints it with the map index; the
@@ -114,7 +127,11 @@ export declare function readAcceptedChoice(responses: Record<string, unknown> |
114
127
  * expected set before acting.
115
128
  */
116
129
  export declare function readAcceptedMultiChoice(responses: Record<string, unknown> | undefined, key: string): string[] | undefined;
117
- /** Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader returned nothing. */
118
- export declare function describeRefusal(responses: Record<string, unknown> | undefined, key: string): string;
130
+ /**
131
+ * Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader
132
+ * returned nothing. Pass the round's ctx so a dropped answer is named as such
133
+ * rather than as 'not answered'.
134
+ */
135
+ export declare function describeRefusal(ctx: Pick<PendingCtx, 'inputResponses' | 'droppedInputResponseKeys'>, key: string): string;
119
136
  export {};
120
137
  //# sourceMappingURL=input-required.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.d.ts","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,kBAAkB,EAElB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACd,MAAM,8BAA8B,CAAC;AAetC,mEAAmE;AACnE,KAAK,SAAS,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC;AAEjE;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,EAAE,SAAS,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAED,kEAAkE;A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AED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,OAAO,CAET;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,MAAM,GAAG,SAAS,CAEpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,MAAM,EAAE,GAAG,SAAS,CAEtB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,IAAI,CAAC,UAAU,EAAE,gBAAgB,GAAG,0BAA0B,CAAC,EACpE,GAAG,EAAE,MAAM,GACV,MAAM,CASR"}
@@ -80,7 +80,11 @@ export async function buildInputRequired(pending, inputs, ctx) {
80
80
  requestedSchema: requestedSchemaFor(input),
81
81
  });
82
82
  }
83
- const requestState = await requestStateCodec.mint({ op: pending.op, paths: [...pending.paths].sort() }, ctx);
83
+ const requestState = await requestStateCodec.mint({
84
+ op: pending.op,
85
+ paths: [...pending.paths].sort(),
86
+ ...(pending.reissued ? { reissued: true } : {}),
87
+ }, ctx);
84
88
  return inputRequired({ inputRequests, requestState });
85
89
  }
86
90
  /**
@@ -101,7 +105,7 @@ const NO_ELICITATION_HINT = {
101
105
  'Call list_roots and use a path under one of the roots it returns.',
102
106
  };
103
107
  /**
104
- * Fail early, and legibly, when the client cannot answer an embedded request.
108
+ * Fail early, and legibly, when the client cannot answer an embedded form.
105
109
  * The SDK checks each `inputRequests` entry against the declared client
106
110
  * capabilities and rejects the whole call with `-32021` before anything reaches
107
111
  * the wire — a protocol error the model never sees. Throwing `FsError` here
@@ -115,12 +119,15 @@ const NO_ELICITATION_HINT = {
115
119
  function assertCanElicit(op, capabilities) {
116
120
  if (capabilities === undefined)
117
121
  return;
118
- if (capabilities.elicitation !== undefined)
122
+ const elicitation = capabilities.elicitation;
123
+ if (elicitation !== undefined &&
124
+ (elicitation.form !== undefined || elicitation.url === undefined)) {
119
125
  return;
126
+ }
120
127
  throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);
121
128
  }
122
- export async function pendingRoundTrip(opts) {
123
- const state = opts.requestState?.();
129
+ export async function pendingRoundTrip(ctx, opts) {
130
+ const state = ctx.requestState?.();
124
131
  // No verified state yet, OR the verified state belongs to a different
125
132
  // flow (e.g. an access-grant round's state is still the retried request's
126
133
  // requestState after the grant was applied, and this call is now the
@@ -129,13 +136,24 @@ export async function pendingRoundTrip(opts) {
129
136
  // input_required rather than treating a foreign-but-valid state as a
130
137
  // tamper/mismatch error.
131
138
  if (state?.op !== opts.op) {
132
- assertCanElicit(opts.op, opts.clientCapabilities);
133
- return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending), opts.serverCtx);
139
+ assertCanElicit(opts.op, ctx.clientCapabilities);
140
+ return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending), ctx.serverCtx);
134
141
  }
135
142
  // Retry for THIS op (R9): the verified state must bind the same pending set.
136
143
  if (!pathsEqual(state.paths, opts.pending)) {
137
144
  throw new FsError(ErrorCode.INVALID_INPUT, `${opts.op}: confirmation does not match the requested paths`);
138
145
  }
146
+ // The client answered, but in a shape the SDK discards before the handler
147
+ // runs (`{ method, result }` around the bare result). Ask the same question
148
+ // once more rather than report a refusal the user never made; the sealed
149
+ // `reissued` flag stops a second retry from looping.
150
+ if (state.reissued !== true && ctx.droppedInputResponseKeys?.length) {
151
+ const dropped = new Set(ctx.droppedInputResponseKeys);
152
+ const inputs = opts.buildInputs(opts.pending);
153
+ if (inputs.some((input) => dropped.has(input.key))) {
154
+ return buildInputRequired({ op: opts.op, paths: opts.pending, reissued: true }, inputs, ctx.serverCtx);
155
+ }
156
+ }
139
157
  return undefined;
140
158
  }
141
159
  /**
@@ -189,9 +207,16 @@ export function readAcceptedChoice(responses, key) {
189
207
  export function readAcceptedMultiChoice(responses, key) {
190
208
  return acceptedContent(responses, key, MultiChoiceContent)?.choice;
191
209
  }
192
- /** Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader returned nothing. */
193
- export function describeRefusal(responses, key) {
194
- const view = inputResponse(responses, key);
210
+ /**
211
+ * Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader
212
+ * returned nothing. Pass the round's ctx so a dropped answer is named as such
213
+ * rather than as 'not answered'.
214
+ */
215
+ export function describeRefusal(ctx, key) {
216
+ if (ctx.droppedInputResponseKeys?.includes(key)) {
217
+ return 'answered in a shape this server cannot read (a wrapped result instead of the bare elicitation result), twice';
218
+ }
219
+ const view = inputResponse(ctx.inputResponses, key);
195
220
  if (view.kind !== 'elicit')
196
221
  return 'not answered';
197
222
  if (view.action === 'decline')
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAmC5C;;;;;;;GAOG;AACH,SAAS,yBAAyB;IAChC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAChD,IAAI,GAAG,EAAE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the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n inputResponse,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.ts';\nimport { Logger } from './observability.ts';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'create' | 'grant';\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\nexport interface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a single-select enum (`choice` field) over\n * these values instead of a boolean `confirm`.\n */\n readonly choices?: readonly string[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n/**\n * What a minted `requestState` is bound to: the JSON-RPC method of the\n * request that minted it and the authenticated caller (`ctx.http` is absent\n * on stdio, so the caller part is empty there and constant across rounds).\n * The SDK stores an HMAC tag of this value in the token and refuses an echo\n * whose context yields a different value.\n */\nfunction requestStateBinding(ctx: ServerContext): string {\n return `${ctx.mcpReq.method}\\0${ctx.http?.authInfo?.clientId ?? ''}`;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> =\n createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n bind: requestStateBinding,\n });\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check. `buildInputRequired` reuses\n// `ConfirmContent` as the no-choices form schema (below), so these sit above it.\nconst ConfirmContent = z.object({ confirm: z.boolean().meta({ title: 'Confirm' }) });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * The form the client renders for one pending input, as the Zod schema the\n * SDK converts to the elicitation wire shape. A boolean `confirm` when no\n * choices are offered; otherwise a `choice` enum over the offered values,\n * wrapped in an array for multi-select so the client may accept a subset.\n * The offered lists are never empty by construction (single-select always\n * offers two literals; multi-select only runs with two or more grant dirs),\n * so no empty-array guard is added. Each field carries a `title` so a host\n * that renders the form labels it instead of showing the property name.\n */\nfunction requestedSchemaFor(input: PendingInput): z.ZodObject {\n if (!input.choices) return ConfirmContent;\n const value = z.enum(input.choices);\n return z.object({\n choice: input.multi ? z.array(value).meta({ title: 'Allow' }) : value.meta({ title: 'Action' }),\n });\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n ctx: ServerContext,\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema: requestedSchemaFor(input),\n });\n }\n const requestState = await requestStateCodec.mint(\n { op: pending.op, paths: [...pending.paths].sort() },\n ctx,\n );\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller supplies `buildInputs` so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly requestState: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only a positively-absent `elicitation` short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n /** The live handler context; the codec binds the minted state to its method and caller. */\n readonly serverCtx: ServerContext;\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n create:\n 'Overwriting an existing file needs a confirmation this client cannot show. ' +\n 'Pass overwrite: true on that entry to replace it without confirming, append: true to add to it, or read it and use edit.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded request.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n if (capabilities.elicitation !== undefined) return;\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = opts.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, opts.clientCapabilities);\n return buildInputRequired(\n { op: opts.op, paths: opts.pending },\n opts.buildInputs(opts.pending),\n opts.serverCtx,\n );\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n return undefined;\n}\n\n/**\n * Round-trip key for `pendingSorted[index]` — the single home of the\n * `confirm_${i}` convention. The build side mints it with the map index; the\n * read side re-derives it from the same sorted pending set the requestState\n * binds (R9), so a format change lands here once instead of at six call\n * sites.\n */\nexport function confirmKey(index: number): string {\n return `confirm_${index}`;\n}\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/** Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader returned nothing. */\nexport function describeRefusal(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string {\n const view = inputResponse(responses, key);\n if (view.kind !== 'elicit') return 'not answered';\n if (view.action === 'decline') return 'declined by the user';\n if (view.action === 'cancel') return 'dismissed by the user';\n return 'answered without a valid choice';\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n // The length check is load-bearing, not an early-out: `every` alone returns\n // true whenever `a` is a prefix of a longer `b`, so a confirmation minted for\n // ['/x'] would authorize a retry for ['/x', '/y'] — a direct R9 bypass.\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n"]}
1
+ {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAA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C,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChF,CAAC","sourcesContent":["// Shared infrastructure for the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n inputResponse,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.ts';\nimport { Logger } from './observability.ts';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'create' | 'grant';\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n /**\n * Set on the state of a round minted because the previous round's answer\n * was dropped by the SDK (`droppedInputResponseKeys`). Sealed in the HMAC\n * payload, so a client cannot clear it: the re-issue happens once.\n */\n readonly reissued?: true;\n}\n\n/** The per-round confirmation context; `ToolCtx` satisfies it structurally. */\nexport interface PendingCtx {\n readonly requestState?: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only positively-absent form support short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n /** `ctx.mcpReq.droppedInputResponseKeys` for this round; see `ToolCtx`. */\n readonly droppedInputResponseKeys?: readonly string[] | undefined;\n readonly inputResponses?: Record<string, unknown> | undefined;\n /** The live handler context; the codec binds the minted state to its method and caller. */\n readonly serverCtx: ServerContext;\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\nexport interface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a single-select enum (`choice` field) over\n * these values instead of a boolean `confirm`.\n */\n readonly choices?: readonly string[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n/**\n * What a minted `requestState` is bound to: the JSON-RPC method of the\n * request that minted it and the authenticated caller (`ctx.http` is absent\n * on stdio, so the caller part is empty there and constant across rounds).\n * The SDK stores an HMAC tag of this value in the token and refuses an echo\n * whose context yields a different value.\n */\nfunction requestStateBinding(ctx: ServerContext): string {\n return `${ctx.mcpReq.method}\\0${ctx.http?.authInfo?.clientId ?? ''}`;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> =\n createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n bind: requestStateBinding,\n });\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check. `buildInputRequired` reuses\n// `ConfirmContent` as the no-choices form schema (below), so these sit above it.\nconst ConfirmContent = z.object({ confirm: z.boolean().meta({ title: 'Confirm' }) });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * The form the client renders for one pending input, as the Zod schema the\n * SDK converts to the elicitation wire shape. A boolean `confirm` when no\n * choices are offered; otherwise a `choice` enum over the offered values,\n * wrapped in an array for multi-select so the client may accept a subset.\n * The offered lists are never empty by construction (single-select always\n * offers two literals; multi-select only runs with two or more grant dirs),\n * so no empty-array guard is added. Each field carries a `title` so a host\n * that renders the form labels it instead of showing the property name.\n */\nfunction requestedSchemaFor(input: PendingInput): z.ZodObject {\n if (!input.choices) return ConfirmContent;\n const value = z.enum(input.choices);\n return z.object({\n choice: input.multi ? z.array(value).meta({ title: 'Allow' }) : value.meta({ title: 'Action' }),\n });\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n ctx: ServerContext,\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema: requestedSchemaFor(input),\n });\n }\n const requestState = await requestStateCodec.mint(\n {\n op: pending.op,\n paths: [...pending.paths].sort(),\n ...(pending.reissued ? { reissued: true as const } : {}),\n },\n ctx,\n );\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller passes the round's `PendingCtx` and supplies `buildInputs`\n * so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n create:\n 'Overwriting an existing file needs a confirmation this client cannot show. ' +\n 'Pass overwrite: true on that entry to replace it without confirming, append: true to add to it, or read it and use edit.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded form.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n const elicitation = capabilities.elicitation;\n if (\n elicitation !== undefined &&\n (elicitation.form !== undefined || elicitation.url === undefined)\n ) {\n return;\n }\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n ctx: PendingCtx,\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = ctx.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, ctx.clientCapabilities);\n return buildInputRequired(\n { op: opts.op, paths: opts.pending },\n opts.buildInputs(opts.pending),\n ctx.serverCtx,\n );\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n // The client answered, but in a shape the SDK discards before the handler\n // runs (`{ method, result }` around the bare result). Ask the same question\n // once more rather than report a refusal the user never made; the sealed\n // `reissued` flag stops a second retry from looping.\n if (state.reissued !== true && ctx.droppedInputResponseKeys?.length) {\n const dropped = new Set(ctx.droppedInputResponseKeys);\n const inputs = opts.buildInputs(opts.pending);\n if (inputs.some((input) => dropped.has(input.key))) {\n return buildInputRequired(\n { op: opts.op, paths: opts.pending, reissued: true },\n inputs,\n ctx.serverCtx,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Round-trip key for `pendingSorted[index]` — the single home of the\n * `confirm_${i}` convention. The build side mints it with the map index; the\n * read side re-derives it from the same sorted pending set the requestState\n * binds (R9), so a format change lands here once instead of at six call\n * sites.\n */\nexport function confirmKey(index: number): string {\n return `confirm_${index}`;\n}\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/**\n * Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader\n * returned nothing. Pass the round's ctx so a dropped answer is named as such\n * rather than as 'not answered'.\n */\nexport function describeRefusal(\n ctx: Pick<PendingCtx, 'inputResponses' | 'droppedInputResponseKeys'>,\n key: string,\n): string {\n if (ctx.droppedInputResponseKeys?.includes(key)) {\n return 'answered in a shape this server cannot read (a wrapped result instead of the bare elicitation result), twice';\n }\n const view = inputResponse(ctx.inputResponses, key);\n if (view.kind !== 'elicit') return 'not answered';\n if (view.action === 'decline') return 'declined by the user';\n if (view.action === 'cancel') return 'dismissed by the user';\n return 'answered without a valid choice';\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n // The length check is load-bearing, not an early-out: `every` alone returns\n // true whenever `a` is a prefix of a longer `b`, so a confirmation minted for\n // ['/x'] would authorize a retry for ['/x', '/y'] — a direct R9 bypass.\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n"]}