@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,625 @@
1
+ /**
2
+ * BRC tools backed by ast-grep (https://ast-grep.github.io), a structural (syntax-tree) code
3
+ * search and rewrite tool:
4
+ * ast_search - find code by AST pattern, compact grep-like results with meta-variable captures
5
+ * ast_rewrite - rewrite code by AST pattern (or YAML rule); dry run (diff preview) by default
6
+ *
7
+ * ast-grep is a BRC "binary" plugin (id "ast-grep", npm package @ast-grep/cli installed into
8
+ * $BRC_HOME/plugins/node by the plugin installer). The native executable is run directly (no npm
9
+ * .cmd shim, no shell), so patterns like `$$$ARGS` need no quoting. Falls back to ast-grep on PATH.
10
+ *
11
+ * Paths go through validatePath() (allowedDirectories); the command through
12
+ * commandManager.validateCommand() (blockedCommands).
13
+ */
14
+ import { spawn } from 'node:child_process';
15
+ import fs from 'node:fs';
16
+ import fsp from 'node:fs/promises';
17
+ import path from 'node:path';
18
+ import { z } from 'zod';
19
+ import { zodToJsonSchema } from 'zod-to-json-schema';
20
+ import { validatePath } from '../core/tools/filesystem.js';
21
+ import { commandManager } from '../core/command-manager.js';
22
+ import { getPlugin } from '../plugins/store.js';
23
+ import { pluginPaths } from '../plugins/paths.js';
24
+ import { findOnPath } from './fast-exec.js';
25
+ import { killTree } from './brc-tools.js';
26
+ const isWindows = process.platform === 'win32';
27
+ // Stay below the relay's 120 s per-call timeout.
28
+ const MAX_TIMEOUT_MS = 100_000;
29
+ const DEFAULT_TIMEOUT_MS = 60_000;
30
+ const MAX_OUTPUT_CHARS = 80_000;
31
+ const MAX_REWRITE_MATCHES = 10_000;
32
+ const MAX_STDERR = 20_000;
33
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError: true } : {}) });
34
+ function isFile(p) {
35
+ try {
36
+ return fs.statSync(p).isFile();
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ function isScript(p) {
43
+ try {
44
+ const fd = fs.openSync(p, 'r');
45
+ const b = Buffer.alloc(2);
46
+ fs.readSync(fd, b, 0, 2, 0);
47
+ fs.closeSync(fd);
48
+ return b.toString('latin1') === '#!';
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ /** Names of the @ast-grep/cli platform packages that may hold the native binary here. */
55
+ export function astGrepPlatformPackages(platform = process.platform, arch = process.arch) {
56
+ if (platform === 'win32')
57
+ return [`cli-win32-${arch}-msvc`];
58
+ if (platform === 'darwin')
59
+ return [`cli-darwin-${arch}`];
60
+ if (platform === 'linux')
61
+ return [`cli-linux-${arch}-gnu`, `cli-linux-${arch}-musl`];
62
+ return [];
63
+ }
64
+ /** Native executable (or JS shim) inside a node_modules directory that contains @ast-grep/cli. */
65
+ function fromNodeModules(nodeModules, binName) {
66
+ const exe = isWindows ? `${binName}.exe` : binName;
67
+ const scope = path.join(nodeModules, '@ast-grep');
68
+ const cli = path.join(scope, 'cli');
69
+ for (const pkg of astGrepPlatformPackages()) {
70
+ for (const dir of [path.join(scope, pkg), path.join(cli, 'node_modules', '@ast-grep', pkg)]) {
71
+ const p = path.join(dir, exe);
72
+ if (isFile(p))
73
+ return { command: p, prefixArgs: [] };
74
+ }
75
+ }
76
+ // postinstall copies/links the native binary into the cli package itself
77
+ const inCli = path.join(cli, exe);
78
+ if (isFile(inCli) && !isScript(inCli))
79
+ return { command: inCli, prefixArgs: [] };
80
+ // last resort: the package's JS launcher, run with this Node
81
+ const shim = path.join(cli, binName);
82
+ if (isFile(shim) && isScript(shim))
83
+ return { command: process.execPath, prefixArgs: [shim] };
84
+ return null;
85
+ }
86
+ const RESOLVE_TTL_MS = 30_000;
87
+ let resolvedExe = null;
88
+ /** Locate ast-grep: installed BRC plugin first, then PATH. null when unavailable or disabled. */
89
+ export function resolveAstGrep() {
90
+ if (resolvedExe && Date.now() - resolvedExe.at < RESOLVE_TTL_MS)
91
+ return resolvedExe.exe;
92
+ let exe = null;
93
+ const rec = getPlugin('ast-grep');
94
+ if (!rec || rec.enabled) {
95
+ if (rec?.status === 'installed') {
96
+ const bin = rec.source.type === 'binary' && rec.source.binName ? rec.source.binName : 'ast-grep';
97
+ const hit = fromNodeModules(path.join(pluginPaths.npmPrefix(), 'node_modules'), bin)
98
+ ?? fromNodeModules(path.join(pluginPaths.npmPrefix(), 'node_modules'), 'ast-grep');
99
+ if (hit)
100
+ exe = { ...hit, via: 'plugin' };
101
+ }
102
+ if (!exe) {
103
+ const pathVar = process.env.PATH ?? process.env.Path;
104
+ const names = process.platform === 'linux' ? ['ast-grep'] : ['ast-grep', 'sg']; // sg is setgroups on Linux
105
+ for (const n of names) {
106
+ const p = findOnPath(n, pathVar, isWindows ? ['.exe'] : ['']);
107
+ if (p) {
108
+ exe = { command: p, prefixArgs: [], via: 'path' };
109
+ break;
110
+ }
111
+ }
112
+ if (!exe && isWindows) {
113
+ // npm global install: <prefix>\ast-grep.cmd + <prefix>\node_modules\@ast-grep\...
114
+ const shim = findOnPath('ast-grep', pathVar, ['.cmd']);
115
+ const hit = shim ? fromNodeModules(path.join(path.dirname(shim), 'node_modules'), 'ast-grep') : null;
116
+ if (hit)
117
+ exe = { ...hit, via: 'path' };
118
+ }
119
+ }
120
+ }
121
+ resolvedExe = { at: Date.now(), exe };
122
+ return exe;
123
+ }
124
+ export function resetAstGrepCache() {
125
+ resolvedExe = null;
126
+ }
127
+ function notInstalledMessage() {
128
+ const rec = getPlugin('ast-grep');
129
+ if (rec && !rec.enabled)
130
+ return 'ast-grep is disabled on this device (plugin "ast-grep"). The device owner can enable it in BRC plugin settings.';
131
+ let msg = 'ast-grep is not installed on this device yet; it is installed automatically in the background - try again shortly (list_plugin_tools shows plugin status).';
132
+ if (rec?.status === 'failed' && rec.error)
133
+ msg += `\nLast install attempt failed: ${rec.error}`;
134
+ else if (rec?.status === 'needs-user' && rec.userAction)
135
+ msg += `\nWaiting for the user: ${rec.userAction}`;
136
+ else if (rec?.status === 'unsupported')
137
+ msg = `ast-grep cannot run on this device${rec.error ? `: ${rec.error}` : '.'}`;
138
+ return msg;
139
+ }
140
+ function runAstGrep(exe, args, cwd, limit, timeoutMs) {
141
+ const started = Date.now();
142
+ return new Promise((resolve) => {
143
+ let child;
144
+ try {
145
+ child = spawn(exe.command, [...exe.prefixArgs, ...args], {
146
+ cwd,
147
+ windowsHide: true,
148
+ stdio: ['ignore', 'pipe', 'pipe'],
149
+ detached: !isWindows,
150
+ env: { ...process.env, NO_COLOR: '1' },
151
+ });
152
+ }
153
+ catch (e) {
154
+ resolve({ matches: [], truncated: false, exitCode: null, stderr: '', timedOut: false, ms: 0, spawnError: e instanceof Error ? e.message : String(e) });
155
+ return;
156
+ }
157
+ const matches = [];
158
+ let truncated = false;
159
+ let timedOut = false;
160
+ let settled = false;
161
+ let buf = '';
162
+ let stderr = '';
163
+ const timer = setTimeout(() => { timedOut = true; killTree(child.pid); }, timeoutMs);
164
+ child.stdout.setEncoding('utf8');
165
+ child.stderr.setEncoding('utf8');
166
+ child.stdout.on('data', (d) => {
167
+ if (truncated)
168
+ return;
169
+ buf += d;
170
+ let nl;
171
+ while ((nl = buf.indexOf('\n')) !== -1) {
172
+ const line = buf.slice(0, nl).trim();
173
+ buf = buf.slice(nl + 1);
174
+ if (!line)
175
+ continue;
176
+ try {
177
+ matches.push(JSON.parse(line));
178
+ }
179
+ catch { /* ignore partial/non-JSON */ }
180
+ if (matches.length >= limit) {
181
+ truncated = true;
182
+ killTree(child.pid);
183
+ return;
184
+ }
185
+ }
186
+ });
187
+ child.stderr.on('data', (d) => { if (stderr.length < MAX_STDERR)
188
+ stderr += d; });
189
+ const finish = (exitCode, spawnError) => {
190
+ if (settled)
191
+ return;
192
+ settled = true;
193
+ clearTimeout(timer);
194
+ const rest = buf.trim();
195
+ if (rest && !truncated) {
196
+ try {
197
+ matches.push(JSON.parse(rest));
198
+ }
199
+ catch { /* ignore */ }
200
+ }
201
+ resolve({ matches, truncated, exitCode, stderr: stderr.slice(0, MAX_STDERR), timedOut, ms: Date.now() - started, spawnError });
202
+ };
203
+ child.on('error', (e) => finish(null, e.message));
204
+ child.on('close', (code) => finish(code));
205
+ });
206
+ }
207
+ /** ast-grep's own failure (bad pattern/rule/lang/path), as opposed to "no matches" (exit 1). */
208
+ function failureText(r) {
209
+ if (r.spawnError)
210
+ return `Failed to start ast-grep: ${r.spawnError}`;
211
+ if (r.timedOut)
212
+ return null;
213
+ if (r.truncated)
214
+ return null;
215
+ if (r.exitCode === 0 || (r.exitCode === 1 && !/\berror\b/i.test(r.stderr)))
216
+ return null;
217
+ return `ast-grep failed (exit code ${r.exitCode}):\n${r.stderr.trim() || '(no error output)'}`;
218
+ }
219
+ // ---------------------------------------------------------------------------
220
+ // Formatting helpers (pure; exported for tests)
221
+ // ---------------------------------------------------------------------------
222
+ function oneLine(s, max) {
223
+ const t = s.replace(/\s+/g, ' ').trim();
224
+ return t.length > max ? `${t.slice(0, max - 3)}...` : t;
225
+ }
226
+ export function displayFile(file) {
227
+ return file.replace(/^\.[\\/]/, '').replace(/\\/g, '/');
228
+ }
229
+ /** "$A=name $B=args $$$ARGS=a, b" (empty when no captures). */
230
+ export function formatCaptures(m) {
231
+ const parts = [];
232
+ const byName = (o) => Object.entries(o).sort(([a], [b]) => a.localeCompare(b));
233
+ for (const [k, v] of byName(m.metaVariables?.single ?? {}))
234
+ parts.push(`$${k}=${oneLine(v.text, 80)}`);
235
+ for (const [k, v] of byName(m.metaVariables?.multi ?? {})) {
236
+ const items = v.map((x) => x.text).filter((t) => t.trim() && t.trim() !== ',');
237
+ parts.push(`$$$${k}=${oneLine(items.join(', '), 120)}`);
238
+ }
239
+ return parts.join(' ');
240
+ }
241
+ /** One grep-like line per match: "file:line:col: text [captures]". Lines are 1-based. */
242
+ export function formatMatchLine(m) {
243
+ const first = m.text.split('\n');
244
+ let t = oneLine(first[0], 200);
245
+ if (first.length > 1)
246
+ t += ` ... (+${first.length - 1} lines)`;
247
+ const caps = formatCaptures(m);
248
+ return `${displayFile(m.file)}:${m.range.start.line + 1}:${m.range.start.column + 1}: ${t}${caps ? ` [${caps}]` : ''}`;
249
+ }
250
+ /** Line start byte offsets of a buffer. */
251
+ function lineStarts(buf) {
252
+ const starts = [0];
253
+ for (let i = 0; i < buf.length; i++)
254
+ if (buf[i] === 0x0a)
255
+ starts.push(i + 1);
256
+ return starts;
257
+ }
258
+ function lineOf(starts, offset) {
259
+ let lo = 0, hi = starts.length - 1;
260
+ while (lo < hi) {
261
+ const mid = (lo + hi + 1) >> 1;
262
+ if (starts[mid] <= offset)
263
+ lo = mid;
264
+ else
265
+ hi = mid - 1;
266
+ }
267
+ return lo;
268
+ }
269
+ /**
270
+ * Apply non-overlapping byte-offset edits and return the new content plus a unified diff
271
+ * (`context` lines around each change). Overlapping edits after the first are skipped.
272
+ */
273
+ export function applyEdits(old, editsIn, displayName, context = 2) {
274
+ const edits = [...editsIn].sort((a, b) => a.start - b.start || a.end - b.end);
275
+ const kept = [];
276
+ for (const e of edits) {
277
+ if (kept.length && e.start < kept[kept.length - 1].end)
278
+ continue;
279
+ kept.push(e);
280
+ }
281
+ if (!kept.length)
282
+ return { content: old, diff: '', applied: 0 };
283
+ const parts = [];
284
+ let pos = 0;
285
+ for (const e of kept) {
286
+ parts.push(old.subarray(pos, e.start), e.replacement);
287
+ pos = e.end;
288
+ }
289
+ parts.push(old.subarray(pos));
290
+ const content = Buffer.concat(parts);
291
+ // Changes = groups of edits touching the same lines; each covers old lines [from, to].
292
+ const starts = lineStarts(old);
293
+ const oldLines = old.toString('utf8').split('\n').map((l) => l.replace(/\r$/, ''));
294
+ const lineEndExcl = (line) => (line + 1 < starts.length ? starts[line + 1] - 1 : old.length);
295
+ const changes = [];
296
+ for (const e of kept) {
297
+ const from = lineOf(starts, e.start);
298
+ const to = lineOf(starts, Math.max(e.start, e.end - 1));
299
+ const last = changes[changes.length - 1];
300
+ if (last && from <= last.to) {
301
+ last.to = Math.max(last.to, to);
302
+ last.edits.push(e);
303
+ }
304
+ else
305
+ changes.push({ from, to, edits: [e] });
306
+ }
307
+ const newLinesOf = (c) => {
308
+ const segs = [];
309
+ let p = starts[c.from];
310
+ for (const e of c.edits) {
311
+ segs.push(old.subarray(p, e.start), e.replacement);
312
+ p = e.end;
313
+ }
314
+ segs.push(old.subarray(p, lineEndExcl(c.to)));
315
+ return Buffer.concat(segs).toString('utf8').split('\n').map((l) => l.replace(/\r$/, ''));
316
+ };
317
+ // Hunks = changes closer than 2*context lines.
318
+ const hunks = [];
319
+ for (const c of changes) {
320
+ const h = hunks[hunks.length - 1];
321
+ if (h && c.from - h[h.length - 1].to - 1 <= 2 * context)
322
+ h.push(c);
323
+ else
324
+ hunks.push([c]);
325
+ }
326
+ let out = `--- a/${displayName}\n+++ b/${displayName}\n`;
327
+ let delta = 0; // new-line offset accumulated from earlier hunks
328
+ for (const h of hunks) {
329
+ const s = Math.max(0, h[0].from - context);
330
+ const e = Math.min(oldLines.length - 1, h[h.length - 1].to + context);
331
+ const body = [];
332
+ let oldCount = 0, newCount = 0;
333
+ let l = s;
334
+ for (const c of h) {
335
+ for (; l < c.from; l++) {
336
+ body.push(` ${oldLines[l]}`);
337
+ oldCount++;
338
+ newCount++;
339
+ }
340
+ for (let k = c.from; k <= c.to; k++) {
341
+ body.push(`-${oldLines[k]}`);
342
+ oldCount++;
343
+ }
344
+ const nl = newLinesOf(c);
345
+ for (const x of nl) {
346
+ body.push(`+${x}`);
347
+ newCount++;
348
+ }
349
+ l = c.to + 1;
350
+ }
351
+ for (; l <= e; l++) {
352
+ body.push(` ${oldLines[l]}`);
353
+ oldCount++;
354
+ newCount++;
355
+ }
356
+ out += `@@ -${s + 1},${oldCount} +${s + 1 + delta},${newCount} @@\n${body.join('\n')}\n`;
357
+ delta += newCount - oldCount;
358
+ }
359
+ return { content, diff: out, applied: kept.length };
360
+ }
361
+ // ---------------------------------------------------------------------------
362
+ // Common argument handling
363
+ // ---------------------------------------------------------------------------
364
+ async function resolveTarget(p) {
365
+ const abs = await validatePath(p);
366
+ const st = await fsp.stat(abs).catch(() => null);
367
+ if (!st)
368
+ throw new Error(`Path not found: ${p}`);
369
+ if (st.isDirectory())
370
+ return { cwd: abs, target: '.', abs, isDir: true };
371
+ return { cwd: path.dirname(abs), target: path.basename(abs), abs, isDir: false };
372
+ }
373
+ function globArgs(globs) {
374
+ const out = [];
375
+ for (const g of globs ?? [])
376
+ if (g.trim())
377
+ out.push('--globs', g);
378
+ return out;
379
+ }
380
+ async function preflight() {
381
+ if (!(await commandManager.validateCommand('ast-grep')))
382
+ return { error: text('Error: Command not allowed: ast-grep', true) };
383
+ const exe = resolveAstGrep();
384
+ if (!exe)
385
+ return { error: text(notInstalledMessage(), true) };
386
+ return { exe };
387
+ }
388
+ function capOutput(s, max = MAX_OUTPUT_CHARS) {
389
+ return s.length > max ? `${s.slice(0, max)}\n\n[... output truncated at ${max} characters; narrow path/globs or lower maxResults ...]` : s;
390
+ }
391
+ // ---------------------------------------------------------------------------
392
+ // ast_search
393
+ // ---------------------------------------------------------------------------
394
+ export const AstSearchArgsSchema = z.object({
395
+ pattern: z.string().min(1).optional().describe('AST pattern, written as code. $X = one node, $$$X = zero or more nodes, $_ = wildcard.'),
396
+ rule: z.string().optional().describe('Alternative to pattern: an ast-grep YAML rule (id, language, rule: {...}).'),
397
+ lang: z.string().optional().describe('Language of the pattern, e.g. ts, tsx, js, py, rust, go, java, c, cpp, cs, rb, kotlin, swift, html, css. Omit to infer from file extensions.'),
398
+ path: z.string().min(1).describe('Directory or file to search (absolute; inside allowed directories).'),
399
+ globs: z.array(z.string()).optional().describe('Include/exclude globs, e.g. ["**/*.ts", "!**/*.test.ts"].'),
400
+ maxResults: z.number().int().min(1).max(5_000).optional().default(200),
401
+ contextLines: z.number().int().min(0).max(10).optional().default(0).describe('Source lines to show around each match.'),
402
+ timeout_ms: z.number().int().min(1_000).max(MAX_TIMEOUT_MS).optional().default(DEFAULT_TIMEOUT_MS),
403
+ });
404
+ function contextBlock(file, m, n, cache) {
405
+ let lines = cache.get(file);
406
+ if (lines === undefined) {
407
+ try {
408
+ lines = fs.readFileSync(file, 'utf8').split('\n').map((l) => l.replace(/\r$/, ''));
409
+ }
410
+ catch {
411
+ lines = null;
412
+ }
413
+ cache.set(file, lines);
414
+ }
415
+ if (!lines)
416
+ return '';
417
+ const s = Math.max(0, m.range.start.line - n);
418
+ const e = Math.min(lines.length - 1, m.range.end.line + n);
419
+ const w = String(e + 1).length;
420
+ const out = [];
421
+ for (let i = s; i <= e; i++) {
422
+ const mark = i >= m.range.start.line && i <= m.range.end.line ? '>' : ' ';
423
+ out.push(` ${mark}${String(i + 1).padStart(w)}| ${lines[i].length > 300 ? `${lines[i].slice(0, 297)}...` : lines[i]}`);
424
+ }
425
+ return out.join('\n');
426
+ }
427
+ export async function handleAstSearch(args) {
428
+ const parsed = AstSearchArgsSchema.safeParse(args);
429
+ if (!parsed.success)
430
+ return text(`Invalid arguments for ast_search: ${parsed.error.message}`, true);
431
+ const a = parsed.data;
432
+ if (!a.pattern === !a.rule)
433
+ return text('ast_search needs exactly one of "pattern" or "rule".', true);
434
+ const pre = await preflight();
435
+ if ('error' in pre)
436
+ return pre.error;
437
+ let t;
438
+ try {
439
+ t = await resolveTarget(a.path);
440
+ }
441
+ catch (e) {
442
+ return text(e instanceof Error ? e.message : String(e), true);
443
+ }
444
+ const cli = a.rule
445
+ ? ['scan', '--inline-rules', a.rule]
446
+ : ['run', '--pattern', a.pattern, ...(a.lang ? ['--lang', a.lang] : [])];
447
+ cli.push('--json=stream', '--color', 'never', ...globArgs(a.globs), t.target);
448
+ const r = await runAstGrep(pre.exe, cli, t.cwd, a.maxResults + 1, a.timeout_ms);
449
+ const fail = failureText(r);
450
+ if (fail)
451
+ return text(fail, true);
452
+ const shown = r.matches.slice(0, a.maxResults);
453
+ const more = r.matches.length > a.maxResults || r.truncated;
454
+ const files = new Set(shown.map((m) => m.file));
455
+ let out = `ast_search ${a.rule ? 'rule' : `pattern ${JSON.stringify(a.pattern)}`}${a.lang ? ` (${a.lang})` : ''} in ${t.abs}\n`;
456
+ if (!shown.length) {
457
+ out += r.timedOut ? `No matches before the ${a.timeout_ms} ms timeout.` : 'No matches.';
458
+ const warn = r.stderr.trim();
459
+ if (warn)
460
+ out += `\nast-grep: ${oneLine(warn, 500)}`;
461
+ if (!r.timedOut)
462
+ out += '\nTips: the pattern must be valid code in the target language; set lang; use $X / $$$X for variable parts.';
463
+ return text(out);
464
+ }
465
+ out += `${shown.length}${more ? '+' : ''} match(es) in ${files.size} file(s)${more ? ` (stopped at maxResults=${a.maxResults})` : ''}${r.timedOut ? ` (TIMED OUT after ${a.timeout_ms} ms; results incomplete)` : ''} · ${r.ms}ms\n\n`;
466
+ const cache = new Map();
467
+ const lines = [];
468
+ for (const m of shown) {
469
+ lines.push(formatMatchLine(m));
470
+ if (a.contextLines > 0)
471
+ lines.push(contextBlock(path.resolve(t.cwd, m.file), m, a.contextLines, cache));
472
+ }
473
+ out += lines.join('\n');
474
+ return text(capOutput(out));
475
+ }
476
+ // ---------------------------------------------------------------------------
477
+ // ast_rewrite
478
+ // ---------------------------------------------------------------------------
479
+ export const AstRewriteArgsSchema = z.object({
480
+ pattern: z.string().min(1).optional().describe('AST pattern to match (use with rewrite and lang).'),
481
+ rewrite: z.string().optional().describe('Replacement code; may reuse meta-variables from the pattern ($X, $$$X).'),
482
+ rule: z.string().optional().describe('Alternative to pattern/rewrite: an ast-grep YAML rule with a fix (id, language, rule: {...}, fix: ...).'),
483
+ lang: z.string().optional().describe('Language of the pattern (required with pattern), e.g. ts, tsx, js, py, rust, go, java.'),
484
+ path: z.string().min(1).describe('Directory or file to rewrite (absolute; inside allowed directories).'),
485
+ globs: z.array(z.string()).optional().describe('Include/exclude globs, e.g. ["src/**/*.ts", "!**/*.d.ts"].'),
486
+ dry_run: z.boolean().optional().default(true).describe('Default true: only preview (diff + counts). Set false to write the files.'),
487
+ contextLines: z.number().int().min(0).max(10).optional().default(2).describe('Context lines in the diff.'),
488
+ timeout_ms: z.number().int().min(1_000).max(MAX_TIMEOUT_MS).optional().default(DEFAULT_TIMEOUT_MS),
489
+ });
490
+ export async function handleAstRewrite(args) {
491
+ const parsed = AstRewriteArgsSchema.safeParse(args);
492
+ if (!parsed.success)
493
+ return text(`Invalid arguments for ast_rewrite: ${parsed.error.message}`, true);
494
+ const a = parsed.data;
495
+ if (a.rule && (a.pattern || a.rewrite !== undefined))
496
+ return text('ast_rewrite: pass either rule, or pattern + rewrite + lang - not both.', true);
497
+ if (!a.rule) {
498
+ if (!a.pattern || a.rewrite === undefined)
499
+ return text('ast_rewrite needs pattern and rewrite (or a YAML rule with a fix).', true);
500
+ if (!a.lang)
501
+ return text('ast_rewrite needs lang with a pattern (e.g. "ts", "py", "rust") so the pattern is parsed correctly.', true);
502
+ }
503
+ const pre = await preflight();
504
+ if ('error' in pre)
505
+ return pre.error;
506
+ let t;
507
+ try {
508
+ t = await resolveTarget(a.path);
509
+ }
510
+ catch (e) {
511
+ return text(e instanceof Error ? e.message : String(e), true);
512
+ }
513
+ const cli = a.rule
514
+ ? ['scan', '--inline-rules', a.rule]
515
+ : ['run', '--pattern', a.pattern, '--rewrite', a.rewrite, '--lang', a.lang];
516
+ cli.push('--json=stream', '--color', 'never', ...globArgs(a.globs), t.target);
517
+ const r = await runAstGrep(pre.exe, cli, t.cwd, MAX_REWRITE_MATCHES + 1, a.timeout_ms);
518
+ const fail = failureText(r);
519
+ if (fail)
520
+ return text(fail, true);
521
+ if (r.timedOut)
522
+ return text(`ast-grep timed out after ${a.timeout_ms} ms; nothing was changed. Narrow path or globs.`, true);
523
+ if (r.truncated)
524
+ return text(`More than ${MAX_REWRITE_MATCHES} matches; nothing was changed. Narrow path or globs.`, true);
525
+ // Group edits per file.
526
+ const byFile = new Map();
527
+ let noFix = 0;
528
+ for (const m of r.matches) {
529
+ if (m.replacement === undefined) {
530
+ noFix++;
531
+ continue;
532
+ }
533
+ const off = m.replacementOffsets ?? m.range.byteOffset;
534
+ const list = byFile.get(m.file) ?? [];
535
+ list.push({ start: off.start, end: off.end, replacement: Buffer.from(m.replacement, 'utf8') });
536
+ byFile.set(m.file, list);
537
+ }
538
+ const head = `ast_rewrite ${a.rule ? 'rule' : `${JSON.stringify(a.pattern)} -> ${JSON.stringify(a.rewrite)}`}${a.lang ? ` (${a.lang})` : ''} in ${t.abs}`;
539
+ if (!byFile.size) {
540
+ let out = `${head}\nNo matches${noFix ? ` with a fix (${noFix} match(es) without a fix; does the rule have "fix:"?)` : ''}. Nothing changed.`;
541
+ const warn = r.stderr.trim();
542
+ if (warn)
543
+ out += `\nast-grep: ${oneLine(warn, 500)}`;
544
+ return text(out);
545
+ }
546
+ let diffs = '';
547
+ let edits = 0, changedFiles = 0;
548
+ const written = [];
549
+ const errors = [];
550
+ for (const [file, list] of byFile) {
551
+ const abs = path.resolve(t.cwd, file);
552
+ try {
553
+ const safe = await validatePath(abs);
554
+ const old = await fsp.readFile(safe);
555
+ const res = applyEdits(old, list, displayFile(file), a.contextLines);
556
+ if (!res.applied || res.content.equals(old))
557
+ continue;
558
+ edits += res.applied;
559
+ changedFiles++;
560
+ diffs += res.diff;
561
+ if (!a.dry_run) {
562
+ await fsp.writeFile(safe, res.content);
563
+ written.push(displayFile(file));
564
+ }
565
+ }
566
+ catch (e) {
567
+ errors.push(`${displayFile(file)}: ${e instanceof Error ? e.message : String(e)}`);
568
+ }
569
+ }
570
+ let out = `${head}\n`;
571
+ out += a.dry_run
572
+ ? `DRY RUN: ${edits} replacement(s) in ${changedFiles} file(s) would be made. Nothing was written; call again with dry_run=false to apply.\n`
573
+ : `APPLIED: ${edits} replacement(s) written to ${written.length} file(s).\n`;
574
+ if (errors.length)
575
+ out += `Errors (${errors.length}):\n${errors.map((x) => ` ${x}`).join('\n')}\n`;
576
+ out += `\n${diffs}`;
577
+ return text(capOutput(out), !!errors.length && !changedFiles);
578
+ }
579
+ // ---------------------------------------------------------------------------
580
+ // Registry
581
+ // ---------------------------------------------------------------------------
582
+ export const AST_GREP_TOOL_HANDLERS = {
583
+ ast_search: handleAstSearch,
584
+ ast_rewrite: handleAstRewrite,
585
+ };
586
+ const PATTERN_HELP = [
587
+ 'Pattern syntax: write the code you are looking for; $NAME matches exactly one AST node (expression, identifier, ...),',
588
+ '$$$NAME matches zero or more nodes (arguments, statements), $_ matches any node without capturing.',
589
+ 'Reusing a name ($A ... $A) requires the same code in both places. Whitespace and formatting do not matter.',
590
+ ].join('\n');
591
+ export function buildAstGrepToolDefinitions() {
592
+ return [
593
+ {
594
+ name: 'ast_search',
595
+ description: [
596
+ 'Structural code search with ast-grep: matches syntax trees, not text, so it ignores formatting, comments and strings',
597
+ 'that merely contain the words. Use it instead of regex search for code shapes (calls, definitions, imports, JSX...).',
598
+ PATTERN_HELP,
599
+ 'Examples: {"pattern":"callTool($NAME, $ARGS)","lang":"ts","path":"/repo/src"} finds every two-argument callTool call;',
600
+ '{"pattern":"console.log($$$ARGS)","lang":"js","path":"/repo"} finds console.log calls with any arguments.',
601
+ 'Returns "file:line:col: matched code [captures]" relative to path. Respects .gitignore. maxResults default 200;',
602
+ 'contextLines shows surrounding source. Alternatively pass rule = an ast-grep YAML rule (id, language, rule) for',
603
+ 'relational queries (inside / has / not).',
604
+ ].join('\n'),
605
+ inputSchema: zodToJsonSchema(AstSearchArgsSchema),
606
+ annotations: { title: 'AST Search', readOnlyHint: true },
607
+ },
608
+ {
609
+ name: 'ast_rewrite',
610
+ description: [
611
+ 'Structural code rewrite with ast-grep. DRY RUN BY DEFAULT: returns a unified diff and counts without changing',
612
+ 'files; call again with dry_run=false to write the changes.',
613
+ PATTERN_HELP,
614
+ 'Meta-variables captured by pattern can be used in rewrite.',
615
+ 'Examples: {"pattern":"oldApi($A, $B)","rewrite":"newApi({ a: $A, b: $B })","lang":"ts","path":"/repo/src"};',
616
+ '{"pattern":"assertEquals($X, $Y)","rewrite":"assert $X == $Y","lang":"py","path":"/repo/tests"}.',
617
+ 'Alternatively pass rule = an ast-grep YAML rule with a fix (id, language, rule: {...}, fix: ...).',
618
+ 'lang is required with pattern. globs narrows files. Respects .gitignore.',
619
+ ].join('\n'),
620
+ inputSchema: zodToJsonSchema(AstRewriteArgsSchema),
621
+ annotations: { title: 'AST Rewrite', readOnlyHint: false, destructiveHint: true, openWorldHint: false },
622
+ },
623
+ ];
624
+ }
625
+ //# sourceMappingURL=ast-grep.js.map