@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 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,SAAS,EAAE,WAAW;IACtB,eAAe,EAAE,iBAAiB;IAClC,aAAa,EAAE,eAAe;IAC9B,iBAAiB,EAAE,mBAAmB;IACtC,mBAAmB,EAAE,qBAAqB;IAC1C,QAAQ,EAAE,UAAU;IACpB,OAAO,EAAE,SAAS;CACV,CAAC;AAgBX,SAAS,KAAK,CAAC,IAAe,EAAE,OAAe,EAAE,OAA8B,EAAE;IAC/E,OAAO;QACL,IAAI;QACJ,OAAO;QACP,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC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const ErrorCode = {\n ACCESS_DENIED: 'ACCESS_DENIED',\n NOT_FOUND: 'NOT_FOUND',\n NOT_FILE: 'NOT_FILE',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n TOO_LARGE: 'TOO_LARGE',\n TIMEOUT: 'TIMEOUT',\n CANCELLED: 'CANCELLED',\n INVALID_PATTERN: 'INVALID_PATTERN',\n INVALID_INPUT: 'INVALID_INPUT',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n SYMLINK_NOT_ALLOWED: 'SYMLINK_NOT_ALLOWED',\n IO_ERROR: 'IO_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nexport interface Problem {\n readonly code: ErrorCode;\n readonly message: string;\n readonly path?: string;\n readonly suggestion?: string;\n}\n\ninterface ProblemFactoryOptions {\n path?: string;\n suggestion?: string;\n}\n\nfunction build(code: ErrorCode, message: string, opts: ProblemFactoryOptions = {}): Problem {\n return {\n code,\n message,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n ...(opts.suggestion !== undefined ? { suggestion: opts.suggestion } : {}),\n };\n}\n\nexport const Problem = {\n invalidInput: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.INVALID_INPUT, msg, o),\n accessDenied: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.ACCESS_DENIED, msg, o),\n timeout: (msg: string, o?: ProblemFactoryOptions): Problem => build(ErrorCode.TIMEOUT, msg, o),\n cancelled: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.CANCELLED, msg, o),\n unknown: (msg: string, o?: ProblemFactoryOptions): Problem => build(ErrorCode.UNKNOWN, msg, o),\n fromUnknown(error: unknown, defaultCode: ErrorCode, path?: string): Problem {\n const problem = classify(error);\n const shouldOverride =\n problem.code === ErrorCode.UNKNOWN || problem.code === ErrorCode.IO_ERROR;\n const code = shouldOverride ? defaultCode : problem.code;\n const suggestion =\n (shouldOverride ? DEFAULT_SUGGESTIONS[code] : undefined) ??\n problem.suggestion ??\n DEFAULT_SUGGESTIONS[problem.code];\n const resolvedPath = path ?? problem.path;\n return build(code, problem.message, {\n ...(resolvedPath !== undefined ? { path: resolvedPath } : {}),\n ...(suggestion !== undefined ? { suggestion } : {}),\n });\n },\n toText(error: unknown, defaultCode: ErrorCode): { code: ErrorCode; text: string } {\n const resolved = Problem.fromUnknown(error, defaultCode);\n return { code: resolved.code, text: formatDetailedError(resolved) };\n },\n} as const;\n\nconst DEFAULT_SUGGESTIONS: Readonly<Partial<Record<ErrorCode, string>>> = {\n [ErrorCode.ACCESS_DENIED]: 'Run list_roots to list allowed directories.',\n [ErrorCode.NOT_FOUND]: 'Run list or find_files to verify the path.',\n [ErrorCode.NOT_FILE]: 'Target is a directory, not a file.',\n [ErrorCode.NOT_DIRECTORY]: 'Target is a file, not a directory.',\n [ErrorCode.TOO_LARGE]: 'Use head/tail or line ranges to read partially.',\n [ErrorCode.TIMEOUT]: 'Reduce scope, depth, or maxResults.',\n [ErrorCode.INVALID_PATTERN]: 'Check syntax and escape special characters.',\n [ErrorCode.PERMISSION_DENIED]: 'Check OS file permissions.',\n [ErrorCode.SYMLINK_NOT_ALLOWED]: 'Symlink escapes allowed directories.',\n};\n\nexport const ERRNO_MAP: Readonly<Record<string, ErrorCode>> = {\n ENOENT: ErrorCode.NOT_FOUND,\n EACCES: ErrorCode.PERMISSION_DENIED,\n EPERM: ErrorCode.PERMISSION_DENIED,\n ENOTDIR: ErrorCode.NOT_DIRECTORY,\n EISDIR: ErrorCode.NOT_FILE,\n ELOOP: ErrorCode.SYMLINK_NOT_ALLOWED,\n ENAMETOOLONG: ErrorCode.INVALID_INPUT,\n ETIMEDOUT: ErrorCode.TIMEOUT,\n EMFILE: ErrorCode.IO_ERROR,\n ENFILE: ErrorCode.IO_ERROR,\n EBUSY: ErrorCode.IO_ERROR,\n ENOTEMPTY: ErrorCode.NOT_DIRECTORY,\n EEXIST: ErrorCode.INVALID_INPUT,\n EINVAL: ErrorCode.INVALID_INPUT,\n};\n\nconst ERRNO_RE = /^E[A-Z]+$/;\n\n// NOT_FOUND is in here (not just ENOENT) because a dangling symlink whose\n// target sits inside an allowed root surfaces as an FsError NOT_FOUND. Skipping\n// the entry is the point of a listing; rethrowing would fail the whole listing.\nexport const SKIPPABLE_FS_CODES: ReadonlySet<ErrorCode> = new Set([\n ErrorCode.ACCESS_DENIED,\n ErrorCode.NOT_FOUND,\n // OS-level EACCES/EPERM on a symlink target during a listing is exactly as\n // skippable as the other three codes.\n ErrorCode.PERMISSION_DENIED,\n ErrorCode.SYMLINK_NOT_ALLOWED,\n]);\n\nexport const SKIPPABLE_ERRNOS: ReadonlySet<string> = new Set(['ENOENT', 'EACCES', 'ELOOP']);\n\ntype ClassificationSignal =\n | { kind: 'abort' }\n | { kind: 'timeout' }\n | { kind: 'errno'; errno: string; syscall?: string; path?: string }\n | { kind: 'unknown' };\n\nfunction readErrnoCode(value: unknown): string | undefined {\n if (!(value instanceof Error)) return undefined;\n const code = (value as { code?: unknown }).code;\n if (typeof code !== 'string') return undefined;\n return code;\n}\n\nfunction isAbortSingle(value: unknown): boolean {\n if (!(value instanceof Error)) return false;\n if (value.name === 'AbortError') return true;\n const code = readErrnoCode(value);\n return code === 'ABORT_ERR';\n}\n\nfunction isTimeoutSingle(value: unknown): boolean {\n if (!(value instanceof Error)) return false;\n if (value.name === 'TimeoutError') return true;\n return readErrnoCode(value) === 'ETIMEDOUT';\n}\n\nfunction readSignalSingle(value: unknown): ClassificationSignal | undefined {\n if (isAbortSingle(value)) return { kind: 'abort' };\n if (isTimeoutSingle(value)) return { kind: 'timeout' };\n const code = readErrnoCode(value);\n if (code !== undefined && ERRNO_RE.test(code)) {\n const v = value as NodeJS.ErrnoException;\n return {\n kind: 'errno',\n errno: code,\n ...(typeof v.syscall === 'string' ? { syscall: v.syscall } : {}),\n ...(typeof v.path === 'string' ? { path: v.path } : {}),\n };\n }\n return undefined;\n}\n\nfunction walkCauseChain(error: unknown): ClassificationSignal {\n let current: unknown = error;\n const visited = new Set<unknown>();\n let abortSeen = false;\n let timeoutSeen = false;\n let errnoSignal: ClassificationSignal | undefined;\n\n while (current !== undefined && current !== null && !visited.has(current)) {\n const signal = readSignalSingle(current);\n if (signal !== undefined) {\n if (signal.kind === 'abort') abortSeen = true;\n else if (signal.kind === 'timeout') timeoutSeen = true;\n else if (signal.kind === 'errno' && errnoSignal === undefined) {\n errnoSignal = signal;\n }\n }\n visited.add(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n if (abortSeen) return { kind: 'abort' };\n if (timeoutSeen) return { kind: 'timeout' };\n if (errnoSignal !== undefined) return errnoSignal;\n return { kind: 'unknown' };\n}\n\nfunction buildProblemFromSignal(signal: ClassificationSignal, error: unknown): Problem {\n const message = formatUnknownErrorMessage(error);\n switch (signal.kind) {\n case 'abort':\n return Problem.cancelled(message);\n case 'timeout':\n return Problem.timeout(message);\n case 'errno': {\n const code = ERRNO_MAP[signal.errno] ?? ErrorCode.IO_ERROR;\n return build(code, message, {\n ...(signal.path !== undefined ? { path: signal.path } : {}),\n });\n }\n case 'unknown':\n return Problem.unknown(message);\n default: {\n const _exhaustive: never = signal;\n return _exhaustive;\n }\n }\n}\n\nexport function isFsError(error: unknown): error is FsError {\n if (!(error instanceof Error) || error.name !== 'FsError') return false;\n if (!('problem' in error)) return false;\n const p = (error as { problem?: unknown }).problem;\n if (p === null || typeof p !== 'object') return false;\n const c = p as Record<string, unknown>;\n return typeof c['code'] === 'string' && typeof c['message'] === 'string';\n}\n\n/** FsError traces to a caller-supplied argument; anything else is server-side. */\nexport function fsErrorCode(error: unknown): ProtocolErrorCode {\n return isFsError(error) ? ProtocolErrorCode.InvalidParams : ProtocolErrorCode.InternalError;\n}\n\n/**\n * Structural discriminator for SDK error classes (`ProtocolError`, `SdkError`).\n * Checks `name` + `code` properties rather than `instanceof` so discrimination\n * survives cross-realm / multi-SDK-copy conditions where the prototype chain\n * breaks. Mirrors the isFsError pattern.\n */\nexport function hasErrorShape(\n error: unknown,\n name: string,\n): error is Error & { code: string | number } {\n if (!(error instanceof Error) || error.name !== name) return false;\n const c = (error as { code?: unknown }).code;\n return typeof c === 'string' || typeof c === 'number';\n}\n\nfunction classify(error: unknown): Problem {\n if (error === null || error === undefined) {\n return Problem.unknown('Unknown error');\n }\n if (isFsError(error)) return error.problem;\n // No `ZodError` branch, deliberately. Tool arguments are validated by\n // `safeParse` inside the SDK's validator seam (tools/define.ts), which never\n // throws — it hands back `z.prettifyError`'s string — and nothing in `src/`\n // calls `.parse()`. A ZodError reaching here would fall through to\n // `Problem.unknown` with Zod's raw JSON-dump `.message`, so if a `.parse()`\n // is ever added, add the branch back with it rather than discovering this.\n if (!(error instanceof Error)) {\n return Problem.unknown(typeof error === 'string' ? error : '[non-Error thrown]');\n }\n const signal = walkCauseChain(error);\n return buildProblemFromSignal(signal, error);\n}\n\nexport function isNodeError(error: unknown): error is NodeJS.ErrnoException {\n if (!(error instanceof Error)) return false;\n if (!('code' in error)) return false;\n const { code } = error as { code?: unknown };\n return typeof code === 'string';\n}\n\n/** True when `error` is a Node errno error with code `ENOENT` (path not found). */\nexport function isNotFoundErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code === 'ENOENT';\n}\n\nfunction isAbortError(error: unknown): boolean {\n return classify(error).code === ErrorCode.CANCELLED;\n}\n\nexport function rethrowIfAborted(error: unknown): void {\n if (isAbortError(error)) throw error;\n}\n\nexport function formatUnknownErrorMessage(error: unknown): string {\n if (typeof error === 'string') return error;\n if (error instanceof Error) return error.message;\n try {\n return JSON.stringify(error);\n } catch {\n return `[non-serializable: ${Object.prototype.toString.call(error)}]`;\n }\n}\n\nexport function normalizeUnknownError(error: unknown): Error {\n return error instanceof Error ? error : new Error(formatUnknownErrorMessage(error));\n}\n\nfunction formatDetailedError(\n error: Pick<Problem, 'code' | 'message' | 'path' | 'suggestion'>,\n): string {\n const lines: string[] = [`${error.code}: ${error.message}`];\n if (error.path && !error.message.includes(error.path)) {\n lines.push(error.path);\n }\n if (error.suggestion) {\n lines.push(error.suggestion);\n }\n return lines.join('\\n');\n}\n\nexport class FsError extends Error {\n readonly problem: Problem;\n\n constructor(code: ErrorCode, message: string, path?: string, cause?: unknown) {\n super(message, cause === undefined ? {} : { cause });\n const suggestion = DEFAULT_SUGGESTIONS[code];\n this.problem = {\n code,\n message,\n ...(path !== undefined ? { path } : {}),\n ...(suggestion !== undefined ? { suggestion } : {}),\n };\n this.name = 'FsError';\n Object.setPrototypeOf(this, FsError.prototype);\n }\n\n get code(): ErrorCode {\n return this.problem.code;\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,SAAS,EAAE,WAAW;IACtB,eAAe,EAAE,iBAAiB;IAClC,aAAa,EAAE,eAAe;IAC9B,iBAAiB,EAAE,mBAAmB;IACtC,mBAAmB,EAAE,qBAAqB;IAC1C,QAAQ,EAAE,UAAU;IACpB,OAAO,EAAE,SAAS;CACV,CAAC;AAgBX,SAAS,KAAK,CAAC,IAAe,EAAE,OAAe,EAAE,OAA8B,EAAE;IAC/E,OAAO;QACL,IAAI;QACJ,OAAO;QACP,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,GAAG,CAAC,IAAI,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,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AAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;CACF","sourcesContent":["import { ProtocolErrorCode } from '@modelcontextprotocol/server';\n\nexport const ErrorCode = {\n ACCESS_DENIED: 'ACCESS_DENIED',\n NOT_FOUND: 'NOT_FOUND',\n NOT_FILE: 'NOT_FILE',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n TOO_LARGE: 'TOO_LARGE',\n TIMEOUT: 'TIMEOUT',\n CANCELLED: 'CANCELLED',\n INVALID_PATTERN: 'INVALID_PATTERN',\n INVALID_INPUT: 'INVALID_INPUT',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n SYMLINK_NOT_ALLOWED: 'SYMLINK_NOT_ALLOWED',\n IO_ERROR: 'IO_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nexport interface Problem {\n readonly code: ErrorCode;\n readonly message: string;\n readonly path?: string;\n readonly suggestion?: string;\n}\n\ninterface ProblemFactoryOptions {\n path?: string;\n suggestion?: string;\n}\n\nfunction build(code: ErrorCode, message: string, opts: ProblemFactoryOptions = {}): Problem {\n return {\n code,\n message,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n ...(opts.suggestion !== undefined ? { suggestion: opts.suggestion } : {}),\n };\n}\n\nexport const Problem = {\n invalidInput: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.INVALID_INPUT, msg, o),\n accessDenied: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.ACCESS_DENIED, msg, o),\n cancelled: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.CANCELLED, msg, o),\n fromUnknown(error: unknown, defaultCode: ErrorCode, path?: string): Problem {\n const problem = classify(error);\n const shouldOverride =\n problem.code === ErrorCode.UNKNOWN || problem.code === ErrorCode.IO_ERROR;\n const code = shouldOverride ? defaultCode : problem.code;\n const suggestion =\n (shouldOverride ? DEFAULT_SUGGESTIONS[code] : undefined) ??\n problem.suggestion ??\n DEFAULT_SUGGESTIONS[problem.code];\n const resolvedPath = path ?? problem.path;\n return build(code, problem.message, {\n ...(resolvedPath !== undefined ? { path: resolvedPath } : {}),\n ...(suggestion !== undefined ? { suggestion } : {}),\n });\n },\n toText(error: unknown, defaultCode: ErrorCode): { code: ErrorCode; text: string } {\n const resolved = Problem.fromUnknown(error, defaultCode);\n return { code: resolved.code, text: formatDetailedError(resolved) };\n },\n} as const;\n\nconst DEFAULT_SUGGESTIONS: Readonly<Partial<Record<ErrorCode, string>>> = {\n [ErrorCode.ACCESS_DENIED]: 'Run list_roots to list allowed directories.',\n [ErrorCode.NOT_FOUND]: 'Run list or find_files to verify the path.',\n [ErrorCode.NOT_FILE]: 'Target is a directory, not a file.',\n [ErrorCode.NOT_DIRECTORY]: 'Target is a file, not a directory.',\n [ErrorCode.TOO_LARGE]: 'Use head/tail or line ranges to read partially.',\n [ErrorCode.TIMEOUT]: 'Reduce scope, depth, or maxResults.',\n [ErrorCode.INVALID_PATTERN]: 'Check syntax and escape special characters.',\n [ErrorCode.PERMISSION_DENIED]: 'Check OS file permissions.',\n [ErrorCode.SYMLINK_NOT_ALLOWED]: 'Symlink escapes allowed directories.',\n};\n\nexport const ERRNO_MAP: Readonly<Record<string, ErrorCode>> = {\n ENOENT: ErrorCode.NOT_FOUND,\n EACCES: ErrorCode.PERMISSION_DENIED,\n EPERM: ErrorCode.PERMISSION_DENIED,\n ENOTDIR: ErrorCode.NOT_DIRECTORY,\n EISDIR: ErrorCode.NOT_FILE,\n ELOOP: ErrorCode.SYMLINK_NOT_ALLOWED,\n ENAMETOOLONG: ErrorCode.INVALID_INPUT,\n ETIMEDOUT: ErrorCode.TIMEOUT,\n EMFILE: ErrorCode.IO_ERROR,\n ENFILE: ErrorCode.IO_ERROR,\n EBUSY: ErrorCode.IO_ERROR,\n ENOTEMPTY: ErrorCode.NOT_DIRECTORY,\n EEXIST: ErrorCode.INVALID_INPUT,\n EINVAL: ErrorCode.INVALID_INPUT,\n};\n\nconst ERRNO_RE = /^E[A-Z]+$/;\n\n// NOT_FOUND is in here (not just ENOENT) because a dangling symlink whose\n// target sits inside an allowed root surfaces as an FsError NOT_FOUND. Skipping\n// the entry is the point of a listing; rethrowing would fail the whole listing.\nexport const SKIPPABLE_FS_CODES: ReadonlySet<ErrorCode> = new Set([\n ErrorCode.ACCESS_DENIED,\n ErrorCode.NOT_FOUND,\n // OS-level EACCES/EPERM on a symlink target during a listing is exactly as\n // skippable as the other three codes.\n ErrorCode.PERMISSION_DENIED,\n ErrorCode.SYMLINK_NOT_ALLOWED,\n]);\n\nexport const SKIPPABLE_ERRNOS: ReadonlySet<string> = new Set(['ENOENT', 'EACCES', 'ELOOP']);\n\n/**\n * Walk `error` and its `cause` chain for the one fact that decides the code: an\n * abort anywhere wins, then a timeout anywhere, then the FIRST errno seen.\n * `visited` guards a cyclic chain. Returns the Problem directly — the\n * intermediate signal union this replaced existed only to be destructured back\n * into a Problem two functions later, and carried a `syscall` nobody read.\n */\nfunction classifyCauseChain(error: unknown): Problem {\n const message = formatUnknownErrorMessage(error);\n const visited = new Set<unknown>();\n let aborted = false;\n let timedOut = false;\n let errno: { code: string; path?: string } | undefined;\n\n for (\n let current: unknown = error;\n current !== undefined && current !== null && !visited.has(current);\n current = (current as { cause?: unknown }).cause\n ) {\n visited.add(current);\n if (!(current instanceof Error)) continue;\n const raw = (current as { code?: unknown }).code;\n const code = typeof raw === 'string' ? raw : undefined;\n // Ordered like the per-error read it replaces: a node that reads as an\n // abort or a timeout never also contributes its errno.\n if (current.name === 'AbortError' || code === 'ABORT_ERR') {\n aborted = true;\n } else if (current.name === 'TimeoutError' || code === 'ETIMEDOUT') {\n timedOut = true;\n } else if (errno === undefined && code !== undefined && ERRNO_RE.test(code)) {\n const { path } = current as NodeJS.ErrnoException;\n errno = { code, ...(typeof path === 'string' ? { path } : {}) };\n }\n }\n\n if (aborted) return Problem.cancelled(message);\n if (timedOut) return build(ErrorCode.TIMEOUT, message);\n if (errno !== undefined) {\n return build(ERRNO_MAP[errno.code] ?? ErrorCode.IO_ERROR, message, {\n ...(errno.path !== undefined ? { path: errno.path } : {}),\n });\n }\n return build(ErrorCode.UNKNOWN, message);\n}\n\nexport function isFsError(error: unknown): error is FsError {\n return error instanceof FsError;\n}\n\n/** FsError traces to a caller-supplied argument; anything else is server-side. */\nexport function fsErrorCode(error: unknown): ProtocolErrorCode {\n return isFsError(error) ? ProtocolErrorCode.InvalidParams : ProtocolErrorCode.InternalError;\n}\n\nfunction classify(error: unknown): Problem {\n if (error === null || error === undefined) {\n return build(ErrorCode.UNKNOWN, 'Unknown error');\n }\n if (isFsError(error)) return error.problem;\n // No `ZodError` branch, deliberately. Tool arguments are validated by\n // `safeParse` inside the SDK's validator seam (tools/define.ts), which never\n // throws — it hands back `z.prettifyError`'s string — and nothing in `src/`\n // calls `.parse()`. A ZodError reaching here would fall through to\n // UNKNOWN with Zod's raw JSON-dump `.message`, so if a `.parse()`\n // is ever added, add the branch back with it rather than discovering this.\n if (!(error instanceof Error)) {\n return build(ErrorCode.UNKNOWN, typeof error === 'string' ? error : '[non-Error thrown]');\n }\n return classifyCauseChain(error);\n}\n\nexport function isNodeError(error: unknown): error is NodeJS.ErrnoException {\n if (!(error instanceof Error)) return false;\n if (!('code' in error)) return false;\n const { code } = error as { code?: unknown };\n return typeof code === 'string';\n}\n\n/** True when `error` is a Node errno error with code `ENOENT` (path not found). */\nexport function isNotFoundErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code === 'ENOENT';\n}\n\n/**\n * Rethrow when `error` reads as cancelled. Answers the question directly rather\n * than through `classify`, which allocated a Problem — and ran\n * `formatUnknownErrorMessage`, i.e. a `JSON.stringify` on a non-Error — for a\n * boolean. This sits in eight catch blocks, several inside per-entry scan loops.\n */\nexport function rethrowIfAborted(error: unknown): void {\n if (isFsError(error)) {\n if (error.code === ErrorCode.CANCELLED) throw error;\n return;\n }\n const visited = new Set<unknown>();\n for (\n let current: unknown = error;\n current !== undefined && current !== null && !visited.has(current);\n current = (current as { cause?: unknown }).cause\n ) {\n visited.add(current);\n if (!(current instanceof Error)) continue;\n if (current.name === 'AbortError' || (current as { code?: unknown }).code === 'ABORT_ERR') {\n throw error;\n }\n }\n}\n\nexport function formatUnknownErrorMessage(error: unknown): string {\n if (typeof error === 'string') return error;\n if (error instanceof Error) return error.message;\n try {\n return JSON.stringify(error);\n } catch {\n return `[non-serializable: ${Object.prototype.toString.call(error)}]`;\n }\n}\n\nexport function normalizeUnknownError(error: unknown): Error {\n return error instanceof Error ? error : new Error(formatUnknownErrorMessage(error));\n}\n\nfunction formatDetailedError(\n error: Pick<Problem, 'code' | 'message' | 'path' | 'suggestion'>,\n): string {\n const lines: string[] = [`${error.code}: ${error.message}`];\n if (error.path && !error.message.includes(error.path)) {\n lines.push(error.path);\n }\n if (error.suggestion) {\n lines.push(error.suggestion);\n }\n return lines.join('\\n');\n}\n\nexport class FsError extends Error {\n readonly problem: Problem;\n\n constructor(code: ErrorCode, message: string, path?: string, cause?: unknown) {\n super(message, cause === undefined ? {} : { cause });\n const suggestion = DEFAULT_SUGGESTIONS[code];\n this.problem = {\n code,\n message,\n ...(path !== undefined ? { path } : {}),\n ...(suggestion !== undefined ? { suggestion } : {}),\n };\n this.name = 'FsError';\n }\n\n get code(): ErrorCode {\n return this.problem.code;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { ContentBlock } from '@modelcontextprotocol/server';
2
- import type { FileKind } from './schema.js';
3
- import type { ResourceStore } from './store.js';
2
+ import type { FileKind } from './schema.ts';
3
+ import type { ResourceStore } from './store.ts';
4
4
  export declare const FILESYSTEM_FILE_URI_TEMPLATE = "filesystem-mcp://file/{+path}";
5
5
  /**
6
6
  * The `{+path}` template-variable form of a path — what `completion/complete`
@@ -28,7 +28,11 @@ export interface WrittenFileMeta {
28
28
  lineCount: number;
29
29
  mimeType: string;
30
30
  kind: FileKind;
31
- resourceUri: string;
31
+ /**
32
+ * Undefined when the resulting file exceeds the text-size cap: the store
33
+ * serves the URI via readRaw, which would reject it with TOO_LARGE.
34
+ */
35
+ resourceUri: string | undefined;
32
36
  /** Undefined when no resource store is configured — nothing to link into. */
33
37
  resourceLink: ContentBlock | undefined;
34
38
  }
@@ -1 +1 @@
1
- {"version":3,"file":"file-uri.d.ts","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAMjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAMhD,eAAO,MAAM,4BAA4B,kCAAkC,CAAC;AAE5E;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMrE;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,GACX,YAAY,CASd;AAED,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,GACX,YAAY,CAOd;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQ3D;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,QAAQ,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB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EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,6EAA6E;IAC7E,YAAY,EAAE,YAAY,GAAG,SAAS,CAAC;CACxC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,aAAa,GAAG,SAAS,GACvC,eAAe,CAiBjB"}
@@ -1,6 +1,7 @@
1
1
  import { basename } from 'node:path';
2
- import { detectMimeFromContent } from './mime.js';
3
- import { countLines } from './read.js';
2
+ import { detectMimeFromContent } from "./mime.js";
3
+ import { countLines } from "./read.js";
4
+ import { getMaxTextFileSize } from "./util.js";
4
5
  // Single owner of the `filesystem-mcp://file/` URI scheme — the template string,
5
6
  // the path→URI encoder, the URI→path decoder, the link blocks built from them,
6
7
  // and the post-write metadata block every write tool reports alongside them.
@@ -66,13 +67,16 @@ export function extractPath(uri) {
66
67
  export function buildWrittenFileMeta(validPath, content, resourceStore) {
67
68
  const size = Buffer.byteLength(content, 'utf-8');
68
69
  const mimeInfo = detectMimeFromContent(validPath, content);
70
+ // An edit or patch can push a readable file past the text-size cap; the
71
+ // store serves the URI via readRaw, which would reject it with TOO_LARGE.
72
+ const servable = size <= getMaxTextFileSize();
69
73
  return {
70
74
  size,
71
75
  lineCount: countLines(content),
72
76
  mimeType: mimeInfo.mimeType,
73
77
  kind: mimeInfo.kind,
74
- resourceUri: buildFileResourceUri(validPath),
75
- resourceLink: resourceStore
78
+ resourceUri: servable ? buildFileResourceUri(validPath) : undefined,
79
+ resourceLink: resourceStore && servable
76
80
  ? buildFileResourceLink(validPath, mimeInfo.mimeType, size)
77
81
  : undefined,
78
82
  };
@@ -1 +1 @@
1
- {"version":3,"file":"file-uri.js","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,EAAE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AG,CAAC,CAAC;QACzB,IAAI,GAAG,CAAC,QAAQ,KAAK,iBAAiB,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,SAAS,CAAC;QAChF,OAAO,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAYD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAClC,SAAiB,EACjB,OAAe,EACf,aAAwC;IAExC,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC3D,OAAO;QACL,IAAI;QACJ,SAAS,EAAE,UAAU,CAAC,OAAO,CAAC;QAC9B,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,WAAW,EAAE,oBAAoB,CAAC,SAAS,CAAC;QAC5C,YAAY,EAAE,aAAa;YACzB,CAAC,CAAC,qBAAqB,CAAC,SAAS,EAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC;YAC3D,CAAC,CAAC,SAAS;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport { detectMimeFromContent } from './mime.js';\nimport { countLines } from './read.js';\nimport type { FileKind } from './schema.js';\nimport type { ResourceStore } from './store.js';\n\n// Single owner of the `filesystem-mcp://file/` URI scheme — the template string,\n// the path→URI encoder, the URI→path decoder, the link blocks built from them,\n// and the post-write metadata block every write tool reports alongside them.\n\nexport const FILESYSTEM_FILE_URI_TEMPLATE = 'filesystem-mcp://file/{+path}';\n\n/**\n * The `{+path}` template-variable form of a path — what `completion/complete`\n * must return, since a client expands a suggestion into the template verbatim.\n * Unescaped, a '#' or '?' in a filename truncates the URI into a fragment or\n * query (silently naming a different path) and a '%' makes the decode throw.\n * Separators are restored so the value still reads as a path.\n */\nexport function encodeFileUriPath(validPath: string): string {\n const posix = validPath.replace(/\\\\/g, '/');\n return encodeURIComponent(posix).replace(/%2F/gi, '/');\n}\n\n/** Inverse of {@link encodeFileUriPath}; `undefined` on invalid percent-encoding. */\nexport function decodeFileUriPath(encoded: string): string | undefined {\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\nexport function buildFileResourceUri(validPath: string): string {\n return `filesystem-mcp://file/${encodeFileUriPath(validPath)}`;\n}\n\n/**\n * The link block for a URI already built by `buildFileResourceUri`. Callers that\n * hold the URI must use this rather than rebuilding from a path: a path that\n * differs only in case (the drive letter, on Windows) yields a *different* URI\n * string, and watchers key on that string — a link and a `resourceUri` that\n * disagree hand the client two subscriptions for one file.\n */\nexport function buildFileResourceLinkFor(\n uri: string,\n name: string,\n mimeType: string,\n size: number,\n): ContentBlock {\n return {\n type: 'resource_link',\n uri,\n name,\n mimeType,\n size,\n annotations: { audience: ['user', 'assistant'] },\n };\n}\n\nexport function buildFileResourceLink(\n validPath: string,\n mimeType: string,\n size: number,\n): ContentBlock {\n return buildFileResourceLinkFor(\n buildFileResourceUri(validPath),\n basename(validPath),\n mimeType,\n size,\n );\n}\n\nexport function extractPath(uri: string): string | undefined {\n try {\n const url = new URL(uri);\n if (url.protocol !== 'filesystem-mcp:' || url.host !== 'file') return undefined;\n return decodeFileUriPath(url.pathname.slice(1));\n } catch {\n return undefined;\n }\n}\n\nexport interface WrittenFileMeta {\n size: number;\n lineCount: number;\n mimeType: string;\n kind: FileKind;\n resourceUri: string;\n /** Undefined when no resource store is configured — nothing to link into. */\n resourceLink: ContentBlock | undefined;\n}\n\n/**\n * The five-step block every write tool runs on its post-write content: size,\n * line count, MIME, the file's resource URI, and the store-gated link block.\n */\nexport function buildWrittenFileMeta(\n validPath: string,\n content: string,\n resourceStore: ResourceStore | undefined,\n): WrittenFileMeta {\n const size = Buffer.byteLength(content, 'utf-8');\n const mimeInfo = detectMimeFromContent(validPath, content);\n return {\n size,\n lineCount: countLines(content),\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n resourceUri: buildFileResourceUri(validPath),\n resourceLink: resourceStore\n ? buildFileResourceLink(validPath, mimeInfo.mimeType, size)\n : undefined,\n };\n}\n"]}
1
+ {"version":3,"file":"file-uri.js","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAGvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAE/C,iFAAiF;AACjF,+EAA+E;AAC/E,6EAA6E;AAE7E,MAAM,CAAC,MAAM,4BAA4B,GAAG,+BAA+B,CAAC;AAE5E;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,SAAiB;IACjD,MAAM,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAC5C,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACzD,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,iBAAiB,CAAC,OAAe;IAC/C,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,SAAiB;IACpD,OAAO,yBAAyB,iBAAiB,CAAC,SAAS,CAAC,EAAE,CAAC;AACjE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wBAAwB,CACtC,GAAW,EACX,IA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AAQ,CAAC,IAAI;QACnB,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS;QACnE,YAAY,EACV,aAAa,IAAI,QAAQ;YACvB,CAAC,CAAC,qBAAqB,CAAC,SAAS,EAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC;YAC3D,CAAC,CAAC,SAAS;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport { detectMimeFromContent } from './mime.ts';\nimport { countLines } from './read.ts';\nimport type { FileKind } from './schema.ts';\nimport type { ResourceStore } from './store.ts';\nimport { getMaxTextFileSize } from './util.ts';\n\n// Single owner of the `filesystem-mcp://file/` URI scheme — the template string,\n// the path→URI encoder, the URI→path decoder, the link blocks built from them,\n// and the post-write metadata block every write tool reports alongside them.\n\nexport const FILESYSTEM_FILE_URI_TEMPLATE = 'filesystem-mcp://file/{+path}';\n\n/**\n * The `{+path}` template-variable form of a path — what `completion/complete`\n * must return, since a client expands a suggestion into the template verbatim.\n * Unescaped, a '#' or '?' in a filename truncates the URI into a fragment or\n * query (silently naming a different path) and a '%' makes the decode throw.\n * Separators are restored so the value still reads as a path.\n */\nexport function encodeFileUriPath(validPath: string): string {\n const posix = validPath.replace(/\\\\/g, '/');\n return encodeURIComponent(posix).replace(/%2F/gi, '/');\n}\n\n/** Inverse of {@link encodeFileUriPath}; `undefined` on invalid percent-encoding. */\nexport function decodeFileUriPath(encoded: string): string | undefined {\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\nexport function buildFileResourceUri(validPath: string): string {\n return `filesystem-mcp://file/${encodeFileUriPath(validPath)}`;\n}\n\n/**\n * The link block for a URI already built by `buildFileResourceUri`. Callers that\n * hold the URI must use this rather than rebuilding from a path: a path that\n * differs only in case (the drive letter, on Windows) yields a *different* URI\n * string, and watchers key on that string — a link and a `resourceUri` that\n * disagree hand the client two subscriptions for one file.\n */\nexport function buildFileResourceLinkFor(\n uri: string,\n name: string,\n mimeType: string,\n size: number,\n): ContentBlock {\n return {\n type: 'resource_link',\n uri,\n name,\n mimeType,\n size,\n annotations: { audience: ['user', 'assistant'] },\n };\n}\n\nexport function buildFileResourceLink(\n validPath: string,\n mimeType: string,\n size: number,\n): ContentBlock {\n return buildFileResourceLinkFor(\n buildFileResourceUri(validPath),\n basename(validPath),\n mimeType,\n size,\n );\n}\n\nexport function extractPath(uri: string): string | undefined {\n try {\n const url = new URL(uri);\n if (url.protocol !== 'filesystem-mcp:' || url.host !== 'file') return undefined;\n return decodeFileUriPath(url.pathname.slice(1));\n } catch {\n return undefined;\n }\n}\n\nexport interface WrittenFileMeta {\n size: number;\n lineCount: number;\n mimeType: string;\n kind: FileKind;\n /**\n * Undefined when the resulting file exceeds the text-size cap: the store\n * serves the URI via readRaw, which would reject it with TOO_LARGE.\n */\n resourceUri: string | undefined;\n /** Undefined when no resource store is configured — nothing to link into. */\n resourceLink: ContentBlock | undefined;\n}\n\n/**\n * The five-step block every write tool runs on its post-write content: size,\n * line count, MIME, the file's resource URI, and the store-gated link block.\n */\nexport function buildWrittenFileMeta(\n validPath: string,\n content: string,\n resourceStore: ResourceStore | undefined,\n): WrittenFileMeta {\n const size = Buffer.byteLength(content, 'utf-8');\n const mimeInfo = detectMimeFromContent(validPath, content);\n // An edit or patch can push a readable file past the text-size cap; the\n // store serves the URI via readRaw, which would reject it with TOO_LARGE.\n const servable = size <= getMaxTextFileSize();\n return {\n size,\n lineCount: countLines(content),\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n resourceUri: servable ? buildFileResourceUri(validPath) : undefined,\n resourceLink:\n resourceStore && servable\n ? buildFileResourceLink(validPath, mimeInfo.mimeType, size)\n : undefined,\n };\n}\n"]}
@@ -41,16 +41,5 @@ export declare function pageTrailer(p: {
41
41
  nextCursor?: string | undefined;
42
42
  stoppedReason?: string | undefined;
43
43
  }): string;
44
- export declare function padEndVisible(s: string, width: number): string;
45
- export declare const cliFmt: {
46
- bold: (t: string) => string;
47
- dim: (t: string) => string;
48
- cyan: (t: string) => string;
49
- yellow: (t: string) => string;
50
- flag: (t: string) => string;
51
- placeholder: (t: string) => string;
52
- section: (t: string) => string;
53
- bool: (v: boolean) => string;
54
- };
55
44
  export {};
56
45
  //# sourceMappingURL=fmt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fmt.d.ts","sourceRoot":"","sources":["../../src/core/fmt.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAkCtC,wBAAgB,YAAY,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,GAAG,MAAM,CAGnE;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,SAAiB,GAAG,MAAM,CAE5F;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAKD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,SAAQ,GAAG,MAAM,CAI9E;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,SAAK,GAAG,MAAM,CAE/E;AAYD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,KA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9E;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,SAAK,GAAG,MAAM,CAE/E;AAYD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACpC,GAAG,MAAM,CAoBT"}
package/dist/core/fmt.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { basename } from 'node:path';
2
- import { stripVTControlCharacters, styleText } from 'node:util';
3
- import { MAX_SEARCH_RESULTS } from './util.js';
2
+ import { MAX_SEARCH_RESULTS } from "./util.js";
4
3
  function buildBody(ctx, phase) {
5
4
  const items = [];
6
5
  if (ctx.subject) {
@@ -96,21 +95,4 @@ export function pageTrailer(p) {
96
95
  }
97
96
  return lines.length > 0 ? `\n\n${lines.join('\n')}` : '';
98
97
  }
99
- // ---------------------------------------------------------------------------
100
- // CLI color helpers
101
- // ---------------------------------------------------------------------------
102
- export function padEndVisible(s, width) {
103
- const visible = stripVTControlCharacters(s).length;
104
- return visible >= width ? s : s + ' '.repeat(width - visible);
105
- }
106
- export const cliFmt = {
107
- bold: (t) => styleText('bold', t),
108
- dim: (t) => styleText('dim', t),
109
- cyan: (t) => styleText('cyan', t),
110
- yellow: (t) => styleText('yellow', t),
111
- flag: (t) => styleText('green', t),
112
- placeholder: (t) => styleText('yellow', t),
113
- section: (t) => styleText(['cyan', 'bold'], t),
114
- bool: (v) => (v ? styleText('green', 'true') : styleText('red', 'false')),
115
- };
116
98
  //# sourceMappingURL=fmt.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fmt.js","sourceRoot":"","sources":["../../src/core/fmt.ts"],"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node:path';\nimport { stripVTControlCharacters, styleText } from 'node:util';\n\nimport { MAX_SEARCH_RESULTS } from './util.js';\n\nexport interface ProgressCtx {\n label: string;\n subject?: string;\n scope?: string;\n current?: number;\n total?: number;\n detail?: string;\n error?: string;\n}\n\ntype Phase = 'tick' | 'done' | 'fail';\n\nfunction buildBody(ctx: ProgressCtx, phase: Phase): string {\n const items: string[] = [];\n if (ctx.subject) {\n items.push(ctx.subject);\n }\n\n switch (phase) {\n case 'tick':\n if (ctx.current !== undefined && ctx.total !== undefined) {\n items.push(`${ctx.current}/${ctx.total}`);\n } else if (ctx.current !== undefined) {\n items.push(String(ctx.current));\n }\n break;\n case 'done':\n if (ctx.scope) {\n items.push(ctx.scope);\n }\n if (ctx.detail) {\n items.push(ctx.detail);\n }\n break;\n case 'fail':\n if (ctx.error) {\n items.push(ctx.error);\n }\n break;\n }\n\n return items.join(' · ');\n}\n\nexport function plainMessage(phase: Phase, ctx: ProgressCtx): string {\n const body = buildBody(ctx, phase);\n return body ? `${ctx.label}: ${body}` : `${ctx.label}:`;\n}\n\nexport function formatCount(count: number, singular: string, plural = `${singular}s`): string {\n return `${String(count)} ${count === 1 ? singular : plural}`;\n}\n\n/**\n * Short label for a path in summary text. `basename` returns '' for a root\n * (`C:\\`, `/`) and for a trailing-slash path, which rendered as a bare\n * separator in the per-path summaries, so fall back to the full path.\n */\nexport function pathLabel(path: string): string {\n return basename(path) || path;\n}\n\n/** Names past this point are noise in a summary line; structuredContent holds them all. */\nconst MAX_ROSTER_ITEMS = 20;\n\n/**\n * Join a per-path summary roster, capped. A 1000-path delete would otherwise\n * name every entry in the text block that `structuredContent` already carries\n * in full.\n */\nexport function joinRoster(items: readonly string[], separator = ' · '): string {\n if (items.length <= MAX_ROSTER_ITEMS) return items.join(separator);\n const shown = items.slice(0, MAX_ROSTER_ITEMS).join(separator);\n return `${shown}${separator}+${String(items.length - MAX_ROSTER_ITEMS)} more`;\n}\n\nexport function truncateProgressPattern(pattern: string, maxLength = 40): string {\n return pattern.length <= maxLength ? pattern : `${pattern.slice(0, maxLength)}…`;\n}\n\n/**\n * `stoppedReason` names the engine's own cap, and `maxResults` is also the name\n * of the caller's page-size argument — spelling the cap out keeps a caller who\n * passed `maxResults: 5` from reading their own argument back.\n */\nconst STOP_REASON_TEXT: Record<string, string> = {\n maxResults: `hit the server's ${String(MAX_SEARCH_RESULTS)}-result scan cap, not your maxResults`,\n timeout: 'hit the time limit, or the request was cancelled',\n};\n\n/**\n * The `//` lines a paged search appends to its text block. Paging and the\n * engine's stop state live in the structured half, which `defineTool` ships\n * under `_meta` for a tool that authors its own text — and no client renders\n * that. These lines are the only place a caller learns that more remains or\n * that the scan was cut. They are independent: a scan can stop early with too\n * few results to page, so a truncation with no cursor must still say so.\n * Prefixed `//` so neither can be mistaken for a result row.\n */\nexport function pageTrailer(p: {\n offset: number;\n shown: number;\n total: number;\n noun: string;\n tool: string;\n nextCursor?: string | undefined;\n stoppedReason?: string | undefined;\n}): string {\n const lines: string[] = [];\n // Position is owed on every page of a split set, including the last one —\n // which has no cursor and would otherwise read as the whole answer.\n if (p.offset > 0 || p.total > p.shown) {\n const next =\n p.nextCursor === undefined\n ? ''\n : ` Next page: ${p.tool} ${JSON.stringify({ cursor: p.nextCursor })}`;\n lines.push(\n `// showing ${String(p.offset + 1)}-${String(p.offset + p.shown)} of ${String(p.total)} ${p.noun}.${next}`,\n );\n }\n if (p.stoppedReason !== undefined) {\n const cause = STOP_REASON_TEXT[p.stoppedReason] ?? `stopped (${p.stoppedReason})`;\n lines.push(\n `// scan stopped early: ${cause}. That total is a floor, not the count. Narrow path or pattern for the rest.`,\n );\n }\n return lines.length > 0 ? `\\n\\n${lines.join('\\n')}` : '';\n}\n\n// ---------------------------------------------------------------------------\n// CLI color helpers\n// ---------------------------------------------------------------------------\n\nexport function padEndVisible(s: string, width: number): string {\n const visible = stripVTControlCharacters(s).length;\n return visible >= width ? s : s + ' '.repeat(width - visible);\n}\n\nexport const cliFmt = {\n bold: (t: string) => styleText('bold', t),\n dim: (t: string) => styleText('dim', t),\n cyan: (t: string) => styleText('cyan', t),\n yellow: (t: string) => styleText('yellow', t),\n flag: (t: string) => styleText('green', t),\n placeholder: (t: string) => styleText('yellow', t),\n section: (t: string) => styleText(['cyan', 'bold'], t),\n bool: (v: boolean) => (v ? styleText('green', 'true') : styleText('red', 'false')),\n};\n"]}
1
+ {"version":3,"file":"fmt.js","sourceRoot":"","sources":["../../src/core/fmt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAc/C,SAAS,SAAS,CAAC,GAAgB,EAAE,KAAY;IAC/C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC1B,CAAC;IAED,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,MAAM;YACT,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzD,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;YAC5C,CAAC;iBAAM,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;gBACrC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;YAClC,CAAC;YACD,MAAM;QACR,KAAK,MAAM;YACT,IAAI,GAAG,CAAC,KAAK,EAAE,CAAC;gBACd,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;YACD,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;gBACf,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAA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AAC,aAAa,CAAC,IAAI,YAAY,CAAC,CAAC,aAAa,GAAG,CAAC;QAClF,KAAK,CAAC,IAAI,CACR,0BAA0B,KAAK,8EAA8E,CAC9G,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import { basename } from 'node:path';\n\nimport { MAX_SEARCH_RESULTS } from './util.ts';\n\nexport interface ProgressCtx {\n label: string;\n subject?: string;\n scope?: string;\n current?: number;\n total?: number;\n detail?: string;\n error?: string;\n}\n\ntype Phase = 'tick' | 'done' | 'fail';\n\nfunction buildBody(ctx: ProgressCtx, phase: Phase): string {\n const items: string[] = [];\n if (ctx.subject) {\n items.push(ctx.subject);\n }\n\n switch (phase) {\n case 'tick':\n if (ctx.current !== undefined && ctx.total !== undefined) {\n items.push(`${ctx.current}/${ctx.total}`);\n } else if (ctx.current !== undefined) {\n items.push(String(ctx.current));\n }\n break;\n case 'done':\n if (ctx.scope) {\n items.push(ctx.scope);\n }\n if (ctx.detail) {\n items.push(ctx.detail);\n }\n break;\n case 'fail':\n if (ctx.error) {\n items.push(ctx.error);\n }\n break;\n }\n\n return items.join(' · ');\n}\n\nexport function plainMessage(phase: Phase, ctx: ProgressCtx): string {\n const body = buildBody(ctx, phase);\n return body ? `${ctx.label}: ${body}` : `${ctx.label}:`;\n}\n\nexport function formatCount(count: number, singular: string, plural = `${singular}s`): string {\n return `${String(count)} ${count === 1 ? singular : plural}`;\n}\n\n/**\n * Short label for a path in summary text. `basename` returns '' for a root\n * (`C:\\`, `/`) and for a trailing-slash path, which rendered as a bare\n * separator in the per-path summaries, so fall back to the full path.\n */\nexport function pathLabel(path: string): string {\n return basename(path) || path;\n}\n\n/** Names past this point are noise in a summary line; structuredContent holds them all. */\nconst MAX_ROSTER_ITEMS = 20;\n\n/**\n * Join a per-path summary roster, capped. A 1000-path delete would otherwise\n * name every entry in the text block that `structuredContent` already carries\n * in full.\n */\nexport function joinRoster(items: readonly string[], separator = ' · '): string {\n if (items.length <= MAX_ROSTER_ITEMS) return items.join(separator);\n const shown = items.slice(0, MAX_ROSTER_ITEMS).join(separator);\n return `${shown}${separator}+${String(items.length - MAX_ROSTER_ITEMS)} more`;\n}\n\nexport function truncateProgressPattern(pattern: string, maxLength = 40): string {\n return pattern.length <= maxLength ? pattern : `${pattern.slice(0, maxLength)}…`;\n}\n\n/**\n * `stoppedReason` names the engine's own cap, and `maxResults` is also the name\n * of the caller's page-size argument — spelling the cap out keeps a caller who\n * passed `maxResults: 5` from reading their own argument back.\n */\nconst STOP_REASON_TEXT: Record<string, string> = {\n maxResults: `hit the server's ${String(MAX_SEARCH_RESULTS)}-result scan cap, not your maxResults`,\n timeout: 'hit the time limit, or the request was cancelled',\n};\n\n/**\n * The `//` lines a paged search appends to its text block. Paging and the\n * engine's stop state live in the structured half, which `defineTool` ships\n * under `_meta` for a tool that authors its own text — and no client renders\n * that. These lines are the only place a caller learns that more remains or\n * that the scan was cut. They are independent: a scan can stop early with too\n * few results to page, so a truncation with no cursor must still say so.\n * Prefixed `//` so neither can be mistaken for a result row.\n */\nexport function pageTrailer(p: {\n offset: number;\n shown: number;\n total: number;\n noun: string;\n tool: string;\n nextCursor?: string | undefined;\n stoppedReason?: string | undefined;\n}): string {\n const lines: string[] = [];\n // Position is owed on every page of a split set, including the last one —\n // which has no cursor and would otherwise read as the whole answer.\n if (p.offset > 0 || p.total > p.shown) {\n const next =\n p.nextCursor === undefined\n ? ''\n : ` Next page: ${p.tool} ${JSON.stringify({ cursor: p.nextCursor })}`;\n lines.push(\n `// showing ${String(p.offset + 1)}-${String(p.offset + p.shown)} of ${String(p.total)} ${p.noun}.${next}`,\n );\n }\n if (p.stoppedReason !== undefined) {\n const cause = STOP_REASON_TEXT[p.stoppedReason] ?? `stopped (${p.stoppedReason})`;\n lines.push(\n `// scan stopped early: ${cause}. That total is a floor, not the count. Narrow path or pattern for the rest.`,\n );\n }\n return lines.length > 0 ? `\\n\\n${lines.join('\\n')}` : '';\n}\n"]}
package/dist/core/fs.d.ts CHANGED
@@ -1,18 +1,28 @@
1
1
  import type { Stats } from 'node:fs';
2
2
  import type { FileHandle } from 'node:fs/promises';
3
3
  import { cp as fsCp, mkdir as fsMkdir, readlink as fsReadlink, rm as fsRm, rmdir as fsRmdir } from 'node:fs/promises';
4
- import type { PathGuard } from './path.js';
5
- import type { EntryType as FileType } from './primitives.js';
6
- import type { ReadFileResult, ReadSpec } from './read.js';
4
+ import type { EntryType as FileType } from './path-utils.ts';
5
+ import type { PathGuard } from './path.ts';
6
+ import type { ReadFileResult, ReadSpec } from './read.ts';
7
7
  export type { FileType };
8
8
  export type { Stats };
9
9
  export type { FileHandle };
10
10
  export declare function isHidden(name: string): boolean;
11
+ /**
12
+ * Line count for a file on disk, counting newline bytes in fixed 64 KiB
13
+ * chunks so an arbitrarily large file (one append's result metadata) costs
14
+ * bounded memory. NOT FileHandle.readLines: it decodes each physical line
15
+ * whole, so a multi-GB single-line log OOMs the server after the append has
16
+ * already landed — a reported failure invites a retry that appends twice.
17
+ * Matches read.ts's countLines semantics: a trailing newline does not open
18
+ * a new line, an unterminated final line counts, an empty file is 0.
19
+ */
20
+ export declare function countFileLines(filePath: string, signal?: AbortSignal): Promise<number>;
11
21
  export declare class GuardedFileSystem {
12
22
  readonly pathGuard: PathGuard;
13
23
  constructor(pathGuard: PathGuard);
14
24
  stat(filePath: string, options?: {
15
- signal?: AbortSignal;
25
+ signal?: AbortSignal | undefined;
16
26
  }): Promise<{
17
27
  stats: Stats;
18
28
  validPath: string;
@@ -41,6 +51,26 @@ export declare class GuardedFileSystem {
41
51
  }): Promise<{
42
52
  validPath: string;
43
53
  }>;
54
+ /**
55
+ * Append to the existing file (created if missing). Deliberately NOT the
56
+ * atomicWriteFile temp+rename dance: the rename would swap in a fresh inode,
57
+ * and the whole point of appending is to extend the file that's already
58
+ * there — inode and mode survive by construction.
59
+ */
60
+ appendFile(filePath: string, content: string, options?: {
61
+ encoding?: BufferEncoding;
62
+ signal?: AbortSignal | undefined;
63
+ }): Promise<{
64
+ validPath: string;
65
+ }>;
66
+ /**
67
+ * Leading bytes of a file, for MIME sniffing without loading the whole
68
+ * file — an append's result must describe the resulting file (which may be
69
+ * a multi-GB log), not the chunk that was appended.
70
+ */
71
+ readLeadingSample(filePath: string, size: number, options?: {
72
+ signal?: AbortSignal | undefined;
73
+ }): Promise<Buffer>;
44
74
  rm(filePath: string, options?: Parameters<typeof fsRm>[1]): Promise<{
45
75
  validPath: string;
46
76
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../src/core/fs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAEL,EAAE,IAAI,IAAI,EAEV,KAAK,IAAI,OAAO,EAIhB,QAAQ,IAAI,UAAU,EAEtB,EAAE,IAAI,IAAI,EACV,KAAK,IAAI,OAAO,EAIjB,MAAM,kBAAkB,CAAC;AAO1B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,KAAK,EAAE,SAAS,IAAI,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAU1D,YAAY,EAAE,QAAQ,EAAE,CAAC;AACzB,YAAY,EAAE,KAAK,EAAE,CAAC;AACtB,YAAY,EAAE,UAAU,EAAE,CAAC;AAmE3B,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE9C;AAED,qBAAa,iBAAiB;IAC5B,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;gBAElB,SAAS,EAAE,SAAS;I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,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAChD,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,CAAC;IAmB1D,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GACjC,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAA;KAAE,CAAC;IAmB9D,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAS3C,YAAY,CAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GACjC,OAAO,CAAC;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,CAAC;IAOjE,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAa9D;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAC9B,EAAE,EAAE,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,OAAO,CAAC,CAalB"}
package/dist/core/fs.js CHANGED
@@ -1,15 +1,19 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { chmod as fsChmod, cp as fsCp, lstat as fsLstat, mkdir as fsMkdir, open as fsOpen, opendir as fsOpendir, readFile as fsReadFile, readlink as fsReadlink, rename as fsRename, rm as fsRm, rmdir as fsRmdir, stat as fsStat, unlink as fsUnlink, writeFile as fsWriteFile, } from 'node:fs/promises';
3
3
  import { dirname, isAbsolute, resolve } from 'node:path';
4
- import { withAbort } from './concurrency.js';
5
- import { ErrorCode, formatUnknownErrorMessage, FsError, isFsError, isNodeError } from './errors.js';
6
- import { detectMimeFromContent } from './mime.js';
7
- import { Logger } from './observability.js';
8
- import { assertFileStats, createTooLargeError, normalizeSpec, readFileWithStats, readNormalized, } from './read.js';
9
- import { getMaxTextFileSize } from './util.js';
4
+ import { withAbort } from "./concurrency.js";
5
+ import { ErrorCode, formatUnknownErrorMessage, FsError, isFsError, isNodeError } from "./errors.js";
6
+ import { detectMimeFromContent } from "./mime.js";
7
+ import { Logger } from "./observability.js";
8
+ import { assertFileStats, createTooLargeError, readFileWithStats } from "./read.js";
9
+ import { getMaxTextFileSize } from "./util.js";
10
10
  // ─── Domain primitives ────────────────────────────────────────────────────────
11
- async function atomicWriteFile(filePath, content, pathGuard, options = {}) {
12
- const { encoding = 'utf-8', signal } = options;
11
+ /**
12
+ * validatePathForWrite + symlink resolution: a write aimed at a link must land
13
+ * on its revalidated target, not create a new file beside the link. ENOENT is
14
+ * the normal new-file case, so it falls through with the original path.
15
+ */
16
+ async function resolveForWrite(pathGuard, filePath) {
13
17
  let validPath = await pathGuard.validatePathForWrite(filePath);
14
18
  try {
15
19
  const stats = await fsLstat(validPath);
@@ -24,6 +28,11 @@ async function atomicWriteFile(filePath, content, pathGuard, options = {}) {
24
28
  throw error;
25
29
  }
26
30
  }
31
+ return validPath;
32
+ }
33
+ async function atomicWriteFile(filePath, content, pathGuard, options = {}) {
34
+ const { encoding = 'utf-8', signal } = options;
35
+ const validPath = await resolveForWrite(pathGuard, filePath);
27
36
  const tempSuffix = randomUUID().replace(/-/g, '').slice(0, 12);
28
37
  const tempPath = `${validPath}.${tempSuffix}.tmp`;
29
38
  // The rename below swaps in the temp file's inode, so the target would
@@ -64,6 +73,45 @@ async function atomicWriteFile(filePath, content, pathGuard, options = {}) {
64
73
  export function isHidden(name) {
65
74
  return name.startsWith('.');
66
75
  }
76
+ const CHAR_LF = 10;
77
+ const LINE_COUNT_CHUNK_BYTES = 64 * 1024;
78
+ /**
79
+ * Line count for a file on disk, counting newline bytes in fixed 64 KiB
80
+ * chunks so an arbitrarily large file (one append's result metadata) costs
81
+ * bounded memory. NOT FileHandle.readLines: it decodes each physical line
82
+ * whole, so a multi-GB single-line log OOMs the server after the append has
83
+ * already landed — a reported failure invites a retry that appends twice.
84
+ * Matches read.ts's countLines semantics: a trailing newline does not open
85
+ * a new line, an unterminated final line counts, an empty file is 0.
86
+ */
87
+ export async function countFileLines(filePath, signal) {
88
+ const handle = await fsOpen(filePath, 'r');
89
+ try {
90
+ let newlines = 0;
91
+ let lastByte = 0;
92
+ let totalBytes = 0;
93
+ const chunk = Buffer.alloc(LINE_COUNT_CHUNK_BYTES);
94
+ for (;;) {
95
+ signal?.throwIfAborted();
96
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
97
+ if (bytesRead === 0)
98
+ break;
99
+ totalBytes += bytesRead;
100
+ for (let i = 0; i < bytesRead; i++) {
101
+ const byte = chunk[i] ?? 0;
102
+ if (byte === CHAR_LF)
103
+ newlines++;
104
+ lastByte = byte;
105
+ }
106
+ }
107
+ // totalBytes is the empty-file sentinel: a NUL (0x00) final byte is real
108
+ // content and must count as an unterminated final line, not "empty".
109
+ return totalBytes === 0 ? 0 : lastByte === CHAR_LF ? newlines : newlines + 1;
110
+ }
111
+ finally {
112
+ await handle.close();
113
+ }
114
+ }
67
115
  export class GuardedFileSystem {
68
116
  pathGuard;
69
117
  constructor(pathGuard) {
@@ -104,6 +152,98 @@ export class GuardedFileSystem {
104
152
  async writeFile(filePath, content, options = {}) {
105
153
  return atomicWriteFile(filePath, content, this.pathGuard, options);
106
154
  }
155
+ /**
156
+ * Append to the existing file (created if missing). Deliberately NOT the
157
+ * atomicWriteFile temp+rename dance: the rename would swap in a fresh inode,
158
+ * and the whole point of appending is to extend the file that's already
159
+ * there — inode and mode survive by construction.
160
+ */
161
+ async appendFile(filePath, content, options = {}) {
162
+ const { encoding = 'utf-8', signal } = options;
163
+ const validPath = await resolveForWrite(this.pathGuard, filePath);
164
+ // Non-regular targets must be rejected before the open: 'a' on a FIFO
165
+ // (POSIX) blocks until a reader appears, and fsOpen takes no signal, so
166
+ // the call would hang unabortable and pin its concurrency slot. The
167
+ // overwrite path can't hang — it writes a temp file and renames over.
168
+ // resolveForWrite has already resolved any symlink to its target, so the
169
+ // lstat here doubles as the new-vs-existing probe for the cleanup below.
170
+ let existed = true;
171
+ try {
172
+ assertFileStats(validPath, await fsLstat(validPath));
173
+ }
174
+ catch (error) {
175
+ if (!isNodeError(error) || error.code !== 'ENOENT')
176
+ throw error;
177
+ existed = false;
178
+ }
179
+ // fs.promises.appendFile takes no signal, so a withAbort race would
180
+ // report failure while the append still lands — a client retry then
181
+ // appends twice. A handle opened with 'a' gets a genuinely abortable
182
+ // FileHandle.writeFile instead, same as the writeFile path. 'a' on a
183
+ // missing target CREATES it, so: check the signal before the open, and
184
+ // if the call then fails after creating the file, remove what it made —
185
+ // an aborted or errored call must not leave a phantom file behind.
186
+ // The pre-open lstat only proves the file was missing a moment ago:
187
+ // 'ax' makes creation exclusive, so a racer that created it in between
188
+ // fails EEXIST, reopens plainly, and never claims cleanup rights over
189
+ // the winner's file.
190
+ signal?.throwIfAborted();
191
+ let created = false;
192
+ let handle;
193
+ if (existed) {
194
+ handle = await fsOpen(validPath, 'a');
195
+ }
196
+ else {
197
+ try {
198
+ handle = await fsOpen(validPath, 'ax');
199
+ created = true;
200
+ }
201
+ catch (error) {
202
+ if (!isNodeError(error) || error.code !== 'EEXIST')
203
+ throw error;
204
+ handle = await fsOpen(validPath, 'a');
205
+ }
206
+ }
207
+ try {
208
+ signal?.throwIfAborted();
209
+ // Ceiling: an append is not transactional, so an abort landing
210
+ // mid-write can leave a prefix of the content on disk. Unwiring the
211
+ // signal would trade that for a silently-completed write; a client
212
+ // that retries is double-appending either way, so the abortable
213
+ // write stays.
214
+ await handle.writeFile(content, { encoding, signal });
215
+ }
216
+ catch (error) {
217
+ if (created) {
218
+ await fsUnlink(validPath).catch((unlinkError) => {
219
+ Logger.warn(`Failed to remove newly created ${validPath} after a failed append: ${formatUnknownErrorMessage(unlinkError)}`);
220
+ });
221
+ }
222
+ throw error;
223
+ }
224
+ finally {
225
+ await handle.close();
226
+ }
227
+ return { validPath };
228
+ }
229
+ /**
230
+ * Leading bytes of a file, for MIME sniffing without loading the whole
231
+ * file — an append's result must describe the resulting file (which may be
232
+ * a multi-GB log), not the chunk that was appended.
233
+ */
234
+ async readLeadingSample(filePath, size, options = {}) {
235
+ const { validPath } = await this.stat(filePath, options);
236
+ const handle = await fsOpen(validPath, 'r');
237
+ try {
238
+ options.signal?.throwIfAborted();
239
+ const buffer = Buffer.alloc(size);
240
+ const { bytesRead } = await handle.read(buffer, 0, size, 0);
241
+ return buffer.subarray(0, bytesRead);
242
+ }
243
+ finally {
244
+ await handle.close();
245
+ }
246
+ }
107
247
  async rm(filePath, options) {
108
248
  const validPath = await this.pathGuard.validatePathForDelete(filePath);
109
249
  await fsRm(validPath, options);
@@ -123,11 +263,10 @@ export class GuardedFileSystem {
123
263
  return { validSource, validDest };
124
264
  }
125
265
  async readFile(filePath, spec) {
126
- const normalized = normalizeSpec(spec);
266
+ spec.signal?.throwIfAborted();
127
267
  const validPath = await this.pathGuard.validateExistingPath(filePath);
128
- normalized.signal?.throwIfAborted();
129
- const stats = await withAbort(fsStat(validPath), normalized.signal);
130
- return readNormalized(filePath, validPath, stats, normalized);
268
+ const stats = await withAbort(fsStat(validPath), spec.signal);
269
+ return readFileWithStats(filePath, validPath, stats, spec);
131
270
  }
132
271
  async readEditableText(filePath, options) {
133
272
  const { stats, validPath } = await this.stat(filePath, options);