@caupulican/pi-adaptative 0.81.37 → 0.81.39

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 (451) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  28. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  29. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  30. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
  32. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  33. package/dist/cli/args.d.ts +3 -0
  34. package/dist/cli/args.d.ts.map +1 -1
  35. package/dist/cli/args.js +15 -0
  36. package/dist/cli/args.js.map +1 -1
  37. package/dist/core/agent-paths.d.ts +49 -0
  38. package/dist/core/agent-paths.d.ts.map +1 -0
  39. package/dist/core/agent-paths.js +107 -0
  40. package/dist/core/agent-paths.js.map +1 -0
  41. package/dist/core/agent-session-services.d.ts.map +1 -1
  42. package/dist/core/agent-session-services.js +3 -3
  43. package/dist/core/agent-session-services.js.map +1 -1
  44. package/dist/core/agent-session.d.ts +234 -17
  45. package/dist/core/agent-session.d.ts.map +1 -1
  46. package/dist/core/agent-session.js +484 -62
  47. package/dist/core/agent-session.js.map +1 -1
  48. package/dist/core/autonomy/contracts.d.ts +9 -0
  49. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  50. package/dist/core/autonomy/contracts.js.map +1 -1
  51. package/dist/core/autonomy/lane-tracker.d.ts +10 -1
  52. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  53. package/dist/core/autonomy/lane-tracker.js +5 -1
  54. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  55. package/dist/core/background-lane-controller.d.ts +122 -6
  56. package/dist/core/background-lane-controller.d.ts.map +1 -1
  57. package/dist/core/background-lane-controller.js +447 -90
  58. package/dist/core/background-lane-controller.js.map +1 -1
  59. package/dist/core/bash-execution-controller.d.ts +4 -0
  60. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  61. package/dist/core/bash-execution-controller.js +7 -1
  62. package/dist/core/bash-execution-controller.js.map +1 -1
  63. package/dist/core/compaction-support.d.ts +13 -3
  64. package/dist/core/compaction-support.d.ts.map +1 -1
  65. package/dist/core/compaction-support.js +43 -7
  66. package/dist/core/compaction-support.js.map +1 -1
  67. package/dist/core/context/context-audit.d.ts +33 -1
  68. package/dist/core/context/context-audit.d.ts.map +1 -1
  69. package/dist/core/context/context-audit.js +31 -5
  70. package/dist/core/context/context-audit.js.map +1 -1
  71. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  72. package/dist/core/context/sqlite-runtime-index.js +13 -7
  73. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  74. package/dist/core/context-gc.d.ts.map +1 -1
  75. package/dist/core/context-gc.js +16 -1
  76. package/dist/core/context-gc.js.map +1 -1
  77. package/dist/core/context-pipeline.d.ts +26 -4
  78. package/dist/core/context-pipeline.d.ts.map +1 -1
  79. package/dist/core/context-pipeline.js +137 -14
  80. package/dist/core/context-pipeline.js.map +1 -1
  81. package/dist/core/cost-guard.d.ts +19 -3
  82. package/dist/core/cost-guard.d.ts.map +1 -1
  83. package/dist/core/cost-guard.js +18 -3
  84. package/dist/core/cost-guard.js.map +1 -1
  85. package/dist/core/delegation/session-worker-result.d.ts +34 -4
  86. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  87. package/dist/core/delegation/session-worker-result.js +64 -4
  88. package/dist/core/delegation/session-worker-result.js.map +1 -1
  89. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-actions.js +1 -1
  91. package/dist/core/delegation/worker-actions.js.map +1 -1
  92. package/dist/core/delegation/worker-result.d.ts +42 -1
  93. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  94. package/dist/core/delegation/worker-result.js +68 -0
  95. package/dist/core/delegation/worker-result.js.map +1 -1
  96. package/dist/core/extensions/loader.d.ts.map +1 -1
  97. package/dist/core/extensions/loader.js +23 -7
  98. package/dist/core/extensions/loader.js.map +1 -1
  99. package/dist/core/extensions/runner.d.ts.map +1 -1
  100. package/dist/core/extensions/runner.js +1 -0
  101. package/dist/core/extensions/runner.js.map +1 -1
  102. package/dist/core/extensions/types.d.ts +51 -0
  103. package/dist/core/extensions/types.d.ts.map +1 -1
  104. package/dist/core/extensions/types.js.map +1 -1
  105. package/dist/core/goal-loop-controller.d.ts +17 -1
  106. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  107. package/dist/core/goal-loop-controller.js +79 -11
  108. package/dist/core/goal-loop-controller.js.map +1 -1
  109. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  110. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  111. package/dist/core/goals/goal-continuation-controller.js +77 -0
  112. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  113. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  114. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  115. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  116. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  117. package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
  118. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  119. package/dist/core/goals/goal-continuation-prompt.js +51 -10
  120. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  121. package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
  122. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  123. package/dist/core/goals/goal-runtime-snapshot.js +87 -4
  124. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +89 -1
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +71 -5
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +56 -2
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +111 -5
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/goals/session-goal-state.d.ts +11 -2
  134. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  135. package/dist/core/goals/session-goal-state.js +32 -17
  136. package/dist/core/goals/session-goal-state.js.map +1 -1
  137. package/dist/core/keybindings.d.ts +10 -0
  138. package/dist/core/keybindings.d.ts.map +1 -1
  139. package/dist/core/keybindings.js +10 -2
  140. package/dist/core/keybindings.js.map +1 -1
  141. package/dist/core/learning/observation-store.d.ts +12 -3
  142. package/dist/core/learning/observation-store.d.ts.map +1 -1
  143. package/dist/core/learning/observation-store.js +30 -15
  144. package/dist/core/learning/observation-store.js.map +1 -1
  145. package/dist/core/learning/skill-curator.d.ts +5 -1
  146. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  147. package/dist/core/learning/skill-curator.js +21 -19
  148. package/dist/core/learning/skill-curator.js.map +1 -1
  149. package/dist/core/local-runtime-controller.d.ts +65 -3
  150. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  151. package/dist/core/local-runtime-controller.js +186 -26
  152. package/dist/core/local-runtime-controller.js.map +1 -1
  153. package/dist/core/memory/providers/file-store.d.ts +1 -1
  154. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  155. package/dist/core/memory/providers/file-store.js +6 -6
  156. package/dist/core/memory/providers/file-store.js.map +1 -1
  157. package/dist/core/model-capability.d.ts +34 -0
  158. package/dist/core/model-capability.d.ts.map +1 -1
  159. package/dist/core/model-capability.js +42 -1
  160. package/dist/core/model-capability.js.map +1 -1
  161. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  162. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  163. package/dist/core/model-router/tool-escalation.js +23 -1
  164. package/dist/core/model-router/tool-escalation.js.map +1 -1
  165. package/dist/core/model-router-controller.d.ts +34 -7
  166. package/dist/core/model-router-controller.d.ts.map +1 -1
  167. package/dist/core/model-router-controller.js +95 -16
  168. package/dist/core/model-router-controller.js.map +1 -1
  169. package/dist/core/models/adaptation-store.d.ts +7 -0
  170. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  171. package/dist/core/models/adaptation-store.js +47 -11
  172. package/dist/core/models/adaptation-store.js.map +1 -1
  173. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  174. package/dist/core/models/default-model-suggestions.js +17 -0
  175. package/dist/core/models/default-model-suggestions.js.map +1 -1
  176. package/dist/core/models/fitness-store.d.ts +3 -0
  177. package/dist/core/models/fitness-store.d.ts.map +1 -1
  178. package/dist/core/models/fitness-store.js +11 -2
  179. package/dist/core/models/fitness-store.js.map +1 -1
  180. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  181. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  182. package/dist/core/models/llamacpp-runtime.js +475 -0
  183. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  184. package/dist/core/models/local-registration.d.ts +40 -0
  185. package/dist/core/models/local-registration.d.ts.map +1 -1
  186. package/dist/core/models/local-registration.js +94 -5
  187. package/dist/core/models/local-registration.js.map +1 -1
  188. package/dist/core/models/local-runtime.d.ts.map +1 -1
  189. package/dist/core/models/local-runtime.js +9 -7
  190. package/dist/core/models/local-runtime.js.map +1 -1
  191. package/dist/core/models/model-ref.d.ts +7 -0
  192. package/dist/core/models/model-ref.d.ts.map +1 -1
  193. package/dist/core/models/model-ref.js +26 -0
  194. package/dist/core/models/model-ref.js.map +1 -1
  195. package/dist/core/models/needle-runtime.d.ts +257 -0
  196. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  197. package/dist/core/models/needle-runtime.js +519 -0
  198. package/dist/core/models/needle-runtime.js.map +1 -0
  199. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  200. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  201. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  202. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  203. package/dist/core/package-manager.d.ts.map +1 -1
  204. package/dist/core/package-manager.js +11 -10
  205. package/dist/core/package-manager.js.map +1 -1
  206. package/dist/core/process-matrix/codes.d.ts +72 -0
  207. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  208. package/dist/core/process-matrix/codes.js +15 -0
  209. package/dist/core/process-matrix/codes.js.map +1 -0
  210. package/dist/core/process-matrix/runtime.d.ts +63 -0
  211. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  212. package/dist/core/process-matrix/runtime.js +310 -0
  213. package/dist/core/process-matrix/runtime.js.map +1 -0
  214. package/dist/core/process-matrix/store.d.ts +22 -0
  215. package/dist/core/process-matrix/store.d.ts.map +1 -0
  216. package/dist/core/process-matrix/store.js +80 -0
  217. package/dist/core/process-matrix/store.js.map +1 -0
  218. package/dist/core/process-matrix/supervisor.d.ts +72 -0
  219. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  220. package/dist/core/process-matrix/supervisor.js +130 -0
  221. package/dist/core/process-matrix/supervisor.js.map +1 -0
  222. package/dist/core/profile-registry.d.ts +7 -0
  223. package/dist/core/profile-registry.d.ts.map +1 -1
  224. package/dist/core/profile-registry.js +20 -0
  225. package/dist/core/profile-registry.js.map +1 -1
  226. package/dist/core/python-runtime.d.ts.map +1 -1
  227. package/dist/core/python-runtime.js +3 -3
  228. package/dist/core/python-runtime.js.map +1 -1
  229. package/dist/core/reflection-controller.d.ts +29 -5
  230. package/dist/core/reflection-controller.d.ts.map +1 -1
  231. package/dist/core/reflection-controller.js +215 -126
  232. package/dist/core/reflection-controller.js.map +1 -1
  233. package/dist/core/reload-blockers.d.ts +36 -0
  234. package/dist/core/reload-blockers.d.ts.map +1 -1
  235. package/dist/core/reload-blockers.js +44 -0
  236. package/dist/core/reload-blockers.js.map +1 -1
  237. package/dist/core/resource-loader.d.ts.map +1 -1
  238. package/dist/core/resource-loader.js +8 -7
  239. package/dist/core/resource-loader.js.map +1 -1
  240. package/dist/core/runtime-builder.d.ts +58 -5
  241. package/dist/core/runtime-builder.d.ts.map +1 -1
  242. package/dist/core/runtime-builder.js +209 -25
  243. package/dist/core/runtime-builder.js.map +1 -1
  244. package/dist/core/scout-controller.d.ts +6 -0
  245. package/dist/core/scout-controller.d.ts.map +1 -1
  246. package/dist/core/scout-controller.js +66 -52
  247. package/dist/core/scout-controller.js.map +1 -1
  248. package/dist/core/sdk.d.ts.map +1 -1
  249. package/dist/core/sdk.js +3 -3
  250. package/dist/core/sdk.js.map +1 -1
  251. package/dist/core/session-role.d.ts +31 -0
  252. package/dist/core/session-role.d.ts.map +1 -0
  253. package/dist/core/session-role.js +52 -0
  254. package/dist/core/session-role.js.map +1 -0
  255. package/dist/core/settings-manager.d.ts +42 -3
  256. package/dist/core/settings-manager.d.ts.map +1 -1
  257. package/dist/core/settings-manager.js +94 -60
  258. package/dist/core/settings-manager.js.map +1 -1
  259. package/dist/core/system-prompt-builder.d.ts +12 -0
  260. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  261. package/dist/core/system-prompt-builder.js +6 -0
  262. package/dist/core/system-prompt-builder.js.map +1 -1
  263. package/dist/core/system-prompt.d.ts +14 -1
  264. package/dist/core/system-prompt.d.ts.map +1 -1
  265. package/dist/core/system-prompt.js +20 -3
  266. package/dist/core/system-prompt.js.map +1 -1
  267. package/dist/core/tasks/session-task-state.d.ts +11 -2
  268. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  269. package/dist/core/tasks/session-task-state.js +27 -11
  270. package/dist/core/tasks/session-task-state.js.map +1 -1
  271. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  272. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  273. package/dist/core/tasks/task-contract-monitor.js +56 -0
  274. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  275. package/dist/core/tasks/task-state.d.ts +8 -0
  276. package/dist/core/tasks/task-state.d.ts.map +1 -1
  277. package/dist/core/tasks/task-state.js +28 -1
  278. package/dist/core/tasks/task-state.js.map +1 -1
  279. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  280. package/dist/core/tool-gate-controller.js +5 -0
  281. package/dist/core/tool-gate-controller.js.map +1 -1
  282. package/dist/core/tool-recovery-log-records.d.ts +7 -0
  283. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  284. package/dist/core/tool-recovery-log-records.js +14 -6
  285. package/dist/core/tool-recovery-log-records.js.map +1 -1
  286. package/dist/core/tool-selection/promotion.d.ts +54 -0
  287. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  288. package/dist/core/tool-selection/promotion.js +81 -0
  289. package/dist/core/tool-selection/promotion.js.map +1 -0
  290. package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
  291. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  292. package/dist/core/tool-selection/tool-performance-store.js +87 -3
  293. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  294. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  295. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  296. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  297. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  298. package/dist/core/tools/bash.d.ts +18 -0
  299. package/dist/core/tools/bash.d.ts.map +1 -1
  300. package/dist/core/tools/bash.js +97 -18
  301. package/dist/core/tools/bash.js.map +1 -1
  302. package/dist/core/tools/delegate-status.d.ts +14 -0
  303. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  304. package/dist/core/tools/delegate-status.js +82 -7
  305. package/dist/core/tools/delegate-status.js.map +1 -1
  306. package/dist/core/tools/delegate.d.ts.map +1 -1
  307. package/dist/core/tools/delegate.js +25 -8
  308. package/dist/core/tools/delegate.js.map +1 -1
  309. package/dist/core/tools/find.d.ts.map +1 -1
  310. package/dist/core/tools/find.js +52 -44
  311. package/dist/core/tools/find.js.map +1 -1
  312. package/dist/core/tools/goal.d.ts +94 -3
  313. package/dist/core/tools/goal.d.ts.map +1 -1
  314. package/dist/core/tools/goal.js +165 -15
  315. package/dist/core/tools/goal.js.map +1 -1
  316. package/dist/core/tools/grep.d.ts.map +1 -1
  317. package/dist/core/tools/grep.js +5 -4
  318. package/dist/core/tools/grep.js.map +1 -1
  319. package/dist/core/tools/model-fitness.d.ts +7 -0
  320. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  321. package/dist/core/tools/model-fitness.js +2 -2
  322. package/dist/core/tools/model-fitness.js.map +1 -1
  323. package/dist/core/tools/render-utils.d.ts.map +1 -1
  324. package/dist/core/tools/render-utils.js +1 -1
  325. package/dist/core/tools/render-utils.js.map +1 -1
  326. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  327. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  328. package/dist/core/tools/shell-contract-router.js +69 -13
  329. package/dist/core/tools/shell-contract-router.js.map +1 -1
  330. package/dist/core/tools/shell-session.d.ts +89 -0
  331. package/dist/core/tools/shell-session.d.ts.map +1 -0
  332. package/dist/core/tools/shell-session.js +432 -0
  333. package/dist/core/tools/shell-session.js.map +1 -0
  334. package/dist/core/tools/task-steps.d.ts +4 -0
  335. package/dist/core/tools/task-steps.d.ts.map +1 -1
  336. package/dist/core/tools/task-steps.js +63 -8
  337. package/dist/core/tools/task-steps.js.map +1 -1
  338. package/dist/core/tools/tmux-dispatch.d.ts +86 -0
  339. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  340. package/dist/core/tools/tmux-dispatch.js +91 -0
  341. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  342. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  343. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  344. package/dist/core/tools/windows-shell-engine.js +153 -0
  345. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  346. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  347. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  348. package/dist/core/tools/windows-shell-state.js +59 -0
  349. package/dist/core/tools/windows-shell-state.js.map +1 -0
  350. package/dist/core/tools/worktree-sync.d.ts +24 -0
  351. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  352. package/dist/core/tools/worktree-sync.js +338 -0
  353. package/dist/core/tools/worktree-sync.js.map +1 -0
  354. package/dist/core/trust-manager.d.ts +4 -1
  355. package/dist/core/trust-manager.d.ts.map +1 -1
  356. package/dist/core/trust-manager.js +20 -2
  357. package/dist/core/trust-manager.js.map +1 -1
  358. package/dist/core/util/atomic-file.d.ts +55 -0
  359. package/dist/core/util/atomic-file.d.ts.map +1 -0
  360. package/dist/core/util/atomic-file.js +255 -0
  361. package/dist/core/util/atomic-file.js.map +1 -0
  362. package/dist/core/util/minimatch-cache.d.ts +33 -0
  363. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  364. package/dist/core/util/minimatch-cache.js +0 -0
  365. package/dist/core/util/minimatch-cache.js.map +1 -0
  366. package/dist/core/worktree-sync/codes.d.ts +227 -0
  367. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  368. package/dist/core/worktree-sync/codes.js +14 -0
  369. package/dist/core/worktree-sync/codes.js.map +1 -0
  370. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  371. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  372. package/dist/core/worktree-sync/git-engine.js +1191 -0
  373. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  374. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  375. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  376. package/dist/core/worktree-sync/lane-gate.js +360 -0
  377. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  378. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  379. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  380. package/dist/core/worktree-sync/runtime.js +96 -0
  381. package/dist/core/worktree-sync/runtime.js.map +1 -0
  382. package/dist/core/worktree-sync/store.d.ts +69 -0
  383. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  384. package/dist/core/worktree-sync/store.js +247 -0
  385. package/dist/core/worktree-sync/store.js.map +1 -0
  386. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  387. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  388. package/dist/core/worktree-sync/watcher.js +93 -0
  389. package/dist/core/worktree-sync/watcher.js.map +1 -0
  390. package/dist/main.d.ts.map +1 -1
  391. package/dist/main.js +94 -0
  392. package/dist/main.js.map +1 -1
  393. package/dist/migrations.d.ts +9 -0
  394. package/dist/migrations.d.ts.map +1 -1
  395. package/dist/migrations.js +38 -0
  396. package/dist/migrations.js.map +1 -1
  397. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  398. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  399. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  400. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  401. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  403. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  404. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  405. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  406. package/dist/modes/interactive/interactive-mode.js +4 -0
  407. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  408. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  409. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  410. package/dist/modes/interactive/local-model-commands.js +290 -3
  411. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  412. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  413. package/dist/modes/interactive/session-flow-commands.js +24 -4
  414. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  415. package/dist/utils/fs-watch.d.ts +11 -0
  416. package/dist/utils/fs-watch.d.ts.map +1 -1
  417. package/dist/utils/fs-watch.js +20 -2
  418. package/dist/utils/fs-watch.js.map +1 -1
  419. package/dist/utils/highlight-js-languages.d.ts +4 -0
  420. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  421. package/dist/utils/highlight-js-languages.js +573 -0
  422. package/dist/utils/highlight-js-languages.js.map +1 -0
  423. package/dist/utils/shell.d.ts +7 -1
  424. package/dist/utils/shell.d.ts.map +1 -1
  425. package/dist/utils/shell.js +39 -9
  426. package/dist/utils/shell.js.map +1 -1
  427. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  428. package/dist/utils/syntax-highlight.js +53 -5
  429. package/dist/utils/syntax-highlight.js.map +1 -1
  430. package/dist/utils/tools-manager.d.ts.map +1 -1
  431. package/dist/utils/tools-manager.js +112 -1
  432. package/dist/utils/tools-manager.js.map +1 -1
  433. package/docs/development.md +2 -0
  434. package/docs/packages.md +1 -1
  435. package/docs/process-matrix.md +120 -0
  436. package/docs/settings.md +5 -2
  437. package/docs/tmux-agent-manager.md +85 -2
  438. package/docs/windows.md +52 -3
  439. package/docs/work-directory.md +29 -0
  440. package/docs/worktree-sync.md +250 -0
  441. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  442. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  443. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  444. package/examples/extensions/sandbox/package-lock.json +2 -2
  445. package/examples/extensions/sandbox/package.json +1 -1
  446. package/examples/extensions/with-deps/package-lock.json +2 -2
  447. package/examples/extensions/with-deps/package.json +1 -1
  448. package/npm-shrinkwrap.json +12 -12
  449. package/package.json +10 -4
  450. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  451. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -13,7 +13,13 @@ export declare function trackDetachedChildPid(pid: number): void;
13
13
  export declare function untrackDetachedChildPid(pid: number): void;
14
14
  export declare function killTrackedDetachedChildren(): void;
15
15
  /**
16
- * Kill a process and all its children (cross-platform)
16
+ * Kill a process and all its children (cross-platform).
17
+ *
18
+ * Windows uses `spawnSync` (not `spawn`) deliberately: callers rely on this function returning
19
+ * only once the tree is actually gone (e.g. before removing a directory that was the killed
20
+ * process's cwd — a directory Windows keeps locked until every handle into it, including a
21
+ * live process's cwd handle, is released). A fire-and-forget async `taskkill` would return before
22
+ * termination completed, leaving a race where the directory is still locked.
17
23
  */
18
24
  export declare function killProcessTree(pid: number): void;
19
25
  //# sourceMappingURL=shell.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../src/utils/shell.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,YAAY,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,EAAE,CAAC;CACf;AAED,eAAO,MAAM,sBAAsB,8EAA8E,CAAC;AAIlH,wBAAgB,wBAAwB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,qBAAqB,CAE5G;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AA2DD,sHAAsH;AACtH,wBAAgB,cAAc,CAC7B,eAAe,CAAC,EAAE,MAAM,EACxB,SAAS,GAAE,qBAAkD,GAC3D,WAAW,CASb;AAED,wBAAgB,WAAW,IAAI,MAAM,CAAC,UAAU,CAY/C;AAQD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEzD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAKlD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAyBjD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawn, spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport type PlatformShellToolName = \"bash\" | \"powershell\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n}\n\nexport const POWERSHELL_UTF8_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\nconst POWERSHELL_ARGS = [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\"];\n\nexport function getPlatformShellToolName(platform: NodeJS.Platform = process.platform): PlatformShellToolName {\n\treturn platform === \"win32\" ? \"powershell\" : \"bash\";\n}\n\nexport function prefixPowerShellCommand(command: string): string {\n\treturn command.trimStart().startsWith(POWERSHELL_UTF8_PREFIX) ? command : `${POWERSHELL_UTF8_PREFIX}${command}`;\n}\n\nfunction findExecutableOnPath(executable: string): string | null {\n\tconst locator = process.platform === \"win32\" ? \"where\" : \"which\";\n\ttry {\n\t\tconst result = spawnSync(locator, [executable], {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 5_000,\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch && (process.platform !== \"win32\" || existsSync(firstMatch))) return firstMatch;\n\t\t}\n\t} catch {\n\t\t// Resolution falls through to known paths or the platform fallback.\n\t}\n\treturn null;\n}\n\nfunction getPowerShellConfig(): ShellConfig {\n\tconst pwshOnPath = findExecutableOnPath(process.platform === \"win32\" ? \"pwsh.exe\" : \"pwsh\");\n\tif (pwshOnPath) return { shell: pwshOnPath, args: [...POWERSHELL_ARGS] };\n\n\tconst knownPaths: string[] = [];\n\tconst programFiles = process.env.ProgramFiles;\n\tif (programFiles) knownPaths.push(`${programFiles}\\\\PowerShell\\\\7\\\\pwsh.exe`);\n\tconst systemRoot = process.env.SystemRoot;\n\tif (systemRoot) knownPaths.push(`${systemRoot}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`);\n\tfor (const path of knownPaths) {\n\t\tif (existsSync(path)) return { shell: path, args: [...POWERSHELL_ARGS] };\n\t}\n\n\tconst windowsPowerShellOnPath = findExecutableOnPath(\"powershell.exe\");\n\tif (windowsPowerShellOnPath) return { shell: windowsPowerShellOnPath, args: [...POWERSHELL_ARGS] };\n\tthrow new Error(\n\t\t\"No PowerShell executable found. Install PowerShell 7 (pwsh), restore Windows PowerShell, or set shellPath in settings.json.\",\n\t);\n}\n\nfunction getBashConfig(): ShellConfig {\n\tif (process.platform === \"win32\") {\n\t\tconst knownPaths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) knownPaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) knownPaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const path of knownPaths) {\n\t\t\tif (existsSync(path)) return { shell: path, args: [\"-c\"] };\n\t\t}\n\t\tconst bashOnPath = findExecutableOnPath(\"bash.exe\");\n\t\tif (bashOnPath) return { shell: bashOnPath, args: [\"-c\"] };\n\t\tthrow new Error(\"No Bash executable found. Install Git Bash or set shellPath in settings.json.\");\n\t}\n\tif (existsSync(\"/bin/bash\")) return { shell: \"/bin/bash\", args: [\"-c\"] };\n\tconst bashOnPath = findExecutableOnPath(\"bash\");\n\treturn bashOnPath ? { shell: bashOnPath, args: [\"-c\"] } : { shell: \"sh\", args: [\"-c\"] };\n}\n\n/** Resolve the requested shell. Runtime callers omit shellName to select PowerShell on Windows and Bash elsewhere. */\nexport function getShellConfig(\n\tcustomShellPath?: string,\n\tshellName: PlatformShellToolName = getPlatformShellToolName(),\n): ShellConfig {\n\tif (customShellPath) {\n\t\tif (!existsSync(customShellPath)) throw new Error(`Custom shell path not found: ${customShellPath}`);\n\t\treturn {\n\t\t\tshell: customShellPath,\n\t\t\targs: shellName === \"powershell\" ? [...POWERSHELL_ARGS] : [\"-c\"],\n\t\t};\n\t}\n\treturn shellName === \"powershell\" ? getPowerShellConfig() : getBashConfig();\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set<number>();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform)\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree\n\t\ttry {\n\t\t\tspawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../src/utils/shell.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,YAAY,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,EAAE,CAAC;CACf;AAED,eAAO,MAAM,sBAAsB,8EAA8E,CAAC;AAIlH,wBAAgB,wBAAwB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,qBAAqB,CAE5G;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAoFD,sHAAsH;AACtH,wBAAgB,cAAc,CAC7B,eAAe,CAAC,EAAE,MAAM,EACxB,SAAS,GAAE,qBAAkD,GAC3D,WAAW,CAcb;AAED,wBAAgB,WAAW,IAAI,MAAM,CAAC,UAAU,CAY/C;AAQD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEzD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAKlD;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAyBjD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport type PlatformShellToolName = \"bash\" | \"powershell\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n}\n\nexport const POWERSHELL_UTF8_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\nconst POWERSHELL_ARGS = [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\"];\n\nexport function getPlatformShellToolName(platform: NodeJS.Platform = process.platform): PlatformShellToolName {\n\treturn platform === \"win32\" ? \"powershell\" : \"bash\";\n}\n\nexport function prefixPowerShellCommand(command: string): string {\n\treturn command.trimStart().startsWith(POWERSHELL_UTF8_PREFIX) ? command : `${POWERSHELL_UTF8_PREFIX}${command}`;\n}\n\nfunction findExecutableOnPath(executable: string): string | null {\n\tconst locator = process.platform === \"win32\" ? \"where\" : \"which\";\n\ttry {\n\t\tconst result = spawnSync(locator, [executable], {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 5_000,\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch && (process.platform !== \"win32\" || existsSync(firstMatch))) return firstMatch;\n\t\t}\n\t} catch {\n\t\t// Resolution falls through to known paths or the platform fallback.\n\t}\n\treturn null;\n}\n\nfunction isPowerShellExecutableAvailable(executable: string): boolean {\n\ttry {\n\t\treturn (\n\t\t\tspawnSync(executable, [...POWERSHELL_ARGS, \"Write-Output ok\"], {\n\t\t\t\tencoding: \"utf-8\",\n\t\t\t\ttimeout: 5_000,\n\t\t\t\twindowsHide: true,\n\t\t\t}).status === 0\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPowerShellConfig(): ShellConfig {\n\tconst pwshOnPath = findExecutableOnPath(process.platform === \"win32\" ? \"pwsh.exe\" : \"pwsh\");\n\tif (pwshOnPath && isPowerShellExecutableAvailable(pwshOnPath)) {\n\t\treturn { shell: pwshOnPath, args: [...POWERSHELL_ARGS] };\n\t}\n\n\tconst knownPaths: string[] = [];\n\tconst programFiles = process.env.ProgramFiles;\n\tif (programFiles) knownPaths.push(`${programFiles}\\\\PowerShell\\\\7\\\\pwsh.exe`);\n\tconst systemRoot = process.env.SystemRoot;\n\tif (systemRoot) knownPaths.push(`${systemRoot}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`);\n\tfor (const path of knownPaths) {\n\t\tif (existsSync(path) && isPowerShellExecutableAvailable(path)) {\n\t\t\treturn { shell: path, args: [...POWERSHELL_ARGS] };\n\t\t}\n\t}\n\n\tconst windowsPowerShellOnPath = findExecutableOnPath(\"powershell.exe\");\n\tif (windowsPowerShellOnPath && isPowerShellExecutableAvailable(windowsPowerShellOnPath)) {\n\t\treturn { shell: windowsPowerShellOnPath, args: [...POWERSHELL_ARGS] };\n\t}\n\tthrow new Error(\n\t\t\"No PowerShell executable found. Install PowerShell 7 (pwsh), restore Windows PowerShell, or set shellPath in settings.json.\",\n\t);\n}\n\nfunction getBashConfig(): ShellConfig {\n\tif (process.platform === \"win32\") {\n\t\tconst knownPaths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) knownPaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) knownPaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const path of knownPaths) {\n\t\t\tif (existsSync(path)) return { shell: path, args: [\"-c\"] };\n\t\t}\n\t\tconst bashOnPath = findExecutableOnPath(\"bash.exe\");\n\t\tif (bashOnPath) return { shell: bashOnPath, args: [\"-c\"] };\n\t\tthrow new Error(\"No Bash executable found. Install Git Bash or set shellPath in settings.json.\");\n\t}\n\tif (existsSync(\"/bin/bash\")) return { shell: \"/bin/bash\", args: [\"-c\"] };\n\tconst bashOnPath = findExecutableOnPath(\"bash\");\n\treturn bashOnPath ? { shell: bashOnPath, args: [\"-c\"] } : { shell: \"sh\", args: [\"-c\"] };\n}\n\n// Platform shell resolution spawns probe processes (`where`/`which`, plus a full PowerShell\n// boot on Windows) and is a process-lifetime invariant, so successful resolutions are cached.\n// Failures are not cached: the user can install a shell and retry without restarting.\nconst resolvedPlatformShellConfigs = new Map<PlatformShellToolName, ShellConfig>();\n\n/** Resolve the requested shell. Runtime callers omit shellName to select PowerShell on Windows and Bash elsewhere. */\nexport function getShellConfig(\n\tcustomShellPath?: string,\n\tshellName: PlatformShellToolName = getPlatformShellToolName(),\n): ShellConfig {\n\tif (customShellPath) {\n\t\tif (!existsSync(customShellPath)) throw new Error(`Custom shell path not found: ${customShellPath}`);\n\t\treturn {\n\t\t\tshell: customShellPath,\n\t\t\targs: shellName === \"powershell\" ? [...POWERSHELL_ARGS] : [\"-c\"],\n\t\t};\n\t}\n\tlet resolved = resolvedPlatformShellConfigs.get(shellName);\n\tif (!resolved) {\n\t\tresolved = shellName === \"powershell\" ? getPowerShellConfig() : getBashConfig();\n\t\tresolvedPlatformShellConfigs.set(shellName, resolved);\n\t}\n\treturn { shell: resolved.shell, args: [...resolved.args] };\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set<number>();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform).\n *\n * Windows uses `spawnSync` (not `spawn`) deliberately: callers rely on this function returning\n * only once the tree is actually gone (e.g. before removing a directory that was the killed\n * process's cwd — a directory Windows keeps locked until every handle into it, including a\n * live process's cwd handle, is released). A fire-and-forget async `taskkill` would return before\n * termination completed, leaving a race where the directory is still locked.\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree; spawnSync blocks until taskkill itself\n\t\t// (and therefore the termination it requested) has finished.\n\t\ttry {\n\t\t\tspawnSync(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { delimiter } from "node:path";
3
- import { spawn, spawnSync } from "child_process";
3
+ import { spawnSync } from "child_process";
4
4
  import { getBinDir } from "../config.js";
5
5
  export const POWERSHELL_UTF8_PREFIX = "try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\n";
6
6
  const POWERSHELL_ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"];
@@ -29,10 +29,23 @@ function findExecutableOnPath(executable) {
29
29
  }
30
30
  return null;
31
31
  }
32
+ function isPowerShellExecutableAvailable(executable) {
33
+ try {
34
+ return (spawnSync(executable, [...POWERSHELL_ARGS, "Write-Output ok"], {
35
+ encoding: "utf-8",
36
+ timeout: 5_000,
37
+ windowsHide: true,
38
+ }).status === 0);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
32
44
  function getPowerShellConfig() {
33
45
  const pwshOnPath = findExecutableOnPath(process.platform === "win32" ? "pwsh.exe" : "pwsh");
34
- if (pwshOnPath)
46
+ if (pwshOnPath && isPowerShellExecutableAvailable(pwshOnPath)) {
35
47
  return { shell: pwshOnPath, args: [...POWERSHELL_ARGS] };
48
+ }
36
49
  const knownPaths = [];
37
50
  const programFiles = process.env.ProgramFiles;
38
51
  if (programFiles)
@@ -41,12 +54,14 @@ function getPowerShellConfig() {
41
54
  if (systemRoot)
42
55
  knownPaths.push(`${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`);
43
56
  for (const path of knownPaths) {
44
- if (existsSync(path))
57
+ if (existsSync(path) && isPowerShellExecutableAvailable(path)) {
45
58
  return { shell: path, args: [...POWERSHELL_ARGS] };
59
+ }
46
60
  }
47
61
  const windowsPowerShellOnPath = findExecutableOnPath("powershell.exe");
48
- if (windowsPowerShellOnPath)
62
+ if (windowsPowerShellOnPath && isPowerShellExecutableAvailable(windowsPowerShellOnPath)) {
49
63
  return { shell: windowsPowerShellOnPath, args: [...POWERSHELL_ARGS] };
64
+ }
50
65
  throw new Error("No PowerShell executable found. Install PowerShell 7 (pwsh), restore Windows PowerShell, or set shellPath in settings.json.");
51
66
  }
52
67
  function getBashConfig() {
@@ -72,6 +87,10 @@ function getBashConfig() {
72
87
  const bashOnPath = findExecutableOnPath("bash");
73
88
  return bashOnPath ? { shell: bashOnPath, args: ["-c"] } : { shell: "sh", args: ["-c"] };
74
89
  }
90
+ // Platform shell resolution spawns probe processes (`where`/`which`, plus a full PowerShell
91
+ // boot on Windows) and is a process-lifetime invariant, so successful resolutions are cached.
92
+ // Failures are not cached: the user can install a shell and retry without restarting.
93
+ const resolvedPlatformShellConfigs = new Map();
75
94
  /** Resolve the requested shell. Runtime callers omit shellName to select PowerShell on Windows and Bash elsewhere. */
76
95
  export function getShellConfig(customShellPath, shellName = getPlatformShellToolName()) {
77
96
  if (customShellPath) {
@@ -82,7 +101,12 @@ export function getShellConfig(customShellPath, shellName = getPlatformShellTool
82
101
  args: shellName === "powershell" ? [...POWERSHELL_ARGS] : ["-c"],
83
102
  };
84
103
  }
85
- return shellName === "powershell" ? getPowerShellConfig() : getBashConfig();
104
+ let resolved = resolvedPlatformShellConfigs.get(shellName);
105
+ if (!resolved) {
106
+ resolved = shellName === "powershell" ? getPowerShellConfig() : getBashConfig();
107
+ resolvedPlatformShellConfigs.set(shellName, resolved);
108
+ }
109
+ return { shell: resolved.shell, args: [...resolved.args] };
86
110
  }
87
111
  export function getShellEnv() {
88
112
  const binDir = getBinDir();
@@ -114,15 +138,21 @@ export function killTrackedDetachedChildren() {
114
138
  trackedDetachedChildPids.clear();
115
139
  }
116
140
  /**
117
- * Kill a process and all its children (cross-platform)
141
+ * Kill a process and all its children (cross-platform).
142
+ *
143
+ * Windows uses `spawnSync` (not `spawn`) deliberately: callers rely on this function returning
144
+ * only once the tree is actually gone (e.g. before removing a directory that was the killed
145
+ * process's cwd — a directory Windows keeps locked until every handle into it, including a
146
+ * live process's cwd handle, is released). A fire-and-forget async `taskkill` would return before
147
+ * termination completed, leaving a race where the directory is still locked.
118
148
  */
119
149
  export function killProcessTree(pid) {
120
150
  if (process.platform === "win32") {
121
- // Use taskkill on Windows to kill process tree
151
+ // Use taskkill on Windows to kill process tree; spawnSync blocks until taskkill itself
152
+ // (and therefore the termination it requested) has finished.
122
153
  try {
123
- spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
154
+ spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
124
155
  stdio: "ignore",
125
- detached: true,
126
156
  windowsHide: true,
127
157
  });
128
158
  }
@@ -1 +1 @@
1
- {"version":3,"file":"shell.js","sourceRoot":"","sources":["../../src/utils/shell.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,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GAAG,CAAC,CAAC;AAAA,CAClC;AAED,MAAM,UAAU,uBAAuB,CAAC,GAAW,EAAQ;IAC1D,wBAAwB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAAA,CACrC;AAED,MAAM,UAAU,2BAA2B,GAAS;IACnD,KAAK,MAAM,GAAG,IAAI,wBAAwB,EAAE,CAAC;QAC5C,eAAe,CAAC,GAAG,CAAC,CAAC;IACtB,CAAC;IACD,wBAAwB,CAAC,KAAK,EAAE,CAAC;AAAA,CACjC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW,EAAQ;IAClD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;QAClC,+CAA+C;QAC/C,IAAI,CAAC;YACJ,KAAK,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE;gBACpD,KAAK,EAAE,QAAQ;gBACf,QAAQ,EAAE,IAAI;gBACd,WAAW,EAAE,IAAI;aACjB,CAAC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACR,kCAAkC;QACnC,CAAC;IACF,CAAC;SAAM,CAAC;QACP,gCAAgC;QAChC,IAAI,CAAC;YACJ,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACR,iEAAiE;YACjE,IAAI,CAAC;gBACJ,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;YAC9B,CAAC;YAAC,MAAM,CAAC;gBACR,uBAAuB;YACxB,CAAC;QACF,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawn, spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport type PlatformShellToolName = \"bash\" | \"powershell\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n}\n\nexport const POWERSHELL_UTF8_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\nconst POWERSHELL_ARGS = [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\"];\n\nexport function getPlatformShellToolName(platform: NodeJS.Platform = process.platform): PlatformShellToolName {\n\treturn platform === \"win32\" ? \"powershell\" : \"bash\";\n}\n\nexport function prefixPowerShellCommand(command: string): string {\n\treturn command.trimStart().startsWith(POWERSHELL_UTF8_PREFIX) ? command : `${POWERSHELL_UTF8_PREFIX}${command}`;\n}\n\nfunction findExecutableOnPath(executable: string): string | null {\n\tconst locator = process.platform === \"win32\" ? \"where\" : \"which\";\n\ttry {\n\t\tconst result = spawnSync(locator, [executable], {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 5_000,\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch && (process.platform !== \"win32\" || existsSync(firstMatch))) return firstMatch;\n\t\t}\n\t} catch {\n\t\t// Resolution falls through to known paths or the platform fallback.\n\t}\n\treturn null;\n}\n\nfunction getPowerShellConfig(): ShellConfig {\n\tconst pwshOnPath = findExecutableOnPath(process.platform === \"win32\" ? \"pwsh.exe\" : \"pwsh\");\n\tif (pwshOnPath) return { shell: pwshOnPath, args: [...POWERSHELL_ARGS] };\n\n\tconst knownPaths: string[] = [];\n\tconst programFiles = process.env.ProgramFiles;\n\tif (programFiles) knownPaths.push(`${programFiles}\\\\PowerShell\\\\7\\\\pwsh.exe`);\n\tconst systemRoot = process.env.SystemRoot;\n\tif (systemRoot) knownPaths.push(`${systemRoot}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`);\n\tfor (const path of knownPaths) {\n\t\tif (existsSync(path)) return { shell: path, args: [...POWERSHELL_ARGS] };\n\t}\n\n\tconst windowsPowerShellOnPath = findExecutableOnPath(\"powershell.exe\");\n\tif (windowsPowerShellOnPath) return { shell: windowsPowerShellOnPath, args: [...POWERSHELL_ARGS] };\n\tthrow new Error(\n\t\t\"No PowerShell executable found. Install PowerShell 7 (pwsh), restore Windows PowerShell, or set shellPath in settings.json.\",\n\t);\n}\n\nfunction getBashConfig(): ShellConfig {\n\tif (process.platform === \"win32\") {\n\t\tconst knownPaths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) knownPaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) knownPaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const path of knownPaths) {\n\t\t\tif (existsSync(path)) return { shell: path, args: [\"-c\"] };\n\t\t}\n\t\tconst bashOnPath = findExecutableOnPath(\"bash.exe\");\n\t\tif (bashOnPath) return { shell: bashOnPath, args: [\"-c\"] };\n\t\tthrow new Error(\"No Bash executable found. Install Git Bash or set shellPath in settings.json.\");\n\t}\n\tif (existsSync(\"/bin/bash\")) return { shell: \"/bin/bash\", args: [\"-c\"] };\n\tconst bashOnPath = findExecutableOnPath(\"bash\");\n\treturn bashOnPath ? { shell: bashOnPath, args: [\"-c\"] } : { shell: \"sh\", args: [\"-c\"] };\n}\n\n/** Resolve the requested shell. Runtime callers omit shellName to select PowerShell on Windows and Bash elsewhere. */\nexport function getShellConfig(\n\tcustomShellPath?: string,\n\tshellName: PlatformShellToolName = getPlatformShellToolName(),\n): ShellConfig {\n\tif (customShellPath) {\n\t\tif (!existsSync(customShellPath)) throw new Error(`Custom shell path not found: ${customShellPath}`);\n\t\treturn {\n\t\t\tshell: customShellPath,\n\t\t\targs: shellName === \"powershell\" ? [...POWERSHELL_ARGS] : [\"-c\"],\n\t\t};\n\t}\n\treturn shellName === \"powershell\" ? getPowerShellConfig() : getBashConfig();\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set<number>();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform)\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree\n\t\ttry {\n\t\t\tspawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"shell.js","sourceRoot":"","sources":["../../src/utils/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MAAM,UAAU,2BAA2B,GAAS;IACnD,KAAK,MAAM,GAAG,IAAI,wBAAwB,EAAE,CAAC;QAC5C,eAAe,CAAC,GAAG,CAAC,CAAC;IACtB,CAAC;IACD,wBAAwB,CAAC,KAAK,EAAE,CAAC;AAAA,CACjC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW,EAAQ;IAClD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;QAClC,uFAAuF;QACvF,6DAA6D;QAC7D,IAAI,CAAC;YACJ,SAAS,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE;gBACxD,KAAK,EAAE,QAAQ;gBACf,WAAW,EAAE,IAAI;aACjB,CAAC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACR,kCAAkC;QACnC,CAAC;IACF,CAAC;SAAM,CAAC;QACP,gCAAgC;QAChC,IAAI,CAAC;YACJ,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACR,iEAAiE;YACjE,IAAI,CAAC;gBACJ,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;YAC9B,CAAC;YAAC,MAAM,CAAC;gBACR,uBAAuB;YACxB,CAAC;QACF,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport type PlatformShellToolName = \"bash\" | \"powershell\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n}\n\nexport const POWERSHELL_UTF8_PREFIX = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\\n\";\n\nconst POWERSHELL_ARGS = [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\"];\n\nexport function getPlatformShellToolName(platform: NodeJS.Platform = process.platform): PlatformShellToolName {\n\treturn platform === \"win32\" ? \"powershell\" : \"bash\";\n}\n\nexport function prefixPowerShellCommand(command: string): string {\n\treturn command.trimStart().startsWith(POWERSHELL_UTF8_PREFIX) ? command : `${POWERSHELL_UTF8_PREFIX}${command}`;\n}\n\nfunction findExecutableOnPath(executable: string): string | null {\n\tconst locator = process.platform === \"win32\" ? \"where\" : \"which\";\n\ttry {\n\t\tconst result = spawnSync(locator, [executable], {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 5_000,\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch && (process.platform !== \"win32\" || existsSync(firstMatch))) return firstMatch;\n\t\t}\n\t} catch {\n\t\t// Resolution falls through to known paths or the platform fallback.\n\t}\n\treturn null;\n}\n\nfunction isPowerShellExecutableAvailable(executable: string): boolean {\n\ttry {\n\t\treturn (\n\t\t\tspawnSync(executable, [...POWERSHELL_ARGS, \"Write-Output ok\"], {\n\t\t\t\tencoding: \"utf-8\",\n\t\t\t\ttimeout: 5_000,\n\t\t\t\twindowsHide: true,\n\t\t\t}).status === 0\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPowerShellConfig(): ShellConfig {\n\tconst pwshOnPath = findExecutableOnPath(process.platform === \"win32\" ? \"pwsh.exe\" : \"pwsh\");\n\tif (pwshOnPath && isPowerShellExecutableAvailable(pwshOnPath)) {\n\t\treturn { shell: pwshOnPath, args: [...POWERSHELL_ARGS] };\n\t}\n\n\tconst knownPaths: string[] = [];\n\tconst programFiles = process.env.ProgramFiles;\n\tif (programFiles) knownPaths.push(`${programFiles}\\\\PowerShell\\\\7\\\\pwsh.exe`);\n\tconst systemRoot = process.env.SystemRoot;\n\tif (systemRoot) knownPaths.push(`${systemRoot}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`);\n\tfor (const path of knownPaths) {\n\t\tif (existsSync(path) && isPowerShellExecutableAvailable(path)) {\n\t\t\treturn { shell: path, args: [...POWERSHELL_ARGS] };\n\t\t}\n\t}\n\n\tconst windowsPowerShellOnPath = findExecutableOnPath(\"powershell.exe\");\n\tif (windowsPowerShellOnPath && isPowerShellExecutableAvailable(windowsPowerShellOnPath)) {\n\t\treturn { shell: windowsPowerShellOnPath, args: [...POWERSHELL_ARGS] };\n\t}\n\tthrow new Error(\n\t\t\"No PowerShell executable found. Install PowerShell 7 (pwsh), restore Windows PowerShell, or set shellPath in settings.json.\",\n\t);\n}\n\nfunction getBashConfig(): ShellConfig {\n\tif (process.platform === \"win32\") {\n\t\tconst knownPaths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) knownPaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) knownPaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const path of knownPaths) {\n\t\t\tif (existsSync(path)) return { shell: path, args: [\"-c\"] };\n\t\t}\n\t\tconst bashOnPath = findExecutableOnPath(\"bash.exe\");\n\t\tif (bashOnPath) return { shell: bashOnPath, args: [\"-c\"] };\n\t\tthrow new Error(\"No Bash executable found. Install Git Bash or set shellPath in settings.json.\");\n\t}\n\tif (existsSync(\"/bin/bash\")) return { shell: \"/bin/bash\", args: [\"-c\"] };\n\tconst bashOnPath = findExecutableOnPath(\"bash\");\n\treturn bashOnPath ? { shell: bashOnPath, args: [\"-c\"] } : { shell: \"sh\", args: [\"-c\"] };\n}\n\n// Platform shell resolution spawns probe processes (`where`/`which`, plus a full PowerShell\n// boot on Windows) and is a process-lifetime invariant, so successful resolutions are cached.\n// Failures are not cached: the user can install a shell and retry without restarting.\nconst resolvedPlatformShellConfigs = new Map<PlatformShellToolName, ShellConfig>();\n\n/** Resolve the requested shell. Runtime callers omit shellName to select PowerShell on Windows and Bash elsewhere. */\nexport function getShellConfig(\n\tcustomShellPath?: string,\n\tshellName: PlatformShellToolName = getPlatformShellToolName(),\n): ShellConfig {\n\tif (customShellPath) {\n\t\tif (!existsSync(customShellPath)) throw new Error(`Custom shell path not found: ${customShellPath}`);\n\t\treturn {\n\t\t\tshell: customShellPath,\n\t\t\targs: shellName === \"powershell\" ? [...POWERSHELL_ARGS] : [\"-c\"],\n\t\t};\n\t}\n\tlet resolved = resolvedPlatformShellConfigs.get(shellName);\n\tif (!resolved) {\n\t\tresolved = shellName === \"powershell\" ? getPowerShellConfig() : getBashConfig();\n\t\tresolvedPlatformShellConfigs.set(shellName, resolved);\n\t}\n\treturn { shell: resolved.shell, args: [...resolved.args] };\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set<number>();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform).\n *\n * Windows uses `spawnSync` (not `spawn`) deliberately: callers rely on this function returning\n * only once the tree is actually gone (e.g. before removing a directory that was the killed\n * process's cwd — a directory Windows keeps locked until every handle into it, including a\n * live process's cwd handle, is released). A fire-and-forget async `taskkill` would return before\n * termination completed, leaving a race where the directory is still locked.\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree; spawnSync blocks until taskkill itself\n\t\t// (and therefore the termination it requested) has finished.\n\t\ttry {\n\t\t\tspawnSync(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"syntax-highlight.d.ts","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;AAC1D,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,KAAK,CAAC,EAAE,cAAc,CAAC;CACvB;AAoED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,cAAmB,GAAG,MAAM,CAoDtF;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAQ9E;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD","sourcesContent":["import hljs from \"highlight.js/lib/index.js\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial<Record<string, HighlightFormatter>>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"</span>\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array<string | undefined>, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"<span\", index)) {\n\t\treturn false;\n\t}\n\tconst nextChar = html[index + \"<span\".length];\n\treturn nextChar === \">\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array<string | undefined> = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tconst html = options.language\n\t\t? hljs.highlight(code, {\n\t\t\t\tlanguage: options.language,\n\t\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t\t}).value\n\t\t: hljs.highlightAuto(code, options.languageSubset).value;\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]}
1
+ {"version":3,"file":"syntax-highlight.d.ts","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;AAC1D,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,KAAK,CAAC,EAAE,cAAc,CAAC;CACvB;AAoED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,cAAmB,GAAG,MAAM,CAoDtF;AAoCD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAqB9E;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGtD","sourcesContent":["import hljs from \"highlight.js/lib/core.js\";\nimport { HIGHLIGHT_LANGUAGE_ALIASES, HIGHLIGHT_LANGUAGE_MODULES } from \"./highlight-js-languages.ts\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial<Record<string, HighlightFormatter>>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"</span>\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array<string | undefined>, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"<span\", index)) {\n\t\treturn false;\n\t}\n\tconst nextChar = html[index + \"<span\".length];\n\treturn nextChar === \">\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array<string | undefined> = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nlet allLanguagesRegistered = false;\n\n// Register a language with highlight.js/lib/core on first use instead of eagerly\n// registering all ~190 bundled languages at import time. `HIGHLIGHT_LANGUAGE_MODULES`\n// and `HIGHLIGHT_LANGUAGE_ALIASES` are generated from the same registration data as\n// highlight.js/lib/index.js (see highlight-js-languages.ts), so resolution is\n// identical: an exact canonical name always wins over an alias (mirrors hljs's own\n// `languages[name] || languages[aliases[name]]` lookup), and when two languages\n// declare the same alias, the language registered last wins (mirrors hljs's\n// registration-order overwrite of its internal alias table).\nfunction ensureLanguageRegistered(name: string): void {\n\tconst lower = name.toLowerCase();\n\tif (hljs.getLanguage(lower)) {\n\t\treturn;\n\t}\n\tconst canonicalName = HIGHLIGHT_LANGUAGE_MODULES[lower] ? lower : HIGHLIGHT_LANGUAGE_ALIASES[lower];\n\tconst languageModule = canonicalName ? HIGHLIGHT_LANGUAGE_MODULES[canonicalName] : undefined;\n\tif (canonicalName && languageModule) {\n\t\thljs.registerLanguage(canonicalName, languageModule);\n\t}\n}\n\nfunction ensureAllLanguagesRegistered(): void {\n\tif (allLanguagesRegistered) {\n\t\treturn;\n\t}\n\tfor (const [canonicalName, languageModule] of Object.entries(HIGHLIGHT_LANGUAGE_MODULES)) {\n\t\tif (!hljs.getLanguage(canonicalName)) {\n\t\t\thljs.registerLanguage(canonicalName, languageModule);\n\t\t}\n\t}\n\tallLanguagesRegistered = true;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tlet html: string;\n\tif (options.language) {\n\t\tensureLanguageRegistered(options.language);\n\t\thtml = hljs.highlight(code, {\n\t\t\tlanguage: options.language,\n\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t}).value;\n\t} else if (options.languageSubset) {\n\t\tfor (const name of options.languageSubset) {\n\t\t\tensureLanguageRegistered(name);\n\t\t}\n\t\thtml = hljs.highlightAuto(code, options.languageSubset).value;\n\t} else {\n\t\t// Full auto-detection with no subset scans every registered language, so there is\n\t\t// no lazy subset to resolve first — register everything to preserve identical\n\t\t// detection results to the eager bundle.\n\t\tensureAllLanguagesRegistered();\n\t\thtml = hljs.highlightAuto(code).value;\n\t}\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\tensureLanguageRegistered(name);\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]}
@@ -1,4 +1,5 @@
1
- import hljs from "highlight.js/lib/index.js";
1
+ import hljs from "highlight.js/lib/core.js";
2
+ import { HIGHLIGHT_LANGUAGE_ALIASES, HIGHLIGHT_LANGUAGE_MODULES } from "./highlight-js-languages.js";
2
3
  import { decodeHtmlEntityAt } from "./html.js";
3
4
  const SPAN_CLOSE = "</span>";
4
5
  const HIGHLIGHT_CLASS_PREFIX = "hljs-";
@@ -103,16 +104,63 @@ export function renderHighlightedHtml(html, theme = {}) {
103
104
  flushText();
104
105
  return output;
105
106
  }
107
+ let allLanguagesRegistered = false;
108
+ // Register a language with highlight.js/lib/core on first use instead of eagerly
109
+ // registering all ~190 bundled languages at import time. `HIGHLIGHT_LANGUAGE_MODULES`
110
+ // and `HIGHLIGHT_LANGUAGE_ALIASES` are generated from the same registration data as
111
+ // highlight.js/lib/index.js (see highlight-js-languages.ts), so resolution is
112
+ // identical: an exact canonical name always wins over an alias (mirrors hljs's own
113
+ // `languages[name] || languages[aliases[name]]` lookup), and when two languages
114
+ // declare the same alias, the language registered last wins (mirrors hljs's
115
+ // registration-order overwrite of its internal alias table).
116
+ function ensureLanguageRegistered(name) {
117
+ const lower = name.toLowerCase();
118
+ if (hljs.getLanguage(lower)) {
119
+ return;
120
+ }
121
+ const canonicalName = HIGHLIGHT_LANGUAGE_MODULES[lower] ? lower : HIGHLIGHT_LANGUAGE_ALIASES[lower];
122
+ const languageModule = canonicalName ? HIGHLIGHT_LANGUAGE_MODULES[canonicalName] : undefined;
123
+ if (canonicalName && languageModule) {
124
+ hljs.registerLanguage(canonicalName, languageModule);
125
+ }
126
+ }
127
+ function ensureAllLanguagesRegistered() {
128
+ if (allLanguagesRegistered) {
129
+ return;
130
+ }
131
+ for (const [canonicalName, languageModule] of Object.entries(HIGHLIGHT_LANGUAGE_MODULES)) {
132
+ if (!hljs.getLanguage(canonicalName)) {
133
+ hljs.registerLanguage(canonicalName, languageModule);
134
+ }
135
+ }
136
+ allLanguagesRegistered = true;
137
+ }
106
138
  export function highlight(code, options = {}) {
107
- const html = options.language
108
- ? hljs.highlight(code, {
139
+ let html;
140
+ if (options.language) {
141
+ ensureLanguageRegistered(options.language);
142
+ html = hljs.highlight(code, {
109
143
  language: options.language,
110
144
  ignoreIllegals: options.ignoreIllegals,
111
- }).value
112
- : hljs.highlightAuto(code, options.languageSubset).value;
145
+ }).value;
146
+ }
147
+ else if (options.languageSubset) {
148
+ for (const name of options.languageSubset) {
149
+ ensureLanguageRegistered(name);
150
+ }
151
+ html = hljs.highlightAuto(code, options.languageSubset).value;
152
+ }
153
+ else {
154
+ // Full auto-detection with no subset scans every registered language, so there is
155
+ // no lazy subset to resolve first — register everything to preserve identical
156
+ // detection results to the eager bundle.
157
+ ensureAllLanguagesRegistered();
158
+ html = hljs.highlightAuto(code).value;
159
+ }
113
160
  return renderHighlightedHtml(html, options.theme);
114
161
  }
115
162
  export function supportsLanguage(name) {
163
+ ensureLanguageRegistered(name);
116
164
  return hljs.getLanguage(name) !== undefined;
117
165
  }
118
166
  //# sourceMappingURL=syntax-highlight.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"syntax-highlight.js","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,2BAA2B,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAY/C,MAAM,UAAU,GAAG,SAAS,CAAC;AAC7B,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC,SAAS,mBAAmB,CAAC,GAAW,EAAsB;IAC7D,MAAM,KAAK,GAAG,uCAAuC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChE,MAAM,UAAU,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,UAAU,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,SAAS,EAAE,CAAC;IACZ,OAAO,MAAM,CAAC;AAAA,CACd;AAED,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,OAAO,GAAqB,EAAE,EAAU;IAC/E,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ;QAC5B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;YACrB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,OAAO,CAAC,cAAc;SACtC,CAAC,CAAC,KAAK;QACT,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC;IAC1D,OAAO,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAClD;AAED,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAW;IACvD,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;AAAA,CAC5C","sourcesContent":["import hljs from \"highlight.js/lib/index.js\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial<Record<string, HighlightFormatter>>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"</span>\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array<string | undefined>, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"<span\", index)) {\n\t\treturn false;\n\t}\n\tconst nextChar = html[index + \"<span\".length];\n\treturn nextChar === \">\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array<string | undefined> = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tconst html = options.language\n\t\t? hljs.highlight(code, {\n\t\t\t\tlanguage: options.language,\n\t\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t\t}).value\n\t\t: hljs.highlightAuto(code, options.languageSubset).value;\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]}
1
+ {"version":3,"file":"syntax-highlight.js","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,0BAA0B,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACrG,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAY/C,MAA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/lib/core.js\";\nimport { HIGHLIGHT_LANGUAGE_ALIASES, HIGHLIGHT_LANGUAGE_MODULES } from \"./highlight-js-languages.ts\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial<Record<string, HighlightFormatter>>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"</span>\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array<string | undefined>, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"<span\", index)) {\n\t\treturn false;\n\t}\n\tconst nextChar = html[index + \"<span\".length];\n\treturn nextChar === \">\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array<string | undefined> = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nlet allLanguagesRegistered = false;\n\n// Register a language with highlight.js/lib/core on first use instead of eagerly\n// registering all ~190 bundled languages at import time. `HIGHLIGHT_LANGUAGE_MODULES`\n// and `HIGHLIGHT_LANGUAGE_ALIASES` are generated from the same registration data as\n// highlight.js/lib/index.js (see highlight-js-languages.ts), so resolution is\n// identical: an exact canonical name always wins over an alias (mirrors hljs's own\n// `languages[name] || languages[aliases[name]]` lookup), and when two languages\n// declare the same alias, the language registered last wins (mirrors hljs's\n// registration-order overwrite of its internal alias table).\nfunction ensureLanguageRegistered(name: string): void {\n\tconst lower = name.toLowerCase();\n\tif (hljs.getLanguage(lower)) {\n\t\treturn;\n\t}\n\tconst canonicalName = HIGHLIGHT_LANGUAGE_MODULES[lower] ? lower : HIGHLIGHT_LANGUAGE_ALIASES[lower];\n\tconst languageModule = canonicalName ? HIGHLIGHT_LANGUAGE_MODULES[canonicalName] : undefined;\n\tif (canonicalName && languageModule) {\n\t\thljs.registerLanguage(canonicalName, languageModule);\n\t}\n}\n\nfunction ensureAllLanguagesRegistered(): void {\n\tif (allLanguagesRegistered) {\n\t\treturn;\n\t}\n\tfor (const [canonicalName, languageModule] of Object.entries(HIGHLIGHT_LANGUAGE_MODULES)) {\n\t\tif (!hljs.getLanguage(canonicalName)) {\n\t\t\thljs.registerLanguage(canonicalName, languageModule);\n\t\t}\n\t}\n\tallLanguagesRegistered = true;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tlet html: string;\n\tif (options.language) {\n\t\tensureLanguageRegistered(options.language);\n\t\thtml = hljs.highlight(code, {\n\t\t\tlanguage: options.language,\n\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t}).value;\n\t} else if (options.languageSubset) {\n\t\tfor (const name of options.languageSubset) {\n\t\t\tensureLanguageRegistered(name);\n\t\t}\n\t\thtml = hljs.highlightAuto(code, options.languageSubset).value;\n\t} else {\n\t\t// Full auto-detection with no subset scans every registered language, so there is\n\t\t// no lazy subset to resolve first — register everything to preserve identical\n\t\t// detection results to the eager bundle.\n\t\tensureAllLanguagesRegistered();\n\t\thtml = hljs.highlightAuto(code).value;\n\t}\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\tensureLanguageRegistered(name);\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.d.ts","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AA8BA,eAAO,MAAM,UAAU,YAAY,CAAC;AAIpC,KAAK,aAAa,GAAG,CAAC,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG;IAAE,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,CAAA;CAAE,CAAC;AAWtF,UAAU,UAAU;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAAC;IACrF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACjD;AAED,QAAA,MAAM,KAAK,EAAE,MAAM,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,UAAU,CAkEjD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,KAAK,CAAC;AAEjD,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,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M,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,6BAA6B,QAAS,CAAC;AAKpD,yEAAyE;AACzE,wBAAgB,wBAAwB,IAAI,iBAAiB,GAAG,SAAS,CAExE;AAED,mMAAmM;AACnM,wBAAgB,qBAAqB,IAAI,OAAO,CAE/C;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,GAAG,EAAE,MAAM,GACT,OAAO,CAIT;AAsED,wBAAsB,oBAAoB,CACzC,MAAM,GAAE,OAAe,EACvB,mBAAmB,GAAE,OAAe;AACpC,sHAAsH;AACtH,QAAQ,CAAC,EAAE,SAAS,aAAa,EAAE,GACjC,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAoC9B;AAoBD,wBAAsB,UAAU,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAsD5G","sourcesContent":["import { createHash } from \"node:crypto\";\nimport chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport {\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\trenameSync,\n\trmSync,\n\twriteFileSync,\n} from \"fs\";\nimport { createRequire } from \"module\";\nimport { arch, platform } from \"os\";\nimport { dirname, join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { pathToFileURL } from \"url\";\nimport { APP_NAME, getAgentDir, getBinDir } from \"../config.ts\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\nconst COMMAND_PROBE_TIMEOUT_MS = 5_000;\nconst ARCHIVE_EXTRACTION_TIMEOUT_MS = 5 * 60_000;\nconst FFF_NODE_VERSION = \"0.9.6\";\nexport const UV_VERSION = \"0.11.28\";\nconst FFF_MANAGED_DIR = join(TOOLS_DIR, \"fff-node\");\nconst FFF_MANAGED_PACKAGE_JSON = join(FFF_MANAGED_DIR, \"package.json\");\n\ntype ModuleRequire = ((id: string) => unknown) & { resolve?: (id: string) => string };\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\tpinnedVersion?: string;\n\tsha256ByAsset?: Readonly<Record<string, string>>;\n}\n\nconst TOOLS: Record<\"fd\" | \"rg\" | \"uv\", ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\tuv: {\n\t\tname: \"uv\",\n\t\trepo: \"astral-sh/uv\",\n\t\tbinaryName: \"uv\",\n\t\tsystemBinaryNames: [\"uv\"],\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: UV_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\tif (plat === \"darwin\") return `uv-${archStr}-apple-darwin.tar.gz`;\n\t\t\tif (plat === \"linux\") return `uv-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\tif (plat === \"win32\") return `uv-${archStr}-pc-windows-msvc.zip`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"uv-aarch64-apple-darwin.tar.gz\": \"33540eb7c883ab857eff79bd5ac2aa31fe27b595abecb4a9c003a2c998447232\",\n\t\t\t\"uv-aarch64-pc-windows-msvc.zip\": \"3248109afad3ec59baad299d324ff53de17e2d9a3b3e21580ffd26744b11e036\",\n\t\t\t\"uv-aarch64-unknown-linux-musl.tar.gz\": \"da10cdfa7d92212b7acb62021a0fd61bcf8580c58c3632ec915d10c3a1a7906b\",\n\t\t\t\"uv-x86_64-apple-darwin.tar.gz\": \"2ad79983127ffca7d77b77ce6a24278d7e4f7b817a1acf72fea5f8124b4aac5e\",\n\t\t\t\"uv-x86_64-pc-windows-msvc.zip\": \"0a23463216d09c6a72ff80ef5dc5a795f07dc1575cb84d24596c2f124a441b7b\",\n\t\t\t\"uv-x86_64-unknown-linux-musl.tar.gz\": \"f02146b371c35c287d860f003ece7345c86e358a3fd70a9b63700cd141ee7fb4\",\n\t\t},\n\t},\n};\n\nexport type ManagedToolName = keyof typeof TOOLS;\n\nexport interface PinnedToolAsset {\n\tversion: string;\n\tassetName: string;\n\texpectedSha256: string;\n}\n\nexport function getPinnedToolAsset(\n\ttool: ManagedToolName,\n\ttargetPlatform: string = platform(),\n\ttargetArchitecture: string = arch(),\n): PinnedToolAsset | null {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config.pinnedVersion || !config.sha256ByAsset) return null;\n\tconst assetName = config.getAssetName(config.pinnedVersion, targetPlatform, targetArchitecture);\n\tif (!assetName) return null;\n\tconst expectedSha256 = config.sha256ByAsset[assetName];\n\treturn expectedSha256 ? { version: config.pinnedVersion, assetName, expectedSha256 } : null;\n}\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\", timeout: COMMAND_PROBE_TIMEOUT_MS });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: ManagedToolName): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** Presence check for a SYSTEM tool the doctor only ever reports on -- never installs. */\nexport interface SystemToolStatus {\n\tpresent: boolean;\n\tcommand?: string;\n\tversion?: string;\n}\n\nconst PYTHON_COMMANDS = [\"python3\", \"python\"];\n\n/**\n * Detect a usable Python interpreter. SYSTEM tool (see src/core/doctor.ts):\n * the doctor reports presence/version, it never installs this itself.\n *\n * @param commands Override the candidate command names, for tests.\n */\nexport function detectPython(commands: readonly string[] = PYTHON_COMMANDS): SystemToolStatus {\n\tfor (const command of commands) {\n\t\ttry {\n\t\t\tconst result = spawnSync(command, [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\t\tif (result.error) continue;\n\t\t\t// Python 2 prints its version to stderr; Python 3 prints to stdout. Some\n\t\t\t// platforms' `python` alias is one or the other, so check both.\n\t\t\tconst version = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim() || undefined;\n\t\t\tif (result.status !== 0 && !version) continue;\n\t\t\treturn { present: true, command, version };\n\t\t} catch {\n\t\t\t// Try the next candidate.\n\t\t}\n\t}\n\treturn { present: false };\n}\n\n/**\n * Runs `<command> --version` (or `versionArgs`) and returns its trimmed\n * combined stdout+stderr, or undefined if the command can't be run. Used by\n * the doctor (src/core/doctor.ts) to show a version alongside a tool it has\n * already located by some other means (e.g. getToolPath(\"rg\"), or the binary\n * path OllamaRuntime.detect() reports) -- callers that only need a yes/no\n * presence check should use commandExists/getToolPath/detectPython instead.\n */\nexport function probeVersion(command: string, versionArgs: readonly string[] = [\"--version\"]): string | undefined {\n\ttry {\n\t\tconst result = spawnSync(command, versionArgs, { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\tif (result.error) return undefined;\n\t\tconst output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n\t\treturn output || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nexport async function verifyFileSha256(filePath: string, expectedSha256: string): Promise<boolean> {\n\tconst hash = createHash(\"sha256\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst stream = createReadStream(filePath);\n\t\tstream.on(\"data\", (chunk) => hash.update(chunk));\n\t\tstream.once(\"error\", reject);\n\t\tstream.once(\"end\", resolve);\n\t});\n\treturn hash.digest(\"hex\") === expectedSha256.toLowerCase();\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\", timeout: ARCHIVE_EXTRACTION_TIMEOUT_MS });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nconst toolDownloadPromises = new Map<ManagedToolName, Promise<string | undefined>>();\n\nexport function runExclusiveToolDownload(\n\ttool: ManagedToolName,\n\tinstaller: () => Promise<string | undefined>,\n): Promise<string | undefined> {\n\tconst existing = toolDownloadPromises.get(tool);\n\tif (existing) return existing;\n\tconst promise = installer().finally(() => {\n\t\tif (toolDownloadPromises.get(tool) === promise) {\n\t\t\ttoolDownloadPromises.delete(tool);\n\t\t}\n\t});\n\ttoolDownloadPromises.set(tool, promise);\n\treturn promise;\n}\n\nasync function downloadTool(tool: ManagedToolName): Promise<string> {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned tools are reproducible; legacy search tools retain their current latest-release behavior.\n\tlet version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst downloadWorkDir = getProcessWorkRun(getAgentDir(), \"downloads\", \"tools\").path;\n\tconst archivePath = join(downloadWorkDir, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download and verify pinned artifacts before extraction.\n\tawait downloadFile(downloadUrl, archivePath);\n\tconst expectedSha256 = config.sha256ByAsset?.[assetName];\n\tif (config.sha256ByAsset && !expectedSha256) {\n\t\tthrow new Error(`No pinned SHA-256 is registered for ${assetName}`);\n\t}\n\tif (expectedSha256 && !(await verifyFileSha256(archivePath, expectedSha256))) {\n\t\tthrow new Error(`SHA-256 verification failed for ${assetName}`);\n\t}\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tdownloadWorkDir,\n\t\t`extract-${config.binaryName}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<ManagedToolName, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n\tuv: \"uv\",\n};\n\nconst FFF_PLATFORM_PACKAGES: Record<string, string> = {\n\t\"darwin/arm64\": \"@ff-labs/fff-bin-darwin-arm64\",\n\t\"darwin/x64\": \"@ff-labs/fff-bin-darwin-x64\",\n\t\"linux/arm64/glibc\": \"@ff-labs/fff-bin-linux-arm64-gnu\",\n\t\"linux/arm64/musl\": \"@ff-labs/fff-bin-linux-arm64-musl\",\n\t\"linux/x64/glibc\": \"@ff-labs/fff-bin-linux-x64-gnu\",\n\t\"linux/x64/musl\": \"@ff-labs/fff-bin-linux-x64-musl\",\n\t\"win32/arm64\": \"@ff-labs/fff-bin-win32-arm64\",\n\t\"win32/x64\": \"@ff-labs/fff-bin-win32-x64\",\n};\n\nlet fffNodeInstallPromise: Promise<unknown | undefined> | undefined;\n\nfunction detectLinuxLibc(): \"glibc\" | \"musl\" {\n\tlet output = \"\";\n\ttry {\n\t\tconst result = spawnSync(\"ldd\", [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5000 });\n\t\toutput = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\t} catch (e: unknown) {\n\t\tconst err = e as { stdout?: string | Buffer; stderr?: string | Buffer };\n\t\toutput = `${String(err.stdout ?? \"\")}${String(err.stderr ?? \"\")}`;\n\t}\n\treturn output.toLowerCase().includes(\"musl\") ? \"musl\" : \"glibc\";\n}\n\nfunction getFffPlatformPackageName(): string | undefined {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tif (plat === \"linux\") {\n\t\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}/${detectLinuxLibc()}`];\n\t}\n\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}`];\n}\n\nfunction createManagedFffRequire(): ModuleRequire | undefined {\n\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) return undefined;\n\treturn createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href);\n}\n\nfunction findFffNodeDistEntry(startPath: string): string | undefined {\n\tlet currentDir = dirname(startPath);\n\twhile (currentDir !== dirname(currentDir)) {\n\t\tconst candidate = join(currentDir, \"node_modules\", \"@ff-labs\", \"fff-node\", \"dist\", \"src\", \"index.js\");\n\t\tif (existsSync(candidate)) return candidate;\n\t\tcurrentDir = dirname(currentDir);\n\t}\n\treturn undefined;\n}\n\nfunction loadFffNodeDistEntry(requireFff: ModuleRequire): unknown | undefined {\n\tif (!requireFff.resolve) return undefined;\n\ttry {\n\t\tconst ffiPath = requireFff.resolve(\"ffi-rs\");\n\t\tconst fffEntry = findFffNodeDistEntry(ffiPath);\n\t\treturn fffEntry ? requireFff(fffEntry) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction loadFffNodeWith(requireFff: ModuleRequire): unknown | undefined {\n\ttry {\n\t\treturn requireFff(\"@ff-labs/fff-node\");\n\t} catch {\n\t\treturn loadFffNodeDistEntry(requireFff);\n\t}\n}\n\n/**\n * @param requires Override the resolution candidates, for tests (mirrors\n * fff-search-backend.ts's loadFffModule(requires?)). Whether this resolves\n * depends on the ambient environment -- @ff-labs/fff-node is a real npm\n * dependency (package.json), so moduleRequire succeeds wherever a normal\n * `npm install`/`npm ci` provisioned it (e.g. CI) even though it fails on a\n * dev checkout that never ran that install here (this repo resolves fff-node\n * via the separate managed-dir path instead). A test asserting \"nothing is\n * available\" must pass `[]` here rather than relying on that being true.\n */\nexport function loadAvailableFffNodePackage(requires?: readonly ModuleRequire[]): unknown | undefined {\n\tconst candidates =\n\t\trequires ??\n\t\t[moduleRequire, executableDirRequire, createManagedFffRequire()].filter((candidate): candidate is ModuleRequire =>\n\t\t\tBoolean(candidate),\n\t\t);\n\tfor (const requireFff of candidates) {\n\t\tconst loaded = loadFffNodeWith(requireFff);\n\t\tif (loaded) return loaded;\n\t}\n\treturn undefined;\n}\n\nasync function runNpmInstall(args: string[]): Promise<{ code: number | null; stderr: string }> {\n\ttry {\n\t\tconst child = spawnProcess(\"npm\", args, {\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet stderr = \"\";\n\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\tstderr = `${stderr}${chunk.toString()}`.slice(-64 * 1024);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\ttimeoutMs: ARCHIVE_EXTRACTION_TIMEOUT_MS,\n\t\t\tkillGraceMs: 2_000,\n\t\t});\n\t\tif (terminal.reason === \"timeout\") {\n\t\t\tstderr = `${stderr}\\nnpm install timed out after ${ARCHIVE_EXTRACTION_TIMEOUT_MS}ms`.trim();\n\t\t}\n\t\treturn { code: terminal.code, stderr };\n\t} catch (error) {\n\t\treturn { code: 1, stderr: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Outcome of the most recent {@link ensureFffNodePackage} call, kept for\n * observability (e.g. a future `doctor` check) since the function itself\n * only ever returns the loaded module or `undefined` either way.\n *\n * `install-failed` is distinguished from `offline`/`unsupported-platform`\n * because it is the only one worth *retrying*: offline mode and an\n * unsupported platform are stable for the life of the process, but a real\n * install attempt can fail on a transient issue (registry hiccup, timeout)\n * that may no longer apply on the next search. See\n * DefaultFffSearchBackend.getFinder in fff-search-backend.ts, which uses\n * this distinction to decide whether a failed finder is retryable.\n */\nexport type FffInstallOutcome =\n\t| { status: \"already-available\" }\n\t| { status: \"offline\" }\n\t| { status: \"unsupported-platform\" }\n\t| { status: \"installed\" }\n\t| { status: \"install-failed\"; reason: string };\n\n/**\n * How long a genuine install failure gates out a NEW npm spawn. An agent turn\n * can fire several find/grep calls in quick succession, and each one now\n * primes the finder in the background (see tryFffFind/tryFffGrep) -- without\n * this, a persistently-failing install (registry down, disk full, ...) would\n * re-spawn npm on every single one of those calls instead of once.\n *\n * This gates the SPAWN inside ensureFffNodePackage, not whether a failed\n * finder is retryable (see isFffInstallRetryable): DefaultFffSearchBackend\n * always evicts a failed finder so the next search re-enters this function,\n * and it is THIS cooldown check -- evaluated fresh, at call time -- that\n * decides whether that re-entry is a real attempt or a fast, spawn-free bail.\n * (An earlier version conflated the two: it gated eviction itself on the\n * cooldown, which is checked once, immediately after the failure it's timing\n * -- i.e. always still within the window -- so the failed finder was never\n * evicted and the retry never got a chance to happen at all.)\n */\nexport const FFF_INSTALL_RETRY_COOLDOWN_MS = 30_000;\n\nlet lastFffInstallOutcome: FffInstallOutcome | undefined;\nlet lastFffInstallFailureAt: number | undefined;\n\n/** The outcome of the last {@link ensureFffNodePackage} call, if any. */\nexport function getLastFffInstallOutcome(): FffInstallOutcome | undefined {\n\treturn lastFffInstallOutcome;\n}\n\n/** Whether the last install outcome was a genuine failure worth retrying (as opposed to a stable \"not applicable\" result). Cooldown-independent by design -- see FFF_INSTALL_RETRY_COOLDOWN_MS. */\nexport function isFffInstallRetryable(): boolean {\n\treturn lastFffInstallOutcome?.status === \"install-failed\";\n}\n\n/**\n * Pure decision logic behind {@link isFffInstallCoolingDown}, exposed directly\n * so tests can assert the cooldown boundary without faking the system clock.\n */\nexport function computeIsFffInstallCoolingDown(\n\toutcome: FffInstallOutcome | undefined,\n\tfailedAt: number | undefined,\n\tnow: number,\n): boolean {\n\tif (outcome?.status !== \"install-failed\") return false;\n\tif (failedAt === undefined) return false;\n\treturn now - failedAt < FFF_INSTALL_RETRY_COOLDOWN_MS;\n}\n\n/** Whether a real install attempt happened too recently to try again right now. */\nfunction isFffInstallCoolingDown(): boolean {\n\treturn computeIsFffInstallCoolingDown(lastFffInstallOutcome, lastFffInstallFailureAt, Date.now());\n}\n\n/** Records a genuine install failure and stamps when it happened, so the cooldown above has a start time to measure from. */\nfunction recordFffInstallFailure(reason: string): void {\n\tlastFffInstallOutcome = { status: \"install-failed\", reason };\n\tlastFffInstallFailureAt = Date.now();\n}\n\nasync function installManagedFffNodePackage(platformPackage: string, silent: boolean): Promise<unknown | undefined> {\n\ttry {\n\t\tmkdirSync(FFF_MANAGED_DIR, { recursive: true });\n\t\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) {\n\t\t\twriteFileSync(FFF_MANAGED_PACKAGE_JSON, '{\"name\":\"pi-managed-fff-node\",\"private\":true,\"version\":\"0.0.0\"}\\n');\n\t\t}\n\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(\"FFF native search not found. Installing managed FFF package...\"));\n\t\t}\n\n\t\tconst args = [\n\t\t\t\"install\",\n\t\t\t\"--ignore-scripts\",\n\t\t\t\"--omit=dev\",\n\t\t\t\"--include=optional\",\n\t\t\t\"--no-audit\",\n\t\t\t\"--no-fund\",\n\t\t\t\"--package-lock=false\",\n\t\t\t\"--prefix\",\n\t\t\tFFF_MANAGED_DIR,\n\t\t\t`@ff-labs/fff-node@${FFF_NODE_VERSION}`,\n\t\t\t`${platformPackage}@${FFF_NODE_VERSION}`,\n\t\t];\n\t\tconst result = await runNpmInstall(args);\n\t\tif (result.code !== 0) {\n\t\t\tconst reason = result.stderr.trim() || `npm exited with code ${result.code}`;\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst loaded = loadFffNodeWith(createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href));\n\t\tif (!loaded) {\n\t\t\tconst reason = \"Managed FFF install completed but @ff-labs/fff-node could not be loaded.\";\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(reason));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"installed\" };\n\t\treturn loaded;\n\t} catch (error) {\n\t\t// Never let a filesystem/spawn surprise (e.g. a read-only home directory)\n\t\t// crash the caller: fall back like any other install failure, but keep\n\t\t// the reason observable.\n\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t}\n\t\trecordFffInstallFailure(reason);\n\t\treturn undefined;\n\t}\n}\n\nexport async function ensureFffNodePackage(\n\tsilent: boolean = false,\n\tforceManagedInstall: boolean = false,\n\t/** Override the \"is it already available\" resolution candidates, for tests. See loadAvailableFffNodePackage's doc. */\n\trequires?: readonly ModuleRequire[],\n): Promise<unknown | undefined> {\n\tconst existing = forceManagedInstall ? undefined : loadAvailableFffNodePackage(requires);\n\tif (existing) {\n\t\tlastFffInstallOutcome = { status: \"already-available\" };\n\t\treturn existing;\n\t}\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(\"FFF native search not found. Offline mode enabled, skipping install.\"));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"offline\" };\n\t\treturn undefined;\n\t}\n\n\t// A prior attempt failed too recently to try again: bail out fast (no npm\n\t// spawn, no platform/libc probing) rather than repeating a doomed attempt.\n\t// Leaves lastFffInstallOutcome/lastFffInstallFailureAt untouched -- this\n\t// isn't a new attempt, so there's nothing new to record.\n\tif (isFffInstallCoolingDown()) {\n\t\treturn undefined;\n\t}\n\n\tconst platformPackage = getFffPlatformPackageName();\n\tif (!platformPackage) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`FFF native search is not available for ${platform()}/${arch()}.`));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"unsupported-platform\" };\n\t\treturn undefined;\n\t}\n\n\tfffNodeInstallPromise ??= installManagedFffNodePackage(platformPackage, silent).finally(() => {\n\t\tfffNodeInstallPromise = undefined;\n\t});\n\treturn fffNodeInstallPromise;\n}\n\nasync function installTermuxManagedTool(tool: ManagedToolName, silent: boolean): Promise<string | undefined> {\n\tconst packageName = TERMUX_PACKAGES[tool];\n\tif (!silent) console.log(chalk.dim(`${TOOLS[tool].name} not found. Installing with Termux pkg...`));\n\tconst child = spawnProcess(\"pkg\", [\"install\", \"-y\", packageName], {\n\t\tenv: process.env,\n\t\tstdio: silent ? \"ignore\" : \"inherit\",\n\t});\n\tconst terminal = await waitForChildProcessWithTermination(child, { timeoutMs: 300_000, killGraceMs: 5_000 });\n\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\tthrow new Error(\n\t\t\t`pkg install ${packageName} ${terminal.reason === \"timeout\" ? \"timed out\" : `exited with code ${terminal.code ?? 1}`}`,\n\t\t);\n\t}\n\treturn getToolPath(tool) ?? undefined;\n}\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or undefined if unavailable\nexport async function ensureTool(tool: ManagedToolName, silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, upstream Linux archives target glibc/musl rather than Bionic.\n\t// uv is a required managed runtime and the user explicitly authorized provisioning it;\n\t// preserve guide-only behavior for optional search tools.\n\tif (platform() === \"android\") {\n\t\tif (tool !== \"uv\") {\n\t\t\tconst packageName = TERMUX_PACKAGES[tool];\n\t\t\tif (!silent) console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${packageName}`));\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn await runExclusiveToolDownload(tool, () => installTermuxManagedTool(tool, silent));\n\t\t} catch (error) {\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`Failed to install ${config.name}: ${error instanceof Error ? error.message : error}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await runExclusiveToolDownload(tool, () => downloadTool(tool));\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"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G;AACH,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,GAAG,EAAE,MAAM,GACT,OAAO,CAIT;AAsED,wBAAsB,oBAAoB,CACzC,MAAM,GAAE,OAAe,EACvB,mBAAmB,GAAE,OAAe;AACpC,sHAAsH;AACtH,QAAQ,CAAC,EAAE,SAAS,aAAa,EAAE,GACjC,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAoC9B;AAoBD,wBAAsB,UAAU,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAsD5G","sourcesContent":["import { createHash } from \"node:crypto\";\nimport chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport {\n\taccessSync,\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tconstants as fsConstants,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { createRequire } from \"module\";\nimport { arch, platform } from \"os\";\nimport { dirname, join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { pathToFileURL } from \"url\";\nimport { APP_NAME, getAgentDir, getBinDir } from \"../config.ts\";\nimport { cacheDir as agentCacheDir, cacheFile } from \"../core/agent-paths.ts\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\nconst COMMAND_PROBE_TIMEOUT_MS = 5_000;\nconst ARCHIVE_EXTRACTION_TIMEOUT_MS = 5 * 60_000;\nconst FFF_NODE_VERSION = \"0.9.6\";\nexport const UV_VERSION = \"0.11.28\";\nconst FFF_MANAGED_DIR = join(TOOLS_DIR, \"fff-node\");\nconst FFF_MANAGED_PACKAGE_JSON = join(FFF_MANAGED_DIR, \"package.json\");\n\ntype ModuleRequire = ((id: string) => unknown) & { resolve?: (id: string) => string };\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\tpinnedVersion?: string;\n\tsha256ByAsset?: Readonly<Record<string, string>>;\n}\n\nconst TOOLS: Record<\"fd\" | \"rg\" | \"uv\", ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\tuv: {\n\t\tname: \"uv\",\n\t\trepo: \"astral-sh/uv\",\n\t\tbinaryName: \"uv\",\n\t\tsystemBinaryNames: [\"uv\"],\n\t\ttagPrefix: \"\",\n\t\tpinnedVersion: UV_VERSION,\n\t\tgetAssetName: (_version, plat, architecture) => {\n\t\t\tif (architecture !== \"arm64\" && architecture !== \"x64\") return null;\n\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\tif (plat === \"darwin\") return `uv-${archStr}-apple-darwin.tar.gz`;\n\t\t\tif (plat === \"linux\") return `uv-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\tif (plat === \"win32\") return `uv-${archStr}-pc-windows-msvc.zip`;\n\t\t\treturn null;\n\t\t},\n\t\tsha256ByAsset: {\n\t\t\t\"uv-aarch64-apple-darwin.tar.gz\": \"33540eb7c883ab857eff79bd5ac2aa31fe27b595abecb4a9c003a2c998447232\",\n\t\t\t\"uv-aarch64-pc-windows-msvc.zip\": \"3248109afad3ec59baad299d324ff53de17e2d9a3b3e21580ffd26744b11e036\",\n\t\t\t\"uv-aarch64-unknown-linux-musl.tar.gz\": \"da10cdfa7d92212b7acb62021a0fd61bcf8580c58c3632ec915d10c3a1a7906b\",\n\t\t\t\"uv-x86_64-apple-darwin.tar.gz\": \"2ad79983127ffca7d77b77ce6a24278d7e4f7b817a1acf72fea5f8124b4aac5e\",\n\t\t\t\"uv-x86_64-pc-windows-msvc.zip\": \"0a23463216d09c6a72ff80ef5dc5a795f07dc1575cb84d24596c2f124a441b7b\",\n\t\t\t\"uv-x86_64-unknown-linux-musl.tar.gz\": \"f02146b371c35c287d860f003ece7345c86e358a3fd70a9b63700cd141ee7fb4\",\n\t\t},\n\t},\n};\n\nexport type ManagedToolName = keyof typeof TOOLS;\n\nexport interface PinnedToolAsset {\n\tversion: string;\n\tassetName: string;\n\texpectedSha256: string;\n}\n\nexport function getPinnedToolAsset(\n\ttool: ManagedToolName,\n\ttargetPlatform: string = platform(),\n\ttargetArchitecture: string = arch(),\n): PinnedToolAsset | null {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config.pinnedVersion || !config.sha256ByAsset) return null;\n\tconst assetName = config.getAssetName(config.pinnedVersion, targetPlatform, targetArchitecture);\n\tif (!assetName) return null;\n\tconst expectedSha256 = config.sha256ByAsset[assetName];\n\treturn expectedSha256 ? { version: config.pinnedVersion, assetName, expectedSha256 } : null;\n}\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\", timeout: COMMAND_PROBE_TIMEOUT_MS });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ninterface CachedToolPath {\n\tpath: string;\n\tmtimeMs: number;\n}\n\nfunction isCachedToolPath(value: unknown): value is CachedToolPath {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn typeof candidate.path === \"string\" && typeof candidate.mtimeMs === \"number\";\n}\n\nfunction getToolPathCacheFile(): string {\n\treturn cacheFile(getAgentDir(), \"tool-paths.json\");\n}\n\n/** Read the persisted cross-run tool-path cache. Missing/corrupt/foreign entries are dropped silently -- a cold cache just means the next resolve re-probes and repopulates it. */\nfunction readToolPathCache(): Partial<Record<ManagedToolName, CachedToolPath>> {\n\ttry {\n\t\tconst raw = readFileSync(getToolPathCacheFile(), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as Record<string, unknown>;\n\t\tconst cache: Partial<Record<ManagedToolName, CachedToolPath>> = {};\n\t\tfor (const tool of Object.keys(TOOLS) as ManagedToolName[]) {\n\t\t\tconst entry = parsed[tool];\n\t\t\tif (isCachedToolPath(entry)) cache[tool] = entry;\n\t\t}\n\t\treturn cache;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction writeToolPathCacheEntry(tool: ManagedToolName, entry: CachedToolPath): void {\n\ttry {\n\t\tconst cacheDir = agentCacheDir(getAgentDir());\n\t\tmkdirSync(cacheDir, { recursive: true });\n\t\tconst cache = readToolPathCache();\n\t\tcache[tool] = entry;\n\t\twriteFileSync(join(cacheDir, \"tool-paths.json\"), JSON.stringify(cache));\n\t} catch {\n\t\t// Best-effort: a failed cache write only costs the next run its probe, same as a cold cache.\n\t}\n}\n\n/** A cached entry is fresh only while its file still exists at the same path with the same mtime -- a deleted/moved/replaced binary invalidates it and forces a re-probe below. */\nfunction isCachedToolPathFresh(entry: CachedToolPath): boolean {\n\ttry {\n\t\treturn statSync(entry.path).mtimeMs === entry.mtimeMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getPathExtensionCandidates(): readonly string[] {\n\tif (platform() !== \"win32\") return [\"\"];\n\tconst pathExt = process.env.PATHEXT || \".COM;.EXE;.BAT;.CMD\";\n\treturn [\"\", ...pathExt.split(\";\").filter(Boolean)];\n}\n\n/**\n * Manually walk PATH to turn a bare command name that commandExists() already confirmed is\n * runnable into an absolute, stat-checkable path. This never decides presence itself (that stays\n * commandExists's job via spawnSync, unchanged) -- it only supplies the path the cross-run cache\n * needs for its mtime staleness check, using stat calls instead of another spawn.\n */\nfunction resolveOnSystemPath(binaryName: string): string | null {\n\tconst pathEnv = process.env.PATH ?? \"\";\n\tconst dirs = pathEnv.split(platform() === \"win32\" ? \";\" : \":\").filter(Boolean);\n\tfor (const dir of dirs) {\n\t\tfor (const ext of getPathExtensionCandidates()) {\n\t\t\tconst candidate = join(dir, binaryName + ext);\n\t\t\tif (!existsSync(candidate)) continue;\n\t\t\ttry {\n\t\t\t\tif (statSync(candidate).isDirectory()) continue;\n\t\t\t\tif (platform() !== \"win32\") accessSync(candidate, fsConstants.X_OK);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn candidate;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction cacheResolvedSystemPath(tool: ManagedToolName, resolvedPath: string): void {\n\ttry {\n\t\twriteToolPathCacheEntry(tool, { path: resolvedPath, mtimeMs: statSync(resolvedPath).mtimeMs });\n\t} catch {\n\t\t// Stat raced with a delete between resolve and here: nothing to cache, still return the path below.\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: ManagedToolName): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\n\t// A system-PATH resolution normally requires commandExists's synchronous\n\t// spawnSync(`<name> --version`) probe below, which is expensive to pay on every process\n\t// startup (this runs once per tool at interactive-mode init, plus again on the first\n\t// find/grep tool call). Persist the resolved absolute path + mtime across runs\n\t// (<agentDir>/cache/tool-paths.json) so a warm run can skip the probe entirely and just\n\t// stat the cached path instead. KNOWN LIMITATION: if a *different* binary of the same name\n\t// starts shadowing the cached one earlier on PATH (e.g. a new install) while the\n\t// originally-cached file itself is untouched, this cache keeps returning the old path until\n\t// that file is deleted/modified -- an intentional narrow staleness window (the returned tool\n\t// still exists and runs; it just isn't the newly-shadowing one), not a correctness bug.\n\tconst cached = readToolPathCache()[tool];\n\tif (cached && isCachedToolPathFresh(cached)) {\n\t\treturn cached.path;\n\t}\n\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\tconst resolved = resolveOnSystemPath(systemBinaryName);\n\t\t\tif (resolved) {\n\t\t\t\tcacheResolvedSystemPath(tool, resolved);\n\t\t\t\treturn resolved;\n\t\t\t}\n\t\t\t// Could not resolve an absolute path to cache (e.g. PATH env raced between the two\n\t\t\t// lookups); still return the bare name so the caller keeps working, uncached.\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** Presence check for a SYSTEM tool the doctor only ever reports on -- never installs. */\nexport interface SystemToolStatus {\n\tpresent: boolean;\n\tcommand?: string;\n\tversion?: string;\n}\n\nconst PYTHON_COMMANDS = [\"python3\", \"python\"];\n\n/**\n * Detect a usable Python interpreter. SYSTEM tool (see src/core/doctor.ts):\n * the doctor reports presence/version, it never installs this itself.\n *\n * @param commands Override the candidate command names, for tests.\n */\nexport function detectPython(commands: readonly string[] = PYTHON_COMMANDS): SystemToolStatus {\n\tfor (const command of commands) {\n\t\ttry {\n\t\t\tconst result = spawnSync(command, [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\t\tif (result.error) continue;\n\t\t\t// Python 2 prints its version to stderr; Python 3 prints to stdout. Some\n\t\t\t// platforms' `python` alias is one or the other, so check both.\n\t\t\tconst version = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim() || undefined;\n\t\t\tif (result.status !== 0 && !version) continue;\n\t\t\treturn { present: true, command, version };\n\t\t} catch {\n\t\t\t// Try the next candidate.\n\t\t}\n\t}\n\treturn { present: false };\n}\n\n/**\n * Runs `<command> --version` (or `versionArgs`) and returns its trimmed\n * combined stdout+stderr, or undefined if the command can't be run. Used by\n * the doctor (src/core/doctor.ts) to show a version alongside a tool it has\n * already located by some other means (e.g. getToolPath(\"rg\"), or the binary\n * path OllamaRuntime.detect() reports) -- callers that only need a yes/no\n * presence check should use commandExists/getToolPath/detectPython instead.\n */\nexport function probeVersion(command: string, versionArgs: readonly string[] = [\"--version\"]): string | undefined {\n\ttry {\n\t\tconst result = spawnSync(command, versionArgs, { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5_000 });\n\t\tif (result.error) return undefined;\n\t\tconst output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n\t\treturn output || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nexport async function verifyFileSha256(filePath: string, expectedSha256: string): Promise<boolean> {\n\tconst hash = createHash(\"sha256\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst stream = createReadStream(filePath);\n\t\tstream.on(\"data\", (chunk) => hash.update(chunk));\n\t\tstream.once(\"error\", reject);\n\t\tstream.once(\"end\", resolve);\n\t});\n\treturn hash.digest(\"hex\") === expectedSha256.toLowerCase();\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\", timeout: ARCHIVE_EXTRACTION_TIMEOUT_MS });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nconst toolDownloadPromises = new Map<ManagedToolName, Promise<string | undefined>>();\n\nexport function runExclusiveToolDownload(\n\ttool: ManagedToolName,\n\tinstaller: () => Promise<string | undefined>,\n): Promise<string | undefined> {\n\tconst existing = toolDownloadPromises.get(tool);\n\tif (existing) return existing;\n\tconst promise = installer().finally(() => {\n\t\tif (toolDownloadPromises.get(tool) === promise) {\n\t\t\ttoolDownloadPromises.delete(tool);\n\t\t}\n\t});\n\ttoolDownloadPromises.set(tool, promise);\n\treturn promise;\n}\n\nasync function downloadTool(tool: ManagedToolName): Promise<string> {\n\tconst config: ToolConfig = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned tools are reproducible; legacy search tools retain their current latest-release behavior.\n\tlet version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst downloadWorkDir = getProcessWorkRun(getAgentDir(), \"downloads\", \"tools\").path;\n\tconst archivePath = join(downloadWorkDir, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download and verify pinned artifacts before extraction.\n\tawait downloadFile(downloadUrl, archivePath);\n\tconst expectedSha256 = config.sha256ByAsset?.[assetName];\n\tif (config.sha256ByAsset && !expectedSha256) {\n\t\tthrow new Error(`No pinned SHA-256 is registered for ${assetName}`);\n\t}\n\tif (expectedSha256 && !(await verifyFileSha256(archivePath, expectedSha256))) {\n\t\tthrow new Error(`SHA-256 verification failed for ${assetName}`);\n\t}\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tdownloadWorkDir,\n\t\t`extract-${config.binaryName}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<ManagedToolName, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n\tuv: \"uv\",\n};\n\nconst FFF_PLATFORM_PACKAGES: Record<string, string> = {\n\t\"darwin/arm64\": \"@ff-labs/fff-bin-darwin-arm64\",\n\t\"darwin/x64\": \"@ff-labs/fff-bin-darwin-x64\",\n\t\"linux/arm64/glibc\": \"@ff-labs/fff-bin-linux-arm64-gnu\",\n\t\"linux/arm64/musl\": \"@ff-labs/fff-bin-linux-arm64-musl\",\n\t\"linux/x64/glibc\": \"@ff-labs/fff-bin-linux-x64-gnu\",\n\t\"linux/x64/musl\": \"@ff-labs/fff-bin-linux-x64-musl\",\n\t\"win32/arm64\": \"@ff-labs/fff-bin-win32-arm64\",\n\t\"win32/x64\": \"@ff-labs/fff-bin-win32-x64\",\n};\n\nlet fffNodeInstallPromise: Promise<unknown | undefined> | undefined;\n\nfunction detectLinuxLibc(): \"glibc\" | \"musl\" {\n\tlet output = \"\";\n\ttry {\n\t\tconst result = spawnSync(\"ldd\", [\"--version\"], { encoding: \"utf-8\", stdio: \"pipe\", timeout: 5000 });\n\t\toutput = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n\t} catch (e: unknown) {\n\t\tconst err = e as { stdout?: string | Buffer; stderr?: string | Buffer };\n\t\toutput = `${String(err.stdout ?? \"\")}${String(err.stderr ?? \"\")}`;\n\t}\n\treturn output.toLowerCase().includes(\"musl\") ? \"musl\" : \"glibc\";\n}\n\nfunction getFffPlatformPackageName(): string | undefined {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tif (plat === \"linux\") {\n\t\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}/${detectLinuxLibc()}`];\n\t}\n\treturn FFF_PLATFORM_PACKAGES[`${plat}/${architecture}`];\n}\n\nfunction createManagedFffRequire(): ModuleRequire | undefined {\n\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) return undefined;\n\treturn createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href);\n}\n\nfunction findFffNodeDistEntry(startPath: string): string | undefined {\n\tlet currentDir = dirname(startPath);\n\twhile (currentDir !== dirname(currentDir)) {\n\t\tconst candidate = join(currentDir, \"node_modules\", \"@ff-labs\", \"fff-node\", \"dist\", \"src\", \"index.js\");\n\t\tif (existsSync(candidate)) return candidate;\n\t\tcurrentDir = dirname(currentDir);\n\t}\n\treturn undefined;\n}\n\nfunction loadFffNodeDistEntry(requireFff: ModuleRequire): unknown | undefined {\n\tif (!requireFff.resolve) return undefined;\n\ttry {\n\t\tconst ffiPath = requireFff.resolve(\"ffi-rs\");\n\t\tconst fffEntry = findFffNodeDistEntry(ffiPath);\n\t\treturn fffEntry ? requireFff(fffEntry) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction loadFffNodeWith(requireFff: ModuleRequire): unknown | undefined {\n\ttry {\n\t\treturn requireFff(\"@ff-labs/fff-node\");\n\t} catch {\n\t\treturn loadFffNodeDistEntry(requireFff);\n\t}\n}\n\n/**\n * @param requires Override the resolution candidates, for tests (mirrors\n * fff-search-backend.ts's loadFffModule(requires?)). Whether this resolves\n * depends on the ambient environment -- @ff-labs/fff-node is a real npm\n * dependency (package.json), so moduleRequire succeeds wherever a normal\n * `npm install`/`npm ci` provisioned it (e.g. CI) even though it fails on a\n * dev checkout that never ran that install here (this repo resolves fff-node\n * via the separate managed-dir path instead). A test asserting \"nothing is\n * available\" must pass `[]` here rather than relying on that being true.\n */\nexport function loadAvailableFffNodePackage(requires?: readonly ModuleRequire[]): unknown | undefined {\n\tconst candidates =\n\t\trequires ??\n\t\t[moduleRequire, executableDirRequire, createManagedFffRequire()].filter((candidate): candidate is ModuleRequire =>\n\t\t\tBoolean(candidate),\n\t\t);\n\tfor (const requireFff of candidates) {\n\t\tconst loaded = loadFffNodeWith(requireFff);\n\t\tif (loaded) return loaded;\n\t}\n\treturn undefined;\n}\n\nasync function runNpmInstall(args: string[]): Promise<{ code: number | null; stderr: string }> {\n\ttry {\n\t\tconst child = spawnProcess(\"npm\", args, {\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet stderr = \"\";\n\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\tstderr = `${stderr}${chunk.toString()}`.slice(-64 * 1024);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\ttimeoutMs: ARCHIVE_EXTRACTION_TIMEOUT_MS,\n\t\t\tkillGraceMs: 2_000,\n\t\t});\n\t\tif (terminal.reason === \"timeout\") {\n\t\t\tstderr = `${stderr}\\nnpm install timed out after ${ARCHIVE_EXTRACTION_TIMEOUT_MS}ms`.trim();\n\t\t}\n\t\treturn { code: terminal.code, stderr };\n\t} catch (error) {\n\t\treturn { code: 1, stderr: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\n/**\n * Outcome of the most recent {@link ensureFffNodePackage} call, kept for\n * observability (e.g. a future `doctor` check) since the function itself\n * only ever returns the loaded module or `undefined` either way.\n *\n * `install-failed` is distinguished from `offline`/`unsupported-platform`\n * because it is the only one worth *retrying*: offline mode and an\n * unsupported platform are stable for the life of the process, but a real\n * install attempt can fail on a transient issue (registry hiccup, timeout)\n * that may no longer apply on the next search. See\n * DefaultFffSearchBackend.getFinder in fff-search-backend.ts, which uses\n * this distinction to decide whether a failed finder is retryable.\n */\nexport type FffInstallOutcome =\n\t| { status: \"already-available\" }\n\t| { status: \"offline\" }\n\t| { status: \"unsupported-platform\" }\n\t| { status: \"installed\" }\n\t| { status: \"install-failed\"; reason: string };\n\n/**\n * How long a genuine install failure gates out a NEW npm spawn. An agent turn\n * can fire several find/grep calls in quick succession, and each one now\n * primes the finder in the background (see tryFffFind/tryFffGrep) -- without\n * this, a persistently-failing install (registry down, disk full, ...) would\n * re-spawn npm on every single one of those calls instead of once.\n *\n * This gates the SPAWN inside ensureFffNodePackage, not whether a failed\n * finder is retryable (see isFffInstallRetryable): DefaultFffSearchBackend\n * always evicts a failed finder so the next search re-enters this function,\n * and it is THIS cooldown check -- evaluated fresh, at call time -- that\n * decides whether that re-entry is a real attempt or a fast, spawn-free bail.\n * (An earlier version conflated the two: it gated eviction itself on the\n * cooldown, which is checked once, immediately after the failure it's timing\n * -- i.e. always still within the window -- so the failed finder was never\n * evicted and the retry never got a chance to happen at all.)\n */\nexport const FFF_INSTALL_RETRY_COOLDOWN_MS = 30_000;\n\nlet lastFffInstallOutcome: FffInstallOutcome | undefined;\nlet lastFffInstallFailureAt: number | undefined;\n\n/** The outcome of the last {@link ensureFffNodePackage} call, if any. */\nexport function getLastFffInstallOutcome(): FffInstallOutcome | undefined {\n\treturn lastFffInstallOutcome;\n}\n\n/** Whether the last install outcome was a genuine failure worth retrying (as opposed to a stable \"not applicable\" result). Cooldown-independent by design -- see FFF_INSTALL_RETRY_COOLDOWN_MS. */\nexport function isFffInstallRetryable(): boolean {\n\treturn lastFffInstallOutcome?.status === \"install-failed\";\n}\n\n/**\n * Pure decision logic behind {@link isFffInstallCoolingDown}, exposed directly\n * so tests can assert the cooldown boundary without faking the system clock.\n */\nexport function computeIsFffInstallCoolingDown(\n\toutcome: FffInstallOutcome | undefined,\n\tfailedAt: number | undefined,\n\tnow: number,\n): boolean {\n\tif (outcome?.status !== \"install-failed\") return false;\n\tif (failedAt === undefined) return false;\n\treturn now - failedAt < FFF_INSTALL_RETRY_COOLDOWN_MS;\n}\n\n/** Whether a real install attempt happened too recently to try again right now. */\nfunction isFffInstallCoolingDown(): boolean {\n\treturn computeIsFffInstallCoolingDown(lastFffInstallOutcome, lastFffInstallFailureAt, Date.now());\n}\n\n/** Records a genuine install failure and stamps when it happened, so the cooldown above has a start time to measure from. */\nfunction recordFffInstallFailure(reason: string): void {\n\tlastFffInstallOutcome = { status: \"install-failed\", reason };\n\tlastFffInstallFailureAt = Date.now();\n}\n\nasync function installManagedFffNodePackage(platformPackage: string, silent: boolean): Promise<unknown | undefined> {\n\ttry {\n\t\tmkdirSync(FFF_MANAGED_DIR, { recursive: true });\n\t\tif (!existsSync(FFF_MANAGED_PACKAGE_JSON)) {\n\t\t\twriteFileSync(FFF_MANAGED_PACKAGE_JSON, '{\"name\":\"pi-managed-fff-node\",\"private\":true,\"version\":\"0.0.0\"}\\n');\n\t\t}\n\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(\"FFF native search not found. Installing managed FFF package...\"));\n\t\t}\n\n\t\tconst args = [\n\t\t\t\"install\",\n\t\t\t\"--ignore-scripts\",\n\t\t\t\"--omit=dev\",\n\t\t\t\"--include=optional\",\n\t\t\t\"--no-audit\",\n\t\t\t\"--no-fund\",\n\t\t\t\"--package-lock=false\",\n\t\t\t\"--prefix\",\n\t\t\tFFF_MANAGED_DIR,\n\t\t\t`@ff-labs/fff-node@${FFF_NODE_VERSION}`,\n\t\t\t`${platformPackage}@${FFF_NODE_VERSION}`,\n\t\t];\n\t\tconst result = await runNpmInstall(args);\n\t\tif (result.code !== 0) {\n\t\t\tconst reason = result.stderr.trim() || `npm exited with code ${result.code}`;\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst loaded = loadFffNodeWith(createRequire(pathToFileURL(FFF_MANAGED_PACKAGE_JSON).href));\n\t\tif (!loaded) {\n\t\t\tconst reason = \"Managed FFF install completed but @ff-labs/fff-node could not be loaded.\";\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(chalk.yellow(reason));\n\t\t\t}\n\t\t\trecordFffInstallFailure(reason);\n\t\t\treturn undefined;\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"installed\" };\n\t\treturn loaded;\n\t} catch (error) {\n\t\t// Never let a filesystem/spawn surprise (e.g. a read-only home directory)\n\t\t// crash the caller: fall back like any other install failure, but keep\n\t\t// the reason observable.\n\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to install FFF native search: ${reason}`));\n\t\t}\n\t\trecordFffInstallFailure(reason);\n\t\treturn undefined;\n\t}\n}\n\nexport async function ensureFffNodePackage(\n\tsilent: boolean = false,\n\tforceManagedInstall: boolean = false,\n\t/** Override the \"is it already available\" resolution candidates, for tests. See loadAvailableFffNodePackage's doc. */\n\trequires?: readonly ModuleRequire[],\n): Promise<unknown | undefined> {\n\tconst existing = forceManagedInstall ? undefined : loadAvailableFffNodePackage(requires);\n\tif (existing) {\n\t\tlastFffInstallOutcome = { status: \"already-available\" };\n\t\treturn existing;\n\t}\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(\"FFF native search not found. Offline mode enabled, skipping install.\"));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"offline\" };\n\t\treturn undefined;\n\t}\n\n\t// A prior attempt failed too recently to try again: bail out fast (no npm\n\t// spawn, no platform/libc probing) rather than repeating a doomed attempt.\n\t// Leaves lastFffInstallOutcome/lastFffInstallFailureAt untouched -- this\n\t// isn't a new attempt, so there's nothing new to record.\n\tif (isFffInstallCoolingDown()) {\n\t\treturn undefined;\n\t}\n\n\tconst platformPackage = getFffPlatformPackageName();\n\tif (!platformPackage) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`FFF native search is not available for ${platform()}/${arch()}.`));\n\t\t}\n\t\tlastFffInstallOutcome = { status: \"unsupported-platform\" };\n\t\treturn undefined;\n\t}\n\n\tfffNodeInstallPromise ??= installManagedFffNodePackage(platformPackage, silent).finally(() => {\n\t\tfffNodeInstallPromise = undefined;\n\t});\n\treturn fffNodeInstallPromise;\n}\n\nasync function installTermuxManagedTool(tool: ManagedToolName, silent: boolean): Promise<string | undefined> {\n\tconst packageName = TERMUX_PACKAGES[tool];\n\tif (!silent) console.log(chalk.dim(`${TOOLS[tool].name} not found. Installing with Termux pkg...`));\n\tconst child = spawnProcess(\"pkg\", [\"install\", \"-y\", packageName], {\n\t\tenv: process.env,\n\t\tstdio: silent ? \"ignore\" : \"inherit\",\n\t});\n\tconst terminal = await waitForChildProcessWithTermination(child, { timeoutMs: 300_000, killGraceMs: 5_000 });\n\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\tthrow new Error(\n\t\t\t`pkg install ${packageName} ${terminal.reason === \"timeout\" ? \"timed out\" : `exited with code ${terminal.code ?? 1}`}`,\n\t\t);\n\t}\n\treturn getToolPath(tool) ?? undefined;\n}\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or undefined if unavailable\nexport async function ensureTool(tool: ManagedToolName, silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, upstream Linux archives target glibc/musl rather than Bionic.\n\t// uv is a required managed runtime and the user explicitly authorized provisioning it;\n\t// preserve guide-only behavior for optional search tools.\n\tif (platform() === \"android\") {\n\t\tif (tool !== \"uv\") {\n\t\t\tconst packageName = TERMUX_PACKAGES[tool];\n\t\t\tif (!silent) console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${packageName}`));\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn await runExclusiveToolDownload(tool, () => installTermuxManagedTool(tool, silent));\n\t\t} catch (error) {\n\t\t\tif (!silent) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.yellow(`Failed to install ${config.name}: ${error instanceof Error ? error.message : error}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await runExclusiveToolDownload(tool, () => downloadTool(tool));\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}