@j0hanz/filesystem-mcp 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +38 -32
  2. package/dist/cli-help.d.ts.map +1 -1
  3. package/dist/cli-help.js +21 -40
  4. package/dist/cli-help.js.map +1 -1
  5. package/dist/cli.d.ts +0 -2
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +24 -46
  8. package/dist/cli.js.map +1 -1
  9. package/dist/core/concurrency.d.ts +5 -17
  10. package/dist/core/concurrency.d.ts.map +1 -1
  11. package/dist/core/concurrency.js +32 -40
  12. package/dist/core/concurrency.js.map +1 -1
  13. package/dist/core/config.d.ts +2 -0
  14. package/dist/core/config.d.ts.map +1 -1
  15. package/dist/core/config.js.map +1 -1
  16. package/dist/core/cursor.d.ts +1 -12
  17. package/dist/core/cursor.d.ts.map +1 -1
  18. package/dist/core/cursor.js +2 -12
  19. package/dist/core/cursor.js.map +1 -1
  20. package/dist/core/errors.d.ts +6 -11
  21. package/dist/core/errors.d.ts.map +1 -1
  22. package/dist/core/errors.js +62 -117
  23. package/dist/core/errors.js.map +1 -1
  24. package/dist/core/file-uri.d.ts +7 -3
  25. package/dist/core/file-uri.d.ts.map +1 -1
  26. package/dist/core/file-uri.js +8 -4
  27. package/dist/core/file-uri.js.map +1 -1
  28. package/dist/core/fmt.d.ts +0 -11
  29. package/dist/core/fmt.d.ts.map +1 -1
  30. package/dist/core/fmt.js +1 -19
  31. package/dist/core/fmt.js.map +1 -1
  32. package/dist/core/fs.d.ts +34 -4
  33. package/dist/core/fs.d.ts.map +1 -1
  34. package/dist/core/fs.js +151 -12
  35. package/dist/core/fs.js.map +1 -1
  36. package/dist/core/glob.d.ts +1 -2
  37. package/dist/core/glob.d.ts.map +1 -1
  38. package/dist/core/glob.js +12 -28
  39. package/dist/core/glob.js.map +1 -1
  40. package/dist/core/input-required.d.ts +19 -29
  41. package/dist/core/input-required.d.ts.map +1 -1
  42. package/dist/core/input-required.js +58 -73
  43. package/dist/core/input-required.js.map +1 -1
  44. package/dist/core/observability.d.ts +9 -0
  45. package/dist/core/observability.d.ts.map +1 -1
  46. package/dist/core/observability.js +13 -2
  47. package/dist/core/observability.js.map +1 -1
  48. package/dist/core/path-completer.d.ts +6 -9
  49. package/dist/core/path-completer.d.ts.map +1 -1
  50. package/dist/core/path-completer.js +28 -55
  51. package/dist/core/path-completer.js.map +1 -1
  52. package/dist/core/path-discovery.d.ts.map +1 -1
  53. package/dist/core/path-discovery.js +3 -4
  54. package/dist/core/path-discovery.js.map +1 -1
  55. package/dist/core/path-utils.d.ts +28 -0
  56. package/dist/core/path-utils.d.ts.map +1 -1
  57. package/dist/core/path-utils.js +57 -2
  58. package/dist/core/path-utils.js.map +1 -1
  59. package/dist/core/path.d.ts +3 -8
  60. package/dist/core/path.d.ts.map +1 -1
  61. package/dist/core/path.js +8 -9
  62. package/dist/core/path.js.map +1 -1
  63. package/dist/core/read.d.ts +3 -22
  64. package/dist/core/read.d.ts.map +1 -1
  65. package/dist/core/read.js +46 -96
  66. package/dist/core/read.js.map +1 -1
  67. package/dist/core/schema.d.ts +8 -9
  68. package/dist/core/schema.d.ts.map +1 -1
  69. package/dist/core/schema.js +11 -14
  70. package/dist/core/schema.js.map +1 -1
  71. package/dist/core/search.d.ts +6 -1
  72. package/dist/core/search.d.ts.map +1 -1
  73. package/dist/core/search.js +21 -23
  74. package/dist/core/search.js.map +1 -1
  75. package/dist/core/sensitive.d.ts +4 -2
  76. package/dist/core/sensitive.d.ts.map +1 -1
  77. package/dist/core/sensitive.js +262 -45
  78. package/dist/core/sensitive.js.map +1 -1
  79. package/dist/core/store.d.ts +41 -16
  80. package/dist/core/store.d.ts.map +1 -1
  81. package/dist/core/store.js +147 -82
  82. package/dist/core/store.js.map +1 -1
  83. package/dist/core/util.d.ts +3 -2
  84. package/dist/core/util.d.ts.map +1 -1
  85. package/dist/core/util.js +5 -6
  86. package/dist/core/util.js.map +1 -1
  87. package/dist/core/watcher-registry.d.ts +1 -1
  88. package/dist/core/watcher-registry.d.ts.map +1 -1
  89. package/dist/core/watcher-registry.js +9 -5
  90. package/dist/core/watcher-registry.js.map +1 -1
  91. package/dist/index.js +5 -6
  92. package/dist/index.js.map +1 -1
  93. package/dist/instructions.js +2 -2
  94. package/dist/instructions.js.map +1 -1
  95. package/dist/prompts.js +1 -1
  96. package/dist/prompts.js.map +1 -1
  97. package/dist/resources.d.ts +11 -19
  98. package/dist/resources.d.ts.map +1 -1
  99. package/dist/resources.js +51 -62
  100. package/dist/resources.js.map +1 -1
  101. package/dist/server.d.ts +4 -5
  102. package/dist/server.d.ts.map +1 -1
  103. package/dist/server.js +15 -11
  104. package/dist/server.js.map +1 -1
  105. package/dist/tools/batch.d.ts +2 -2
  106. package/dist/tools/batch.js +3 -3
  107. package/dist/tools/batch.js.map +1 -1
  108. package/dist/tools/create.d.ts +1 -1
  109. package/dist/tools/create.d.ts.map +1 -1
  110. package/dist/tools/create.js +168 -17
  111. package/dist/tools/create.js.map +1 -1
  112. package/dist/tools/define.d.ts +15 -9
  113. package/dist/tools/define.d.ts.map +1 -1
  114. package/dist/tools/define.js +48 -94
  115. package/dist/tools/define.js.map +1 -1
  116. package/dist/tools/delete.d.ts +1 -1
  117. package/dist/tools/delete.d.ts.map +1 -1
  118. package/dist/tools/delete.js +23 -23
  119. package/dist/tools/delete.js.map +1 -1
  120. package/dist/tools/diff.d.ts +1 -1
  121. package/dist/tools/diff.d.ts.map +1 -1
  122. package/dist/tools/diff.js +7 -37
  123. package/dist/tools/diff.js.map +1 -1
  124. package/dist/tools/edit.d.ts +1 -1
  125. package/dist/tools/edit.d.ts.map +1 -1
  126. package/dist/tools/edit.js +101 -92
  127. package/dist/tools/edit.js.map +1 -1
  128. package/dist/tools/find-files.d.ts +1 -1
  129. package/dist/tools/find-files.d.ts.map +1 -1
  130. package/dist/tools/find-files.js +18 -37
  131. package/dist/tools/find-files.js.map +1 -1
  132. package/dist/tools/index.d.ts +10 -10
  133. package/dist/tools/index.d.ts.map +1 -1
  134. package/dist/tools/index.js +14 -13
  135. package/dist/tools/index.js.map +1 -1
  136. package/dist/tools/list-roots.d.ts +1 -1
  137. package/dist/tools/list-roots.js +3 -3
  138. package/dist/tools/list-roots.js.map +1 -1
  139. package/dist/tools/list.d.ts +1 -1
  140. package/dist/tools/list.d.ts.map +1 -1
  141. package/dist/tools/list.js +23 -29
  142. package/dist/tools/list.js.map +1 -1
  143. package/dist/tools/move.d.ts +1 -1
  144. package/dist/tools/move.d.ts.map +1 -1
  145. package/dist/tools/move.js +31 -45
  146. package/dist/tools/move.js.map +1 -1
  147. package/dist/tools/patch.d.ts +1 -1
  148. package/dist/tools/patch.js +7 -7
  149. package/dist/tools/patch.js.map +1 -1
  150. package/dist/tools/progress.d.ts +17 -28
  151. package/dist/tools/progress.d.ts.map +1 -1
  152. package/dist/tools/progress.js +42 -94
  153. package/dist/tools/progress.js.map +1 -1
  154. package/dist/tools/read.d.ts +1 -1
  155. package/dist/tools/read.d.ts.map +1 -1
  156. package/dist/tools/read.js +10 -12
  157. package/dist/tools/read.js.map +1 -1
  158. package/dist/tools/replace-text.d.ts +1 -1
  159. package/dist/tools/replace-text.d.ts.map +1 -1
  160. package/dist/tools/replace-text.js +32 -49
  161. package/dist/tools/replace-text.js.map +1 -1
  162. package/dist/tools/search-text.d.ts +1 -1
  163. package/dist/tools/search-text.d.ts.map +1 -1
  164. package/dist/tools/search-text.js +82 -45
  165. package/dist/tools/search-text.js.map +1 -1
  166. package/dist/tools/stat.d.ts +1 -1
  167. package/dist/tools/stat.d.ts.map +1 -1
  168. package/dist/tools/stat.js +9 -29
  169. package/dist/tools/stat.js.map +1 -1
  170. package/dist/transport/http-policy.js +4 -4
  171. package/dist/transport/http-policy.js.map +1 -1
  172. package/dist/transport/http.d.ts +2 -2
  173. package/dist/transport/http.d.ts.map +1 -1
  174. package/dist/transport/http.js +21 -18
  175. package/dist/transport/http.js.map +1 -1
  176. package/dist/transport/shared.d.ts +2 -2
  177. package/dist/transport/shared.js +2 -2
  178. package/dist/transport/shared.js.map +1 -1
  179. package/dist/transport/stdio.d.ts +4 -3
  180. package/dist/transport/stdio.d.ts.map +1 -1
  181. package/dist/transport/stdio.js +7 -6
  182. package/dist/transport/stdio.js.map +1 -1
  183. package/dist/transport.d.ts +2 -2
  184. package/dist/transport.js +2 -2
  185. package/dist/transport.js.map +1 -1
  186. package/package.json +6 -13
  187. package/dist/core/page-store.d.ts +0 -41
  188. package/dist/core/page-store.d.ts.map +0 -1
  189. package/dist/core/page-store.js +0 -74
  190. package/dist/core/page-store.js.map +0 -1
  191. package/dist/core/primitives.d.ts +0 -34
  192. package/dist/core/primitives.d.ts.map +0 -1
  193. package/dist/core/primitives.js +0 -63
  194. package/dist/core/primitives.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { acceptedContent, createRequestStateCodec, inputRequired, } from '@modelcontextprotocol/server';
1
+ import { acceptedContent, createRequestStateCodec, inputRequired, inputResponse, } from '@modelcontextprotocol/server';
2
2
  import { randomBytes } from 'node:crypto';
3
3
  import * as z from 'zod/v4';
4
- import { ErrorCode, FsError } from './errors.js';
5
- import { Logger } from './observability.js';
4
+ import { ErrorCode, FsError } from "./errors.js";
5
+ import { Logger } from "./observability.js";
6
6
  /**
7
7
  * HMAC key for the requestState codec. Read once from
8
8
  * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random
@@ -24,9 +24,20 @@ function configuredRequestStateKey() {
24
24
  // Built on first use, not at module load, so an unset env var costs nothing at
25
25
  // import and the random per-boot fallback is minted only once something needs it.
26
26
  let codec;
27
+ /**
28
+ * What a minted `requestState` is bound to: the JSON-RPC method of the
29
+ * request that minted it and the authenticated caller (`ctx.http` is absent
30
+ * on stdio, so the caller part is empty there and constant across rounds).
31
+ * The SDK stores an HMAC tag of this value in the token and refuses an echo
32
+ * whose context yields a different value.
33
+ */
34
+ export function requestStateBinding(ctx) {
35
+ return `${ctx.mcpReq.method}\0${ctx.http?.authInfo?.clientId ?? ''}`;
36
+ }
27
37
  function getRequestStateCodec() {
28
38
  codec ??= createRequestStateCodec({
29
39
  key: configuredRequestStateKey() ?? randomBytes(32),
40
+ bind: requestStateBinding,
30
41
  });
31
42
  return codec;
32
43
  }
@@ -40,76 +51,46 @@ export const requestStateCodec = {
40
51
  mint: (payload, ctx) => getRequestStateCodec().mint(payload, ctx),
41
52
  verify: (state, ctx) => getRequestStateCodec().verify(state, ctx),
42
53
  };
54
+ // Response shapes handed to the SDK's schema-aware `acceptedContent` overload:
55
+ // it returns `undefined` for a missing key, a decline/cancel, a non-elicit
56
+ // response, AND a payload that fails validation — one call covers every refusal
57
+ // case the readers below used to hand-check. `buildInputRequired` reuses
58
+ // `ConfirmContent` as the no-choices form schema (below), so these sit above it.
59
+ const ConfirmContent = z.object({ confirm: z.boolean().meta({ title: 'Confirm' }) });
60
+ const ChoiceContent = z.object({ choice: z.string() });
61
+ const MultiChoiceContent = z.object({ choice: z.array(z.string()) });
43
62
  /**
44
- * Build a single-select enum confirmation input. The form renders a `choice`
45
- * field whose options are the titled `choices`; the caller reads the selection
46
- * with `readAcceptedChoice`.
47
- */
48
- export function choiceInput(key, message, choices) {
49
- return { key, message, choices };
50
- }
51
- /**
52
- * Build a multi-select enum confirmation input. Like `choiceInput` but the
53
- * form renders `choice` as a string array (`MultiSelectEnumSchema` shape), so
54
- * the client may accept a subset; the caller reads the accepted set with
55
- * `readAcceptedMultiChoice`.
63
+ * The form the client renders for one pending input, as the Zod schema the
64
+ * SDK converts to the elicitation wire shape. A boolean `confirm` when no
65
+ * choices are offered; otherwise a `choice` enum over the offered values,
66
+ * wrapped in an array for multi-select so the client may accept a subset.
67
+ * The offered lists are never empty by construction (single-select always
68
+ * offers two literals; multi-select only runs with two or more grant dirs),
69
+ * so no empty-array guard is added. Each field carries a `title` so a host
70
+ * that renders the form labels it instead of showing the property name.
56
71
  */
57
- export function multiSelectInput(key, message, choices) {
58
- return {
59
- key,
60
- message,
61
- choices,
62
- multi: true,
63
- };
72
+ function requestedSchemaFor(input) {
73
+ if (!input.choices)
74
+ return ConfirmContent;
75
+ const value = z.enum(input.choices);
76
+ return z.object({
77
+ choice: input.multi ? z.array(value).meta({ title: 'Allow' }) : value.meta({ title: 'Action' }),
78
+ });
64
79
  }
65
80
  /**
66
81
  * Build an `input_required` result carrying one boolean confirmation per pending
67
82
  * item, plus the integrity-protected `requestState` sealing the operation kind
68
83
  * and sorted target paths. `mint` is async (HMAC + base64url).
69
84
  */
70
- export async function buildInputRequired(pending, inputs) {
85
+ export async function buildInputRequired(pending, inputs, ctx) {
71
86
  const inputRequests = {};
72
87
  for (const input of inputs) {
73
- const requestedSchema = input.choices
74
- ? input.multi
75
- ? {
76
- // Multi-select enum (matches MultiSelectEnumSchema): `choice` is a
77
- // string array; the client may accept a subset of the offered dirs.
78
- type: 'object',
79
- properties: {
80
- choice: {
81
- type: 'array',
82
- items: {
83
- anyOf: input.choices.map((c) => ({ const: c.value, title: c.title })),
84
- },
85
- },
86
- },
87
- required: ['choice'],
88
- }
89
- : {
90
- type: 'object',
91
- properties: {
92
- choice: {
93
- type: 'string',
94
- oneOf: input.choices.map((c) => ({ const: c.value, title: c.title })),
95
- },
96
- },
97
- required: ['choice'],
98
- }
99
- : {
100
- type: 'object',
101
- properties: { confirm: { type: 'boolean', title: 'Confirm' } },
102
- required: ['confirm'],
103
- };
104
88
  inputRequests[input.key] = inputRequired.elicit({
105
89
  message: input.message,
106
- requestedSchema,
90
+ requestedSchema: requestedSchemaFor(input),
107
91
  });
108
92
  }
109
- const requestState = await requestStateCodec.mint({
110
- op: pending.op,
111
- paths: [...pending.paths].sort(),
112
- });
93
+ const requestState = await requestStateCodec.mint({ op: pending.op, paths: [...pending.paths].sort() }, ctx);
113
94
  return inputRequired({ inputRequests, requestState });
114
95
  }
115
96
  /**
@@ -124,6 +105,8 @@ const NO_ELICITATION_HINT = {
124
105
  'Delete the destination first, or move to a path that does not exist yet.',
125
106
  copy: 'Overwriting an existing destination needs a confirmation this client cannot show. ' +
126
107
  'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',
108
+ create: 'Overwriting an existing file needs a confirmation this client cannot show. ' +
109
+ 'Pass overwrite: true on that entry to replace it without confirming, append: true to add to it, or read it and use edit.',
127
110
  grant: 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +
128
111
  'Call list_roots and use a path under one of the roots it returns.',
129
112
  };
@@ -157,7 +140,7 @@ export async function pendingRoundTrip(opts) {
157
140
  // tamper/mismatch error.
158
141
  if (state?.op !== opts.op) {
159
142
  assertCanElicit(opts.op, opts.clientCapabilities);
160
- return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending));
143
+ return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending), opts.serverCtx);
161
144
  }
162
145
  // Retry for THIS op (R9): the verified state must bind the same pending set.
163
146
  if (!pathsEqual(state.paths, opts.pending)) {
@@ -165,13 +148,6 @@ export async function pendingRoundTrip(opts) {
165
148
  }
166
149
  return undefined;
167
150
  }
168
- // Response shapes handed to the SDK's schema-aware `acceptedContent` overload:
169
- // it returns `undefined` for a missing key, a decline/cancel, a non-elicit
170
- // response, AND a payload that fails validation — one call covers every refusal
171
- // case the readers below used to hand-check.
172
- const ConfirmContent = z.object({ confirm: z.boolean() });
173
- const ChoiceContent = z.object({ choice: z.string() });
174
- const MultiChoiceContent = z.object({ choice: z.array(z.string()) });
175
151
  /**
176
152
  * Round-trip key for `pendingSorted[index]` — the single home of the
177
153
  * `confirm_${i}` convention. The build side mints it with the map index; the
@@ -223,6 +199,17 @@ export function readAcceptedChoice(responses, key) {
223
199
  export function readAcceptedMultiChoice(responses, key) {
224
200
  return acceptedContent(responses, key, MultiChoiceContent)?.choice;
225
201
  }
202
+ /** Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader returned nothing. */
203
+ export function describeRefusal(responses, key) {
204
+ const view = inputResponse(responses, key);
205
+ if (view.kind !== 'elicit')
206
+ return 'not answered';
207
+ if (view.action === 'decline')
208
+ return 'declined by the user';
209
+ if (view.action === 'cancel')
210
+ return 'dismissed by the user';
211
+ return 'answered without a valid choice';
212
+ }
226
213
  /**
227
214
  * Order-independent equality of two sorted, de-duplicated path lists. Used to
228
215
  * compare a recomputed pending set against the `requestState`-bound set (R9):
@@ -230,11 +217,9 @@ export function readAcceptedMultiChoice(responses, key) {
230
217
  * it without allocating.
231
218
  */
232
219
  function pathsEqual(a, b) {
233
- if (a.length !== b.length)
234
- return false;
235
- for (let i = 0; i < a.length; i++)
236
- if (a[i] !== b[i])
237
- return false;
238
- return true;
220
+ // The length check is load-bearing, not an early-out: `every` alone returns
221
+ // true whenever `a` is a prefix of a longer `b`, so a confirmation minted for
222
+ // ['/x'] would authorize a retry for ['/x', '/y'] — a direct R9 bypass.
223
+ return a.length === b.length && a.every((value, index) => value === b[index]);
239
224
  }
240
225
  //# sourceMappingURL=input-required.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,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,CAAC;QACR,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACvC,IAAI,KAAK,CAAC,MAAM,IAAI,E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AC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,CAAoB,EAAE,CAAoB;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IACnE,OAAO,IAAI,CAAC;AACd,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} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.js';\nimport { Logger } from './observability.js';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | '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. */\ninterface 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 titled single-select enum (`choice` field)\n * instead of a boolean `confirm`. Each entry is a `{ value, title }` pair.\n */\n readonly choices?: readonly { value: string; title: 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// Built on first use, not at module load, so an unset env var costs nothing at\n// import and the random per-boot fallback is minted only once something needs it.\nlet codec: RequestStateCodec<PendingState> | undefined;\n\nfunction getRequestStateCodec(): RequestStateCodec<PendingState> {\n codec ??= createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n });\n return codec;\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 mint: (payload, ctx) => getRequestStateCodec().mint(payload, ctx),\n verify: (state, ctx) => getRequestStateCodec().verify(state, ctx),\n};\n\n/**\n * Build a single-select enum confirmation input. The form renders a `choice`\n * field whose options are the titled `choices`; the caller reads the selection\n * with `readAcceptedChoice`.\n */\nexport function choiceInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return { key, message, choices };\n}\n\n/**\n * Build a multi-select enum confirmation input. Like `choiceInput` but the\n * form renders `choice` as a string array (`MultiSelectEnumSchema` shape), so\n * the client may accept a subset; the caller reads the accepted set with\n * `readAcceptedMultiChoice`.\n */\nexport function multiSelectInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return {\n key,\n message,\n choices,\n multi: true,\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): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n const requestedSchema = input.choices\n ? input.multi\n ? {\n // Multi-select enum (matches MultiSelectEnumSchema): `choice` is a\n // string array; the client may accept a subset of the offered dirs.\n type: 'object' as const,\n properties: {\n choice: {\n type: 'array' as const,\n items: {\n anyOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: {\n choice: {\n type: 'string' as const,\n oneOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: { confirm: { type: 'boolean' as const, title: 'Confirm' } },\n required: ['confirm'],\n };\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema,\n });\n }\n const requestState = await requestStateCodec.mint({\n op: pending.op,\n paths: [...pending.paths].sort(),\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}\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 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({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending));\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// 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.\nconst ConfirmContent = z.object({ confirm: z.boolean() });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\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 * 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 if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n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M,CAAC;AAChE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;AACrE,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,eAAe,CAC7B,SAA8C,EAC9C,GAAW;IAEX,MAAM,IAAI,GAAG,aAAa,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAC3C,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC;IAClD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,sBAAsB,CAAC;IAC7D,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ;QAAE,OAAO,uBAAuB,CAAC;IAC7D,OAAO,iCAAiC,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,CAAoB,EAAE,CAAoB;IAC5D,4EAA4E;IAC5E,8EAA8E;IAC9E,wEAAwE;IACxE,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,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\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// Built on first use, not at module load, so an unset env var costs nothing at\n// import and the random per-boot fallback is minted only once something needs it.\nlet codec: RequestStateCodec<PendingState> | undefined;\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 */\nexport function requestStateBinding(ctx: ServerContext): string {\n return `${ctx.mcpReq.method}\\0${ctx.http?.authInfo?.clientId ?? ''}`;\n}\n\nfunction getRequestStateCodec(): RequestStateCodec<PendingState> {\n codec ??= createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n bind: requestStateBinding,\n });\n return codec;\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 mint: (payload, ctx) => getRequestStateCodec().mint(payload, ctx),\n verify: (state, ctx) => getRequestStateCodec().verify(state, ctx),\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,4 +1,13 @@
1
1
  export type LoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';
2
+ /**
3
+ * A client-supplied value (a JSON-RPC id, a `traceparent`, a tool's own log
4
+ * message) made safe for one stderr line: a control character or a Unicode
5
+ * line/paragraph separator (U+2028/U+2029, which `\p{Cc}` misses) would let
6
+ * a caller forge extra log lines, and an unbounded value would let it flood
7
+ * one. `max` bounds the value; pass `Infinity` for free text that is only
8
+ * flattened.
9
+ */
10
+ export declare function sanitizeLogField(value: string, max?: number): string;
2
11
  export declare const Logger: {
3
12
  emit: (level: LoggingLevel, message: string) => void;
4
13
  info: (message: string, ...args: unknown[]) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA2DzF,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
1
+ {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA2DzF;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,GAAG,MAAM,CAEjE;AAED,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
@@ -1,5 +1,5 @@
1
- import { cli } from './config.js';
2
- import { warnInvalidSetting } from './primitives.js';
1
+ import { cli } from "./config.js";
2
+ import { warnInvalidSetting } from "./path-utils.js";
3
3
  // RFC 5424 severities, most severe first. A message is emitted when its
4
4
  // severity is at least as high as the configured minimum.
5
5
  const LEVEL_ORDER = [
@@ -54,6 +54,17 @@ function write(level, message, args) {
54
54
  const prefix = `[${level}]`;
55
55
  console.error(`${prefix} ${message}`, ...args);
56
56
  }
57
+ /**
58
+ * A client-supplied value (a JSON-RPC id, a `traceparent`, a tool's own log
59
+ * message) made safe for one stderr line: a control character or a Unicode
60
+ * line/paragraph separator (U+2028/U+2029, which `\p{Cc}` misses) would let
61
+ * a caller forge extra log lines, and an unbounded value would let it flood
62
+ * one. `max` bounds the value; pass `Infinity` for free text that is only
63
+ * flattened.
64
+ */
65
+ export function sanitizeLogField(value, max = 128) {
66
+ return value.replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, ' ').slice(0, max);
67
+ }
57
68
  export const Logger = {
58
69
  emit: (level, message) => {
59
70
  write(level, message, []);
@@ -1 +1 @@
1
- {"version":3,"file":"observability.js","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAKrD,wEAAwE;AACxE,0DAA0D;AAC1D,MAAM,WAAW,GAA4B;IAC3C,WAAW;IACX,OAAO;IACP,UAAU;IACV,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;CACR,CAAC;AAEF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAQ,WAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,aA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,MAAM,GAAG;IACpB,IAAI,EAAE,CAAC,KAAmB,EAAE,OAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC5B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAAC,EAAU,EAAE,KAAa,EAAE,MAAc,EAAE,KAAc;IACzF,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { cli } from './config.js';\nimport { warnInvalidSetting } from './primitives.js';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}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EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAAC,EAAU,EAAE,KAAa,EAAE,MAAc,EAAE,KAAc;IACzF,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { cli } from './config.ts';\nimport { warnInvalidSetting } from './path-utils.ts';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\n/**\n * A client-supplied value (a JSON-RPC id, a `traceparent`, a tool's own log\n * message) made safe for one stderr line: a control character or a Unicode\n * line/paragraph separator (U+2028/U+2029, which `\\p{Cc}` misses) would let\n * a caller forge extra log lines, and an unbounded value would let it flood\n * one. `max` bounds the value; pass `Infinity` for free text that is only\n * flattened.\n */\nexport function sanitizeLogField(value: string, max = 128): string {\n return value.replace(/[\\p{Cc}\\p{Zl}\\p{Zp}]+/gu, ' ').slice(0, max);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);\n}\n"]}
@@ -1,10 +1,7 @@
1
- import type { PathGuard } from './path.js';
2
- export declare class PathCompleter {
3
- private cache;
4
- private readonly pathGuard;
5
- constructor(pathGuard: PathGuard);
6
- suggest(value: string): Promise<string[]>;
7
- private setCacheValue;
8
- private completePath;
9
- }
1
+ import type { PathGuard } from './path.ts';
2
+ /**
3
+ * Path suggestions for `completion/complete` on the file template. One
4
+ * `opendir` per call; clients debounce, so nothing is cached here.
5
+ */
6
+ export declare function suggestPaths(pathGuard: PathGuard, value: string): Promise<string[]>;
10
7
  //# sourceMappingURL=path-completer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"path-completer.d.ts","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAwL3C,qBAAa,aAAa;IACxB,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAY;gBAE1B,SAAS,EAAE,SAAS;IAI1B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAa/C,OAAO,CAAC,aAAa;YAOP,YAAY;CA8B3B"}
1
+ {"version":3,"file":"path-completer.d.ts","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AA2K3C;;;GAGG;AACH,wBAAsB,YAAY,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA0BzF"}
@@ -1,17 +1,11 @@
1
1
  import { opendir, stat } from 'node:fs/promises';
2
2
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
3
- import { isNodeError, isNotFoundErrno, rethrowIfAborted } from './errors.js';
4
- import { Logger } from './observability.js';
5
- import { isPathWithinDirectories, isSamePath, normalizePath } from './path-utils.js';
6
- import { resolveRealPath } from './path.js';
7
- import { isSlash, toPosixPath } from './primitives.js';
3
+ import { isNodeError, isNotFoundErrno, rethrowIfAborted } from "./errors.js";
4
+ import { Logger } from "./observability.js";
5
+ import { isPathWithinDirectories, isSamePath, isSlash, normalizePath, toPosixPath, } from "./path-utils.js";
6
+ import { resolveRealPath } from "./path.js";
8
7
  const MAX_COMPLETION_ITEMS = 100;
9
- const COMPLETION_RATE_LIMIT_MS = 100;
10
- const MAX_COMPLETION_CACHE_KEYS = 128;
11
- // ─── pure path-completion helpers (no instance state) ───────────────────────
12
- // Formerly static methods on PathCompleter. They take `allowed` explicitly and
13
- // touch no state, so they read as plain functions rather than a class used as
14
- // a namespace. PathCompleter keeps only the cache and the path guard.
8
+ // ─── pure path-completion helpers ───────────────────────────────────────────
15
9
  function hasTrailingSeparator(value) {
16
10
  return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));
17
11
  }
@@ -149,52 +143,31 @@ function getSearchContext(currentValue, allowed) {
149
143
  }
150
144
  return undefined;
151
145
  }
152
- // ─── PathCompleter: cache + path guard ───────────────────────────────────────
153
- export class PathCompleter {
154
- cache = new Map();
155
- pathGuard;
156
- constructor(pathGuard) {
157
- this.pathGuard = pathGuard;
158
- }
159
- async suggest(value) {
160
- const now = Date.now();
161
- const cacheEntry = this.cache.get(value);
162
- if (cacheEntry && now - cacheEntry.ms < COMPLETION_RATE_LIMIT_MS) {
163
- return cacheEntry.result;
164
- }
165
- const results = await this.completePath(value);
166
- this.setCacheValue(value, { ms: now, result: results });
167
- return results;
168
- }
169
- setCacheValue(key, entry) {
170
- // Entries are stale after COMPLETION_RATE_LIMIT_MS anyway, so the cap only
171
- // has to bound memory — dropping the whole map beats per-key LRU eviction.
172
- if (this.cache.size >= MAX_COMPLETION_CACHE_KEYS)
173
- this.cache.clear();
174
- this.cache.set(key, entry);
175
- }
176
- async completePath(value) {
177
- const allowed = this.pathGuard.getAllowedDirectories();
178
- try {
179
- if (!value) {
180
- return allowed.slice(0, MAX_COMPLETION_ITEMS);
181
- }
182
- const context = getSearchContext(value, allowed);
183
- if (!context) {
184
- return findRootPrefixMatches(value, allowed).slice(0, MAX_COMPLETION_ITEMS);
185
- }
186
- const { searchDir, prefix } = context;
187
- const dirMatches = await findMatchesInDirectory(searchDir, prefix, allowed, this.pathGuard.isSensitive.bind(this.pathGuard));
188
- const rootMatches = findMatchingRoots(searchDir, prefix, allowed);
189
- return mergeCompletionMatches(dirMatches, rootMatches).slice(0, MAX_COMPLETION_ITEMS);
146
+ /**
147
+ * Path suggestions for `completion/complete` on the file template. One
148
+ * `opendir` per call; clients debounce, so nothing is cached here.
149
+ */
150
+ export async function suggestPaths(pathGuard, value) {
151
+ const allowed = pathGuard.getAllowedDirectories();
152
+ try {
153
+ if (!value) {
154
+ return allowed.slice(0, MAX_COMPLETION_ITEMS);
190
155
  }
191
- catch (error) {
192
- rethrowIfAborted(error);
193
- Logger.warn('PathCompleter: completion failed, returning empty list', {
194
- error: error instanceof Error ? (error.stack ?? error.message) : String(error),
195
- });
196
- return [];
156
+ const context = getSearchContext(value, allowed);
157
+ if (!context) {
158
+ return findRootPrefixMatches(value, allowed).slice(0, MAX_COMPLETION_ITEMS);
197
159
  }
160
+ const { searchDir, prefix } = context;
161
+ const dirMatches = await findMatchesInDirectory(searchDir, prefix, allowed, (p) => pathGuard.isSensitive(p));
162
+ const rootMatches = findMatchingRoots(searchDir, prefix, allowed);
163
+ return mergeCompletionMatches(dirMatches, rootMatches).slice(0, MAX_COMPLETION_ITEMS);
164
+ }
165
+ catch (error) {
166
+ rethrowIfAborted(error);
167
+ Logger.warn('suggestPaths: completion failed, returning empty list', {
168
+ error: error instanceof Error ? (error.stack ?? error.message) : String(error),
169
+ });
170
+ return [];
198
171
  }
199
172
  }
200
173
  //# sourceMappingURL=path-completer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"path-completer.js","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,EAAE,MAAM,E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EAAE;gBACpE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC/E,CAAC,CAAC;YACH,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { opendir, stat } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\n\nimport { isNodeError, isNotFoundErrno, rethrowIfAborted } from './errors.js';\nimport { Logger } from './observability.js';\nimport { isPathWithinDirectories, isSamePath, normalizePath } from './path-utils.js';\nimport type { PathGuard } from './path.js';\nimport { resolveRealPath } from './path.js';\nimport { isSlash, toPosixPath } from './primitives.js';\n\nconst MAX_COMPLETION_ITEMS = 100;\nconst COMPLETION_RATE_LIMIT_MS = 100;\nconst MAX_COMPLETION_CACHE_KEYS = 128;\n\ninterface CacheEntry {\n ms: number;\n result: string[];\n}\n\n// ─── pure path-completion helpers (no instance state) ───────────────────────\n// Formerly static methods on PathCompleter. They take `allowed` explicitly and\n// touch no state, so they read as plain functions rather than a class used as\n// a namespace. PathCompleter keeps only the cache and the path guard.\n\nfunction hasTrailingSeparator(value: string): boolean {\n return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));\n}\n\nfunction resolveFromBase(\n base: string,\n rawValue: string,\n trailingSeparator: boolean,\n): { searchDir: string; prefix: string } {\n const normalizedValue = normalizePath(resolve(base, rawValue));\n if (trailingSeparator) return { searchDir: normalizedValue, prefix: '' };\n return {\n searchDir: dirname(normalizedValue),\n prefix: basename(normalizedValue),\n };\n}\n\nfunction parseNamedRootInput(value: string): { rootName: string; remainder: string } | undefined {\n const normalizedInput = toPosixPath(value);\n if (!normalizedInput) return undefined;\n const slashIndex = normalizedInput.indexOf('/');\n if (slashIndex === -1) return { rootName: normalizedInput, remainder: '' };\n const rootName = normalizedInput.slice(0, slashIndex);\n if (!rootName) return undefined;\n return { rootName, remainder: normalizedInput.slice(slashIndex + 1) };\n}\n\nfunction findAllowedRootByName(rootName: string, allowed: readonly string[]): string | undefined {\n const normalizedRootName = rootName.toLowerCase();\n return allowed.find((candidate) => basename(candidate).toLowerCase() === normalizedRootName);\n}\n\nfunction resolveNamedRootContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const parsed = parseNamedRootInput(currentValue);\n if (!parsed) return undefined;\n const root = findAllowedRootByName(parsed.rootName, allowed);\n if (!root) return undefined;\n const trailingSeparator = hasTrailingSeparator(currentValue);\n return resolveFromBase(root, parsed.remainder, trailingSeparator);\n}\n\nasync function isAllowedCompletionDirectory(\n path: string,\n allowed: readonly string[],\n): Promise<boolean> {\n if (!isPathWithinDirectories(path, allowed)) return false;\n try {\n const stats = await stat(path);\n if (!stats.isDirectory()) return false;\n const real = await resolveRealPath(path);\n return real !== null && isPathWithinDirectories(real, allowed);\n } catch (err) {\n if (!isNotFoundErrno(err) && (!isNodeError(err) || err.code !== 'EACCES')) {\n Logger.debug('isAllowedCompletionDirectory: unexpected probe error', {\n path,\n error: String(err),\n });\n }\n return false;\n }\n}\n\nfunction withDirectorySeparator(value: string): string {\n return value.endsWith(sep) ? value : `${value}${sep}`;\n}\n\nfunction collectAllowedRoots(\n allowed: readonly string[],\n predicate: (root: string) => boolean,\n): string[] {\n return allowed.filter(predicate).map(withDirectorySeparator);\n}\n\nfunction findRootPrefixMatches(currentValue: string, allowed: readonly string[]): string[] {\n const rootPrefix = parseNamedRootInput(currentValue)?.rootName.toLowerCase() ?? '';\n if (!rootPrefix) return collectAllowedRoots(allowed, () => true);\n return collectAllowedRoots(allowed, (root) =>\n basename(root).toLowerCase().startsWith(rootPrefix),\n );\n}\n\nfunction findMatchingRoots(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n): string[] {\n const lowerPrefix = prefix.toLowerCase();\n const normalizedSearchDir = normalizePath(searchDir);\n return collectAllowedRoots(allowed, (root) => {\n const rootDir = dirname(root);\n if (!isSamePath(rootDir, normalizedSearchDir)) return false;\n return basename(root).toLowerCase().startsWith(lowerPrefix);\n });\n}\n\nfunction mergeCompletionMatches(\n dirMatches: readonly string[],\n rootMatches: readonly string[],\n): string[] {\n const isDir = (v: string): boolean => v.endsWith(sep);\n return [...new Set([...dirMatches, ...rootMatches])].sort(\n (left, right) => Number(isDir(right)) - Number(isDir(left)) || left.localeCompare(right),\n );\n}\n\nasync function findMatchesInDirectory(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n isSensitive?: (path: string) => boolean,\n): Promise<string[]> {\n const matches: string[] = [];\n if (!(await isAllowedCompletionDirectory(searchDir, allowed))) return matches;\n try {\n // Stream via opendir and collect every match; the MAX_COMPLETION_ITEMS\n // cap is applied AFTER the alphabetical sort in mergeCompletionMatches\n // (slice at the call site). Capping here would keep the opendir-first\n // 100, not the alphabetically-first 100 — the sort would only reorder\n // an already-arbitrary subset.\n const dir = await opendir(searchDir);\n try {\n const lowerPrefix = prefix.toLowerCase();\n for await (const entry of dir) {\n if (prefix !== '' && !entry.name.toLowerCase().startsWith(lowerPrefix)) continue;\n const fullPath = join(searchDir, entry.name);\n if (isSensitive?.(fullPath)) continue;\n matches.push(entry.isDirectory() ? `${fullPath}${sep}` : fullPath);\n }\n } finally {\n await dir.close().catch(() => {\n /* dir already closed or opendir never resolved */\n });\n }\n } catch (err) {\n if (!isNodeError(err) || (err.code !== 'ENOENT' && err.code !== 'EACCES')) {\n Logger.warn('PathCompleter.findMatchesInDirectory: readdir failed', {\n searchDir,\n error: String(err),\n });\n }\n }\n return matches;\n}\n\nfunction getSearchContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const trailingSeparator = hasTrailingSeparator(currentValue);\n if (isAbsolute(currentValue)) {\n return resolveFromBase(parse(currentValue).root || sep, currentValue, trailingSeparator);\n }\n const namedRootContext = resolveNamedRootContext(currentValue, allowed);\n if (namedRootContext) return namedRootContext;\n if (allowed.length === 1) {\n const base = allowed[0];\n if (base) return resolveFromBase(base, currentValue, trailingSeparator);\n }\n return undefined;\n}\n\n// ─── PathCompleter: cache + path guard ───────────────────────────────────────\n\nexport class PathCompleter {\n private cache = new Map<string, CacheEntry>();\n private readonly pathGuard: PathGuard;\n\n constructor(pathGuard: PathGuard) {\n this.pathGuard = pathGuard;\n }\n\n async suggest(value: string): Promise<string[]> {\n const now = Date.now();\n const cacheEntry = this.cache.get(value);\n\n if (cacheEntry && now - cacheEntry.ms < COMPLETION_RATE_LIMIT_MS) {\n return cacheEntry.result;\n }\n\n const results = await this.completePath(value);\n this.setCacheValue(value, { ms: now, result: results });\n return results;\n }\n\n private setCacheValue(key: string, entry: CacheEntry): void {\n // Entries are stale after COMPLETION_RATE_LIMIT_MS anyway, so the cap only\n // has to bound memory — dropping the whole map beats per-key LRU eviction.\n if (this.cache.size >= MAX_COMPLETION_CACHE_KEYS) this.cache.clear();\n this.cache.set(key, entry);\n }\n\n private async completePath(value: string): Promise<string[]> {\n const allowed = this.pathGuard.getAllowedDirectories();\n\n try {\n if (!value) {\n return allowed.slice(0, MAX_COMPLETION_ITEMS);\n }\n\n const context = getSearchContext(value, allowed);\n if (!context) {\n return findRootPrefixMatches(value, allowed).slice(0, MAX_COMPLETION_ITEMS);\n }\n\n const { searchDir, prefix } = context;\n const dirMatches = await findMatchesInDirectory(\n searchDir,\n prefix,\n allowed,\n this.pathGuard.isSensitive.bind(this.pathGuard),\n );\n const rootMatches = findMatchingRoots(searchDir, prefix, allowed);\n return mergeCompletionMatches(dirMatches, rootMatches).slice(0, MAX_COMPLETION_ITEMS);\n } catch (error) {\n rethrowIfAborted(error);\n Logger.warn('PathCompleter: completion failed, returning empty list', {\n error: error instanceof Error ? (error.stack ?? error.message) : String(error),\n });\n return [];\n }\n }\n}\n"]}
1
+ {"version":3,"file":"path-completer.js","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,I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O,EAAE,CAAC,CAAC,EAAE,EAAE,CAChF,SAAS,CAAC,WAAW,CAAC,CAAC,CAAC,CACzB,CAAC;QACF,MAAM,WAAW,GAAG,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QAClE,OAAO,sBAAsB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;IACxF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,gBAAgB,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,CAAC,IAAI,CAAC,uDAAuD,EAAE;YACnE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;SAC/E,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { opendir, stat } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\n\nimport { isNodeError, isNotFoundErrno, rethrowIfAborted } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport {\n isPathWithinDirectories,\n isSamePath,\n isSlash,\n normalizePath,\n toPosixPath,\n} from './path-utils.ts';\nimport type { PathGuard } from './path.ts';\nimport { resolveRealPath } from './path.ts';\n\nconst MAX_COMPLETION_ITEMS = 100;\n\n// ─── pure path-completion helpers ───────────────────────────────────────────\n\nfunction hasTrailingSeparator(value: string): boolean {\n return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));\n}\n\nfunction resolveFromBase(\n base: string,\n rawValue: string,\n trailingSeparator: boolean,\n): { searchDir: string; prefix: string } {\n const normalizedValue = normalizePath(resolve(base, rawValue));\n if (trailingSeparator) return { searchDir: normalizedValue, prefix: '' };\n return {\n searchDir: dirname(normalizedValue),\n prefix: basename(normalizedValue),\n };\n}\n\nfunction parseNamedRootInput(value: string): { rootName: string; remainder: string } | undefined {\n const normalizedInput = toPosixPath(value);\n if (!normalizedInput) return undefined;\n const slashIndex = normalizedInput.indexOf('/');\n if (slashIndex === -1) return { rootName: normalizedInput, remainder: '' };\n const rootName = normalizedInput.slice(0, slashIndex);\n if (!rootName) return undefined;\n return { rootName, remainder: normalizedInput.slice(slashIndex + 1) };\n}\n\nfunction findAllowedRootByName(rootName: string, allowed: readonly string[]): string | undefined {\n const normalizedRootName = rootName.toLowerCase();\n return allowed.find((candidate) => basename(candidate).toLowerCase() === normalizedRootName);\n}\n\nfunction resolveNamedRootContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const parsed = parseNamedRootInput(currentValue);\n if (!parsed) return undefined;\n const root = findAllowedRootByName(parsed.rootName, allowed);\n if (!root) return undefined;\n const trailingSeparator = hasTrailingSeparator(currentValue);\n return resolveFromBase(root, parsed.remainder, trailingSeparator);\n}\n\nasync function isAllowedCompletionDirectory(\n path: string,\n allowed: readonly string[],\n): Promise<boolean> {\n if (!isPathWithinDirectories(path, allowed)) return false;\n try {\n const stats = await stat(path);\n if (!stats.isDirectory()) return false;\n const real = await resolveRealPath(path);\n return real !== null && isPathWithinDirectories(real, allowed);\n } catch (err) {\n if (!isNotFoundErrno(err) && (!isNodeError(err) || err.code !== 'EACCES')) {\n Logger.debug('isAllowedCompletionDirectory: unexpected probe error', {\n path,\n error: String(err),\n });\n }\n return false;\n }\n}\n\nfunction withDirectorySeparator(value: string): string {\n return value.endsWith(sep) ? value : `${value}${sep}`;\n}\n\nfunction collectAllowedRoots(\n allowed: readonly string[],\n predicate: (root: string) => boolean,\n): string[] {\n return allowed.filter(predicate).map(withDirectorySeparator);\n}\n\nfunction findRootPrefixMatches(currentValue: string, allowed: readonly string[]): string[] {\n const rootPrefix = parseNamedRootInput(currentValue)?.rootName.toLowerCase() ?? '';\n if (!rootPrefix) return collectAllowedRoots(allowed, () => true);\n return collectAllowedRoots(allowed, (root) =>\n basename(root).toLowerCase().startsWith(rootPrefix),\n );\n}\n\nfunction findMatchingRoots(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n): string[] {\n const lowerPrefix = prefix.toLowerCase();\n const normalizedSearchDir = normalizePath(searchDir);\n return collectAllowedRoots(allowed, (root) => {\n const rootDir = dirname(root);\n if (!isSamePath(rootDir, normalizedSearchDir)) return false;\n return basename(root).toLowerCase().startsWith(lowerPrefix);\n });\n}\n\nfunction mergeCompletionMatches(\n dirMatches: readonly string[],\n rootMatches: readonly string[],\n): string[] {\n const isDir = (v: string): boolean => v.endsWith(sep);\n return [...new Set([...dirMatches, ...rootMatches])].sort(\n (left, right) => Number(isDir(right)) - Number(isDir(left)) || left.localeCompare(right),\n );\n}\n\nasync function findMatchesInDirectory(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n isSensitive?: (path: string) => boolean,\n): Promise<string[]> {\n const matches: string[] = [];\n if (!(await isAllowedCompletionDirectory(searchDir, allowed))) return matches;\n try {\n // Stream via opendir and collect every match; the MAX_COMPLETION_ITEMS\n // cap is applied AFTER the alphabetical sort in mergeCompletionMatches\n // (slice at the call site). Capping here would keep the opendir-first\n // 100, not the alphabetically-first 100 — the sort would only reorder\n // an already-arbitrary subset.\n const dir = await opendir(searchDir);\n try {\n const lowerPrefix = prefix.toLowerCase();\n for await (const entry of dir) {\n if (prefix !== '' && !entry.name.toLowerCase().startsWith(lowerPrefix)) continue;\n const fullPath = join(searchDir, entry.name);\n if (isSensitive?.(fullPath)) continue;\n matches.push(entry.isDirectory() ? `${fullPath}${sep}` : fullPath);\n }\n } finally {\n await dir.close().catch(() => {\n /* dir already closed or opendir never resolved */\n });\n }\n } catch (err) {\n if (!isNodeError(err) || (err.code !== 'ENOENT' && err.code !== 'EACCES')) {\n Logger.warn('PathCompleter.findMatchesInDirectory: readdir failed', {\n searchDir,\n error: String(err),\n });\n }\n }\n return matches;\n}\n\nfunction getSearchContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const trailingSeparator = hasTrailingSeparator(currentValue);\n if (isAbsolute(currentValue)) {\n return resolveFromBase(parse(currentValue).root || sep, currentValue, trailingSeparator);\n }\n const namedRootContext = resolveNamedRootContext(currentValue, allowed);\n if (namedRootContext) return namedRootContext;\n if (allowed.length === 1) {\n const base = allowed[0];\n if (base) return resolveFromBase(base, currentValue, trailingSeparator);\n }\n return undefined;\n}\n\n/**\n * Path suggestions for `completion/complete` on the file template. One\n * `opendir` per call; clients debounce, so nothing is cached here.\n */\nexport async function suggestPaths(pathGuard: PathGuard, value: string): Promise<string[]> {\n const allowed = pathGuard.getAllowedDirectories();\n\n try {\n if (!value) {\n return allowed.slice(0, MAX_COMPLETION_ITEMS);\n }\n\n const context = getSearchContext(value, allowed);\n if (!context) {\n return findRootPrefixMatches(value, allowed).slice(0, MAX_COMPLETION_ITEMS);\n }\n\n const { searchDir, prefix } = context;\n const dirMatches = await findMatchesInDirectory(searchDir, prefix, allowed, (p) =>\n pathGuard.isSensitive(p),\n );\n const rootMatches = findMatchingRoots(searchDir, prefix, allowed);\n return mergeCompletionMatches(dirMatches, rootMatches).slice(0, MAX_COMPLETION_ITEMS);\n } catch (error) {\n rethrowIfAborted(error);\n Logger.warn('suggestPaths: completion failed, returning empty list', {\n error: error instanceof Error ? (error.stack ?? error.message) : String(error),\n });\n return [];\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"path-discovery.d.ts","sourceRoot":"","sources":["../../src/core/path-discovery.ts"],"names":[],"mappings":"AAiBA,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,MAAM,EACd,IAAI,GAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAC9E,OAAO,CAAC,MAAM,EAAE,CAAC,CAwBnB;AAED,wBAAgB,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAiC9D;AAID,wBAAsB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAwC1F"}
1
+ {"version":3,"file":"path-discovery.d.ts","sourceRoot":"","sources":["../../src/core/path-discovery.ts"],"names":[],"mappings":"AAgBA,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,MAAM,EACd,IAAI,GAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAC9E,OAAO,CAAC,MAAM,EAAE,CAAC,CAwBnB;AAED,wBAAgB,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAiC9D;AAID,wBAAsB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAwC1F"}
@@ -1,10 +1,9 @@
1
1
  import { realpath, stat } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join, parse } from 'node:path';
4
- import { formatUnknownErrorMessage } from './errors.js';
5
- import { Logger } from './observability.js';
6
- import { isPathWithinDirectories, isSamePath, normalizePath } from './path-utils.js';
7
- import { splitDirList } from './primitives.js';
4
+ import { formatUnknownErrorMessage } from "./errors.js";
5
+ import { Logger } from "./observability.js";
6
+ import { isPathWithinDirectories, isSamePath, normalizePath, splitDirList } from "./path-utils.js";
8
7
  // Resolve a configured env-var directory list (FS_ALLOWED_DIRS / FS_ROOT_BOUNDARY)
9
8
  // into normalized, verified directories. Each entry is stat'd; a non-directory
10
9
  // warns and is dropped, a missing entry warns unless `allowMissing` is set (in