@belboy47/brc-agent 0.0.0-stage → 2.0.17-lab.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (413) hide show
  1. package/LICENSE +30 -0
  2. package/LICENSE-desktop-commander +21 -0
  3. package/NOTICE +13 -0
  4. package/README.md +58 -2
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +354 -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 +97 -0
  66. package/dist/core/tools/config.js +265 -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/docker-client.d.ts +47 -0
  267. package/dist/runtime/docker-client.js +40 -0
  268. package/dist/runtime/docker-client.js.map +1 -0
  269. package/dist/runtime/errors.d.ts +9 -0
  270. package/dist/runtime/errors.js +56 -0
  271. package/dist/runtime/errors.js.map +1 -0
  272. package/dist/runtime/failure-log.d.ts +22 -0
  273. package/dist/runtime/failure-log.js +112 -0
  274. package/dist/runtime/failure-log.js.map +1 -0
  275. package/dist/runtime/fast-batch.d.ts +55 -0
  276. package/dist/runtime/fast-batch.js +104 -0
  277. package/dist/runtime/fast-batch.js.map +1 -0
  278. package/dist/runtime/file-safety.d.ts +7 -0
  279. package/dist/runtime/file-safety.js +134 -0
  280. package/dist/runtime/file-safety.js.map +1 -0
  281. package/dist/runtime/generic-code.d.ts +9 -0
  282. package/dist/runtime/generic-code.js +123 -0
  283. package/dist/runtime/generic-code.js.map +1 -0
  284. package/dist/runtime/graph-outline.d.ts +54 -0
  285. package/dist/runtime/graph-outline.js +118 -0
  286. package/dist/runtime/graph-outline.js.map +1 -0
  287. package/dist/runtime/harness.d.ts +61 -0
  288. package/dist/runtime/harness.js +102 -0
  289. package/dist/runtime/harness.js.map +1 -0
  290. package/dist/runtime/instruction-context.d.ts +23 -0
  291. package/dist/runtime/instruction-context.js +136 -0
  292. package/dist/runtime/instruction-context.js.map +1 -0
  293. package/dist/runtime/lab-mode.d.ts +4 -0
  294. package/dist/runtime/lab-mode.js +18 -0
  295. package/dist/runtime/lab-mode.js.map +1 -0
  296. package/dist/runtime/languages.d.ts +30 -0
  297. package/dist/runtime/languages.js +59 -0
  298. package/dist/runtime/languages.js.map +1 -0
  299. package/dist/runtime/nav-cache.d.ts +2 -0
  300. package/dist/runtime/nav-cache.js +12 -0
  301. package/dist/runtime/nav-cache.js.map +1 -0
  302. package/dist/runtime/operations.d.ts +40 -0
  303. package/dist/runtime/operations.js +86 -0
  304. package/dist/runtime/operations.js.map +1 -0
  305. package/dist/runtime/platform-capabilities.d.ts +20 -0
  306. package/dist/runtime/platform-capabilities.js +36 -0
  307. package/dist/runtime/platform-capabilities.js.map +1 -0
  308. package/dist/runtime/program-runner.d.ts +4 -0
  309. package/dist/runtime/program-runner.js +73 -0
  310. package/dist/runtime/program-runner.js.map +1 -0
  311. package/dist/runtime/project-context.d.ts +53 -0
  312. package/dist/runtime/project-context.js +90 -0
  313. package/dist/runtime/project-context.js.map +1 -0
  314. package/dist/runtime/project-files.d.ts +2 -0
  315. package/dist/runtime/project-files.js +3 -0
  316. package/dist/runtime/project-files.js.map +1 -0
  317. package/dist/runtime/project-index.d.ts +40 -0
  318. package/dist/runtime/project-index.js +158 -0
  319. package/dist/runtime/project-index.js.map +1 -0
  320. package/dist/runtime/resource-limits.d.ts +42 -0
  321. package/dist/runtime/resource-limits.js +50 -0
  322. package/dist/runtime/resource-limits.js.map +1 -0
  323. package/dist/runtime/scratch-budget.d.ts +11 -0
  324. package/dist/runtime/scratch-budget.js +107 -0
  325. package/dist/runtime/scratch-budget.js.map +1 -0
  326. package/dist/runtime/search-diagnostics.d.ts +3 -0
  327. package/dist/runtime/search-diagnostics.js +45 -0
  328. package/dist/runtime/search-diagnostics.js.map +1 -0
  329. package/dist/runtime/toolchains.d.ts +25 -0
  330. package/dist/runtime/toolchains.js +70 -0
  331. package/dist/runtime/toolchains.js.map +1 -0
  332. package/dist/runtime/worker-coordination.d.ts +314 -0
  333. package/dist/runtime/worker-coordination.js +564 -0
  334. package/dist/runtime/worker-coordination.js.map +1 -0
  335. package/dist/runtime/workspace.d.ts +151 -0
  336. package/dist/runtime/workspace.js +267 -0
  337. package/dist/runtime/workspace.js.map +1 -0
  338. package/dist/service.d.ts +3 -0
  339. package/dist/service.js +102 -0
  340. package/dist/service.js.map +1 -0
  341. package/dist/terminal-setup.d.ts +33 -0
  342. package/dist/terminal-setup.js +219 -0
  343. package/dist/terminal-setup.js.map +1 -0
  344. package/dist/terminal-shortcuts.d.ts +22 -0
  345. package/dist/terminal-shortcuts.js +145 -0
  346. package/dist/terminal-shortcuts.js.map +1 -0
  347. package/dist/terminal-ui.d.ts +20 -0
  348. package/dist/terminal-ui.js +53 -0
  349. package/dist/terminal-ui.js.map +1 -0
  350. package/dist/tools/ast-grep.d.ts +132 -0
  351. package/dist/tools/ast-grep.js +625 -0
  352. package/dist/tools/ast-grep.js.map +1 -0
  353. package/dist/tools/brc-tools.d.ts +112 -0
  354. package/dist/tools/brc-tools.js +599 -0
  355. package/dist/tools/brc-tools.js.map +1 -0
  356. package/dist/tools/check-tools.d.ts +4 -0
  357. package/dist/tools/check-tools.js +29 -0
  358. package/dist/tools/check-tools.js.map +1 -0
  359. package/dist/tools/coding-tools.d.ts +33 -0
  360. package/dist/tools/coding-tools.js +190 -0
  361. package/dist/tools/coding-tools.js.map +1 -0
  362. package/dist/tools/command-shell.d.ts +17 -0
  363. package/dist/tools/command-shell.js +84 -0
  364. package/dist/tools/command-shell.js.map +1 -0
  365. package/dist/tools/dev-extras.d.ts +42 -0
  366. package/dist/tools/dev-extras.js +135 -0
  367. package/dist/tools/dev-extras.js.map +1 -0
  368. package/dist/tools/edit-tools.d.ts +4 -0
  369. package/dist/tools/edit-tools.js +293 -0
  370. package/dist/tools/edit-tools.js.map +1 -0
  371. package/dist/tools/fast-exec.d.ts +11 -0
  372. package/dist/tools/fast-exec.js +202 -0
  373. package/dist/tools/fast-exec.js.map +1 -0
  374. package/dist/tools/image-tools.d.ts +37 -0
  375. package/dist/tools/image-tools.js +293 -0
  376. package/dist/tools/image-tools.js.map +1 -0
  377. package/dist/tools/jobs.d.ts +227 -0
  378. package/dist/tools/jobs.js +608 -0
  379. package/dist/tools/jobs.js.map +1 -0
  380. package/dist/tools/ops-tools.d.ts +8 -0
  381. package/dist/tools/ops-tools.js +58 -0
  382. package/dist/tools/ops-tools.js.map +1 -0
  383. package/dist/tools/plugin-tools.d.ts +38 -0
  384. package/dist/tools/plugin-tools.js +133 -0
  385. package/dist/tools/plugin-tools.js.map +1 -0
  386. package/dist/tools/rtk.d.ts +60 -0
  387. package/dist/tools/rtk.js +245 -0
  388. package/dist/tools/rtk.js.map +1 -0
  389. package/dist/tools/sandbox-tools.d.ts +41 -0
  390. package/dist/tools/sandbox-tools.js +146 -0
  391. package/dist/tools/sandbox-tools.js.map +1 -0
  392. package/dist/tools/worker-tools.d.ts +231 -0
  393. package/dist/tools/worker-tools.js +55 -0
  394. package/dist/tools/worker-tools.js.map +1 -0
  395. package/dist/tools/workspace-batch.d.ts +262 -0
  396. package/dist/tools/workspace-batch.js +188 -0
  397. package/dist/tools/workspace-batch.js.map +1 -0
  398. package/dist/transport/pairing.d.ts +22 -0
  399. package/dist/transport/pairing.js +154 -0
  400. package/dist/transport/pairing.js.map +1 -0
  401. package/dist/transport/plugin-admin.d.ts +33 -0
  402. package/dist/transport/plugin-admin.js +156 -0
  403. package/dist/transport/plugin-admin.js.map +1 -0
  404. package/dist/transport/relay-url.d.ts +3 -0
  405. package/dist/transport/relay-url.js +38 -0
  406. package/dist/transport/relay-url.js.map +1 -0
  407. package/dist/transport/result-budget.d.ts +11 -0
  408. package/dist/transport/result-budget.js +45 -0
  409. package/dist/transport/result-budget.js.map +1 -0
  410. package/dist/transport/ws-client.d.ts +64 -0
  411. package/dist/transport/ws-client.js +242 -0
  412. package/dist/transport/ws-client.js.map +1 -0
  413. package/package.json +70 -5
@@ -0,0 +1,929 @@
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import fs from 'fs/promises';
4
+ import { validatePath } from './tools/filesystem.js';
5
+ import { capture } from './utils/capture.js';
6
+ import { getRipgrepPath } from './utils/ripgrep-resolver.js';
7
+ import { isExcelFile } from './utils/files/index.js';
8
+ import { getCallContext, checkCancelled } from '../context.js';
9
+ const MAX_LINE_TEXT = 400;
10
+ const capLine = (s) => {
11
+ if (s === undefined)
12
+ return undefined;
13
+ const t = s.replace(/\r?\n$/, '');
14
+ return t.length > MAX_LINE_TEXT ? t.slice(0, MAX_LINE_TEXT) + '…' : t;
15
+ };
16
+ /**
17
+ * Search Session Manager - handles ripgrep processes like terminal sessions
18
+ * Supports both file search and content search with progressive results
19
+ */ export class SearchManager {
20
+ sessions = new Map();
21
+ sessionCounter = 0;
22
+ /**
23
+ * Start a new search session (like start_process)
24
+ * Returns immediately with initial state and results
25
+ */
26
+ async startSearch(options) {
27
+ checkCancelled();
28
+ options = { ...options, maxResults: Math.min(10000, Math.max(1, options.maxResults ?? 1000)) };
29
+ if (this.sessions.size >= 32) {
30
+ for (const [id, old] of this.sessions) {
31
+ if (old.isComplete)
32
+ this.sessions.delete(id);
33
+ if (this.sessions.size < 32)
34
+ break;
35
+ }
36
+ if (this.sessions.size >= 32)
37
+ throw new Error('SEARCH_BUSY: stop an active search before starting another.');
38
+ }
39
+ const sessionId = `search_${++this.sessionCounter}_${Date.now()}`;
40
+ // Validate path first
41
+ const validPath = await validatePath(options.rootPath);
42
+ // Build ripgrep arguments
43
+ const args = this.buildRipgrepArgs({ ...options, rootPath: validPath });
44
+ // Get ripgrep path with fallback resolution
45
+ let rgPath;
46
+ try {
47
+ rgPath = await getRipgrepPath();
48
+ }
49
+ catch (err) {
50
+ throw new Error(`Failed to locate ripgrep binary: ${err instanceof Error ? err.message : String(err)}`);
51
+ }
52
+ // Start ripgrep process
53
+ const rgProcess = spawn(rgPath, args, { windowsHide: true }); // Prevent visible console windows on Windows
54
+ if (!rgProcess.pid) {
55
+ throw new Error('Failed to start ripgrep process');
56
+ }
57
+ // Create session
58
+ const session = {
59
+ id: sessionId,
60
+ process: rgProcess,
61
+ results: [],
62
+ isComplete: false,
63
+ isError: false,
64
+ startTime: Date.now(),
65
+ lastReadTime: Date.now(),
66
+ options,
67
+ buffer: '',
68
+ totalMatches: 0,
69
+ bytesStored: 0,
70
+ totalContextLines: 0
71
+ };
72
+ this.sessions.set(sessionId, session);
73
+ // Set up process event handlers
74
+ this.setupProcessHandlers(session);
75
+ const signal = getCallContext()?.signal;
76
+ const abort = () => this.stopLimited(session, 'cancelled');
77
+ signal?.addEventListener('abort', abort, { once: true });
78
+ if (signal?.aborted)
79
+ abort();
80
+ rgProcess.once('close', () => signal?.removeEventListener('abort', abort));
81
+ rgProcess.once('error', () => signal?.removeEventListener('abort', abort));
82
+ // Start cleanup interval now that we have a session
83
+ startCleanupIfNeeded();
84
+ // Set up timeout if specified and auto-terminate
85
+ // For exact filename searches, use a shorter default timeout
86
+ const timeoutMs = options.timeout ?? (this.isExactFilename(options.pattern) ? 1500 : undefined);
87
+ let killTimer = null;
88
+ if (timeoutMs) {
89
+ killTimer = setTimeout(() => {
90
+ if (!session.isComplete && !session.process.killed) {
91
+ this.stopLimited(session, 'timeout');
92
+ }
93
+ }, timeoutMs);
94
+ }
95
+ // Clear timer on process completion
96
+ session.process.once('close', () => {
97
+ if (killTimer) {
98
+ clearTimeout(killTimer);
99
+ killTimer = null;
100
+ }
101
+ });
102
+ session.process.once('error', () => {
103
+ if (killTimer) {
104
+ clearTimeout(killTimer);
105
+ killTimer = null;
106
+ }
107
+ });
108
+ capture('search_session_started', {
109
+ sessionId,
110
+ searchType: options.searchType,
111
+ hasTimeout: !!timeoutMs,
112
+ timeoutMs,
113
+ requestedPath: options.rootPath,
114
+ validatedPath: validPath
115
+ });
116
+ // For content searches, only search Excel files when contextually relevant:
117
+ // - filePattern explicitly targets Excel files (*.xlsx, *.xls, etc.)
118
+ // - or rootPath is an Excel file itself
119
+ const shouldSearchExcel = options.searchType === 'content' &&
120
+ this.shouldIncludeExcelSearch(options.filePattern, validPath);
121
+ if (shouldSearchExcel) {
122
+ this.searchExcelFiles(validPath, options.pattern, options.ignoreCase !== false, options.maxResults, options.filePattern, // Pass filePattern to filter Excel files too
123
+ options.literalSearch // Respect literalSearch flag for Office files
124
+ ).then(excelResults => {
125
+ // Add Excel results to session (merged after initial response)
126
+ for (const result of excelResults) {
127
+ if (!this.addResult(session, result))
128
+ break;
129
+ }
130
+ }).catch((err) => {
131
+ // Log Excel search errors but don't fail the whole search
132
+ capture('excel_search_error', { error: err instanceof Error ? err.message : String(err) });
133
+ });
134
+ }
135
+ // For content searches, also search DOCX files
136
+ const shouldSearchDocx = options.searchType === 'content' &&
137
+ this.shouldIncludeDocxSearch(options.filePattern, validPath);
138
+ if (shouldSearchDocx) {
139
+ this.searchDocxFiles(validPath, options.pattern, options.ignoreCase !== false, options.maxResults, options.filePattern, options.literalSearch // Respect literalSearch flag for Office files
140
+ ).then(docxResults => {
141
+ for (const result of docxResults) {
142
+ if (!this.addResult(session, result))
143
+ break;
144
+ }
145
+ }).catch((err) => {
146
+ capture('docx_search_error', { error: err instanceof Error ? err.message : String(err) });
147
+ });
148
+ }
149
+ // Wait for first chunk of data or early completion instead of fixed delay
150
+ // Excel search runs in background and results are merged via readSearchResults
151
+ const firstChunk = new Promise(resolve => {
152
+ const onData = () => {
153
+ session.process.stdout?.off('data', onData);
154
+ resolve();
155
+ };
156
+ session.process.stdout?.once('data', onData);
157
+ setTimeout(resolve, 40); // cap at 40ms instead of 50-100ms
158
+ });
159
+ // Only wait for ripgrep first chunk - Excel results merge asynchronously
160
+ if (!options.skipInitialWait)
161
+ await firstChunk;
162
+ return {
163
+ sessionId,
164
+ isComplete: session.isComplete,
165
+ isError: session.isError,
166
+ results: [...session.results],
167
+ totalResults: session.totalMatches,
168
+ runtime: Date.now() - session.startTime
169
+ };
170
+ }
171
+ /**
172
+ * Read search results with offset-based pagination (like read_file)
173
+ * Supports both range reading and tail behavior
174
+ */
175
+ /**
176
+ * BRC: resolve on the next sign of progress (new ripgrep output or process exit) or after ms.
177
+ * Lets blocking callers react immediately instead of polling on a fixed interval.
178
+ */
179
+ waitForActivity(sessionId, ms) {
180
+ const session = this.sessions.get(sessionId);
181
+ if (!session || session.isComplete)
182
+ return Promise.resolve();
183
+ return new Promise((resolve) => {
184
+ const proc = session.process;
185
+ const done = () => {
186
+ clearTimeout(timer);
187
+ proc.stdout?.off('data', done);
188
+ proc.off('close', done);
189
+ // let the manager's own data/close handlers run first
190
+ setImmediate(resolve);
191
+ };
192
+ const timer = setTimeout(done, Math.max(1, ms));
193
+ proc.stdout?.once('data', done);
194
+ proc.once('close', done);
195
+ });
196
+ }
197
+ readSearchResults(sessionId, offset = 0, length = 100) {
198
+ const session = this.sessions.get(sessionId);
199
+ if (!session) {
200
+ throw new Error(`Search session ${sessionId} not found`);
201
+ }
202
+ // Get all results (excluding internal markers)
203
+ const allResults = session.results.filter(r => r.file !== '__LAST_READ_MARKER__');
204
+ // Handle negative offsets (tail behavior) - like file reading
205
+ if (offset < 0) {
206
+ const tailCount = Math.abs(offset);
207
+ const tailResults = allResults.slice(-tailCount);
208
+ return {
209
+ results: tailResults,
210
+ returnedCount: tailResults.length,
211
+ totalResults: session.totalMatches + session.totalContextLines,
212
+ totalMatches: session.totalMatches, // Actual matches only
213
+ isComplete: session.isComplete,
214
+ isError: session.isError && !!session.error?.trim(), // Only error if we have actual errors
215
+ error: session.error?.trim() || undefined,
216
+ hasMoreResults: false, // Tail always returns what's available
217
+ runtime: Date.now() - session.startTime,
218
+ stopReason: session.stopReason,
219
+ wasIncomplete: session.wasIncomplete
220
+ };
221
+ }
222
+ // Handle positive offsets (range behavior) - like file reading
223
+ const slicedResults = allResults.slice(offset, offset + length);
224
+ const hasMoreResults = offset + length < allResults.length || !session.isComplete;
225
+ session.lastReadTime = Date.now();
226
+ return {
227
+ results: slicedResults,
228
+ returnedCount: slicedResults.length,
229
+ totalResults: session.totalMatches + session.totalContextLines,
230
+ totalMatches: session.totalMatches, // Actual matches only
231
+ isComplete: session.isComplete,
232
+ isError: session.isError && !!session.error?.trim(), // Only error if we have actual errors
233
+ error: session.error?.trim() || undefined,
234
+ hasMoreResults,
235
+ runtime: Date.now() - session.startTime,
236
+ stopReason: session.stopReason,
237
+ wasIncomplete: session.wasIncomplete
238
+ };
239
+ }
240
+ /**
241
+ * Terminate a search session (like force_terminate)
242
+ */
243
+ terminateSearch(sessionId) {
244
+ const session = this.sessions.get(sessionId);
245
+ if (!session) {
246
+ return false;
247
+ }
248
+ if (!session.process.killed) {
249
+ session.process.kill('SIGTERM');
250
+ }
251
+ // Don't delete session immediately - let user read final results
252
+ // It will be cleaned up by cleanup process
253
+ return true;
254
+ }
255
+ /**
256
+ * Get list of active search sessions (like list_sessions)
257
+ */
258
+ listSearchSessions() {
259
+ return Array.from(this.sessions.values()).map(session => ({
260
+ id: session.id,
261
+ searchType: session.options.searchType,
262
+ pattern: session.options.pattern,
263
+ isComplete: session.isComplete,
264
+ isError: session.isError,
265
+ runtime: Date.now() - session.startTime,
266
+ totalResults: session.totalMatches + session.totalContextLines
267
+ }));
268
+ }
269
+ /**
270
+ * Search Excel files for content matches
271
+ * Called during content search to include Excel files alongside text files
272
+ * Searches ALL sheets in each Excel file (row-wise for cross-column matching)
273
+ *
274
+ * TODO: Refactor - Extract Excel search logic to separate module (src/utils/search/excel-search.ts)
275
+ * and inject into SearchManager, similar to how file handlers are structured in src/utils/files/
276
+ * This would allow adding other file type searches (PDF, etc.) without bloating search-manager.ts
277
+ */
278
+ async searchExcelFiles(rootPath, pattern, ignoreCase, maxResults, filePattern, _literalSearch) {
279
+ const results = [];
280
+ // Office file search always uses literal matching to prevent ReDoS.
281
+ // Regex patterns are treated as literal strings — this is intentional.
282
+ const searchTerm = ignoreCase ? pattern.toLowerCase() : pattern;
283
+ // Find Excel files recursively
284
+ let excelFiles = await this.findExcelFiles(rootPath);
285
+ // Filter by filePattern if provided
286
+ if (filePattern) {
287
+ const patterns = filePattern.split('|').map(p => p.trim()).filter(Boolean);
288
+ excelFiles = excelFiles.filter(filePath => {
289
+ const fileName = path.basename(filePath);
290
+ return patterns.some(pat => {
291
+ // Support glob-like patterns
292
+ if (pat.includes('*')) {
293
+ // Escape all regex metacharacters first (preserving * for glob expansion),
294
+ // then convert the remaining * wildcards to .* for glob matching.
295
+ // Without this, patterns like report(2024).xlsx or [draft].xlsx would be
296
+ // misinterpreted as regex groups/character-classes.
297
+ const regexPat = pat
298
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape metacharacters except *
299
+ .replace(/\*/g, '.*'); // glob * → regex .*
300
+ return new RegExp(`^${regexPat}$`, 'i').test(fileName);
301
+ }
302
+ // Exact match (case-insensitive)
303
+ return fileName.toLowerCase() === pat.toLowerCase();
304
+ });
305
+ });
306
+ }
307
+ // Dynamically import ExcelJS to search all sheets
308
+ const ExcelJS = await import('exceljs');
309
+ for (const filePath of excelFiles) {
310
+ if (maxResults && results.length >= maxResults)
311
+ break;
312
+ try {
313
+ const workbook = new ExcelJS.default.Workbook();
314
+ await workbook.xlsx.readFile(filePath);
315
+ // Search ALL sheets in the workbook (row-wise for speed and cross-column matching)
316
+ for (const worksheet of workbook.worksheets) {
317
+ if (maxResults && results.length >= maxResults)
318
+ break;
319
+ const sheetName = worksheet.name;
320
+ // Iterate through rows (faster than cell-by-cell)
321
+ worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
322
+ if (maxResults && results.length >= maxResults)
323
+ return;
324
+ // Build a concatenated string of all cell values in the row
325
+ const rowValues = [];
326
+ row.eachCell({ includeEmpty: false }, (cell) => {
327
+ if (cell.value === null || cell.value === undefined)
328
+ return;
329
+ let cellStr;
330
+ if (typeof cell.value === 'object') {
331
+ if ('result' in cell.value) {
332
+ cellStr = String(cell.value.result ?? '');
333
+ }
334
+ else if ('richText' in cell.value) {
335
+ cellStr = cell.value.richText.map((rt) => rt.text).join('');
336
+ }
337
+ else if ('text' in cell.value) {
338
+ cellStr = String(cell.value.text);
339
+ }
340
+ else {
341
+ cellStr = String(cell.value);
342
+ }
343
+ }
344
+ else {
345
+ cellStr = String(cell.value);
346
+ }
347
+ if (cellStr.trim()) {
348
+ rowValues.push(cellStr);
349
+ }
350
+ });
351
+ // Join all cell values with space for cross-column matching
352
+ const rowText = rowValues.join(' ');
353
+ const textToSearch = ignoreCase ? rowText.toLowerCase() : rowText;
354
+ const matchIndex = textToSearch.indexOf(searchTerm);
355
+ if (matchIndex !== -1) {
356
+ const matchContext = this.getMatchContext(rowText, matchIndex, searchTerm.length);
357
+ results.push({
358
+ file: `${filePath}:${sheetName}!Row${rowNumber}`,
359
+ line: rowNumber,
360
+ match: matchContext,
361
+ type: 'content'
362
+ });
363
+ }
364
+ });
365
+ }
366
+ }
367
+ catch (error) {
368
+ // Skip files that can't be read (permission issues, corrupted, etc.)
369
+ continue;
370
+ }
371
+ }
372
+ return results;
373
+ }
374
+ /**
375
+ * Find all Excel files in a directory recursively
376
+ */
377
+ async findExcelFiles(rootPath) {
378
+ const excelFiles = [];
379
+ async function walk(dir) {
380
+ try {
381
+ const entries = await fs.readdir(dir, { withFileTypes: true });
382
+ for (const entry of entries) {
383
+ const fullPath = path.join(dir, entry.name);
384
+ if (entry.isDirectory()) {
385
+ // Skip node_modules, .git, etc.
386
+ if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
387
+ await walk(fullPath);
388
+ }
389
+ }
390
+ else if (entry.isFile() && isExcelFile(entry.name)) {
391
+ excelFiles.push(fullPath);
392
+ }
393
+ }
394
+ }
395
+ catch {
396
+ // Skip directories we can't read
397
+ }
398
+ }
399
+ // Check if rootPath is a file or directory
400
+ try {
401
+ const stats = await fs.stat(rootPath);
402
+ if (stats.isFile() && isExcelFile(rootPath)) {
403
+ return [rootPath];
404
+ }
405
+ else if (stats.isDirectory()) {
406
+ await walk(rootPath);
407
+ }
408
+ }
409
+ catch {
410
+ // Path doesn't exist or can't be accessed
411
+ }
412
+ return excelFiles;
413
+ }
414
+ /**
415
+ * Determine if DOCX search should be included based on context
416
+ */
417
+ shouldIncludeDocxSearch(filePattern, rootPath) {
418
+ const docxExtensions = ['.docx'];
419
+ if (rootPath) {
420
+ const lowerPath = rootPath.toLowerCase();
421
+ if (docxExtensions.some(ext => lowerPath.endsWith(ext))) {
422
+ return true;
423
+ }
424
+ }
425
+ if (filePattern) {
426
+ const lowerPattern = filePattern.toLowerCase();
427
+ if (docxExtensions.some(ext => lowerPattern.includes(`*${ext}`) || lowerPattern.endsWith(ext))) {
428
+ return true;
429
+ }
430
+ }
431
+ return false;
432
+ }
433
+ /**
434
+ * Search DOCX files for content matches
435
+ * Extracts <w:t> text from document.xml and searches it
436
+ */
437
+ async searchDocxFiles(rootPath, pattern, ignoreCase, maxResults, filePattern, _literalSearch) {
438
+ const results = [];
439
+ // Office file search always uses literal matching to prevent ReDoS.
440
+ // Regex patterns are treated as literal strings — this is intentional.
441
+ const searchTerm = ignoreCase ? pattern.toLowerCase() : pattern;
442
+ let docxFiles = await this.findDocxFiles(rootPath);
443
+ if (filePattern) {
444
+ const patterns = filePattern.split('|').map(p => p.trim()).filter(Boolean);
445
+ docxFiles = docxFiles.filter(filePath => {
446
+ const fileName = path.basename(filePath);
447
+ return patterns.some(pat => {
448
+ if (pat.includes('*')) {
449
+ const regexPat = pat
450
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape metacharacters except *
451
+ .replace(/\*/g, '.*'); // glob * → regex .*
452
+ return new RegExp(`^${regexPat}$`, 'i').test(fileName);
453
+ }
454
+ return fileName.toLowerCase() === pat.toLowerCase();
455
+ });
456
+ });
457
+ }
458
+ const PizZip = docxFiles.length ? (await import('pizzip')).default : null;
459
+ for (const filePath of docxFiles) {
460
+ if (maxResults && results.length >= maxResults)
461
+ break;
462
+ if (!PizZip)
463
+ break;
464
+ try {
465
+ const buf = await fs.readFile(filePath);
466
+ const zip = new PizZip(buf);
467
+ // Search all XML parts that can contain text
468
+ const xmlParts = ['word/document.xml', 'word/header1.xml', 'word/header2.xml',
469
+ 'word/header3.xml', 'word/footer1.xml', 'word/footer2.xml', 'word/footer3.xml'];
470
+ for (const xmlPath of xmlParts) {
471
+ if (maxResults && results.length >= maxResults)
472
+ break;
473
+ const file = zip.file(xmlPath);
474
+ if (!file)
475
+ continue;
476
+ const xml = file.asText();
477
+ // Extract all <w:t> text with position tracking
478
+ const wtRe = /<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>/g;
479
+ let m;
480
+ let lineNum = 0;
481
+ while ((m = wtRe.exec(xml)) !== null) {
482
+ if (maxResults && results.length >= maxResults)
483
+ break;
484
+ const text = m[1];
485
+ if (!text || !text.trim())
486
+ continue;
487
+ lineNum++;
488
+ const textToSearch = ignoreCase ? text.toLowerCase() : text;
489
+ const matchIndex = textToSearch.indexOf(searchTerm);
490
+ if (matchIndex !== -1) {
491
+ const matchContext = this.getMatchContext(text, matchIndex, searchTerm.length);
492
+ const partName = xmlPath === 'word/document.xml' ? '' : `:${xmlPath.replace('word/', '')}`;
493
+ results.push({
494
+ file: `${filePath}${partName}`,
495
+ line: lineNum,
496
+ match: matchContext,
497
+ type: 'content'
498
+ });
499
+ }
500
+ }
501
+ }
502
+ }
503
+ catch {
504
+ continue;
505
+ }
506
+ }
507
+ return results;
508
+ }
509
+ /**
510
+ * Find all DOCX files in a directory recursively
511
+ */
512
+ async findDocxFiles(rootPath) {
513
+ const docxFiles = [];
514
+ const isDocx = (name) => name.toLowerCase().endsWith('.docx');
515
+ async function walk(dir) {
516
+ try {
517
+ const entries = await fs.readdir(dir, { withFileTypes: true });
518
+ for (const entry of entries) {
519
+ const fullPath = path.join(dir, entry.name);
520
+ if (entry.isDirectory()) {
521
+ if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
522
+ await walk(fullPath);
523
+ }
524
+ }
525
+ else if (entry.isFile() && isDocx(entry.name)) {
526
+ docxFiles.push(fullPath);
527
+ }
528
+ }
529
+ }
530
+ catch { /* skip */ }
531
+ }
532
+ try {
533
+ const stats = await fs.stat(rootPath);
534
+ if (stats.isFile() && isDocx(rootPath)) {
535
+ return [rootPath];
536
+ }
537
+ else if (stats.isDirectory()) {
538
+ await walk(rootPath);
539
+ }
540
+ }
541
+ catch { /* skip */ }
542
+ return docxFiles;
543
+ }
544
+ /**
545
+ * Extract context around a match for display (show surrounding text)
546
+ */
547
+ getMatchContext(text, matchStart, matchLength) {
548
+ const contextChars = 50; // chars before and after match
549
+ const start = Math.max(0, matchStart - contextChars);
550
+ const end = Math.min(text.length, matchStart + matchLength + contextChars);
551
+ let context = text.substring(start, end);
552
+ // Add ellipsis if truncated
553
+ if (start > 0)
554
+ context = '...' + context;
555
+ if (end < text.length)
556
+ context = context + '...';
557
+ return context;
558
+ }
559
+ /**
560
+ * Clean up completed sessions older than specified time
561
+ * Called automatically by cleanup interval
562
+ */
563
+ cleanupSessions(maxAge = 5 * 60 * 1000) {
564
+ const cutoffTime = Date.now() - maxAge;
565
+ for (const [sessionId, session] of this.sessions) {
566
+ if (session.isComplete && session.lastReadTime < cutoffTime) {
567
+ this.sessions.delete(sessionId);
568
+ }
569
+ }
570
+ }
571
+ /**
572
+ * Get total number of active sessions (excluding completed ones)
573
+ */
574
+ getActiveSessionCount() {
575
+ return Array.from(this.sessions.values()).filter(session => !session.isComplete).length;
576
+ }
577
+ /**
578
+ * Detect if pattern looks like an exact filename
579
+ * (has file extension and no glob wildcards)
580
+ */
581
+ isExactFilename(pattern) {
582
+ return /\.[a-zA-Z0-9]+$/.test(pattern) &&
583
+ !this.isGlobPattern(pattern);
584
+ }
585
+ /**
586
+ * Detect if pattern contains glob wildcards
587
+ */
588
+ isGlobPattern(pattern) {
589
+ return pattern.includes('*') ||
590
+ pattern.includes('?') ||
591
+ pattern.includes('[') ||
592
+ pattern.includes('{') ||
593
+ pattern.includes(']') ||
594
+ pattern.includes('}');
595
+ }
596
+ /**
597
+ * Determine if Excel search should be included based on context
598
+ * Only searches Excel files when:
599
+ * - filePattern explicitly targets Excel files (*.xlsx, *.xls, *.xlsm, *.xlsb)
600
+ * - or the rootPath itself is an Excel file
601
+ */
602
+ shouldIncludeExcelSearch(filePattern, rootPath) {
603
+ const excelExtensions = ['.xlsx', '.xls', '.xlsm', '.xlsb'];
604
+ // Check if rootPath is an Excel file
605
+ if (rootPath) {
606
+ const lowerPath = rootPath.toLowerCase();
607
+ if (excelExtensions.some(ext => lowerPath.endsWith(ext))) {
608
+ return true;
609
+ }
610
+ }
611
+ // Check if filePattern targets Excel files
612
+ if (filePattern) {
613
+ const lowerPattern = filePattern.toLowerCase();
614
+ // Check for patterns like *.xlsx, *.xls, or explicit Excel extensions
615
+ if (excelExtensions.some(ext => lowerPattern.includes(`*${ext}`) ||
616
+ lowerPattern.endsWith(ext))) {
617
+ return true;
618
+ }
619
+ }
620
+ return false;
621
+ }
622
+ buildRipgrepArgs(options) {
623
+ const args = [];
624
+ if (options.searchType === 'content') {
625
+ // Content search mode
626
+ args.push('--json', '--line-number');
627
+ // Add literal search support for content searches
628
+ if (options.literalSearch) {
629
+ args.push('-F'); // Fixed string matching (literal)
630
+ }
631
+ if (options.contextLines && options.contextLines > 0) {
632
+ args.push('-C', options.contextLines.toString());
633
+ }
634
+ }
635
+ else {
636
+ // File search mode
637
+ args.push('--files');
638
+ }
639
+ // Case-insensitive: content searches use -i flag, file searches use --iglob
640
+ if (options.searchType === 'content' && options.ignoreCase !== false) {
641
+ args.push('-i');
642
+ }
643
+ if (options.includeHidden) {
644
+ args.push('--hidden');
645
+ }
646
+ if (options.maxResults && options.maxResults > 0) {
647
+ args.push('-m', options.maxResults.toString());
648
+ }
649
+ // File pattern filtering (for file type restrictions like *.js, *.d.ts)
650
+ if (options.filePattern) {
651
+ const patterns = options.filePattern
652
+ .split('|')
653
+ .map(p => p.trim())
654
+ .filter(Boolean);
655
+ for (const p of patterns) {
656
+ if (options.searchType === 'content') {
657
+ args.push('-g', p);
658
+ }
659
+ else {
660
+ // For file search: use --iglob for case-insensitive or --glob for case-sensitive
661
+ if (options.ignoreCase !== false) {
662
+ args.push('--iglob', p);
663
+ }
664
+ else {
665
+ args.push('--glob', p);
666
+ }
667
+ }
668
+ }
669
+ }
670
+ // Handle the main search pattern
671
+ if (options.searchType === 'files') {
672
+ // For file search: determine how to treat the pattern
673
+ const globFlag = options.ignoreCase !== false ? '--iglob' : '--glob';
674
+ if (this.isExactFilename(options.pattern)) {
675
+ // Exact filename: use appropriate glob flag with the exact pattern
676
+ args.push(globFlag, options.pattern);
677
+ }
678
+ else if (this.isGlobPattern(options.pattern)) {
679
+ // Already a glob pattern: use appropriate glob flag as-is
680
+ args.push(globFlag, options.pattern);
681
+ }
682
+ else {
683
+ // Substring/fuzzy search: wrap with wildcards
684
+ args.push(globFlag, `*${options.pattern}*`);
685
+ }
686
+ // Add the root path for file mode
687
+ args.push(options.rootPath);
688
+ }
689
+ else {
690
+ // Content search: terminate options before the pattern to prevent
691
+ // patterns starting with '-' being interpreted as flags
692
+ args.push('--', options.pattern, options.rootPath);
693
+ }
694
+ return args;
695
+ }
696
+ setupProcessHandlers(session) {
697
+ const { process } = session;
698
+ process.stdout?.setEncoding('utf8');
699
+ process.stdout?.on('data', (data) => {
700
+ if (session.stopReason)
701
+ return;
702
+ session.buffer += data;
703
+ this.processBufferedOutput(session);
704
+ if (session.buffer.length > 262144)
705
+ this.stopLimited(session, 'output_limit');
706
+ });
707
+ process.stderr?.on('data', (data) => {
708
+ const errorText = data.toString();
709
+ // Store error text for potential user display, but don't capture individual errors
710
+ // We'll capture incomplete search status in the completion event instead
711
+ session.error = ((session.error || '') + errorText).slice(0, 8192);
712
+ // Filter meaningful errors
713
+ const filteredErrors = errorText
714
+ .split('\n')
715
+ .filter(line => {
716
+ const trimmed = line.trim();
717
+ // Skip empty lines and lines with just symbols/numbers/colons
718
+ if (!trimmed || trimmed.match(/^[\)\(\s\d:]*$/))
719
+ return false;
720
+ // Skip all ripgrep system errors that start with "rg:"
721
+ if (trimmed.startsWith('rg:'))
722
+ return false;
723
+ return true;
724
+ });
725
+ // Only add to session.error if there are actual meaningful errors after filtering
726
+ if (filteredErrors.length > 0) {
727
+ const meaningfulErrors = filteredErrors.join('\n').trim();
728
+ if (meaningfulErrors) {
729
+ session.error = ((session.error || '') + meaningfulErrors + '\n').slice(0, 8192);
730
+ capture('search_session_error', {
731
+ sessionId: session.id,
732
+ error: meaningfulErrors.substring(0, 200)
733
+ });
734
+ }
735
+ }
736
+ });
737
+ process.on('close', (code) => {
738
+ // Process any remaining buffer content
739
+ if (session.buffer.trim()) {
740
+ this.processBufferedOutput(session, true);
741
+ }
742
+ session.isComplete = true;
743
+ // Track if search was incomplete due to access issues
744
+ // Ripgrep exit code 2 means "some files couldn't be searched"
745
+ if (code === 2) {
746
+ session.wasIncomplete = true;
747
+ if (session.totalMatches === 0) {
748
+ session.isError = true;
749
+ session.error ||= 'ripgrep search failed';
750
+ }
751
+ }
752
+ // Only treat as error if:
753
+ // 1. Unexpected exit code (not 0, 1, or 2) AND
754
+ // 2. We have meaningful errors after filtering AND
755
+ // 3. We found no results at all
756
+ if (code !== 0 && code !== 1 && code !== 2) {
757
+ // Codes 0=success, 1=no matches, 2=some files couldn't be searched
758
+ if (session.error?.trim() && session.totalMatches === 0) {
759
+ session.isError = true;
760
+ session.error = session.error || `ripgrep exited with code ${code}`;
761
+ }
762
+ }
763
+ // If we have results, don't mark as error even if there were permission issues
764
+ if (session.totalMatches > 0) {
765
+ session.isError = false;
766
+ }
767
+ capture('search_session_completed', {
768
+ sessionId: session.id,
769
+ exitCode: code,
770
+ totalResults: session.totalMatches + session.totalContextLines,
771
+ totalMatches: session.totalMatches,
772
+ runtime: Date.now() - session.startTime,
773
+ stopReason: session.stopReason,
774
+ wasIncomplete: session.wasIncomplete || false // NEW: Track incomplete searches
775
+ });
776
+ // Rely on cleanupSessions(maxAge) only; no per-session timer
777
+ });
778
+ process.on('error', (error) => {
779
+ session.isComplete = true;
780
+ session.isError = true;
781
+ session.error = `Process error: ${error.message}`;
782
+ // Rely on cleanupSessions(maxAge) only; no per-session timer
783
+ });
784
+ }
785
+ stopLimited(session, reason) {
786
+ if (!session.stopReason)
787
+ session.stopReason = reason;
788
+ session.wasIncomplete = true;
789
+ session.buffer = '';
790
+ if (!session.process.killed)
791
+ session.process.kill('SIGTERM');
792
+ }
793
+ addResult(session, result) {
794
+ if (session.stopReason)
795
+ return false;
796
+ const match = !(result.type === 'content' && result.isContext);
797
+ if (match && session.totalMatches >= (session.options.maxResults ?? 1000)) {
798
+ this.stopLimited(session, 'limit');
799
+ return false;
800
+ }
801
+ if (result.match)
802
+ result.match = result.match.slice(0, 2000);
803
+ const bytes = Buffer.byteLength(JSON.stringify(result));
804
+ if (session.bytesStored + bytes > 2 * 1024 * 1024 || session.results.length >= 30000) {
805
+ this.stopLimited(session, 'output_limit');
806
+ return false;
807
+ }
808
+ session.bytesStored += bytes;
809
+ session.results.push(result);
810
+ if (match)
811
+ session.totalMatches++;
812
+ else
813
+ session.totalContextLines++;
814
+ if (match && session.totalMatches >= (session.options.maxResults ?? 1000))
815
+ this.stopLimited(session, 'limit');
816
+ return true;
817
+ }
818
+ processBufferedOutput(session, isFinal = false) {
819
+ const lines = session.buffer.split('\n');
820
+ // Keep the last incomplete line in the buffer unless this is final processing
821
+ if (!isFinal) {
822
+ session.buffer = lines.pop() || '';
823
+ }
824
+ else {
825
+ session.buffer = '';
826
+ }
827
+ for (const line of lines) {
828
+ if (session.stopReason)
829
+ break;
830
+ if (line.length > 262144) {
831
+ this.stopLimited(session, 'output_limit');
832
+ break;
833
+ }
834
+ if (!line.trim())
835
+ continue;
836
+ const result = this.parseLine(line, session.options.searchType);
837
+ if (result) {
838
+ if (!this.addResult(session, result))
839
+ break;
840
+ // Early termination for exact filename matches (if enabled)
841
+ if (session.options.earlyTermination !== false && // Default to true
842
+ session.options.searchType === 'files' &&
843
+ this.isExactFilename(session.options.pattern)) {
844
+ const pat = path.normalize(session.options.pattern);
845
+ const filePath = path.normalize(result.file);
846
+ const ignoreCase = session.options.ignoreCase !== false;
847
+ const ends = ignoreCase
848
+ ? filePath.toLowerCase().endsWith(pat.toLowerCase())
849
+ : filePath.endsWith(pat);
850
+ if (ends) {
851
+ // Found exact match, terminate search early
852
+ setTimeout(() => {
853
+ if (!session.process.killed) {
854
+ session.process.kill('SIGTERM');
855
+ }
856
+ }, 100); // Small delay to allow any remaining results
857
+ break;
858
+ }
859
+ }
860
+ }
861
+ }
862
+ }
863
+ parseLine(line, searchType) {
864
+ if (searchType === 'content') {
865
+ // Parse JSON output from content search
866
+ try {
867
+ const parsed = JSON.parse(line);
868
+ if (parsed.type === 'match') {
869
+ // Handle multiple submatches per line - return first submatch
870
+ const submatch = parsed.data?.submatches?.[0];
871
+ return {
872
+ file: parsed.data.path.text,
873
+ line: parsed.data.line_number,
874
+ match: submatch?.match?.text || parsed.data.lines.text,
875
+ type: 'content',
876
+ lineText: capLine(parsed.data.lines?.text),
877
+ };
878
+ }
879
+ if (parsed.type === 'context') {
880
+ return {
881
+ file: parsed.data.path.text,
882
+ line: parsed.data.line_number,
883
+ match: parsed.data.lines.text.trim(),
884
+ type: 'content',
885
+ lineText: capLine(parsed.data.lines?.text),
886
+ isContext: true,
887
+ };
888
+ }
889
+ // Handle summary to reconcile totals
890
+ if (parsed.type === 'summary') {
891
+ // Optional: could reconcile totalMatches with parsed.data.stats?.matchedLines
892
+ return null;
893
+ }
894
+ return null;
895
+ }
896
+ catch (error) {
897
+ // Skip invalid JSON lines
898
+ return null;
899
+ }
900
+ }
901
+ else {
902
+ // File search - each line is a file path
903
+ return {
904
+ file: line.trim(),
905
+ type: 'file'
906
+ };
907
+ }
908
+ }
909
+ }
910
+ // Global search manager instance
911
+ export const searchManager = new SearchManager();
912
+ // Cleanup management - run on fixed schedule
913
+ let cleanupInterval = null;
914
+ /**
915
+ * Start cleanup interval - now runs on fixed schedule
916
+ */
917
+ function startCleanupIfNeeded() {
918
+ if (!cleanupInterval) {
919
+ cleanupInterval = setInterval(() => {
920
+ searchManager.cleanupSessions();
921
+ }, 5 * 60 * 1000);
922
+ cleanupInterval.unref();
923
+ // Also check immediately after a short delay (let search process finish)
924
+ setTimeout(() => {
925
+ searchManager.cleanupSessions();
926
+ }, 1000).unref();
927
+ }
928
+ }
929
+ //# sourceMappingURL=search-manager.js.map