@belboy47/brc-agent 0.0.0-stage → 2.0.18

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 (416) hide show
  1. package/LICENSE +30 -0
  2. package/LICENSE-desktop-commander +21 -0
  3. package/NOTICE +13 -0
  4. package/README.md +64 -2
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +487 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/context.d.ts +31 -0
  9. package/dist/context.js +11 -0
  10. package/dist/context.js.map +1 -0
  11. package/dist/core/command-manager.d.ts +8 -0
  12. package/dist/core/command-manager.js +242 -0
  13. package/dist/core/command-manager.js.map +1 -0
  14. package/dist/core/config-field-definitions.d.ts +41 -0
  15. package/dist/core/config-field-definitions.js +38 -0
  16. package/dist/core/config-field-definitions.js.map +1 -0
  17. package/dist/core/config-manager.d.ts +102 -0
  18. package/dist/core/config-manager.js +451 -0
  19. package/dist/core/config-manager.js.map +1 -0
  20. package/dist/core/config.d.ts +6 -0
  21. package/dist/core/config.js +20 -0
  22. package/dist/core/config.js.map +1 -0
  23. package/dist/core/custom-stdio.d.ts +9 -0
  24. package/dist/core/custom-stdio.js +2 -0
  25. package/dist/core/custom-stdio.js.map +1 -0
  26. package/dist/core/error-handlers.d.ts +7 -0
  27. package/dist/core/error-handlers.js +16 -0
  28. package/dist/core/error-handlers.js.map +1 -0
  29. package/dist/core/file-transfer.d.ts +16 -0
  30. package/dist/core/file-transfer.js +316 -0
  31. package/dist/core/file-transfer.js.map +1 -0
  32. package/dist/core/handlers/edit-search-handlers.d.ts +6 -0
  33. package/dist/core/handlers/edit-search-handlers.js +7 -0
  34. package/dist/core/handlers/edit-search-handlers.js.map +1 -0
  35. package/dist/core/handlers/filesystem-handlers.d.ts +38 -0
  36. package/dist/core/handlers/filesystem-handlers.js +535 -0
  37. package/dist/core/handlers/filesystem-handlers.js.map +1 -0
  38. package/dist/core/handlers/history-handlers.d.ts +12 -0
  39. package/dist/core/handlers/history-handlers.js +68 -0
  40. package/dist/core/handlers/history-handlers.js.map +1 -0
  41. package/dist/core/handlers/index.d.ts +7 -0
  42. package/dist/core/handlers/index.js +9 -0
  43. package/dist/core/handlers/index.js.map +1 -0
  44. package/dist/core/handlers/process-handlers.d.ts +9 -0
  45. package/dist/core/handlers/process-handlers.js +16 -0
  46. package/dist/core/handlers/process-handlers.js.map +1 -0
  47. package/dist/core/handlers/search-handlers.d.ts +17 -0
  48. package/dist/core/handlers/search-handlers.js +336 -0
  49. package/dist/core/handlers/search-handlers.js.map +1 -0
  50. package/dist/core/handlers/terminal-handlers.d.ts +21 -0
  51. package/dist/core/handlers/terminal-handlers.js +36 -0
  52. package/dist/core/handlers/terminal-handlers.js.map +1 -0
  53. package/dist/core/handlers/transfer-handlers.d.ts +4 -0
  54. package/dist/core/handlers/transfer-handlers.js +76 -0
  55. package/dist/core/handlers/transfer-handlers.js.map +1 -0
  56. package/dist/core/search-manager.d.ts +162 -0
  57. package/dist/core/search-manager.js +929 -0
  58. package/dist/core/search-manager.js.map +1 -0
  59. package/dist/core/terminal-manager.d.ts +126 -0
  60. package/dist/core/terminal-manager.js +671 -0
  61. package/dist/core/terminal-manager.js.map +1 -0
  62. package/dist/core/tool-definitions.d.ts +9 -0
  63. package/dist/core/tool-definitions.js +1020 -0
  64. package/dist/core/tool-definitions.js.map +1 -0
  65. package/dist/core/tools/config.d.ts +98 -0
  66. package/dist/core/tools/config.js +279 -0
  67. package/dist/core/tools/config.js.map +1 -0
  68. package/dist/core/tools/edit.d.ts +49 -0
  69. package/dist/core/tools/edit.js +540 -0
  70. package/dist/core/tools/edit.js.map +1 -0
  71. package/dist/core/tools/feedback.d.ts +8 -0
  72. package/dist/core/tools/feedback.js +133 -0
  73. package/dist/core/tools/feedback.js.map +1 -0
  74. package/dist/core/tools/filesystem.d.ts +84 -0
  75. package/dist/core/tools/filesystem.js +991 -0
  76. package/dist/core/tools/filesystem.js.map +1 -0
  77. package/dist/core/tools/fuzzySearch.d.ts +14 -0
  78. package/dist/core/tools/fuzzySearch.js +141 -0
  79. package/dist/core/tools/fuzzySearch.js.map +1 -0
  80. package/dist/core/tools/fuzzySearchCore.d.ts +52 -0
  81. package/dist/core/tools/fuzzySearchCore.js +126 -0
  82. package/dist/core/tools/fuzzySearchCore.js.map +1 -0
  83. package/dist/core/tools/improved-process-tools.d.ts +24 -0
  84. package/dist/core/tools/improved-process-tools.js +645 -0
  85. package/dist/core/tools/improved-process-tools.js.map +1 -0
  86. package/dist/core/tools/mime-types.d.ts +3 -0
  87. package/dist/core/tools/mime-types.js +29 -0
  88. package/dist/core/tools/mime-types.js.map +1 -0
  89. package/dist/core/tools/pdf/extract-images.d.ts +34 -0
  90. package/dist/core/tools/pdf/extract-images.js +133 -0
  91. package/dist/core/tools/pdf/extract-images.js.map +1 -0
  92. package/dist/core/tools/pdf/index.d.ts +6 -0
  93. package/dist/core/tools/pdf/index.js +4 -0
  94. package/dist/core/tools/pdf/index.js.map +1 -0
  95. package/dist/core/tools/pdf/lib/pdf2md.d.ts +36 -0
  96. package/dist/core/tools/pdf/lib/pdf2md.js +77 -0
  97. package/dist/core/tools/pdf/lib/pdf2md.js.map +1 -0
  98. package/dist/core/tools/pdf/manipulations.d.ts +13 -0
  99. package/dist/core/tools/pdf/manipulations.js +100 -0
  100. package/dist/core/tools/pdf/manipulations.js.map +1 -0
  101. package/dist/core/tools/pdf/markdown.d.ts +26 -0
  102. package/dist/core/tools/pdf/markdown.js +276 -0
  103. package/dist/core/tools/pdf/markdown.js.map +1 -0
  104. package/dist/core/tools/pdf/utils.d.ts +12 -0
  105. package/dist/core/tools/pdf/utils.js +35 -0
  106. package/dist/core/tools/pdf/utils.js.map +1 -0
  107. package/dist/core/tools/process.d.ts +17 -0
  108. package/dist/core/tools/process.js +88 -0
  109. package/dist/core/tools/process.js.map +1 -0
  110. package/dist/core/tools/prompts.d.ts +28 -0
  111. package/dist/core/tools/prompts.js +260 -0
  112. package/dist/core/tools/prompts.js.map +1 -0
  113. package/dist/core/tools/schemas.d.ts +594 -0
  114. package/dist/core/tools/schemas.js +282 -0
  115. package/dist/core/tools/schemas.js.map +1 -0
  116. package/dist/core/tools/usage.d.ts +5 -0
  117. package/dist/core/tools/usage.js +25 -0
  118. package/dist/core/tools/usage.js.map +1 -0
  119. package/dist/core/types.d.ts +83 -0
  120. package/dist/core/types.js +2 -0
  121. package/dist/core/types.js.map +1 -0
  122. package/dist/core/ui/file-preview/shared/preview-file-types.d.ts +5 -0
  123. package/dist/core/ui/file-preview/shared/preview-file-types.js +60 -0
  124. package/dist/core/ui/file-preview/shared/preview-file-types.js.map +1 -0
  125. package/dist/core/utils/ab-test.d.ts +12 -0
  126. package/dist/core/utils/ab-test.js +105 -0
  127. package/dist/core/utils/ab-test.js.map +1 -0
  128. package/dist/core/utils/capture.d.ts +12 -0
  129. package/dist/core/utils/capture.js +38 -0
  130. package/dist/core/utils/capture.js.map +1 -0
  131. package/dist/core/utils/dockerPrompt.d.ts +17 -0
  132. package/dist/core/utils/dockerPrompt.js +54 -0
  133. package/dist/core/utils/dockerPrompt.js.map +1 -0
  134. package/dist/core/utils/feature-flags.d.ts +59 -0
  135. package/dist/core/utils/feature-flags.js +218 -0
  136. package/dist/core/utils/feature-flags.js.map +1 -0
  137. package/dist/core/utils/files/base.d.ts +173 -0
  138. package/dist/core/utils/files/base.js +6 -0
  139. package/dist/core/utils/files/base.js.map +1 -0
  140. package/dist/core/utils/files/binary.d.ts +21 -0
  141. package/dist/core/utils/files/binary.js +66 -0
  142. package/dist/core/utils/files/binary.js.map +1 -0
  143. package/dist/core/utils/files/docx.d.ts +47 -0
  144. package/dist/core/utils/files/docx.js +678 -0
  145. package/dist/core/utils/files/docx.js.map +1 -0
  146. package/dist/core/utils/files/excel.d.ts +24 -0
  147. package/dist/core/utils/files/excel.js +438 -0
  148. package/dist/core/utils/files/excel.js.map +1 -0
  149. package/dist/core/utils/files/factory.d.ts +29 -0
  150. package/dist/core/utils/files/factory.js +103 -0
  151. package/dist/core/utils/files/factory.js.map +1 -0
  152. package/dist/core/utils/files/image.d.ts +21 -0
  153. package/dist/core/utils/files/image.js +79 -0
  154. package/dist/core/utils/files/image.js.map +1 -0
  155. package/dist/core/utils/files/index.d.ts +9 -0
  156. package/dist/core/utils/files/index.js +15 -0
  157. package/dist/core/utils/files/index.js.map +1 -0
  158. package/dist/core/utils/files/pdf.d.ts +32 -0
  159. package/dist/core/utils/files/pdf.js +141 -0
  160. package/dist/core/utils/files/pdf.js.map +1 -0
  161. package/dist/core/utils/files/text.d.ts +70 -0
  162. package/dist/core/utils/files/text.js +552 -0
  163. package/dist/core/utils/files/text.js.map +1 -0
  164. package/dist/core/utils/fuzzySearchLogger.d.ts +26 -0
  165. package/dist/core/utils/fuzzySearchLogger.js +9 -0
  166. package/dist/core/utils/fuzzySearchLogger.js.map +1 -0
  167. package/dist/core/utils/lineEndingHandler.d.ts +21 -0
  168. package/dist/core/utils/lineEndingHandler.js +78 -0
  169. package/dist/core/utils/lineEndingHandler.js.map +1 -0
  170. package/dist/core/utils/logger.d.ts +17 -0
  171. package/dist/core/utils/logger.js +5 -0
  172. package/dist/core/utils/logger.js.map +1 -0
  173. package/dist/core/utils/mcp-ui-ab-test.d.ts +13 -0
  174. package/dist/core/utils/mcp-ui-ab-test.js +63 -0
  175. package/dist/core/utils/mcp-ui-ab-test.js.map +1 -0
  176. package/dist/core/utils/open-browser.d.ts +9 -0
  177. package/dist/core/utils/open-browser.js +47 -0
  178. package/dist/core/utils/open-browser.js.map +1 -0
  179. package/dist/core/utils/process-detection.d.ts +23 -0
  180. package/dist/core/utils/process-detection.js +151 -0
  181. package/dist/core/utils/process-detection.js.map +1 -0
  182. package/dist/core/utils/ripgrep-resolver.d.ts +9 -0
  183. package/dist/core/utils/ripgrep-resolver.js +96 -0
  184. package/dist/core/utils/ripgrep-resolver.js.map +1 -0
  185. package/dist/core/utils/system-info.d.ts +72 -0
  186. package/dist/core/utils/system-info.js +723 -0
  187. package/dist/core/utils/system-info.js.map +1 -0
  188. package/dist/core/utils/toolHistory.d.ts +31 -0
  189. package/dist/core/utils/toolHistory.js +17 -0
  190. package/dist/core/utils/toolHistory.js.map +1 -0
  191. package/dist/core/utils/trackTools.d.ts +1 -0
  192. package/dist/core/utils/trackTools.js +3 -0
  193. package/dist/core/utils/trackTools.js.map +1 -0
  194. package/dist/core/utils/unsupportedParams.d.ts +24 -0
  195. package/dist/core/utils/unsupportedParams.js +67 -0
  196. package/dist/core/utils/unsupportedParams.js.map +1 -0
  197. package/dist/core/utils/usageTracker.d.ts +125 -0
  198. package/dist/core/utils/usageTracker.js +475 -0
  199. package/dist/core/utils/usageTracker.js.map +1 -0
  200. package/dist/core/utils/welcome-onboarding.d.ts +11 -0
  201. package/dist/core/utils/welcome-onboarding.js +100 -0
  202. package/dist/core/utils/welcome-onboarding.js.map +1 -0
  203. package/dist/core/utils/withTimeout.d.ts +28 -0
  204. package/dist/core/utils/withTimeout.js +86 -0
  205. package/dist/core/utils/withTimeout.js.map +1 -0
  206. package/dist/core/version.d.ts +1 -0
  207. package/dist/core/version.js +2 -0
  208. package/dist/core/version.js.map +1 -0
  209. package/dist/dispatcher.d.ts +7 -0
  210. package/dist/dispatcher.js +179 -0
  211. package/dist/dispatcher.js.map +1 -0
  212. package/dist/index.d.ts +6 -0
  213. package/dist/index.js +7 -0
  214. package/dist/index.js.map +1 -0
  215. package/dist/plugins/cli-commands.d.ts +5 -0
  216. package/dist/plugins/cli-commands.js +240 -0
  217. package/dist/plugins/cli-commands.js.map +1 -0
  218. package/dist/plugins/defaults.d.ts +62 -0
  219. package/dist/plugins/defaults.js +260 -0
  220. package/dist/plugins/defaults.js.map +1 -0
  221. package/dist/plugins/first-run.d.ts +16 -0
  222. package/dist/plugins/first-run.js +89 -0
  223. package/dist/plugins/first-run.js.map +1 -0
  224. package/dist/plugins/host.d.ts +20 -0
  225. package/dist/plugins/host.js +175 -0
  226. package/dist/plugins/host.js.map +1 -0
  227. package/dist/plugins/installer.d.ts +21 -0
  228. package/dist/plugins/installer.js +350 -0
  229. package/dist/plugins/installer.js.map +1 -0
  230. package/dist/plugins/locate.d.ts +15 -0
  231. package/dist/plugins/locate.js +99 -0
  232. package/dist/plugins/locate.js.map +1 -0
  233. package/dist/plugins/manager.d.ts +32 -0
  234. package/dist/plugins/manager.js +139 -0
  235. package/dist/plugins/manager.js.map +1 -0
  236. package/dist/plugins/paths.d.ts +32 -0
  237. package/dist/plugins/paths.js +49 -0
  238. package/dist/plugins/paths.js.map +1 -0
  239. package/dist/plugins/python.d.ts +55 -0
  240. package/dist/plugins/python.js +234 -0
  241. package/dist/plugins/python.js.map +1 -0
  242. package/dist/plugins/store.d.ts +12 -0
  243. package/dist/plugins/store.js +76 -0
  244. package/dist/plugins/store.js.map +1 -0
  245. package/dist/plugins/types.d.ts +112 -0
  246. package/dist/plugins/types.js +9 -0
  247. package/dist/plugins/types.js.map +1 -0
  248. package/dist/plugins/util.d.ts +37 -0
  249. package/dist/plugins/util.js +283 -0
  250. package/dist/plugins/util.js.map +1 -0
  251. package/dist/runtime/activity.d.ts +49 -0
  252. package/dist/runtime/activity.js +158 -0
  253. package/dist/runtime/activity.js.map +1 -0
  254. package/dist/runtime/browser-workflow.d.ts +21 -0
  255. package/dist/runtime/browser-workflow.js +51 -0
  256. package/dist/runtime/browser-workflow.js.map +1 -0
  257. package/dist/runtime/code-graph.d.ts +156 -0
  258. package/dist/runtime/code-graph.js +330 -0
  259. package/dist/runtime/code-graph.js.map +1 -0
  260. package/dist/runtime/code-structure.d.ts +53 -0
  261. package/dist/runtime/code-structure.js +152 -0
  262. package/dist/runtime/code-structure.js.map +1 -0
  263. package/dist/runtime/coding-session.d.ts +97 -0
  264. package/dist/runtime/coding-session.js +142 -0
  265. package/dist/runtime/coding-session.js.map +1 -0
  266. package/dist/runtime/detach.d.ts +114 -0
  267. package/dist/runtime/detach.js +505 -0
  268. package/dist/runtime/detach.js.map +1 -0
  269. package/dist/runtime/docker-client.d.ts +47 -0
  270. package/dist/runtime/docker-client.js +40 -0
  271. package/dist/runtime/docker-client.js.map +1 -0
  272. package/dist/runtime/errors.d.ts +9 -0
  273. package/dist/runtime/errors.js +56 -0
  274. package/dist/runtime/errors.js.map +1 -0
  275. package/dist/runtime/failure-log.d.ts +22 -0
  276. package/dist/runtime/failure-log.js +112 -0
  277. package/dist/runtime/failure-log.js.map +1 -0
  278. package/dist/runtime/fast-batch.d.ts +55 -0
  279. package/dist/runtime/fast-batch.js +104 -0
  280. package/dist/runtime/fast-batch.js.map +1 -0
  281. package/dist/runtime/file-safety.d.ts +7 -0
  282. package/dist/runtime/file-safety.js +134 -0
  283. package/dist/runtime/file-safety.js.map +1 -0
  284. package/dist/runtime/generic-code.d.ts +9 -0
  285. package/dist/runtime/generic-code.js +123 -0
  286. package/dist/runtime/generic-code.js.map +1 -0
  287. package/dist/runtime/graph-outline.d.ts +54 -0
  288. package/dist/runtime/graph-outline.js +118 -0
  289. package/dist/runtime/graph-outline.js.map +1 -0
  290. package/dist/runtime/harness.d.ts +61 -0
  291. package/dist/runtime/harness.js +102 -0
  292. package/dist/runtime/harness.js.map +1 -0
  293. package/dist/runtime/instruction-context.d.ts +23 -0
  294. package/dist/runtime/instruction-context.js +136 -0
  295. package/dist/runtime/instruction-context.js.map +1 -0
  296. package/dist/runtime/lab-mode.d.ts +32 -0
  297. package/dist/runtime/lab-mode.js +138 -0
  298. package/dist/runtime/lab-mode.js.map +1 -0
  299. package/dist/runtime/languages.d.ts +30 -0
  300. package/dist/runtime/languages.js +59 -0
  301. package/dist/runtime/languages.js.map +1 -0
  302. package/dist/runtime/nav-cache.d.ts +2 -0
  303. package/dist/runtime/nav-cache.js +12 -0
  304. package/dist/runtime/nav-cache.js.map +1 -0
  305. package/dist/runtime/operations.d.ts +40 -0
  306. package/dist/runtime/operations.js +86 -0
  307. package/dist/runtime/operations.js.map +1 -0
  308. package/dist/runtime/platform-capabilities.d.ts +20 -0
  309. package/dist/runtime/platform-capabilities.js +36 -0
  310. package/dist/runtime/platform-capabilities.js.map +1 -0
  311. package/dist/runtime/program-runner.d.ts +4 -0
  312. package/dist/runtime/program-runner.js +73 -0
  313. package/dist/runtime/program-runner.js.map +1 -0
  314. package/dist/runtime/project-context.d.ts +53 -0
  315. package/dist/runtime/project-context.js +90 -0
  316. package/dist/runtime/project-context.js.map +1 -0
  317. package/dist/runtime/project-files.d.ts +2 -0
  318. package/dist/runtime/project-files.js +3 -0
  319. package/dist/runtime/project-files.js.map +1 -0
  320. package/dist/runtime/project-index.d.ts +40 -0
  321. package/dist/runtime/project-index.js +158 -0
  322. package/dist/runtime/project-index.js.map +1 -0
  323. package/dist/runtime/resource-limits.d.ts +42 -0
  324. package/dist/runtime/resource-limits.js +50 -0
  325. package/dist/runtime/resource-limits.js.map +1 -0
  326. package/dist/runtime/scratch-budget.d.ts +11 -0
  327. package/dist/runtime/scratch-budget.js +107 -0
  328. package/dist/runtime/scratch-budget.js.map +1 -0
  329. package/dist/runtime/search-diagnostics.d.ts +3 -0
  330. package/dist/runtime/search-diagnostics.js +45 -0
  331. package/dist/runtime/search-diagnostics.js.map +1 -0
  332. package/dist/runtime/toolchains.d.ts +25 -0
  333. package/dist/runtime/toolchains.js +70 -0
  334. package/dist/runtime/toolchains.js.map +1 -0
  335. package/dist/runtime/worker-coordination.d.ts +314 -0
  336. package/dist/runtime/worker-coordination.js +564 -0
  337. package/dist/runtime/worker-coordination.js.map +1 -0
  338. package/dist/runtime/workspace.d.ts +151 -0
  339. package/dist/runtime/workspace.js +267 -0
  340. package/dist/runtime/workspace.js.map +1 -0
  341. package/dist/service.d.ts +3 -0
  342. package/dist/service.js +102 -0
  343. package/dist/service.js.map +1 -0
  344. package/dist/terminal-setup.d.ts +33 -0
  345. package/dist/terminal-setup.js +219 -0
  346. package/dist/terminal-setup.js.map +1 -0
  347. package/dist/terminal-shortcuts.d.ts +22 -0
  348. package/dist/terminal-shortcuts.js +145 -0
  349. package/dist/terminal-shortcuts.js.map +1 -0
  350. package/dist/terminal-ui.d.ts +20 -0
  351. package/dist/terminal-ui.js +53 -0
  352. package/dist/terminal-ui.js.map +1 -0
  353. package/dist/tools/ast-grep.d.ts +132 -0
  354. package/dist/tools/ast-grep.js +625 -0
  355. package/dist/tools/ast-grep.js.map +1 -0
  356. package/dist/tools/brc-tools.d.ts +112 -0
  357. package/dist/tools/brc-tools.js +599 -0
  358. package/dist/tools/brc-tools.js.map +1 -0
  359. package/dist/tools/check-tools.d.ts +4 -0
  360. package/dist/tools/check-tools.js +29 -0
  361. package/dist/tools/check-tools.js.map +1 -0
  362. package/dist/tools/coding-tools.d.ts +33 -0
  363. package/dist/tools/coding-tools.js +190 -0
  364. package/dist/tools/coding-tools.js.map +1 -0
  365. package/dist/tools/command-shell.d.ts +17 -0
  366. package/dist/tools/command-shell.js +84 -0
  367. package/dist/tools/command-shell.js.map +1 -0
  368. package/dist/tools/dev-extras.d.ts +42 -0
  369. package/dist/tools/dev-extras.js +135 -0
  370. package/dist/tools/dev-extras.js.map +1 -0
  371. package/dist/tools/edit-tools.d.ts +4 -0
  372. package/dist/tools/edit-tools.js +293 -0
  373. package/dist/tools/edit-tools.js.map +1 -0
  374. package/dist/tools/fast-exec.d.ts +11 -0
  375. package/dist/tools/fast-exec.js +202 -0
  376. package/dist/tools/fast-exec.js.map +1 -0
  377. package/dist/tools/image-tools.d.ts +37 -0
  378. package/dist/tools/image-tools.js +293 -0
  379. package/dist/tools/image-tools.js.map +1 -0
  380. package/dist/tools/jobs.d.ts +227 -0
  381. package/dist/tools/jobs.js +608 -0
  382. package/dist/tools/jobs.js.map +1 -0
  383. package/dist/tools/ops-tools.d.ts +8 -0
  384. package/dist/tools/ops-tools.js +58 -0
  385. package/dist/tools/ops-tools.js.map +1 -0
  386. package/dist/tools/plugin-tools.d.ts +38 -0
  387. package/dist/tools/plugin-tools.js +133 -0
  388. package/dist/tools/plugin-tools.js.map +1 -0
  389. package/dist/tools/rtk.d.ts +60 -0
  390. package/dist/tools/rtk.js +245 -0
  391. package/dist/tools/rtk.js.map +1 -0
  392. package/dist/tools/sandbox-tools.d.ts +41 -0
  393. package/dist/tools/sandbox-tools.js +146 -0
  394. package/dist/tools/sandbox-tools.js.map +1 -0
  395. package/dist/tools/worker-tools.d.ts +231 -0
  396. package/dist/tools/worker-tools.js +55 -0
  397. package/dist/tools/worker-tools.js.map +1 -0
  398. package/dist/tools/workspace-batch.d.ts +262 -0
  399. package/dist/tools/workspace-batch.js +188 -0
  400. package/dist/tools/workspace-batch.js.map +1 -0
  401. package/dist/transport/pairing.d.ts +22 -0
  402. package/dist/transport/pairing.js +154 -0
  403. package/dist/transport/pairing.js.map +1 -0
  404. package/dist/transport/plugin-admin.d.ts +33 -0
  405. package/dist/transport/plugin-admin.js +156 -0
  406. package/dist/transport/plugin-admin.js.map +1 -0
  407. package/dist/transport/relay-url.d.ts +3 -0
  408. package/dist/transport/relay-url.js +38 -0
  409. package/dist/transport/relay-url.js.map +1 -0
  410. package/dist/transport/result-budget.d.ts +11 -0
  411. package/dist/transport/result-budget.js +45 -0
  412. package/dist/transport/result-budget.js.map +1 -0
  413. package/dist/transport/ws-client.d.ts +64 -0
  414. package/dist/transport/ws-client.js +242 -0
  415. package/dist/transport/ws-client.js.map +1 -0
  416. package/package.json +89 -3
@@ -0,0 +1,991 @@
1
+ import fs from "fs/promises";
2
+ import path from "path";
3
+ import os from 'os';
4
+ import fetch from 'cross-fetch';
5
+ import { execFile } from 'child_process';
6
+ import { promisify } from 'util';
7
+ import { capture } from '../utils/capture.js';
8
+ import { withTimeout, runWithAbortableTimeout } from '../utils/withTimeout.js';
9
+ import { configManager } from '../config-manager.js';
10
+ import { getFileHandler, TextFileHandler } from '../utils/files/index.js';
11
+ import { isPdfFile } from "./mime-types.js";
12
+ // BRC: the PDF stack (md-to-pdf/puppeteer, pdf-lib, unpdf) is heavy; load it on demand.
13
+ const loadPdf = () => import('./pdf/index.js');
14
+ // CONSTANTS SECTION - Consolidate all timeouts and thresholds
15
+ const FILE_OPERATION_TIMEOUTS = {
16
+ PATH_VALIDATION: 10000, // 10 seconds
17
+ URL_FETCH: 30000, // 30 seconds
18
+ FILE_READ: 30000, // 30 seconds
19
+ };
20
+ // Cap file read operations at 3 minutes. The MCP client's hard per-call limit
21
+ // is ~4 minutes; timing out at 3m lets us abort the underlying fs op and return
22
+ // a useful error (e.g. the cloud-storage guidance in buildPermissionError)
23
+ // BEFORE the client gives up with an opaque "No result received after 4
24
+ // minutes". Paired with runWithAbortableTimeout so the read is actually
25
+ // cancelled (fd/thread released), not just abandoned.
26
+ export const READ_OPERATION_TIMEOUT_MS = 3 * 60 * 1000; // 3 minutes
27
+ const FILE_SIZE_LIMITS = {
28
+ LINE_COUNT_LIMIT: 10 * 1024 * 1024, // 10MB for line counting
29
+ };
30
+ // UTILITY FUNCTIONS - Eliminate duplication
31
+ /**
32
+ * Get MIME type information for a file
33
+ * @param filePath Path to the file
34
+ * @returns Object with mimeType and isImage properties
35
+ */
36
+ async function getMimeTypeInfo(filePath) {
37
+ const { getMimeType, isImageFile, isPdfFile } = await import('./mime-types.js');
38
+ const mimeType = getMimeType(filePath);
39
+ const isImage = isImageFile(mimeType);
40
+ const isPdf = isPdfFile(mimeType);
41
+ return { mimeType, isImage, isPdf };
42
+ }
43
+ /**
44
+ * Get file extension for telemetry purposes
45
+ * @param filePath Path to the file
46
+ * @returns Lowercase file extension
47
+ */
48
+ function getFileExtension(filePath) {
49
+ return path.extname(filePath).toLowerCase();
50
+ }
51
+ /**
52
+ * Get default read length from configuration
53
+ * @returns Default number of lines to read
54
+ */
55
+ async function getDefaultReadLength() {
56
+ const config = await configManager.getConfig();
57
+ return config.fileReadLineLimit ?? 1000; // Default to 1000 lines if not set
58
+ }
59
+ /**
60
+ * Returns a helpful error message when a file operation fails with a permission
61
+ * or timeout error.
62
+ *
63
+ * Lists all common causes without path-based detection — the AI receiving this
64
+ * error should inspect the path and inform the user which cause is most likely
65
+ * (e.g. cloud storage folder, network drive, system file, locked file, etc.)
66
+ */
67
+ function buildPermissionError(filePath, errCode) {
68
+ const isMac = process.platform === 'darwin';
69
+ const isTimeout = errCode === 'ETIMEDOUT';
70
+ const lines = [
71
+ `Cannot read file — ${isTimeout ? 'operation timed out' : 'permission denied'} (${errCode}).`,
72
+ `Path: ${filePath}`,
73
+ ``,
74
+ `[AI: based on the path above, determine which cause is most likely and explain it to the user.]`,
75
+ ``,
76
+ `Possible causes and fixes:`,
77
+ ` 1. File is in cloud storage (Google Drive / iCloud / Dropbox / OneDrive) but not downloaded locally.`,
78
+ ` → Right-click the file and choose "Download Now", "Make Available Offline", or "Keep on This Device".`,
79
+ ` 2. Cloud storage app is not running or not signed in.`,
80
+ ` → Open your cloud storage app and make sure it is syncing.`,
81
+ ` 3. File is on a network drive or virtual filesystem that is currently unavailable.`,
82
+ ` → Check that the network share or drive is mounted and accessible.`,
83
+ ` 4. File has restricted permissions (e.g. system file, locked by another process, or chmod 000).`,
84
+ ` → Check file permissions or close any app that may have the file open.`,
85
+ ` 5. The app does not have permission to access this location (macOS Full Disk Access).`,
86
+ ];
87
+ if (isMac) {
88
+ lines.push(` → Go to System Settings → Privacy & Security → Full Disk Access and enable Claude.`);
89
+ lines.push(` → To open that pane directly, run in terminal:`);
90
+ lines.push(` open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"`);
91
+ lines.push(` Then find "Claude" in the list and enable the toggle next to it.`);
92
+ }
93
+ else {
94
+ lines.push(` → Check that the app has permission to access this file location.`);
95
+ }
96
+ return new Error(lines.join('\n'));
97
+ }
98
+ // Initialize allowed directories from configuration
99
+ async function getAllowedDirs() {
100
+ try {
101
+ let allowedDirectories;
102
+ const config = await configManager.getConfig();
103
+ if (config.allowedDirectories && Array.isArray(config.allowedDirectories)) {
104
+ allowedDirectories = config.allowedDirectories;
105
+ }
106
+ else {
107
+ // Fall back to default directories if not configured
108
+ allowedDirectories = [
109
+ os.homedir() // User's home directory
110
+ ];
111
+ // Update config with default
112
+ await configManager.setValue('allowedDirectories', allowedDirectories);
113
+ }
114
+ return allowedDirectories;
115
+ }
116
+ catch (error) {
117
+ console.error('Failed to initialize allowed directories:', error);
118
+ // Keep the default permissive path
119
+ }
120
+ return [];
121
+ }
122
+ // Normalize all paths consistently
123
+ function normalizePath(p) {
124
+ const normalized = path.normalize(expandHome(p));
125
+ // Only Windows is case-insensitive; lowercasing elsewhere let /A and /a share allowed-directory checks.
126
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
127
+ }
128
+ function expandHome(filepath) {
129
+ if (filepath.startsWith('~/') || filepath === '~') {
130
+ return path.join(os.homedir(), filepath.slice(1));
131
+ }
132
+ return filepath;
133
+ }
134
+ /**
135
+ * Recursively validates parent directories until it finds a valid one
136
+ * This function handles the case where we need to create nested directories
137
+ * and we need to check if any of the parent directories exist
138
+ *
139
+ * @param directoryPath The path to validate
140
+ * @returns Promise<boolean> True if a valid parent directory was found
141
+ */
142
+ async function validateParentDirectories(directoryPath) {
143
+ const parentDir = path.dirname(directoryPath);
144
+ // Base case: we've reached the root or the same directory (shouldn't happen normally)
145
+ if (parentDir === directoryPath || parentDir === path.dirname(parentDir)) {
146
+ return false;
147
+ }
148
+ try {
149
+ // Check if the parent directory exists
150
+ await fs.realpath(parentDir);
151
+ return true;
152
+ }
153
+ catch {
154
+ // Parent doesn't exist, recursively check its parent
155
+ return validateParentDirectories(parentDir);
156
+ }
157
+ }
158
+ /**
159
+ * Checks if a path is within any of the allowed directories
160
+ *
161
+ * @param pathToCheck Path to check
162
+ * @returns boolean True if path is allowed
163
+ */
164
+ async function isPathAllowed(pathToCheck) {
165
+ // If root directory is allowed, all paths are allowed
166
+ const allowedDirectories = await getAllowedDirs();
167
+ if (allowedDirectories.includes('/') || allowedDirectories.length === 0) {
168
+ return true;
169
+ }
170
+ let normalizedPathToCheck = normalizePath(pathToCheck);
171
+ if (normalizedPathToCheck.slice(-1) === path.sep) {
172
+ normalizedPathToCheck = normalizedPathToCheck.slice(0, -1);
173
+ }
174
+ // Check if the path is within any allowed directory
175
+ const isAllowed = allowedDirectories.some(allowedDir => {
176
+ let normalizedAllowedDir = normalizePath(allowedDir);
177
+ if (normalizedAllowedDir.slice(-1) === path.sep) {
178
+ normalizedAllowedDir = normalizedAllowedDir.slice(0, -1);
179
+ }
180
+ // Check if path is exactly the allowed directory
181
+ if (normalizedPathToCheck === normalizedAllowedDir) {
182
+ return true;
183
+ }
184
+ // Check if path is a subdirectory of the allowed directory
185
+ // Make sure to add a separator to prevent partial directory name matches
186
+ // e.g. /home/user vs /home/username
187
+ const subdirCheck = normalizedPathToCheck.startsWith(normalizedAllowedDir + path.sep);
188
+ if (subdirCheck) {
189
+ return true;
190
+ }
191
+ // If allowed directory is the root (C:\ on Windows), allow access to the entire drive
192
+ if (normalizedAllowedDir === 'c:' && process.platform === 'win32') {
193
+ return normalizedPathToCheck.startsWith('c:');
194
+ }
195
+ return false;
196
+ });
197
+ return isAllowed;
198
+ }
199
+ /**
200
+ * Validates a path to ensure it can be accessed or created.
201
+ * For existing paths, returns the real path (resolving symlinks).
202
+ * For non-existent paths, validates parent directories to ensure they exist.
203
+ *
204
+ * @param requestedPath The path to validate
205
+ * @returns Promise<string> The validated path
206
+ * @throws Error if the path or its parent directories don't exist or if the path is not allowed
207
+ */
208
+ export async function validatePath(requestedPath) {
209
+ const validationOperation = async () => {
210
+ // Expand home directory if present
211
+ const expandedPath = expandHome(requestedPath);
212
+ // Convert to absolute path
213
+ const absoluteOriginal = path.isAbsolute(expandedPath)
214
+ ? path.resolve(expandedPath)
215
+ : path.resolve(process.cwd(), expandedPath);
216
+ // Attempt to resolve symlinks to get the real path
217
+ // This will succeed if the path exists and all symlinks in the chain are valid
218
+ // It will fail with ENOENT if:
219
+ // - The path itself doesn't exist, OR
220
+ // - A symlink exists but points to a non-existent target (broken symlink)
221
+ let resolvedRealPath = null;
222
+ try {
223
+ resolvedRealPath = await fs.realpath(absoluteOriginal, { encoding: 'utf8' });
224
+ }
225
+ catch (error) {
226
+ const err = error;
227
+ // Only throw for non-ENOENT errors (e.g., permission denied, I/O errors)
228
+ if (!err.code || err.code !== 'ENOENT') {
229
+ capture('server_path_realpath_error', {
230
+ error: err.message,
231
+ path: absoluteOriginal
232
+ });
233
+ throw new Error(`Failed to resolve symlink for path: ${absoluteOriginal}. Error: ${err.message}`);
234
+ }
235
+ // SECURITY FIX: When the full path doesn't exist (e.g., writing a new file),
236
+ // resolve the parent directory to detect symlinks in the path chain.
237
+ // Without this, an attacker could create a symlink inside an allowed directory
238
+ // pointing to a restricted location, then write to a non-existent file through
239
+ // that symlink — bypassing the directory restriction check.
240
+ try {
241
+ const parentDir = path.dirname(absoluteOriginal);
242
+ const resolvedParent = await fs.realpath(parentDir, { encoding: 'utf8' });
243
+ const basename = path.basename(absoluteOriginal);
244
+ resolvedRealPath = path.join(resolvedParent, basename);
245
+ }
246
+ catch {
247
+ // Parent also doesn't exist — walk up the tree to find
248
+ // the deepest existing ancestor and resolve it
249
+ let current = absoluteOriginal;
250
+ let remaining = [];
251
+ while (true) {
252
+ const parent = path.dirname(current);
253
+ if (parent === current)
254
+ break; // reached filesystem root
255
+ remaining.unshift(path.basename(current));
256
+ current = parent;
257
+ try {
258
+ const resolvedAncestor = await fs.realpath(current, { encoding: 'utf8' });
259
+ resolvedRealPath = path.join(resolvedAncestor, ...remaining);
260
+ break;
261
+ }
262
+ catch {
263
+ // keep walking up
264
+ }
265
+ }
266
+ }
267
+ }
268
+ const pathForNextCheck = resolvedRealPath ?? absoluteOriginal;
269
+ // Check if path is allowed
270
+ if (!(await isPathAllowed(pathForNextCheck))) {
271
+ capture('server_path_validation_error', {
272
+ error: 'Path not allowed',
273
+ allowedDirsCount: (await getAllowedDirs()).length
274
+ });
275
+ throw new Error(`Path not allowed: ${requestedPath}. Must be within one of these directories: ${(await getAllowedDirs()).join(', ')}`);
276
+ }
277
+ // SECURITY: Always return the resolved path (with symlinks resolved) so that
278
+ // all subsequent file operations (read, write, mkdir, etc.) operate on the
279
+ // canonical target, not on a symlink that could point outside allowed directories.
280
+ // pathForNextCheck already holds resolvedRealPath ?? absoluteOriginal from above.
281
+ // Check if path exists
282
+ try {
283
+ // fs.stat() will automatically follow symlinks, so we get existence info
284
+ await fs.stat(pathForNextCheck);
285
+ return pathForNextCheck;
286
+ }
287
+ catch (error) {
288
+ // Path doesn't exist - validate parent directories
289
+ if (await validateParentDirectories(pathForNextCheck)) {
290
+ // Return the resolved path if a valid parent exists
291
+ // This will be used for folder creation and many other file operations
292
+ return pathForNextCheck;
293
+ }
294
+ // If no valid parent found, return the resolved path anyway
295
+ return pathForNextCheck;
296
+ }
297
+ };
298
+ // Execute with timeout
299
+ const result = await withTimeout(validationOperation(), FILE_OPERATION_TIMEOUTS.PATH_VALIDATION, `Path validation operation`, // Generic name for telemetry
300
+ null);
301
+ if (result === null) {
302
+ // Keep original path in error for AI but a generic message for telemetry
303
+ capture('server_path_validation_timeout', {
304
+ timeoutMs: FILE_OPERATION_TIMEOUTS.PATH_VALIDATION
305
+ });
306
+ throw new Error(`Path validation failed for path: ${requestedPath}`);
307
+ }
308
+ return result;
309
+ }
310
+ /**
311
+ * Read file content from a URL
312
+ * @param url URL to fetch content from
313
+ * @returns File content or file result with metadata
314
+ */
315
+ export async function readFileFromUrl(url) {
316
+ // Import the MIME type utilities
317
+ const { isImageFile } = await import('./mime-types.js');
318
+ // Set up fetch with timeout
319
+ const controller = new AbortController();
320
+ const timeoutId = setTimeout(() => controller.abort(), FILE_OPERATION_TIMEOUTS.URL_FETCH);
321
+ try {
322
+ const response = await fetch(url, {
323
+ signal: controller.signal
324
+ });
325
+ // Clear the timeout since fetch completed
326
+ clearTimeout(timeoutId);
327
+ if (!response.ok) {
328
+ throw new Error(`HTTP error! Status: ${response.status}`);
329
+ }
330
+ // Get MIME type from Content-Type header or infer from URL
331
+ const contentType = response.headers.get('content-type') || 'text/plain';
332
+ const isImage = isImageFile(contentType);
333
+ const isPdf = isPdfFile(contentType) || url.toLowerCase().endsWith('.pdf');
334
+ // NEW: Add PDF handling before image check
335
+ if (isPdf) {
336
+ // Use URL directly - pdfreader handles URL downloads internally
337
+ const { parsePdfToMarkdown } = await loadPdf();
338
+ const pdfResult = await parsePdfToMarkdown(url);
339
+ return {
340
+ content: "",
341
+ mimeType: 'text/plain',
342
+ metadata: {
343
+ isImage: false,
344
+ isPdf: true,
345
+ author: pdfResult.metadata.author,
346
+ title: pdfResult.metadata.title,
347
+ totalPages: pdfResult.metadata.totalPages,
348
+ pages: pdfResult.pages
349
+ }
350
+ };
351
+ }
352
+ else if (isImage) {
353
+ // For images, convert to base64
354
+ const buffer = await response.arrayBuffer();
355
+ const content = Buffer.from(buffer).toString('base64');
356
+ return { content, mimeType: contentType, metadata: { isImage } };
357
+ }
358
+ else {
359
+ // For text content
360
+ const content = await response.text();
361
+ return { content, mimeType: contentType, metadata: { isImage } };
362
+ }
363
+ }
364
+ catch (error) {
365
+ // Clear the timeout to prevent memory leaks
366
+ clearTimeout(timeoutId);
367
+ // Return error information instead of throwing
368
+ const errorMessage = error instanceof DOMException && error.name === 'AbortError'
369
+ ? `URL fetch timed out after ${FILE_OPERATION_TIMEOUTS.URL_FETCH}ms: ${url}`
370
+ : `Failed to fetch URL: ${error instanceof Error ? error.message : String(error)}`;
371
+ throw new Error(errorMessage);
372
+ }
373
+ }
374
+ /**
375
+ * Read file content from the local filesystem
376
+ * @param filePath Path to the file
377
+ * @param options Read options (offset, length, sheet, range)
378
+ * @returns File content or file result with metadata
379
+ */
380
+ export async function readFileFromDisk(filePath, options) {
381
+ const { offset = 0, sheet, range } = options ?? {};
382
+ let { length } = options ?? {};
383
+ // Add validation for required parameters
384
+ if (!filePath || typeof filePath !== 'string') {
385
+ throw new Error('Invalid file path provided');
386
+ }
387
+ // Get default length from config if not provided
388
+ if (length === undefined) {
389
+ length = await getDefaultReadLength();
390
+ }
391
+ const validPath = await validatePath(filePath);
392
+ // Get file extension for telemetry
393
+ const fileExtension = getFileExtension(validPath);
394
+ // Check if path is a directory — return listing instead of EISDIR error
395
+ try {
396
+ const stats = await fs.stat(validPath);
397
+ if (stats.isDirectory()) {
398
+ const dirListOp = async () => {
399
+ const entries = await listDirectory(validPath);
400
+ const listing = entries.join('\n');
401
+ return {
402
+ content: `This is a directory, not a file. Use the list_directory tool instead of read_file for directories.\n\n${listing}`,
403
+ mimeType: 'text/plain',
404
+ metadata: { isImage: false, isDirectory: true }
405
+ };
406
+ };
407
+ const dirResult = await withTimeout(dirListOp(), FILE_OPERATION_TIMEOUTS.FILE_READ, 'Directory listing fallback', null);
408
+ if (dirResult === null) {
409
+ throw new Error(`Directory listing timed out for: ${filePath}`);
410
+ }
411
+ return dirResult;
412
+ }
413
+ }
414
+ catch (error) {
415
+ // If stat itself failed, fall through to the read path which will produce a proper error.
416
+ // But if this was a directory-listing error, re-throw — don't let it fall into the file-read path.
417
+ const err = error;
418
+ if (err.message?.includes('Directory listing') || err.message?.includes('list_directory')) {
419
+ throw error;
420
+ }
421
+ // stat() failed (e.g. ENOENT) — fall through to the read path below
422
+ }
423
+ // Check file size before attempting to read
424
+ try {
425
+ const stats = await fs.stat(validPath);
426
+ // Capture file extension in telemetry without capturing the file path
427
+ capture('server_read_file', {
428
+ fileExtension: fileExtension,
429
+ offset: offset,
430
+ length: length,
431
+ fileSize: stats.size
432
+ });
433
+ }
434
+ catch (error) {
435
+ console.error('error catch ' + error);
436
+ const errorMessage = error instanceof Error ? error.message : String(error);
437
+ capture('server_read_file_error', { error: errorMessage, fileExtension: fileExtension });
438
+ // If we can't stat the file, continue anyway and let the read operation handle errors
439
+ }
440
+ // Read under an abortable timeout so a hung/stalled read is cancelled
441
+ // (fd/thread freed) rather than leaked until the OS call returns.
442
+ const readOperation = async (signal) => {
443
+ // Get appropriate handler for this file type (async - includes binary detection)
444
+ const handler = await getFileHandler(validPath);
445
+ // Use handler to read the file
446
+ const result = await handler.read(validPath, {
447
+ offset,
448
+ length,
449
+ sheet,
450
+ range,
451
+ includeStatusMessage: true,
452
+ signal
453
+ });
454
+ // Return with content as string
455
+ // For images: content is already base64-encoded string from handler
456
+ // For text: content may be string or Buffer, convert to UTF-8 string
457
+ let content;
458
+ if (typeof result.content === 'string') {
459
+ content = result.content;
460
+ }
461
+ else if (result.metadata?.isImage) {
462
+ // Image buffer should be base64 encoded, not UTF-8 converted
463
+ content = result.content.toString('base64');
464
+ }
465
+ else {
466
+ content = result.content.toString('utf8');
467
+ }
468
+ return {
469
+ content,
470
+ mimeType: result.mimeType,
471
+ metadata: result.metadata
472
+ };
473
+ };
474
+ // Execute with a 3-minute, cancellable timeout
475
+ let result;
476
+ try {
477
+ result = await runWithAbortableTimeout((signal) => readOperation(signal), READ_OPERATION_TIMEOUT_MS, `Read file operation for ${filePath}`);
478
+ }
479
+ catch (error) {
480
+ const err = error;
481
+ // runWithAbortableTimeout rejects with an Error whose .code is 'ETIMEDOUT'
482
+ // on timeout; fs rejects with EPERM/EACCES. Map all to the guidance error.
483
+ if (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'ETIMEDOUT') {
484
+ throw buildPermissionError(filePath, err.code);
485
+ }
486
+ throw error;
487
+ }
488
+ if (result == null) {
489
+ // Handles the impossible case where withTimeout resolves to null instead of throwing
490
+ throw new Error('Failed to read the file');
491
+ }
492
+ return result;
493
+ }
494
+ /**
495
+ * Read a file from either the local filesystem or a URL
496
+ * @param filePath Path to the file or URL
497
+ * @param options Read options (isUrl, offset, length, sheet, range)
498
+ * @returns File content or file result with metadata
499
+ */
500
+ export async function readFile(filePath, options) {
501
+ const { isUrl, offset, length, sheet, range } = options ?? {};
502
+ return isUrl
503
+ ? readFileFromUrl(filePath)
504
+ : readFileFromDisk(filePath, { offset, length, sheet, range });
505
+ }
506
+ /**
507
+ * Read file content without status messages for internal operations
508
+ * This function preserves exact file content including original line endings,
509
+ * which is essential for edit operations that need to maintain file formatting.
510
+ * @param filePath Path to the file
511
+ * @param offset Starting line number to read from (default: 0)
512
+ * @param length Maximum number of lines to read (default: from config or 1000)
513
+ * @returns File content without status headers, with preserved line endings
514
+ */
515
+ export async function readFileInternal(filePath, offset = 0, length) {
516
+ // Get default length from config if not provided
517
+ if (length === undefined) {
518
+ length = await getDefaultReadLength();
519
+ }
520
+ const validPath = await validatePath(filePath);
521
+ // Get file extension and MIME type
522
+ const fileExtension = getFileExtension(validPath);
523
+ const { mimeType, isImage } = await getMimeTypeInfo(validPath);
524
+ if (isImage) {
525
+ throw new Error('Cannot read image files as text for internal operations');
526
+ }
527
+ // IMPORTANT: For internal operations (especially edit operations), we must
528
+ // preserve exact file content including original line endings.
529
+ // We cannot use readline-based reading as it strips line endings.
530
+ // Read entire file content preserving line endings, under a 3-minute,
531
+ // cancellable timeout so an edit on a stalled/cloud path can't hang forever
532
+ // (previously this read had no timeout at all).
533
+ const content = await runWithAbortableTimeout((signal) => fs.readFile(validPath, { encoding: 'utf8', signal }), READ_OPERATION_TIMEOUT_MS, `Internal read for ${filePath}`);
534
+ // If we need to apply offset/length, do it while preserving line endings
535
+ if (offset === 0 && length >= Number.MAX_SAFE_INTEGER) {
536
+ // Most common case for edit operations: read entire file
537
+ return content;
538
+ }
539
+ // Handle offset/length by splitting on line boundaries while preserving line endings
540
+ const lines = TextFileHandler.splitLinesPreservingEndings(content);
541
+ // Apply offset and length
542
+ const selectedLines = lines.slice(offset, offset + length);
543
+ // Join back together (this preserves the original line endings)
544
+ return selectedLines.join('');
545
+ }
546
+ export async function writeFile(filePath, content, mode = 'rewrite') {
547
+ const validPath = await validatePath(filePath);
548
+ // Get file extension for telemetry
549
+ const fileExtension = getFileExtension(validPath);
550
+ // Calculate content metrics
551
+ const contentBytes = Buffer.from(content).length;
552
+ const lineCount = TextFileHandler.countLines(content);
553
+ // Capture file extension and operation details in telemetry without capturing the file path
554
+ capture('server_write_file', {
555
+ fileExtension: fileExtension,
556
+ mode: mode,
557
+ contentBytes: contentBytes,
558
+ lineCount: lineCount
559
+ });
560
+ // Get appropriate handler for this file type (async - includes binary detection)
561
+ const handler = await getFileHandler(validPath);
562
+ // Use handler to write the file
563
+ await handler.write(validPath, content, mode);
564
+ }
565
+ /** Run async tasks with bounded concurrency, preserving input order. */
566
+ async function mapWithConcurrency(items, limit, fn) {
567
+ const out = new Array(items.length);
568
+ let next = 0;
569
+ const worker = async () => {
570
+ while (next < items.length) {
571
+ const i = next++;
572
+ out[i] = await fn(items[i]);
573
+ }
574
+ };
575
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
576
+ return out;
577
+ }
578
+ export async function readMultipleFiles(entries) {
579
+ return mapWithConcurrency(entries, 8, async (entry) => {
580
+ const filePath = typeof entry === 'string' ? entry : entry.path;
581
+ const range = typeof entry === 'string' ? undefined : entry;
582
+ try {
583
+ const validPath = await validatePath(filePath);
584
+ const fileResult = await readFile(validPath, range && (range.offset !== undefined || range.length !== undefined)
585
+ ? { offset: range.offset ?? 0, length: range.length ?? await getDefaultReadLength() }
586
+ : undefined);
587
+ // Handle content conversion properly for images vs text
588
+ let content;
589
+ if (typeof fileResult.content === 'string') {
590
+ content = fileResult.content;
591
+ }
592
+ else if (fileResult.metadata?.isImage) {
593
+ content = fileResult.content.toString('base64');
594
+ }
595
+ else {
596
+ content = fileResult.content.toString('utf8');
597
+ }
598
+ return {
599
+ path: filePath,
600
+ content,
601
+ mimeType: fileResult.mimeType,
602
+ isImage: fileResult.metadata?.isImage ?? false,
603
+ isPdf: fileResult.metadata?.isPdf ?? false,
604
+ payload: fileResult.metadata?.isPdf ? {
605
+ metadata: {
606
+ author: fileResult.metadata.author,
607
+ title: fileResult.metadata.title,
608
+ totalPages: fileResult.metadata.totalPages ?? 0
609
+ },
610
+ pages: fileResult.metadata.pages ?? []
611
+ } : undefined
612
+ };
613
+ }
614
+ catch (error) {
615
+ const errorMessage = error instanceof Error ? error.message : String(error);
616
+ return {
617
+ path: filePath,
618
+ error: errorMessage
619
+ };
620
+ }
621
+ });
622
+ }
623
+ export async function createDirectory(dirPath) {
624
+ const validPath = await validatePath(dirPath);
625
+ await fs.mkdir(validPath, { recursive: true });
626
+ }
627
+ export async function listDirectory(dirPath, depth = 2) {
628
+ const validPath = await validatePath(dirPath);
629
+ const MAX_NESTED_ITEMS = 100; // Maximum items to show per nested directory
630
+ // BRC: subdirectories are read concurrently (bounded, to stay clear of EMFILE);
631
+ // results are assembled in the same order as a sequential walk.
632
+ const MAX_CONCURRENT_READDIR = 32;
633
+ let active = 0;
634
+ const waiting = [];
635
+ async function readdirLimited(p) {
636
+ if (active >= MAX_CONCURRENT_READDIR)
637
+ await new Promise((r) => waiting.push(r));
638
+ active++;
639
+ try {
640
+ return await fs.readdir(p, { withFileTypes: true });
641
+ }
642
+ finally {
643
+ active--;
644
+ waiting.shift()?.();
645
+ }
646
+ }
647
+ async function listRecursive(currentPath, currentDepth, relativePath = '', isTopLevel = true) {
648
+ const out = [];
649
+ if (currentDepth <= 0)
650
+ return out;
651
+ let entries;
652
+ try {
653
+ entries = await readdirLimited(currentPath);
654
+ }
655
+ catch (error) {
656
+ const err = error;
657
+ const displayPath = relativePath || path.basename(currentPath);
658
+ // Distinguish "not found" from "permission denied" so AI and UI get accurate info.
659
+ if (err.code === 'ENOENT') {
660
+ out.push(`[NOT_FOUND] ${displayPath} — path does not exist`);
661
+ }
662
+ else if (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'ETIMEDOUT') {
663
+ out.push(`[DENIED] ${displayPath} — not accessible (permission denied, cloud-only file, or Full Disk Access not granted)`);
664
+ }
665
+ else {
666
+ out.push(`[DENIED] ${displayPath}`);
667
+ }
668
+ return out;
669
+ }
670
+ // Apply filtering for nested directories (not top level)
671
+ const totalEntries = entries.length;
672
+ let entriesToShow = entries;
673
+ let filteredCount = 0;
674
+ if (!isTopLevel && totalEntries > MAX_NESTED_ITEMS) {
675
+ entriesToShow = entries.slice(0, MAX_NESTED_ITEMS);
676
+ filteredCount = totalEntries - MAX_NESTED_ITEMS;
677
+ }
678
+ // Start all subdirectory walks first, then collect them in entry order.
679
+ const children = entriesToShow.map((entry) => {
680
+ if (!entry.isDirectory() || currentDepth <= 1)
681
+ return null;
682
+ const fullPath = path.join(currentPath, entry.name);
683
+ const displayPath = relativePath ? path.join(relativePath, entry.name) : entry.name;
684
+ return (async () => {
685
+ try {
686
+ // Validate the path before recursing
687
+ await validatePath(fullPath);
688
+ }
689
+ catch {
690
+ // If validation fails, skip it (as before)
691
+ return [];
692
+ }
693
+ return listRecursive(fullPath, currentDepth - 1, displayPath, false);
694
+ })();
695
+ });
696
+ for (let i = 0; i < entriesToShow.length; i++) {
697
+ const entry = entriesToShow[i];
698
+ const displayPath = relativePath ? path.join(relativePath, entry.name) : entry.name;
699
+ out.push(`${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${displayPath}`);
700
+ const child = children[i];
701
+ if (child)
702
+ for (const line of await child)
703
+ out.push(line);
704
+ }
705
+ // Add warning message if items were filtered
706
+ if (filteredCount > 0) {
707
+ const displayPath = relativePath || path.basename(currentPath);
708
+ out.push(`[WARNING] ${displayPath}: ${filteredCount} items hidden (showing first ${MAX_NESTED_ITEMS} of ${totalEntries} total)`);
709
+ }
710
+ return out;
711
+ }
712
+ return listRecursive(validPath, depth, '', true);
713
+ }
714
+ export async function moveFile(sourcePath, destinationPath) {
715
+ const validSourcePath = await validatePath(sourcePath);
716
+ const validDestPath = await validatePath(destinationPath);
717
+ await fs.rename(validSourcePath, validDestPath);
718
+ }
719
+ export async function searchFiles(rootPath, pattern) {
720
+ // Use the new search manager for better performance
721
+ // This provides a temporary compatibility layer until we fully migrate to search sessions
722
+ const { searchManager } = await import('../search-manager.js');
723
+ try {
724
+ const result = await searchManager.startSearch({
725
+ rootPath,
726
+ pattern,
727
+ searchType: 'files',
728
+ ignoreCase: true,
729
+ maxResults: 5000, // Higher limit for compatibility
730
+ earlyTermination: true, // Use early termination for better performance
731
+ });
732
+ const sessionId = result.sessionId;
733
+ // Poll for results until complete
734
+ let allResults = [];
735
+ let isComplete = result.isComplete;
736
+ let startTime = Date.now();
737
+ // Add initial results
738
+ for (const searchResult of result.results) {
739
+ if (searchResult.type === 'file') {
740
+ allResults.push(searchResult.file);
741
+ }
742
+ }
743
+ while (!isComplete) {
744
+ await new Promise(resolve => setTimeout(resolve, 100)); // Wait 100ms
745
+ const results = searchManager.readSearchResults(sessionId);
746
+ isComplete = results.isComplete;
747
+ // Add new file paths to results
748
+ for (const searchResult of results.results) {
749
+ if (searchResult.file !== '__LAST_READ_MARKER__' && searchResult.type === 'file') {
750
+ allResults.push(searchResult.file);
751
+ }
752
+ }
753
+ // Safety check to prevent infinite loops (30 second timeout)
754
+ if (Date.now() - startTime > 30000) {
755
+ searchManager.terminateSearch(sessionId);
756
+ break;
757
+ }
758
+ }
759
+ // Log only the count of found files, not their paths
760
+ capture('server_search_files_complete', {
761
+ resultsCount: allResults.length,
762
+ patternLength: pattern.length,
763
+ usedRipgrep: true
764
+ });
765
+ return allResults;
766
+ }
767
+ catch (error) {
768
+ // Fallback to original Node.js implementation if ripgrep fails
769
+ capture('server_search_files_ripgrep_fallback', {
770
+ error: error instanceof Error ? error.message : 'Unknown error'
771
+ });
772
+ return await searchFilesNodeJS(rootPath, pattern);
773
+ }
774
+ }
775
+ // Keep the original Node.js implementation as fallback
776
+ async function searchFilesNodeJS(rootPath, pattern) {
777
+ const results = [];
778
+ async function search(currentPath) {
779
+ let entries;
780
+ try {
781
+ entries = await fs.readdir(currentPath, { withFileTypes: true });
782
+ }
783
+ catch (error) {
784
+ return; // Skip this directory on error
785
+ }
786
+ for (const entry of entries) {
787
+ const fullPath = path.join(currentPath, entry.name);
788
+ try {
789
+ await validatePath(fullPath);
790
+ if (entry.name.toLowerCase().includes(pattern.toLowerCase())) {
791
+ results.push(fullPath);
792
+ }
793
+ if (entry.isDirectory()) {
794
+ await search(fullPath);
795
+ }
796
+ }
797
+ catch (error) {
798
+ continue;
799
+ }
800
+ }
801
+ }
802
+ try {
803
+ // Validate root path before starting search
804
+ const validPath = await validatePath(rootPath);
805
+ await search(validPath);
806
+ // Log only the count of found files, not their paths
807
+ capture('server_search_files_complete', {
808
+ resultsCount: results.length,
809
+ patternLength: pattern.length,
810
+ usedRipgrep: false
811
+ });
812
+ return results;
813
+ }
814
+ catch (error) {
815
+ // For telemetry only - sanitize error info
816
+ capture('server_search_files_error', {
817
+ errorType: error instanceof Error ? error.name : 'Unknown',
818
+ error: 'Error with root path',
819
+ isRootPathError: true
820
+ });
821
+ // Re-throw the original error for the caller
822
+ throw error;
823
+ }
824
+ }
825
+ export async function getFileInfo(filePath) {
826
+ const validPath = await validatePath(filePath);
827
+ // Get fs.stat as a fallback for any missing fields
828
+ const stats = await fs.stat(validPath);
829
+ const fallbackInfo = {
830
+ size: stats.size,
831
+ created: stats.birthtime,
832
+ modified: stats.mtime,
833
+ accessed: stats.atime,
834
+ isDirectory: stats.isDirectory(),
835
+ isFile: stats.isFile(),
836
+ permissions: stats.mode.toString(8).slice(-3),
837
+ fileType: 'text',
838
+ metadata: undefined,
839
+ };
840
+ // Get appropriate handler for this file type (async - includes binary detection)
841
+ const handler = await getFileHandler(validPath);
842
+ // Use handler to get file info, with fallback
843
+ let fileInfo;
844
+ try {
845
+ fileInfo = await handler.getInfo(validPath);
846
+ }
847
+ catch (error) {
848
+ // If handler fails, use fallback stats
849
+ fileInfo = fallbackInfo;
850
+ }
851
+ // Convert to legacy format (for backward compatibility)
852
+ // Use handler values with fallback to fs.stat values for any missing fields
853
+ const info = {
854
+ size: fileInfo.size ?? fallbackInfo.size,
855
+ created: fileInfo.created ?? fallbackInfo.created,
856
+ modified: fileInfo.modified ?? fallbackInfo.modified,
857
+ accessed: fileInfo.accessed ?? fallbackInfo.accessed,
858
+ isDirectory: fileInfo.isDirectory ?? fallbackInfo.isDirectory,
859
+ isFile: fileInfo.isFile ?? fallbackInfo.isFile,
860
+ permissions: fileInfo.permissions ?? fallbackInfo.permissions,
861
+ fileType: fileInfo.fileType ?? fallbackInfo.fileType,
862
+ };
863
+ // Add type-specific metadata from file handler
864
+ if (fileInfo.metadata) {
865
+ // For text files
866
+ if (fileInfo.metadata.lineCount !== undefined) {
867
+ info.lineCount = fileInfo.metadata.lineCount;
868
+ info.lastLine = fileInfo.metadata.lineCount - 1;
869
+ info.appendPosition = fileInfo.metadata.lineCount;
870
+ }
871
+ // For Excel files
872
+ if (fileInfo.metadata.sheets) {
873
+ info.sheets = fileInfo.metadata.sheets;
874
+ info.isExcelFile = true;
875
+ }
876
+ // For images
877
+ if (fileInfo.metadata.isImage) {
878
+ info.isImage = true;
879
+ }
880
+ // For PDF files
881
+ if (fileInfo.metadata.isPdf) {
882
+ info.isPdf = true;
883
+ info.totalPages = fileInfo.metadata.totalPages;
884
+ if (fileInfo.metadata.title)
885
+ info.title = fileInfo.metadata.title;
886
+ if (fileInfo.metadata.author)
887
+ info.author = fileInfo.metadata.author;
888
+ }
889
+ // For binary files
890
+ if (fileInfo.metadata.isBinary) {
891
+ info.isBinary = true;
892
+ }
893
+ }
894
+ return info;
895
+ }
896
+ /**
897
+ * Write content to a PDF file.
898
+ * Can create a new PDF from Markdown string, or modify an existing PDF using operations.
899
+ *
900
+ * @param filePath Path to the output PDF file
901
+ * @param content Markdown string (for creation) or array of operations (for modification)
902
+ * @param options Options for PDF generation or modification. For modification, can include `sourcePdf`.
903
+ */
904
+ export async function writePdf(filePath, content, outputPath, options = {}) {
905
+ const validPath = await validatePath(filePath);
906
+ const fileExtension = getFileExtension(validPath);
907
+ if (typeof content === 'string') {
908
+ // --- PDF CREATION MODE ---
909
+ capture('server_write_pdf', {
910
+ fileExtension: fileExtension,
911
+ contentLength: content.length,
912
+ mode: 'create'
913
+ });
914
+ const { parseMarkdownToPdf } = await loadPdf();
915
+ const pdfBuffer = await parseMarkdownToPdf(content, options);
916
+ // Use outputPath if provided, otherwise overwrite input file
917
+ const targetPath = outputPath ? await validatePath(outputPath) : validPath;
918
+ await fs.writeFile(targetPath, pdfBuffer);
919
+ }
920
+ else if (Array.isArray(content)) {
921
+ // Use outputPath if provided, otherwise overwrite input file
922
+ const targetPath = outputPath ? await validatePath(outputPath) : validPath;
923
+ const operations = [];
924
+ // Validate paths in operations
925
+ for (const o of content) {
926
+ if (o.type === 'insert') {
927
+ if (o.sourcePdfPath) {
928
+ o.sourcePdfPath = await validatePath(o.sourcePdfPath);
929
+ }
930
+ }
931
+ operations.push(o);
932
+ }
933
+ capture('server_write_pdf', {
934
+ fileExtension: fileExtension,
935
+ operationCount: operations.length,
936
+ mode: 'modify',
937
+ deleteCount: operations.filter(op => op.type === 'delete').length,
938
+ insertCount: operations.filter(op => op.type === 'insert').length
939
+ });
940
+ // Perform the PDF editing
941
+ const { editPdf } = await loadPdf();
942
+ const modifiedPdfBuffer = await editPdf(validPath, operations);
943
+ // Write the modified PDF to the output path
944
+ await fs.writeFile(targetPath, modifiedPdfBuffer);
945
+ }
946
+ else {
947
+ throw new Error('Invalid content type for writePdf. Expected string (markdown) or array of operations.');
948
+ }
949
+ }
950
+ const execFileAsync = promisify(execFile);
951
+ const DEFAULT_EDITOR_NEGATIVE_CACHE_MS = 5 * 60 * 1000;
952
+ const defaultEditorCache = new Map();
953
+ function escapeAppleScriptString(value) {
954
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
955
+ }
956
+ export async function getDefaultEditorMetadata(filePath) {
957
+ if (os.platform() !== 'darwin') {
958
+ return {};
959
+ }
960
+ let cacheKey = '';
961
+ try {
962
+ const extension = path.extname(filePath).toLowerCase();
963
+ cacheKey = extension || path.basename(filePath).toLowerCase();
964
+ const cached = defaultEditorCache.get(cacheKey);
965
+ if (cached) {
966
+ if (!cached.expiresAt || cached.expiresAt > Date.now()) {
967
+ return cached.metadata;
968
+ }
969
+ defaultEditorCache.delete(cacheKey);
970
+ }
971
+ const script = `set appAlias to default application of (info for POSIX file "${escapeAppleScriptString(filePath)}")\nreturn (name of (info for appAlias)) & linefeed & POSIX path of appAlias`;
972
+ const { stdout } = await execFileAsync('osascript', ['-e', script], { timeout: 12000 });
973
+ const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);
974
+ const defaultEditorName = lines[lines.length - 2]?.replace(/\.app$/i, '') ?? '';
975
+ const defaultEditorPath = lines[lines.length - 1] ?? '';
976
+ if (defaultEditorName && defaultEditorPath.startsWith('/')) {
977
+ const metadata = { defaultEditorName, defaultEditorPath };
978
+ defaultEditorCache.set(cacheKey, { metadata });
979
+ return metadata;
980
+ }
981
+ defaultEditorCache.set(cacheKey, { metadata: {}, expiresAt: Date.now() + DEFAULT_EDITOR_NEGATIVE_CACHE_MS });
982
+ }
983
+ catch {
984
+ if (cacheKey) {
985
+ defaultEditorCache.set(cacheKey, { metadata: {}, expiresAt: Date.now() + DEFAULT_EDITOR_NEGATIVE_CACHE_MS });
986
+ }
987
+ // Generic UI fallback is good enough if detection fails.
988
+ }
989
+ return {};
990
+ }
991
+ //# sourceMappingURL=filesystem.js.map