pi-agent-ide 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (342) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +81 -23
  3. package/assets/gallery/apply-editing.png +0 -0
  4. package/assets/gallery/debugging.png +0 -0
  5. package/assets/gallery/read-web.png +0 -0
  6. package/assets/gallery/search-replace.png +0 -0
  7. package/assets/gallery/terminal.png +0 -0
  8. package/assets/gallery/tool-editing.png +0 -0
  9. package/dist/chunk-22CLOM2D.js +1 -0
  10. package/dist/{chunk-LY6U5EAD.js → chunk-2527OQ4Y.js} +1 -1
  11. package/dist/chunk-3XJ3KDPZ.js +16 -0
  12. package/dist/chunk-5JELU6RV.js +7 -0
  13. package/dist/chunk-DDKHZZDO.js +5 -0
  14. package/dist/chunk-FEDVTZJG.js +1 -0
  15. package/dist/chunk-HSM6R7IB.js +27 -0
  16. package/dist/chunk-K5G4FDXD.js +1 -0
  17. package/dist/chunk-M5IVSCR2.js +1 -0
  18. package/dist/chunk-OYWIZII6.js +1 -0
  19. package/dist/chunk-P7XO5CIP.js +2 -0
  20. package/dist/chunk-PCZH7GOX.js +26 -0
  21. package/dist/{chunk-DQXPQOF7.js → chunk-SQ7ZTGOP.js} +1 -1
  22. package/dist/entry-10.js +1 -1
  23. package/dist/entry-11.js +1 -1
  24. package/dist/entry-12.js +1 -1
  25. package/dist/entry-13.js +1 -1
  26. package/dist/entry-14.js +1 -1
  27. package/dist/entry-15.js +1 -1
  28. package/dist/entry-16.js +1 -0
  29. package/dist/entry-18.js +1 -1
  30. package/dist/entry-19.js +1 -1
  31. package/dist/entry-20.js +1 -1
  32. package/dist/entry-21.js +1 -1
  33. package/dist/entry-22.js +1 -2
  34. package/dist/entry-23.js +2 -1
  35. package/dist/entry-24.js +1 -1
  36. package/dist/entry-25.js +1 -1
  37. package/dist/entry-26.js +1 -1
  38. package/dist/entry-27.js +1 -12
  39. package/dist/entry-28.js +12 -1
  40. package/dist/entry-29.js +1 -1
  41. package/dist/entry-30.js +1 -1
  42. package/dist/entry-31.js +1 -1
  43. package/dist/entry-32.js +1 -4
  44. package/dist/entry-33.js +3 -8
  45. package/dist/entry-34.js +9 -1
  46. package/dist/entry-35.js +1 -1
  47. package/dist/entry-36.js +1 -1
  48. package/dist/entry-37.js +1 -1
  49. package/dist/entry-38.js +1 -1
  50. package/dist/entry-39.js +1 -1
  51. package/dist/entry-40.js +1 -1
  52. package/dist/entry-41.js +1 -18
  53. package/dist/entry-42.js +18 -1
  54. package/dist/entry-43.js +1 -1
  55. package/dist/entry-44.js +1 -1
  56. package/dist/entry-45.js +1 -1
  57. package/dist/entry-46.js +1 -7
  58. package/dist/entry-47.js +7 -11
  59. package/dist/entry-48.js +11 -1
  60. package/dist/entry-49.js +1 -1
  61. package/dist/entry-50.js +1 -1
  62. package/dist/entry-51.js +1 -1
  63. package/dist/entry-52.js +1 -1
  64. package/dist/entry-53.js +1 -1
  65. package/dist/entry-54.js +1 -1
  66. package/dist/entry-55.js +1 -1
  67. package/dist/entry-56.js +1 -0
  68. package/dist/entry-57.js +0 -1
  69. package/dist/entry-58.js +1 -0
  70. package/dist/entry-59.js +0 -1
  71. package/dist/entry-60.js +1 -1
  72. package/dist/entry-61.js +1 -1
  73. package/dist/entry-62.js +1 -1
  74. package/dist/entry-63.js +1 -1
  75. package/dist/entry-64.js +1 -1
  76. package/dist/entry-65.js +1 -0
  77. package/dist/entry-66.js +0 -1
  78. package/dist/entry-67.js +1 -0
  79. package/dist/entry-68.js +0 -1
  80. package/dist/entry-69.js +1 -1
  81. package/dist/entry-70.js +1 -1
  82. package/dist/entry-71.js +1 -203
  83. package/dist/entry-72.js +254 -25
  84. package/dist/entry-73.js +30 -2
  85. package/dist/entry-74.js +2 -1
  86. package/dist/entry-75.js +1 -1
  87. package/dist/entry-76.js +1 -1
  88. package/dist/entry-77.js +3 -3
  89. package/dist/entry-78.js +3 -1
  90. package/dist/entry-79.js +1 -1
  91. package/dist/entry-80.js +1 -1
  92. package/dist/entry-81.js +1 -0
  93. package/dist/pi-agent-ide.js +3 -3
  94. package/docs/configuration.md +3 -1
  95. package/docs/development.md +0 -6
  96. package/docs/tools.md +12 -0
  97. package/node_modules/pi-agent-doctor/package.json +6 -6
  98. package/node_modules/pi-agent-doctor/runtime/entry-22.js +1 -0
  99. package/node_modules/pi-agent-filesystem/package.json +7 -7
  100. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  101. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  102. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  103. package/node_modules/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  104. package/node_modules/pi-agent-ide-ast/package.json +12 -11
  105. package/node_modules/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  106. package/node_modules/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  107. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  108. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  109. package/node_modules/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  110. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  111. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  112. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  113. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +3 -1
  114. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  115. package/node_modules/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  116. package/node_modules/pi-agent-image/package.json +3 -3
  117. package/node_modules/pi-agent-invariant/package.json +2 -2
  118. package/node_modules/pi-agent-pdf/package.json +3 -3
  119. package/node_modules/pi-agent-read/package.json +11 -11
  120. package/node_modules/pi-agent-read/runtime/entry-41.js +0 -1
  121. package/node_modules/pi-agent-read/runtime/entry-42.js +2 -0
  122. package/node_modules/pi-agent-read/src/api/read-parameters.ts +2 -2
  123. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  124. package/node_modules/pi-agent-resource/package.json +2 -2
  125. package/node_modules/pi-agent-search/package.json +7 -7
  126. package/node_modules/pi-agent-search/runtime/entry-46.js +0 -1
  127. package/node_modules/pi-agent-search-text/package.json +9 -9
  128. package/node_modules/pi-agent-search-text/runtime/entry-48.js +1 -0
  129. package/node_modules/pi-agent-search-text/src/resolvers.ts +32 -27
  130. package/node_modules/pi-agent-search-text/src/search-session.ts +27 -1
  131. package/node_modules/pi-agent-text/package.json +3 -3
  132. package/node_modules/pi-agent-text/runtime/entry-50.js +1 -0
  133. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  134. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  135. package/node_modules/pi-agent-text-anchor-exact/index.ts +3 -3
  136. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  137. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  138. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  139. package/node_modules/pi-agent-text-anchor-exact/src/config.ts +2 -2
  140. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  141. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  142. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  143. package/node_modules/pi-agent-text-editor/package.json +25 -25
  144. package/node_modules/pi-agent-text-editor/runtime/entry-71.js +0 -1
  145. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  146. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  147. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  148. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  149. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  150. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  151. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  152. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  153. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  154. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  155. package/node_modules/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  156. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  157. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  158. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  159. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  160. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  161. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  162. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  163. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  164. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  165. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  166. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  167. package/node_modules/pi-agent-tool-ui/runtime/entry-76.js +1 -0
  168. package/node_modules/pi-agent-web/package.json +7 -7
  169. package/node_modules/pi-agent-web/src/resolver.ts +128 -1
  170. package/node_modules/pi-agent-web-html/package.json +3 -3
  171. package/node_modules/pi-agent-web-image/package.json +4 -4
  172. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  173. package/node_modules/pi-agent-web-text/package.json +4 -4
  174. package/node_modules/pi-agent-web-text/runtime/entry-81.js +2 -0
  175. package/package.json +44 -39
  176. package/src/api/path-identity.ts +15 -0
  177. package/src/composite/builtin-extensions.ts +7 -2
  178. package/src/composite/module-labels.ts +4 -0
  179. package/src/composite/module-settings.ts +34 -14
  180. package/src/composite/preferences.ts +46 -3
  181. package/src/composite/selection.ts +5 -1
  182. package/src/doctor/inventory.ts +7 -2
  183. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  185. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  186. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  187. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  188. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-23.js +2 -0
  189. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  190. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  191. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  192. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  193. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  194. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-81.js +2 -0
  195. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-77.js +2 -0
  196. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +128 -1
  197. package/src/extensions/pi-agent-read/package.json +11 -11
  198. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  199. package/src/extensions/pi-agent-read/runtime/entry-42.js +2 -0
  200. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
  201. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  202. package/src/extensions/pi-agent-search/package.json +7 -7
  203. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  204. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-48.js +1 -0
  205. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-49.js +1 -0
  206. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +32 -27
  207. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +27 -1
  208. package/src/extensions/pi-agent-search/runtime/entry-46.js +0 -1
  209. package/src/extensions/pi-agent-search/runtime/entry-47.js +2 -0
  210. package/src/extensions/pi-agent-text-editor/package.json +25 -25
  211. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  212. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  213. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +3 -3
  214. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  215. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  216. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  217. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/config.ts +2 -2
  218. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  219. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  220. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  221. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  222. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  223. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  224. package/src/extensions/pi-agent-text-editor/runtime/entry-71.js +0 -1
  225. package/src/extensions/pi-agent-text-editor/runtime/entry-72.js +2 -0
  226. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  227. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  228. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  229. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  230. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  231. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  232. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  233. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  234. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  235. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  236. package/src/extensions/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  237. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  238. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  239. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  240. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  241. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  242. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  243. package/src/pi-agent-ide.ts +15 -2
  244. package/src/plugins/pi-agent-ide-ast/package.json +12 -11
  245. package/src/plugins/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  246. package/src/plugins/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  247. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  248. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  249. package/src/plugins/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  250. package/src/plugins/pi-agent-ide-debugger/index.ts +3 -9
  251. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +31 -0
  252. package/src/plugins/pi-agent-ide-debugger/src/breakpoint-view.ts +3 -1
  253. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +24 -23
  254. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -2
  255. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +55 -17
  256. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -22
  257. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  258. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  259. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  260. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +3 -1
  261. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  262. package/src/plugins/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  263. package/src/plugins/pi-agent-ide-processes/src/registry.ts +6 -0
  264. package/src/plugins/pi-agent-ide-processes/src/ui.ts +28 -11
  265. package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
  266. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +2 -0
  267. package/src/plugins/pi-agent-ide-terminal/src/search.ts +32 -2
  268. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +5 -4
  269. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
  270. package/src/plugins/pi-agent-ide-terminal/src/types.ts +3 -1
  271. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +1 -1
  272. package/src/plugins/pi-agent-ide-vision/index.ts +232 -0
  273. package/src/plugins/pi-agent-ide-vision/src/vision.ts +530 -0
  274. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +30 -0
  275. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +33 -0
  276. package/dist/chunk-5PLV4HLG.js +0 -1
  277. package/dist/chunk-BGUSBUUD.js +0 -26
  278. package/dist/chunk-G725MARR.js +0 -16
  279. package/dist/chunk-HKXDP2FD.js +0 -7
  280. package/dist/chunk-J4RTW44E.js +0 -1
  281. package/dist/chunk-QH4ZUDOD.js +0 -1
  282. package/dist/chunk-WGGIQ7IJ.js +0 -1
  283. package/dist/chunk-ZG2MWXCR.js +0 -2
  284. package/dist/chunk-ZUMN6U77.js +0 -27
  285. package/dist/entry-17.js +0 -1
  286. package/docs/evaluation.md +0 -14
  287. package/node_modules/pi-agent-doctor/runtime/entry-17.js +0 -1
  288. package/node_modules/pi-agent-filesystem/runtime/entry-22.js +0 -2
  289. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  290. package/node_modules/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  291. package/node_modules/pi-agent-image/runtime/entry-34.js +0 -1
  292. package/node_modules/pi-agent-resource/runtime/entry-42.js +0 -1
  293. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  294. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  295. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  296. package/node_modules/pi-agent-text-editor/runtime/entry-55.js +0 -1
  297. package/node_modules/pi-agent-tool-call-interception/runtime/entry-74.js +0 -1
  298. package/node_modules/pi-agent-web/runtime/entry-76.js +0 -2
  299. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  300. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-22.js +0 -2
  301. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-77.js +0 -2
  302. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +0 -2
  303. package/src/extensions/pi-agent-read/runtime/entry-37.js +0 -1
  304. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +0 -2
  305. package/src/extensions/pi-agent-search/runtime/entry-43.js +0 -1
  306. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  307. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  308. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  309. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  310. package/src/extensions/pi-agent-text-editor/runtime/entry-55.js +0 -1
  311. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  312. package/src/plugins/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  313. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-23.js +0 -0
  314. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  315. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  316. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  317. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  318. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  319. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
  320. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-35.js +0 -0
  321. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-36.js +0 -0
  322. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-37.js +0 -0
  323. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-43.js +0 -0
  324. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-47.js +0 -0
  325. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-49.js +0 -0
  326. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-72.js +0 -0
  327. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  328. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-75.js +0 -0
  329. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-77.js +0 -0
  330. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  331. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  332. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  333. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  334. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  335. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  336. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  337. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  338. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  339. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  340. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  341. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  342. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
@@ -0,0 +1,27 @@
1
+ import{a as se,b as de,c as ue}from"./chunk-ESPNEJHK.js";import{a as ie}from"./chunk-M5IVSCR2.js";import{a as Z}from"./chunk-MGCHOGQD.js";import{a as X,b as Y}from"./chunk-T6LX2RX5.js";import{a as oe}from"./chunk-L7JMDDSD.js";import{a as ne,b as ae}from"./chunk-O6LE42GK.js";import{a as T}from"./chunk-K5G4FDXD.js";import{c as re}from"./chunk-YHUTTZC6.js";import{a as te}from"./chunk-6CZO43OH.js";import{a as Q,b as ee}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{d as P,e as h}from"./chunk-N34ATN52.js";import{a as i}from"./chunk-EI7MMDWY.js";import k from"node:path";import{access as nt}from"node:fs/promises";import{StringEnum as at}from"@earendil-works/pi-ai";import{defineTool as ot}from"@earendil-works/pi-coding-agent";import{Type as w}from"typebox";import{access as L}from"node:fs/promises";async function I(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await P(o.command,r,e))return o;return n[0]}i(I,"resolvePythonDebuggerCommand");var le=[{language:"c",backend:"lldb-dap",status:"verified"},{language:"cpp",backend:"lldb-dap",status:"verified"},{language:"csharp",backend:"netcoredbg",status:"verified"},{language:"dart",backend:"dart debug_adapter",status:"verified"},{language:"elixir",backend:"elixir-ls",status:"verified"},{language:"go",backend:"dlv dap",status:"verified"},{language:"java",backend:"kotlin-debug-adapter",status:"verified"},{language:"javascript",backend:"vscode-js-debug",status:"verified"},{language:"julia",backend:"DebugAdapter.jl",status:"verified"},{language:"kotlin",backend:"kotlin-debug-adapter",status:"verified"},{language:"lua",backend:"local-lua-debugger-vscode",status:"verified"},{language:"php",backend:"vscode-php-debug",status:"verified"},{language:"powershell",backend:"PowerShellEditorServices",status:"verified"},{language:"python",backend:"debugpy",status:"verified"},{language:"r",backend:"vscDebugger",status:"verified"},{language:"ruby",backend:"rdbg",status:"verified"},{language:"rust",backend:"lldb-dap",status:"verified"},{language:"shell",backend:"bash-debug-adapter",status:"verified"},{language:"swift",backend:"lldb-dap",status:"verified"},{language:"typescript",backend:"vscode-js-debug",status:"verified"},{language:"zig",backend:"lldb-dap",status:"verified"}],G=[{id:"dart-debug-adapter",name:"Dart debug adapter",kind:"debugger",languages:["dart"],executables:["dart"],dependencies:["Dart SDK 3.13.3"],documentation:"https://github.com/dart-lang/sdk/tree/main/third_party/pkg/dap",debugger:{runtimeExecutables:["dart"],adapterExecutables:["dart"],platforms:["linux","win32"],install:"Install Dart SDK 3.13.3 from the official Dart archive."}},{id:"debugpy",name:"debugpy",kind:"debugger",languages:["python"],executables:["python3"],dependencies:["debugpy"],documentation:"https://github.com/microsoft/debugpy",debugger:{runtimeExecutables:["python3"],adapterExecutables:["python3"],platforms:["linux","win32"],install:"Install Python 3 and debugpy for that interpreter."}},{id:"delve",name:"Delve",kind:"debugger",languages:["go"],executables:["dlv"],dependencies:["github.com/go-delve/delve/cmd/dlv@v1.25.2"],documentation:"https://github.com/go-delve/delve/tree/master/Documentation/api/dap",debugger:{runtimeExecutables:["go"],adapterExecutables:["dlv"],platforms:["linux","win32"],install:"Install Go and Delve. Native Windows support requires amd64."}},{id:"elixir-ls-debug-adapter",name:"ElixirLS debug adapter",kind:"debugger",languages:["elixir"],executables:["elixir","mix"],dependencies:["Elixir","Erlang/OTP","ElixirLS 0.31.1"],documentation:"https://github.com/elixir-lsp/elixir-ls",debugger:{runtimeExecutables:["elixir","mix"],adapterExecutables:["debug_adapter.sh","debug_adapter.bat"],platforms:["linux","win32"],install:"Install compatible Erlang/OTP and Elixir releases plus ElixirLS 0.31.1. Use debug_adapter.bat on Windows."}},{id:"vsc-debugger",name:"vscDebugger",kind:"debugger",languages:["r"],executables:["R"],dependencies:["R 4.5.3","R6 2.6.1","jsonlite 2.0.0","vscDebugger 0.5.9"],documentation:"https://manuelhentschel.github.io/vscDebugger/",debugger:{runtimeExecutables:["R"],adapterExecutables:["R"],platforms:["linux","win32"],install:"Install R 4.5.3 and vscDebugger 0.5.9 for that R installation."}},{id:"julia-debug-adapter",name:"DebugAdapter.jl",kind:"debugger",languages:["julia"],executables:["julia"],dependencies:["Julia 1.13.0","DebugAdapter.jl 3.2.1"],documentation:"https://github.com/julia-vscode/DebugAdapter.jl",debugger:{runtimeExecutables:["julia"],adapterExecutables:["julia"],platforms:["linux"],install:"Install Julia 1.13.0 and add DebugAdapter.jl 3.2.1 to /opt/pi-debug-adapters/julia."}},{id:"kotlin-debug-adapter",name:"Kotlin Debug Adapter",kind:"debugger",languages:["java","kotlin"],executables:["kotlin-debug-adapter"],dependencies:["fwcd/kotlin-debug-adapter 0.4.4","Temurin JDK 21.0.8+9","Kotlin compiler 2.2.20 for Kotlin builds"],documentation:"https://github.com/fwcd/kotlin-debug-adapter",debugger:{runtimeExecutables:["java"],adapterExecutables:["kotlin-debug-adapter"],platforms:["linux"],install:"Install Temurin JDK 21.0.8+9 and fwcd/kotlin-debug-adapter 0.4.4. Compile the target with debug information before launching it."}},{id:"netcoredbg",name:"NetCoreDbg",kind:"debugger",languages:["csharp"],executables:["netcoredbg"],dependencies:["Samsung/netcoredbg 3.2.0-1092",".NET SDK 8"],documentation:"https://github.com/Samsung/netcoredbg",debugger:{runtimeExecutables:["dotnet"],adapterExecutables:["netcoredbg"],platforms:["linux","win32"],install:"Install .NET SDK 8 and NetCoreDbg 3.2.0-1092. On Windows, ensure the selected dotnet SDK is on PATH."}},{id:"lldb-dap",name:"lldb-dap",kind:"debugger",languages:["c","cpp","rust"],executables:["lldb-dap-18","lldb-dap"],dependencies:["lldb-18"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:[],adapterExecutables:["lldb-dap-18","lldb-dap"],platforms:["linux"],install:"Install LLDB 18 and compile the target with debug information."}},{id:"lldb-dap-swift",name:"lldb-dap for Swift",kind:"debugger",languages:["swift"],executables:["lldb-dap"],dependencies:["Swift 6.3.3 toolchain"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:["swiftc"],adapterExecutables:["lldb-dap"],platforms:["linux"],install:"Install the official Swift 6.3.3 Linux toolchain, which includes swiftc and lldb-dap."}},{id:"lldb-dap-zig",name:"lldb-dap for Zig",kind:"debugger",languages:["zig"],executables:["lldb-dap-18","lldb-dap"],dependencies:["Zig 0.15.2","lldb-18"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:["zig"],adapterExecutables:["lldb-dap-18","lldb-dap"],platforms:["linux","win32"],install:"Install Zig 0.15.2 and LLDB 18, then compile the target in Debug mode with the LLVM backend (-fllvm) so LLDB can inspect locals."}},{id:"local-lua-debugger",name:"Local Lua Debugger",kind:"debugger",languages:["lua"],executables:["lua","node"],dependencies:["local-lua-debugger-vscode 0.3.3"],documentation:"https://github.com/tomblind/local-lua-debugger-vscode",debugger:{runtimeExecutables:["lua","node"],adapterExecutables:["debugAdapter.js"],platforms:["linux","win32"],install:"Install Lua 5.3, Node 24, and local-lua-debugger-vscode 0.3.3."}},{id:"powershell-editor-services-debug",name:"PowerShell Editor Services",kind:"debugger",languages:["powershell"],executables:["pwsh"],dependencies:["PowerShellEditorServices 4.7.0"],documentation:"https://github.com/PowerShell/PowerShellEditorServices",debugger:{runtimeExecutables:["pwsh"],adapterExecutables:["Start-EditorServices.ps1"],platforms:["linux","win32"],install:"Install PowerShell 7.4.13 and PowerShellEditorServices 4.7.0."}},{id:"rdbg",name:"rdbg",kind:"debugger",languages:["ruby"],executables:["rdbg"],dependencies:["debug gem 1.11.0 or newer"],documentation:"https://github.com/ruby/debug",debugger:{runtimeExecutables:["ruby"],adapterExecutables:["rdbg","rdbg.bat"],platforms:["linux","win32"],install:"Install Ruby and debug gem 1.11.0 or newer."}},{id:"vscode-bash-debug",name:"Bash Debug",kind:"debugger",languages:["shell"],executables:["bash","node"],dependencies:["Bash Debug 0.3.9"],documentation:"https://github.com/rogalmic/vscode-bash-debug",debugger:{runtimeExecutables:["bash","node"],adapterExecutables:["bashDebug.js"],platforms:["linux"],install:"Install Bash, Node 24, and Bash Debug 0.3.9."}},{id:"vscode-php-debug",name:"PHP Debug",kind:"debugger",languages:["php"],executables:["php","node"],dependencies:["PHP Debug 1.40.1","Xdebug"],documentation:"https://github.com/xdebug/vscode-php-debug",debugger:{runtimeExecutables:["php","node"],adapterExecutables:["phpDebug.js"],platforms:["linux","win32"],install:"Install PHP with Xdebug, Node 24, and PHP Debug 1.40.1."}},{id:"vscode-js-debug",name:"vscode-js-debug",kind:"debugger",languages:["javascript","typescript"],executables:["node"],dependencies:["@vscode/js-debug"],documentation:"https://github.com/microsoft/vscode-js-debug",debugger:{runtimeExecutables:["node"],adapterExecutables:["dapDebugServer.js"],platforms:["linux","win32"],install:"Install Node 24 and js-debug-dap v1.117.0 from the official release archive."}}];function q(r){return G.find(e=>e.languages.includes(r))}i(q,"debuggerRecipeForLanguage");var ce="/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js",pe="/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh",ge={protocol:X,apiVersion:1,id:"debugger",setup(r){for(let e of G)r.addToolRecipe(e);r.addSetupCheck({id:"effective-config",inspect:Ce}),r.addCheck({id:"adapters",title:"Debug adapters",run:Be})}};async function Ce(r,e=process.platform){let t=new Map([...r.detectedLanguageIds].map(q).filter(a=>a!==void 0).map(a=>[a.id,a])),n=[...r.detectedLanguageIds].flatMap(a=>{let s=q(a);return s===void 0?[]:[{kind:"debugger",languageId:a,toolId:s.id}]}),o=[];for(let a of le)a.status==="planned"&&r.detectedLanguageIds.has(a.language)&&o.push({id:`debugger-${a.language}-not-verified`,message:`${a.backend} is selected for ${a.language}, but its Linux debugger integration is not verified yet`});for(let a of t.values()){let s=a.debugger;if(s===void 0)continue;let d=e==="linux"||e==="darwin"||e==="win32"?e:void 0;if(d===void 0||!s.platforms.includes(d)){o.push({id:`debugger-${a.id}-platform`,category:"unsupported-platform",message:`${a.name} does not support the ${e} debugger recipe`});continue}let l=a.id==="debugpy"?await I(r.cwd,r.env,e):void 0,u=await Le(l===void 0?s.runtimeExecutables:[l.command],r.cwd,r.env);if(u!==void 0){o.push({id:`debugger-${a.id}-runtime`,category:"missing-runtime",message:`Runtime ${u} is unavailable. ${s.install}`});continue}if(!await je(a.id,r.cwd,r.env,e)){o.push({id:`debugger-${a.id}-adapter`,category:"missing-adapter",message:`${a.name} is not installed. ${s.install}`});continue}await qe(a.id,r.cwd,r.env,e)||o.push({id:`debugger-${a.id}-startup`,category:"adapter-startup",message:`${a.name} is installed but cannot start. ${s.install}`})}return{selections:n,actions:o}}i(Ce,"inspectDebuggerSetup");async function Be(r){let e=[...new Map([...r.detectedLanguageIds].map(q).filter(t=>t!==void 0).map(t=>[t.id,t])).values()];return e.length===0?[{status:"skip",message:"No supported executable language was detected"}]:Promise.all(e.map(async t=>{let n=await be(t.id,r.cwd,r.env);return{status:n.ok?"pass":"fail",message:`${t.name}: ${n.ok?"available":"unavailable"}`,detail:n.detail}}))}i(Be,"checkDebuggerAdapters");async function Le(r,e,t){for(let n of r)if(!await P(n,e,t))return n}i(Le,"firstMissingExecutable");async function je(r,e,t,n=process.platform){if(r==="elixir-ls-debug-adapter")try{return await L(t.PI_ELIXIR_LS_DEBUG_PATH??pe),!0}catch{return!1}if(r==="vsc-debugger")return(await h(t.PI_R_PATH??"R",["--vanilla","--quiet","-e","quit(status=if (requireNamespace('vscDebugger', quietly=TRUE)) 0 else 1)"],e,t)).ok;if(r==="vscode-js-debug")try{return await L(t.PI_JS_DEBUG_PATH??ce),!0}catch{return!1}if(r.startsWith("lldb-dap"))return await P(t.PI_LLDB_DAP_PATH??(n==="win32"?"lldb-dap":"lldb-dap-18"),e,t)||await P("lldb-dap",e,t);if(r==="delve")return P(t.PI_DELVE_PATH??"dlv",e,t);if(r==="kotlin-debug-adapter")return P(t.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",e,t);if(r==="julia-debug-adapter")try{return await L(`${t.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia"}/Project.toml`),!0}catch{return!1}if(r==="dart-debug-adapter")return P(t.PI_DART_PATH??"dart",e,t);let o=await I(e,t,n);return(await h(o.command,[...o.args,"-c","import importlib.util; raise SystemExit(importlib.util.find_spec('debugpy') is None)"],e,t)).ok}i(je,"adapterInstalled");async function qe(r,e,t,n=process.platform){return(await be(r,e,t,n)).ok}i(qe,"adapterAvailable");async function be(r,e,t,n=process.platform){if(r==="elixir-ls-debug-adapter")return B(t.PI_ELIXIR_LS_DEBUG_PATH??pe,e,t);if(r==="vsc-debugger")return h(t.PI_R_PATH??"R",["--vanilla","--quiet","-e","library(vscDebugger); cat(as.character(packageVersion('vscDebugger')))"],e,t);if(r==="dart-debug-adapter")return h(t.PI_DART_PATH??"dart",["--version"],e,t);if(r==="debugpy"){let a=await I(e,t,n);return h(a.command,[...a.args,"-c","import debugpy; print(debugpy.__version__)"],e,t)}if(r==="delve")return h(t.PI_DELVE_PATH??"dlv",["version"],e,t);if(r==="julia-debug-adapter"){let a=t.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia";return h(t.PI_JULIA_PATH??"julia",[`--project=${a}`,"--startup-file=no","-e","using DebugAdapter"],e,t)}if(r==="kotlin-debug-adapter"){let a=await h(t.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",["--help"],e,t);return a.ok?h("java",["-version"],e,t):a}if(r==="netcoredbg"){let a=await h(t.PI_NETCOREDBG_PATH??"netcoredbg",["--version"],e,t);return a.ok?h("dotnet",["--version"],e,t):a}if(r.startsWith("lldb-dap")){let a=t.PI_LLDB_DAP_PATH??(n==="win32"?"lldb-dap":await P("lldb-dap-18",e,t)?"lldb-dap-18":"lldb-dap");return h(a,["--version"],e,t)}if(r==="rdbg")return h(t.PI_RUBY_DEBUG_PATH??"rdbg",["--version"],e,t);if(r==="vscode-php-debug"){let a=await h(t.PI_PHP_PATH??"php",["-r","exit(extension_loaded('xdebug') ? 0 : 1);"],e,t);return a.ok?B(t.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js",e,t):a}if(r==="local-lua-debugger"){let a=await h(t.PI_LUA_PATH??"lua",["-v"],e,t);return a.ok?B(t.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js",e,t):a}if(r==="vscode-bash-debug"){let a=await h(t.PI_BASH_PATH??"bash",["--version"],e,t);return a.ok?B(t.PI_BASH_DEBUG_PATH??"/opt/pi-debug-adapters/bash-debug/extension/out/bashDebug.js",e,t):a}if(r==="powershell-editor-services-debug"){let a=await h(t.PI_PWSH_PATH??"pwsh",["--version"],e,t),s=t.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";return a.ok?B(`${s}/PowerShellEditorServices/Start-EditorServices.ps1`,e,t):a}let o=t.PI_JS_DEBUG_PATH??ce;try{await L(o)}catch{return{ok:!1,detail:`${o} does not exist`}}return h(process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1]); console.log(process.version)",o],e,t)}i(be,"probeAdapter");async function B(r,e,t){try{await L(r)}catch{return{ok:!1,detail:`${r} does not exist`}}return h(process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1])",r],e,t)}i(B,"probeAdapterFile");import He from"node:path";import{fileURLToPath as Fe}from"node:url";function me(r){return{id:"debug-breakpoints",present(e,t){let n=r.get(t.source),o=r.sourceFile(t.source)??fe(t.source,t.cwd)??fe(e.source,t.cwd);if(o===void 0)return e;let a=r.breakpointsForFile(o,n?.source);if(a.length===0)return e;let s=Oe(a);return{...e,lines:e.lines.map(d=>{let l=s.get(d.lineNumber);return l===void 0?d:{...d,presentation:{...d.presentation,suffix:`${d.presentation?.suffix??""}${Ne(l)}`,compactSuffix:`${d.presentation?.compactSuffix??""}${Ue(l)}`}}})}}}}i(me,"createBreakpointPresenter");function Oe(r){let e=new Map;for(let t of r){let n=e.get(t.line)??[];n.push(t),e.set(t.line,n)}return e}i(Oe,"groupByLine");function fe(r,e){if(r.startsWith("file://"))return Fe(r);if(!/^[a-z][a-z\d+.-]*:/iu.test(r))return He.resolve(e,r)}i(fe,"filesystemSource");function Ne(r){return r.map(e=>` ${e.verified?"\u25CF":"\u25CB"} breakpoint ${e.source} (${e.verified?"verified":"pending"})`).join("")}i(Ne,"renderAgentBreakpoints");function Ue(r){let t=r.filter(o=>o.verified).length===r.length?"\u25CF":"\u25CB",n=r.length===1?"breakpoint":`${r.length} breakpoints`;return` ${t} ${n}`}i(Ue,"renderUserBreakpoints");import H from"node:path";import{Text as J}from"@earendil-works/pi-tui";function W(r,e,t,n){return new J(`${n.fg("toolTitle",r)} ${n.fg("muted",`\xB7 ${Pe(e,t)}`)}
2
+ ${n.fg("accent","\u25C6 configure debugger")}`,0,0)}i(W,"renderDebugCall");function he(r,e,t){return new J(`${ve(r,t)}
3
+ ${t.fg("accent",Ge(e))}`,0,0)}i(he,"renderDebugActionCall");function j(r,e,t){return new J(Me(r,e,t).join(`
4
+ `),0,0)}i(j,"renderDebugResult");function ye(r,e){let t=[ve(r,e),we(r.status,e)];return r.stop?.frame!==void 0&&t.push(` ${e.fg("warning","\u25CF")} ${r.stop.frame.name} ${e.fg("muted",`\xB7 ${De(r.stop)}`)}`),t}i(ye,"renderActiveDebugger");function Me(r,e,t){let n=[];if(r.status==="stopped"&&r.stop!==void 0){n.push(t.fg("warning",`\u25CF stopped \xB7 ${r.stop.reason}`),t.fg("text",`${r.stop.frame?.name??"unknown frame"} ${t.fg("muted",`\xB7 ${De(r.stop)}`)}`));for(let a of r.stop.sourceLines){let s=a.current?t.fg("warning",">"):t.fg("dim","\u2502"),d=a.current?"text":"dim";n.push(`${s} ${String(a.lineNumber).padStart(4)} ${t.fg(d,a.content)}`)}let o=e?r.stop.variables:r.stop.variables.slice(0,6);if(o.length>0){n.push(t.fg("muted","Locals"));for(let a of o)n.push(` ${t.fg("accent",a.name.padEnd(16))} ${t.fg("toolOutput",a.value)}${a.type===void 0?"":t.fg("dim",` ${a.type}`)}`);o.length<r.stop.variables.length&&n.push(t.fg("muted",` \u2026 ${r.stop.variables.length-o.length} more`))}return n}if(n.push(we(r.status,t)),r.breakpoints.length>0){let o=r.breakpoints.filter(a=>a.verified).length;n.push(t.fg("muted",`${r.breakpoints.length} breakpoint${r.breakpoints.length===1?"":"s"} \xB7 ${o} verified`))}return n}i(Me,"debugResultLines");function ve(r,e){return`${e.fg("toolTitle",r.options.adapter)} ${e.fg("muted",`\xB7 ${Pe(r.options.program,r.options.cwd)}`)}`}i(ve,"debugIdentity");function Ge(r){let e=r.trim().toLowerCase();return e==="start"?"\u25B6 start debugging":e==="continue"?"\u25B6 continue":e==="step over"?"\u21B7 step over":e==="step into"?"\u2193 step into":e==="step out"?"\u2191 step out":e.startsWith("breakpoint ")?`\u25CF add ${e}`:e.startsWith("delete-breakpoint ")?`\u25CB remove breakpoint \xB7 ${e.slice(18)}`:e==="breakpoint"?"\u25CF add breakpoint":e==="delete-breakpoint"?"\u25CB remove breakpoint":e==="delete-session"?"\u25A0 stop debugging":e}i(Ge,"actionLabel");function we(r,e){return r==="configured"?e.fg("muted","\u25C7 ready"):r==="running"?e.fg("accent","\u25CF running"):r==="stopped"?e.fg("warning","\u25CF stopped"):e.fg("success","\u25A0 stopped debugging")}i(we,"statusLine");function De(r){let e=r.frame?.source?.path??r.frame?.source?.name??"unknown";return`${H.basename(e)}:${r.frame?.line??"?"}`}i(De,"shortFrame");function Pe(r,e){let t=H.relative(e,r),n=".".repeat(2),o=t===n||t.startsWith(`${n}${H.sep}`);return t.length>0&&!o?t:H.basename(r)}i(Pe,"shortPath");function V(r){if(typeof r!="object"||r===null)return;let e=r.metadata;if(typeof e!="object"||e===null)return;let t=e.semanticAction;if(typeof t!="object"||t===null)return;let n=t.snapshot;return typeof n=="object"&&n!==null?n:void 0}i(V,"debuggerSnapshotFromResult");function Se(r){return{id:"debugger",onDidChange:i(e=>r.onDidChange(e),"onDidChange"),list:i(()=>r.list().map(e=>r.snapshot(e)).filter(e=>e.status==="configured"||e.status==="running"||e.status==="stopped").map(e=>({source:e.source,kind:"debugger",title:e.options.adapter,description:e.options.program,status:e.status==="configured"?"configured":e.status==="stopped"?"paused":"running",renderSummary:i(t=>ye(e,t),"renderSummary"),renderDetail:i(t=>j(e,!0,t),"renderDetail"),stop:i(()=>r.delete(e.source),"stop")})),"list")}}i(Se,"debuggerProcessProvider");import $ from"cross-spawn";import{randomBytes as ke}from"node:crypto";import{rmSync as Ve}from"node:fs";import{mkdtemp as ze,readFile as Ae,rm as Ke}from"node:fs/promises";import Te from"node:net";import{tmpdir as Xe}from"node:os";import y from"node:path";import Je from"cross-spawn";import We from"node:net";var S=class r{static{i(this,"DapClient")}#a;#u;#l;#o=new Map;#b=[];#i=new Set;#f=new Set;#r=Buffer.alloc(0);#p=1;#s;#g;#n;constructor(e,t,n){this.#a=e,this.#u=t,this.#l=n,e.on("data",o=>this.#t(o)),e.once("error",o=>this.#c(o)),e.once("close",()=>this.#c(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#c(o)),n.once("exit",(o,a)=>{this.#c(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Je(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#p=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=We.createConnection({port:e,host:t}),s=i(d=>o(d),"fail");a.once("error",s),a.once("connect",()=>{a.off("error",s),n(new r(a,a))})})}onReverseRequest(e){this.#g=e}onEvent(e){return this.#f.add(e),()=>this.#f.delete(e)}request(e,t,n={}){if(this.#s!==void 0)return Promise.reject(this.#s);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#n=void 0);let o=this.#p++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},s=new Promise((d,l)=>{let u,c=i(()=>{u!==void 0&&clearTimeout(u),n.signal?.removeEventListener("abort",b)},"cleanup"),b=i(()=>{this.#o.delete(o),c(),l(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(u=setTimeout(()=>{this.#o.delete(o),c(),l(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#o.set(o,{resolve:i(p=>d(p),"resolve"),reject:l,cleanup:c}),n.signal?.addEventListener("abort",b,{once:!0})});return this.#d(a),s}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#b.findIndex(s=>o.has(s.event));return a>=0?Promise.resolve(this.#b.splice(a,1)[0]):this.#s!==void 0?Promise.reject(this.#s):new Promise((s,d)=>{let l={events:o,resolve:i(c=>{clearTimeout(l.timer),this.#i.delete(l),s(c)},"resolve"),reject:i(c=>{clearTimeout(l.timer),this.#i.delete(l),d(c)},"reject"),timer:setTimeout(()=>{this.#i.delete(l),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(l);let u=i(()=>l.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?u():n?.addEventListener("abort",u,{once:!0})})}close(){this.#a.destroy(),this.#u.destroy(),this.#l!==void 0&&!this.#l.killed&&this.#l.kill(),this.#c(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#u.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
5
+ \r
6
+ `),t]))}#t(e){for(this.#r=Buffer.concat([this.#r,e]);;){let t=this.#r.indexOf(`\r
7
+ \r
8
+ `);if(t<0)return;let n=this.#r.subarray(0,t).toString("ascii"),o=/^Content-Length:\s*(\d+)$/imu.exec(n);if(o===null){this.#c(new Error("Debug adapter sent a frame without Content-Length"));return}let a=Number(o[1]),s=t+4;if(this.#r.length<s+a)return;let d=this.#r.subarray(s,s+a).toString("utf8");this.#r=this.#r.subarray(s+a);try{this.#m(JSON.parse(d))}catch(l){this.#c(l instanceof Error?l:new Error(String(l)));return}}}#m(e){if(e.type==="event")if(e.event==="stopped"){let t=JSON.stringify(e.body??null);if(t===this.#n)return;this.#n=t}else e.event==="continued"&&(this.#n=void 0);if(e.type==="response"){let t=this.#o.get(e.request_seq);if(t===void 0)return;this.#o.delete(e.request_seq),t.cleanup(),e.success?t.resolve(e.body):t.reject(new Error(`${e.command}: ${e.message??"failed"}`));return}if(e.type==="event"){for(let n of this.#f)n(e);let t=[...this.#i].find(n=>n.events.has(e.event));t===void 0?this.#b.push(e):t.resolve(e);return}this.#e(e)}async#e(e){try{if(this.#g===void 0)throw new Error(`Client does not support reverse request ${e.command}`);let t=await this.#g(e);this.#d({seq:this.#p++,type:"response",request_seq:e.seq,success:!0,command:e.command,...t===void 0?{}:{body:t}})}catch(t){this.#d({seq:this.#p++,type:"response",request_seq:e.seq,success:!1,command:e.command,message:t instanceof Error?t.message:String(t)})}}#c(e){if(this.#s===void 0){this.#s=e;for(let t of this.#o.values())t.cleanup(),t.reject(e);this.#o.clear();for(let t of this.#i)t.reject(e);this.#i.clear()}}};var O=class{static{i(this,"DebugSessionManager")}#a=new Map;#u=new Set;create(e){let t=ke(6).toString("hex"),n={id:t,source:`debug:${t}`,options:{...e,sourceFile:e.sourceFile??e.program},breakpoints:new Map,status:"configured",stopGeneration:0};return this.#a.set(t,n),this.#e(n),n}get(e){let t=/^debug:([a-f\d]{12})(?:\/|$)/u.exec(e);return t===null?void 0:this.#a.get(t[1])}list(){return[...this.#a.values()]}snapshot(e){return{id:e.id,source:e.source,options:e.options,status:e.status,breakpoints:[...e.breakpoints.values()].map(t=>({...t})),...e.stop===void 0?{}:{stop:e.stop}}}onDidChange(e){return this.#u.add(e),()=>this.#u.delete(e)}breakpointsForFile(e,t){return this.list().filter(n=>t===void 0||n.source===t).flatMap(n=>[...n.breakpoints.values()]).filter(n=>T(n.file,e))}sourceFile(e){let t=this.get(e);return t!==void 0&&e===`${t.source}/source`?t.options.sourceFile:void 0}sourceResource(e){return`${e.source}/source`}readSource(e){let t=this.sourceFile(e);return t===void 0?Promise.reject(new Error(`Unknown debug source ${e}`)):Ae(t,"utf8")}async addBreakpoint(e,t,n){let o=this.get(e),a=this.sourceFile(e);if(o===void 0||a===void 0)throw new Error(`Unknown debug source ${e}`);if(o.status==="terminated")throw new Error("Cannot add a breakpoint to a terminated session");let s=ke(5).toString("hex"),d={id:s,source:`${o.source}/breakpoint/${s}`,file:a,line:t,verified:!1};return o.breakpoints.set(s,d),o.client!==void 0&&await this.#d(o,o.client,a,n),this.#e(o),d}breakpoint(e){let t=this.get(e);return t===void 0?void 0:[...t.breakpoints.values()].find(n=>n.source===e)}async start(e,t){return this.#l(e,t,2)}async#l(e,t,n){if(e.status!=="configured")throw new Error(`Session is already ${e.status}`);e.options.adapter==="powershell"&&(e.adapterTemporaryDirectory=await ze(y.join(Xe(),"pi-powershell-debug-")));let o=await rt(e.options,e.adapterTemporaryDirectory),a=e.options.adapter==="node"?await this.#s(e):e.options.adapter==="delve"?await this.#b(e):e.options.adapter==="ruby"?await this.#o(e):e.options.adapter==="julia"?await this.#i(e):e.options.adapter==="r"?await this.#f(e):S.start(o.command,o.args,e.options.cwd);e.client=a,e.controlClient=a,e.clients=[a],e.options.adapter==="node"&&(e.targetReady=new Promise(s=>{e.resolveTargetReady=s})),e.status="running",this.#e(e);try{e.options.adapter!=="r"&&await Ee(a,o.adapterID,t);let s=a.waitForAnyEvent(["initialized"],3e4,t),d=a.request(o.request,o.launch,{signal:t});await s,await this.#n(e,a,t);let l=a.request("configurationDone",void 0,{signal:t});if(e.options.adapter==="java"||e.options.adapter==="kotlin"?l.catch(()=>{}):await l,await d,e.options.adapter==="r"&&(e.rStarted=!0),e.targetReady!==void 0&&await e.targetReady,await this.#t(e,t),this.snapshot(e).status==="terminated"&&n>0&&(e.options.adapter==="dart"||e.options.adapter==="kotlin")&&e.breakpoints.size>0){for(let u of e.clients??[a])u.close();e.adapterProcess?.kill(),await K(e),e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.adapterProcess=void 0,e.status="configured";for(let u of e.breakpoints.values())u.verified=!1;return this.#e(e),await this.#l(e,t,n-1)}return e}catch(s){for(let d of e.clients??[a])d.close();throw e.adapterProcess?.kill(),await K(e),e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.adapterProcess=void 0,e.targetReady=void 0,e.resolveTargetReady=void 0,e.status="configured",this.#e(e),s}}async command(e,t,n){if(e.status!=="stopped"||e.stop===void 0)throw new Error(`Cannot ${t} while session is ${e.status}`);let o=_(e),a=e.stop.threadId;return await o.request(t,{threadId:a},{signal:n}),e.stop=void 0,e.status="running",this.#e(e),await this.#t(e,n),e}async delete(e,t){let n=this.get(e);if(n===void 0)throw new Error(`Unknown debug session ${e}`);let o=/\/breakpoint\/([a-f\d]{10})$/u.exec(e);if(o!==null){let a=n.breakpoints.get(o[1]);if(a===void 0)throw new Error(`Unknown debug breakpoint ${e}`);n.breakpoints.delete(a.id),n.client!==void 0&&n.status!=="terminated"&&await this.#d(n,n.client,a.file,t),this.#e(n);return}if(e!==n.source)throw new Error(`Cannot delete debug resource ${e}`);if(n.client!==void 0){(n.controlClient??n.client).request("disconnect",{terminateDebuggee:!0},{signal:t,timeoutMs:500}).catch(()=>{});for(let a of n.clients??[n.client])a.close()}await Re(n.adapterProcess),await K(n),n.status="terminated",this.#e(n),this.#a.delete(n.id)}dispose(){for(let e of this.#a.values()){for(let t of e.clients??(e.client===void 0?[]:[e.client]))t.close();Re(e.adapterProcess),e.adapterTemporaryDirectory!==void 0&&Ve(e.adapterTemporaryDirectory,{recursive:!0,force:!0})}this.#a.clear()}async#o(e){let t=await F(),n=process.env.PI_RUBY_DEBUG_PATH??"rdbg";return e.adapterProcess=$(n,["--open","--host","127.0.0.1","--port",String(t),"--no-rc","--",e.options.program,...e.options.args],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),z(e.adapterProcess,`rdbg:${String(t)}`),await _e(e.adapterProcess,"Debugger can attach via TCP/IP","rdbg"),S.connect(t)}async#b(e){let t=await F(),n=process.env.PI_DELVE_PATH??"dlv";return e.adapterProcess=$(n,["dap",`--listen=127.0.0.1:${String(t)}`,"--log=false"],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),e.adapterProcess.stderr?.on("data",()=>{}),await _e(e.adapterProcess,"DAP server listening","Delve"),S.connect(t)}async#i(e){let t=await F(),n=process.env.PI_JULIA_PATH??"julia",o=process.env.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia",a='using Sockets, DebugAdapter; server = listen(ip"127.0.0.1", parse(Int, ARGS[1])); conn = accept(server); run(DebugAdapter.DebugSession(conn)); close(server)';return e.adapterProcess=$(n,["--startup-file=no","--history-file=no",`--project=${o}`,"-e",a,String(t)],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),z(e.adapterProcess,`DebugAdapter.jl:${String(t)}`),await new Promise(s=>setTimeout(s,25)),xe(t,"DebugAdapter.jl")}async#f(e){let t=Te.createServer();await new Promise((d,l)=>{t.once("error",l),t.listen(0,"127.0.0.1",()=>d())});let n=t.address();if(n===null||typeof n=="string")throw t.close(),new Error("Could not start the vscDebugger DAP listener");let o=new Promise((d,l)=>{t.once("connection",u=>{t.close();let c=S.fromSocket(u,2);c.onEvent(b=>this.#r(e,b)),d(c)}),t.once("error",l)}),a=process.env.PI_R_PATH??"R";e.rPromptInputs=[],e.rAtBrowserPrompt=!1,e.rStarted=!1,e.adapterProcess=$(a,["--vanilla","--quiet"],{cwd:e.options.cwd,env:process.env,stdio:["pipe","pipe","pipe"]}),z(e.adapterProcess,`vscDebugger:${String(n.port)}`),this.#p(e);let s=Qe({seq:1,type:"request",command:"initialize",arguments:{clientID:"pi-agent-ide",adapterID:"R-Debugger",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsWriteToStdinEvent:!0,supportsStdoutReading:!0,rStrings:{packageName:"vscDebugger",prompt:"__PI_R_PROMPT__",continue:"__PI_R_CONTINUE__",attachName:"tools:vscDebugger"},useDapSocket:!0,dapHost:"127.0.0.1",dapPort:n.port}});return e.adapterProcess.stdin?.write(`library(vscDebugger); vscDebugger:::.vsc.handleDap(${JSON.stringify(s)})
9
+ `),et(o,e.adapterProcess,t)}#r(e,t){if(process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(`[vscDebugger:event] ${JSON.stringify(t)}
10
+ `),t.event!=="custom")return;let n=x(t.body),o=typeof n.reason=="string"?n.reason:"",a=typeof n.text=="string"?n.text:"";if(!(o!=="writeToStdin"||a.length===0)){if(n.when==="browserPrompt"&&e.rAtBrowserPrompt===!0){e.rAtBrowserPrompt=!1,e.adapterProcess?.stdin?.write(`${a}
11
+ `);return}e.rPromptInputs?.push(a)}}#p(e){let t="";e.adapterProcess?.stdout?.on("data",n=>{for(t+=n.toString("utf8");;){let o=/Browse\[\d+\]> /u.exec(t),a=/(?:^|\r?\n)__PI_R_PROMPT__(?:\r?\n|$)/u.exec(t),s=o?.index??Number.POSITIVE_INFINITY,d=a?.index??Number.POSITIVE_INFINITY;if(!Number.isFinite(s)&&!Number.isFinite(d)){t=t.slice(-128);return}if(s<d){t=t.slice(s+(o?.[0].length??0));let l=e.rPromptInputs?.shift();l===void 0?(e.rAtBrowserPrompt=!0,setTimeout(()=>{e.rAtBrowserPrompt===!0&&(e.rAtBrowserPrompt=!1,e.adapterProcess?.stdin?.write(`vscDebugger::.vsc.listenForDAP(timeout=-1)
12
+ `))},100)):e.adapterProcess?.stdin?.write(`${l}
13
+ `)}else t=t.slice(d+(a?.[0].length??0)),e.adapterProcess?.stdin?.write(`vscDebugger::.vsc.listenForDAP(timeout=-1)
14
+ `),e.rStarted===!0&&e.client?.request("custom",{reason:"showingPrompt",which:"topLevel"}).catch(()=>{})}})}async#s(e){let t=await F(),n=process.env.PI_JS_DEBUG_PATH??"/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js";e.adapterProcess=$(process.execPath,[n,String(t),"127.0.0.1"],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),e.adapterProcess.stderr?.on("data",()=>{}),await tt(e.adapterProcess);let o=await xe(t);return o.onReverseRequest(this.#g(e,t)),o}#g(e,t){return async n=>{if(n.command!=="startDebugging")throw new Error(`Client does not support reverse request ${n.command}`);let o=x(n.arguments),a=x(o.configuration),s=await S.connect(t);e.clients?.push(s),s.onReverseRequest(this.#g(e,t)),await Ee(s,"pwa-node");let d=s.waitForEvent("initialized"),l=s.request(typeof o.request=="string"?o.request:"launch",{...a,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(e.options.program),"**","*.js")]});return await d,e.client=s,await this.#n(e,s),await s.request("configurationDone"),await l,e.resolveTargetReady?.(),{}}}async#n(e,t,n){let o=new Set([...e.breakpoints.values()].map(a=>a.file));for(let a of o)await this.#d(e,t,a,n)}async#d(e,t,n,o){let a=[...e.breakpoints.values()].filter(d=>d.file===n),s=await t.request("setBreakpoints",{source:{path:n,name:y.basename(n)},breakpoints:a.map(({line:d})=>({line:d})),sourceModified:!1},{signal:o});for(let[d,l]of a.entries())l.verified=s.breakpoints?.[d]?.verified===!0}async#t(e,t){let n=await _(e).waitForAnyEvent(["stopped","terminated","exited","loadedSource","breakpoint","custom"],3e4,t),o=x(n.body);if(n.event==="custom"&&e.options.adapter==="r"){await this.#t(e,t);return}if(n.event==="loadedSource"){let a=x(o.source),s=typeof a.path=="string"?y.resolve(a.path):void 0,d=s===void 0?void 0:[...e.breakpoints.values()].find(l=>T(l.file,s))?.file;d!==void 0&&await this.#d(e,_(e),d,t),await this.#t(e,t);return}if(n.event==="breakpoint"){let a=x(o.breakpoint),s=x(a.source);for(let d of e.breakpoints.values())a.verified===!0&&typeof a.line=="number"&&a.line===d.line&&typeof s.path=="string"&&T(s.path,d.file)&&(d.verified=!0);await this.#t(e,t);return}if(o.reason==="exit"){e.status="terminated",e.stop=void 0,this.#e(e);return}if(e.options.adapter==="node"&&o.reason==="entry"){await this.#n(e,_(e),t);let a=typeof o.threadId=="number"?o.threadId:1;await _(e).request("continue",{threadId:a},{signal:t}),await this.#t(e,t);return}if((e.options.adapter==="dart"||e.options.adapter==="kotlin")&&o.reason==="entry"){let a=_(e);if(await this.#n(e,a,t),e.options.adapter==="kotlin"){let d=Date.now()+5e3;for(;[...e.breakpoints.values()].some(l=>!l.verified)&&Date.now()<d;)await new Promise(l=>setTimeout(l,50)),await this.#n(e,a,t)}let s=typeof o.threadId=="number"?o.threadId:1;await a.request("continue",{threadId:s},{signal:t}),await this.#t(e,t);return}if(n.event!=="stopped"){e.status="terminated",e.stop=void 0,this.#e(e);return}if(await this.#m(e,n,e.options.adapter!=="shell"),e.options.adapter==="r"&&e.stop?.frame?.source?.path===void 0){e.stopGeneration--,e.stop=void 0,e.status="running",await this.#t(e,t);return}if(e.options.adapter==="shell"&&e.stop?.frame!==void 0&&![...e.breakpoints.values()].some(a=>T(a.file,e.stop?.frame?.source?.path??"")&&a.line===e.stop?.frame?.line)){let a=e.stop.threadId;e.stopGeneration--,e.stop=void 0,e.status="running",await _(e).request("continue",{threadId:a},{signal:t}),await this.#t(e,t);return}e.options.adapter==="shell"&&this.#e(e)}async#m(e,t,n=!0){let o=_(e),a=x(t.body),s=(await o.request("threads")).threads?.[0]?.id,d=typeof a.threadId=="number"?a.threadId:s;if(d===void 0)throw new Error("Debugger stopped without a thread");let l=(await Ze(o,d,e.options.adapter==="dart")).stackFrames?.[0];if(l?.source?.path!==void 0)for(let c of e.breakpoints.values())T(c.file,l.source.path)&&c.line===l.line&&(c.verified=!0);let u=[];if(l!==void 0){let c=(await o.request("scopes",{frameId:l.id})).scopes??[],b=e.options.adapter==="r"?c:c.filter(p=>[p.name.toLowerCase(),p.presentationHint?.toLowerCase()].some(g=>g?.includes("local")===!0||g==="variables"));for(let p of b){let g=await o.request("variables",{variablesReference:p.variablesReference,start:0,count:100});u.push(...g.variables??[])}}e.stopGeneration++,e.stop={generation:e.stopGeneration,reason:typeof a.reason=="string"?a.reason:"stopped",threadId:d,...l===void 0?{}:{frame:l},variables:u,sourceLines:l===void 0?[]:await Ye(l)},e.status="stopped",n&&this.#e(e)}#e(e){let t=this.snapshot(e);for(let n of this.#u)n(t)}};async function Ye(r){let e=r.source?.path;if(e===void 0)return[];try{let t=(await Ae(e,"utf8")).split(/\r?\n/u),n=Math.max(1,r.line-2),o=Math.min(t.length,r.line+2);return t.slice(n-1,o).map((a,s)=>({lineNumber:n+s,content:a,current:n+s===r.line}))}catch{return[]}}i(Ye,"sourceWindow");async function Ze(r,e,t){let n=Date.now()+1e3,o;do{try{let a=await r.request("stackTrace",{threadId:e});if(!t||(a.stackFrames?.length??0)>0)return a;o=new Error("Debugger stack is not ready")}catch(a){if(o=a,!t)throw a}await new Promise(a=>setTimeout(a,25))}while(Date.now()<n);throw o instanceof Error?o:new Error("Could not read debugger stack")}i(Ze,"requestStackTrace");function N(r){let e=[`Session: ${r.source}`,`Adapter: ${r.options.adapter}`,`Program: ${y.relative(r.options.cwd,r.options.program)||r.options.program}`,`Status: ${r.status}`];if(r.breakpoints.size>0){e.push("","Breakpoints:");for(let t of r.breakpoints.values())e.push(`- ${t.source} ${y.relative(r.options.cwd,t.file)}:${t.line} (${t.verified?"verified":"pending"})`)}if(r.stop!==void 0){let{stop:t}=r;if(e.push("",`Stop: ${t.generation} (${t.reason})`,`Thread: ${t.threadId}`),t.frame!==void 0&&e.push(`Frame: ${t.frame.name} at ${t.frame.source?.path??t.frame.source?.name??"unknown"}:${t.frame.line}`),t.variables.length>0){e.push("","Locals:");for(let n of t.variables)e.push(`- ${n.name}: ${n.value}${n.type===void 0?"":` (${n.type})`}`)}}return e.join(`
15
+ `)}i(N,"renderDebugSession");function _(r){if(r.client===void 0)throw new Error("Debug adapter is not running");return r.client}i(_,"requiredClient");function x(r){return typeof r=="object"&&r!==null?r:{}}i(x,"asRecord");function Qe(r){let e=JSON.stringify(r);return`Content-Length: ${Buffer.byteLength(e,"utf8")}\r
16
+ \r
17
+ ${e}`}i(Qe,"dapFrame");function Ee(r,e,t){return r.request("initialize",{clientID:"pi-agent-ide",adapterID:e,pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsRunInTerminalRequest:!1,supportsStartDebuggingRequest:!0},{signal:t})}i(Ee,"initializeClient");function F(){return new Promise((r,e)=>{let t=Te.createServer();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let n=t.address();if(n===null||typeof n=="string"){t.close(),e(new Error("Could not allocate a debug adapter port"));return}t.close(o=>o===void 0?r(n.port):e(o))})})}i(F,"availablePort");function z(r,e){if(process.env.PI_DEBUG_DAP_TRACE==="1"){process.stderr.write(`[${e}] pid=${String(r.pid)}
18
+ `),r.once("exit",(t,n)=>process.stderr.write(`[${e}] exit code=${String(t)} signal=${String(n)}
19
+ `));for(let t of[r.stdout,r.stderr])t?.on("data",n=>process.stderr.write(`[${e}] ${n.toString("utf8")}`))}}i(z,"traceAdapterProcess");function et(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),s=i(()=>{clearTimeout(a),e.off("error",d),e.off("exit",l)},"cleanup"),d=i(u=>{s(),t.close(),e.killed||e.kill(),o(u)},"fail"),l=i(u=>d(new Error(`vscDebugger exited with code ${String(u)} before connecting`)),"onExit");e.once("error",d),e.once("exit",l),r.then(u=>{s(),n(u)},d)})}i(et,"waitForRAdapterConnection");function _e(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(u=>u!==null),s=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=i(()=>{clearTimeout(s);for(let u of a)u.off("data",l)},"cleanup"),l=i(u=>{u.toString("utf8").includes(e)&&(d(),n())},"onData");for(let u of a)u.on("data",l);r.once("error",u=>{d(),o(u)}),r.once("exit",u=>{d(),o(new Error(`${t} server exited with code ${String(u)}`))})})}i(_e,"waitForAdapterReady");function tt(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=i(s=>{s.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",s=>t(new Error(`js-debug server exited with code ${s}`)))})}i(tt,"waitForJsDebugReady");async function xe(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await S.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}i(xe,"connectWithRetry");async function K(r){r.adapterTemporaryDirectory!==void 0&&(await Ke(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}i(K,"removeAdapterTemporaryDirectory");async function Re(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=$("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}i(Re,"terminateOwnedAdapterProcess");async function rt(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await I(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="java"||r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:y.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:y.dirname(y.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:r.cwd}};if(r.adapter==="shell"){let n=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??y.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:y.join(n,"bashdb_dir/bashdb"),pathBashdbLib:y.join(n,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(r.adapter==="powershell"){let n=process.env.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";if(e===void 0)throw new Error("PowerShell debugger temporary directory was not created");return{command:process.env.PI_PWSH_PATH??"pwsh",args:["-NoLogo","-NoProfile","-Command",`& '${y.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${y.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${y.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${n.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:r.program,createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}return{command:process.execPath,args:[],adapterID:"pwa-node",request:"launch",launch:{...t,type:"pwa-node",console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(r.program),"**","*.js")]}}}i(rt,"adapterRecipe");var it=w.Object({adapter:at(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed DAP adapter for Dart, Python, Go, Java, Elixir, Julia, Kotlin, C, C++, Rust, Swift, Zig, Lua, C#, JavaScript, TypeScript, PHP, PowerShell, R, Ruby, or shell scripts."}),program:w.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:w.Optional(w.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:w.Optional(w.Array(w.String(),{description:"Arguments passed to the debugged program."})),mainClass:w.Optional(w.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:w.Optional(w.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function st(r){let e=de("debugger")??new O,t=new Map,n=Ie(e,"debugger-source"),o=Ie(e,"debugger-input"),a=ie(r).add(Se(e)),s=me(e),d={protocol:Q,apiVersion:ee,id:"debugger",setup(u){u.addResolver({resolver:n,matchesCall:i(c=>e.sourceFile(c)!==void 0,"matchesCall"),renderCall(c,b,p){let g=A(c)?c:{},f=typeof g.path=="string"?g.path:"",m=e.get(f),v=e.sourceFile(f);if(m===void 0||v===void 0)throw new Error("Debugger source header lost its session");let D=k.relative(m.options.cwd,v),E=Array.isArray(g.views)?g.views.filter(M=>typeof M=="string"):[],R=typeof g.offset=="number"?g.offset:1,C=typeof g.limit=="number"?g.limit:void 0,U=C===void 0?String(R):`${R}-${R+C-1}`;return re(p.lastComponent,{tool:"debug file",primary:{text:`${D}:${U}`,color:"accent",underline:!0},qualifiers:E.length===0?[]:[{text:`views ${E.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},...E.length===0?[]:[{label:"views",value:E.join(",")}]],expanded:p.expanded},b)}}),u.addView({view:"breakpoints",presenter:s}),u.describe('views: ["breakpoints"] \u2014 show current debugger breakpoints beside source lines. On a normal file, all current sessions are included; on a debug source, results are session-scoped. debug:<session> \u2014 debugger state. Read the returned debug source before selecting a breakpoint line.'),u.addPromptGuideline('Use views: ["breakpoints"] when current breakpoint locations matter. Create a debug session with debug. Read the returned debug source to get current anchors, insert text "breakpoint" at one source anchor, then insert "start" on the session. Use read for the latest stop and delete for a breakpoint or the session.')}},l={protocol:ne,apiVersion:ae,id:"debugger",setup(u){u.addResolver({resolver:o}),u.tool("insert").addSemanticHandler({matches:i(c=>dt(c,e),"matches"),execute:i(async(c,b)=>{let p=b,g=$e(e,p.path);if(e.sourceFile(p.path)!==void 0){if(p.text!=="breakpoint"||p.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let f=await c.resolveAnchor("anchor"),m=await e.addBreakpoint(p.path,f.lineNumber,c.signal);return{source:m.source,summary:`Breakpoint ${m.source} created at ${k.relative(g.options.cwd,m.file)}:${m.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:m.file,line:m.line,verified:m.verified,snapshot:e.snapshot(g)}}}if(p.path!==g.source||p.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");return await lt(e,g,p.text,c.signal),{source:g.source,summary:N(g),data:pt(e,g,p.text)}},"execute")}),u.tool("delete").addSemanticHandler({matches:i(c=>ut(c,e),"matches"),execute:i(async(c,b)=>{let p=b.path,g=$e(e,p),f=e.snapshot(g);t.set(p,f);let m=p.includes("/breakpoint/");await e.delete(p,c.signal);let v=m?e.snapshot(g):{...f,status:"terminated"};return{source:p,summary:`Deleted ${p}.`,data:{kind:m?"debug-breakpoint":"debug-session",deleted:!0,snapshot:v}}},"execute")}),u.describe('For debug:<session> resources, insert performs debugger actions without changing source text. On a debug source, insert "breakpoint" at an anchor. On the session, insert start, continue, step over, step into, or step out. Delete removes a breakpoint or terminates the session.');for(let c of["insert","delete"])u.addToolRenderer({tool:c,matches(b,p){return p==="call"?A(b)&&typeof b.path=="string"&&(e.get(b.path)!==void 0||t.has(b.path)):V(A(b)&&"details"in b?b.details:b)!==void 0},renderCall(b,p,g){let f=b,m=f.path===void 0?void 0:e.get(f.path),v=f.path===void 0?void 0:t.get(f.path),D=g.state;m!==void 0?D.snapshot=e.snapshot(m):v!==void 0&&(D.snapshot=v);let E=D.snapshot;if(E===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:e.breakpoint(f.path)??E.breakpoints.find(M=>M.source===f.path),C=f.path===void 0?void 0:e.sourceFile(f.path),U=c==="delete"?R===void 0?"delete-session":`delete-breakpoint ${k.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&C!==void 0?`breakpoint ${k.basename(C)}:${bt(f)}`:f.text??"debug action";return he(E,U,p)},renderResult(b,p,g){let f=V(b.details);if(f===void 0)throw new Error("Debugger result is missing its session");return j(f,p.expanded,g)}})}};await Promise.all([Z(r,ge),te(r,d)]),await oe(r,l),r.registerTool(ot({name:"debug",label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:it,async execute(u,c,b,p,g){let f=k.resolve(g.cwd,c.cwd??"."),m=k.resolve(f,c.program);try{await nt(m);let v=e.create({adapter:c.adapter,program:m,sourceFile:k.resolve(f,c.source??c.program),args:c.args??[],cwd:f,...c.mainClass===void 0?{}:{mainClass:c.mainClass}}),D=ct(e,v);return{content:[{type:"text",text:`${N(v)}
20
+ Source: ${D.sourceResource}
21
+ Breakpoints: ${D.breakpointsResource}
22
+
23
+ Next: read ${D.sourceResource} with views ["anchors"], then insert a breakpoint at an anchor.`}],details:D}}catch(v){return{content:[{type:"text",text:v instanceof Error?v.message:String(v)}],details:{adapter:c.adapter,program:m,cwd:f,status:"failed"},isError:!0}}},renderCall(u,c){let b=k.resolve(process.cwd(),typeof u.cwd=="string"?u.cwd:"."),p=k.resolve(b,typeof u.program=="string"?u.program:"program");return W(typeof u.adapter=="string"?u.adapter:"debugger",p,b,c)},renderResult(u,c,b){let p=A(u.details)?u.details.snapshot:void 0;if(typeof p=="object"&&p!==null)return j(p,c.expanded,b);let g=u.details;return W(g.adapter,g.program,g.cwd,b)}})),r.on("session_shutdown",u=>{if(a(),u.reason!=="quit"){se("debugger",e);return}ue("debugger",e),e.dispose()})}i(st,"registerDebugger");function Ie(r,e){return{id:e,tryResolve(t){let n=r.get(t);return n===void 0?Promise.resolve({kind:"not-handled"}):Promise.resolve({kind:"resolved",resource:{source:t,async read(){let o=r.sourceFile(t);if(o!==void 0)return[ft(o,await r.readSource(t))];if(t===`${n.source}/breakpoints`)return[{type:"text",text:gt(n)}];let a=r.breakpoint(t);if(t!==n.source&&a===void 0)throw new Error(`Unknown debug resource ${t}`);return[{type:"text",text:a===void 0?N(n):`Breakpoint: ${a.source}
24
+ File: ${a.file}
25
+ Line: ${a.line}
26
+ Status: ${a.verified?"verified":"pending"}`}]}}})}}}i(Ie,"createDebugResourceResolver");function dt(r,e){if(!A(r)||typeof r.path!="string"||typeof r.text!="string")return!1;let t=e.get(r.path);return t!==void 0&&(r.path===t.source||e.sourceFile(r.path)!==void 0)}i(dt,"matchesDebugInsert");function ut(r,e){if(!A(r)||typeof r.path!="string")return!1;let t=e.get(r.path);return t!==void 0&&(r.path===t.source||r.path.startsWith(`${t.source}/breakpoint/`))}i(ut,"matchesDebugDelete");async function lt(r,e,t,n){switch(t.trim().toLowerCase()){case"start":{await r.start(e,n);return}case"continue":{await r.command(e,"continue",n);return}case"step over":{await r.command(e,"next",n);return}case"step into":{await r.command(e,"stepIn",n);return}case"step out":{await r.command(e,"stepOut",n);return}default:throw new Error(`Unknown debug command ${JSON.stringify(t)}`)}}i(lt,"executeSessionCommand");function ct(r,e){return{source:e.source,sourceResource:r.sourceResource(e),breakpointsResource:`${e.source}/breakpoints`,adapter:e.options.adapter,program:e.options.program,cwd:e.options.cwd,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:t,file:n,line:o,verified:a})=>({source:t,file:n,line:o,verified:a})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(ct,"debugDetails");function pt(r,e,t){return{kind:"debug-command",command:t,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:n,file:o,line:a,verified:s})=>({source:n,file:o,line:a,verified:s})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(pt,"debugActionData");function gt(r){return r.breakpoints.size===0?`No breakpoints in ${r.source}.`:[...r.breakpoints.values()].map(e=>`${e.verified?"\u25CF":"\u25CB"} ${e.file}:${e.line} \xB7 ${e.source}`).join(`
27
+ `)}i(gt,"renderBreakpointList");function $e(r,e){let t=r.get(e);if(t===void 0)throw new Error(`Unknown debug session ${e}`);return t}i($e,"requiredSession");function bt(r){let e=A(r)&&typeof r.anchor=="string"?r.anchor:void 0;return/^(\d+)#/u.exec(e??"")?.[1]??e??"selected line"}i(bt,"breakpointLine");function A(r){return typeof r=="object"&&r!==null}i(A,"isRecord");function ft(r,e){return{type:"text",text:e,sourceLines:Object.fromEntries(e.split(/\r?\n/u).map((t,n)=>[String(n+1),{source:r,lineNumber:n+1,content:t}]))}}i(ft,"debugSourceContent");export{st as default};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-EI7MMDWY.js";import e from"node:path";function c(s,i,r=process.platform){let a=r==="win32"?e.win32:e.posix,t=o(p=>{let n=a.resolve(p);return r==="win32"?n.toLowerCase():n},"normalize");return t(s)===t(i)}o(c,"sameFilePath");export{c as a};
@@ -0,0 +1 @@
1
+ import{a as s}from"./chunk-EI7MMDWY.js";var n=class{static{s(this,"AgentIdeProcessRegistry")}#t=new Map;#s=new Set;#e=new Map;add(e){return this.#e.get(e.id)?.(),this.#t.set(e.id,e),this.#e.set(e.id,e.onDidChange(()=>this.#n())),this.#n(),()=>{this.#t.get(e.id)===e&&(this.#e.get(e.id)?.(),this.#e.delete(e.id),this.#t.delete(e.id),this.#n())}}list(){return[...this.#t.values()].flatMap(e=>e.list())}onDidChange(e){return this.#s.add(e),()=>this.#s.delete(e)}dispose(){for(let e of this.#e.values())e();this.#e.clear(),this.#t.clear(),this.#s.clear()}#n(){for(let e of this.#s)e()}},i=new WeakMap;function r(t){let e=i.get(t);return e===void 0&&(e=new n,i.set(t,e)),e}s(r,"agentIdeProcessRegistry");export{r as a};
@@ -0,0 +1 @@
1
+ import{a as w}from"./chunk-M5IVSCR2.js";import{a as S,b as M}from"./chunk-EJ5OACQM.js";import{a as n}from"./chunk-EI7MMDWY.js";import{Container as _,Key as x,matchesKey as P,SelectList as k,Text as v,truncateToWidth as T,visibleWidth as A}from"@earendil-works/pi-tui";var I=class{constructor(e,o,s){this.registry=e;this.activityMode=o;e.onDidChange(()=>this.#s()),s.registerCommand("agent-ide-processes",{description:"Show active terminal and debugger processes created by Agent IDE",handler:n(async(d,c)=>{if(this.bind(c),c.mode!=="tui"){c.ui.notify("The Agent IDE process overlay requires the TUI.","info");return}await this.#r(c)},"handler")})}static{n(this,"AgentIdeProcessesUi")}#t;#i=!1;#e;bind(e){this.#i||(this.#t=e,this.#s())}dispose(){this.#i=!0,this.#e!==void 0&&clearInterval(this.#e),this.#e=void 0,this.#t?.ui.setWidget("agent-ide-processes",void 0),this.#t?.ui.setStatus("agent-ide-processes",void 0),this.#t=void 0}#n(){return this.registry.list()}#s(){let e=this.#t;if(this.#i||e===void 0||!e.hasUI)return;let o=this.#n();if(this.activityMode==="off"||o.length===0){e.ui.setWidget("agent-ide-processes",void 0),e.ui.setStatus("agent-ide-processes",void 0),this.#e!==void 0&&clearInterval(this.#e),this.#e=void 0;return}if(this.activityMode==="compact"){e.ui.setWidget("agent-ide-processes",void 0),e.ui.setStatus("agent-ide-processes",`Agent IDE processes: ${o.length}`);return}e.ui.setStatus("agent-ide-processes",void 0),e.ui.setWidget("agent-ide-processes",(s,d)=>({invalidate(){},render:n(c=>q(o,c,d),"render")}),{placement:"belowEditor"}),this.#e??=setInterval(()=>this.#s(),1e3)}async#r(e){for(;;){if(this.#n().length===0){e.ui.notify("No active Agent IDE processes.","info");return}let o=n(()=>{},"disposeRefresh"),s,d;try{d=await e.ui.custom((g,a,O,E)=>{let h=this.#n(),l="list",f,$=n(r=>{let u=h.map(t=>({value:t.source,label:`${t.status} ${t.kind} ${t.title}`,description:t.description})),p=new k(u,Math.min(u.length,12),{selectedPrefix:n(t=>a.fg("accent",t),"selectedPrefix"),selectedText:n(t=>a.fg("accent",t),"selectedText"),description:n(t=>a.fg("muted",t),"description"),scrollInfo:n(t=>a.fg("dim",t),"scrollInfo"),noMatch:n(t=>a.fg("warning",t),"noMatch")}),y=u.findIndex(t=>t.value===r);return y>=0&&p.setSelectedIndex(y),p.onSelect=t=>{f=h.find(W=>W.source===t.value),l="detail",g.requestRender()},p.onCancel=()=>E(null),p},"createList"),m=$(),C=n(()=>{let r=f?.source??m.getSelectedItem()?.value;h=this.#n(),f=l==="list"?void 0:h.find(u=>u.source===r),m=$(r),g.requestRender()},"refresh");return o=this.registry.onDidChange(C),s=setInterval(C,1e3),{invalidate:n(()=>m.invalidate(),"invalidate"),render(r){let u=new _;l==="list"?(u.addChild(m),u.addChild(new v(a.fg("dim",h.length===0?"esc close":"enter view \xB7 d stop \xB7 esc close"),1,0))):f===void 0?(u.addChild(new v(a.fg("warning","Process is no longer active."),1,0)),u.addChild(new v(a.fg("dim","esc back"),1,0))):(u.addChild(f.renderDetail(a)),u.addChild(new v(a.fg(l==="confirm"?"warning":"dim",l==="confirm"?"Stop this process? y confirm \xB7 n/esc cancel":l==="input"?"input mode \xB7 type to send \xB7 esc stop input":f.sendInput===void 0?"esc back \xB7 d stop":"i input \xB7 esc back \xB7 d stop"),1,0)));let p=n(t=>a.fg("accent",t),"accent"),y=Math.max(1,r-2);return[D("Agent IDE Processes",`${h.length} active`,r,p),...u.render(y).map(t=>b(t,r,p)),R(r,p)]},handleInput(r){l==="list"?r==="d"?(f=h.find(u=>u.source===m.getSelectedItem()?.value),f!==void 0&&(l="confirm")):m.handleInput(r):l==="detail"?P(r,x.escape)?l="list":r==="d"&&f!==void 0?l="confirm":r==="i"&&f?.sendInput!==void 0&&(l="input"):l==="input"?P(r,x.escape)?l="detail":f?.sendInput?.(r):r==="y"&&f!==void 0?E({source:f.source}):(r==="n"||P(r,x.escape))&&(l="detail"),g.requestRender()}}},{overlay:!0,overlayOptions:{width:"75%",maxHeight:"80%",minWidth:52}})}finally{o(),s!==void 0&&clearInterval(s)}if(d===null)return;let c=this.#n().find(g=>g.source===d.source);c!==void 0&&await c.stop()}}};function q(i,e,o){if(i.length===0)return[];let s=n(c=>o.fg("accent",c),"accent"),d=[D("Agent IDE Processes",`${i.length} active`,e,s)];for(let[c,g]of i.entries()){for(let a of g.renderSummary(o))d.push(b(` ${a} `,e,s));c<i.length-1&&d.push(b("",e,s))}return d.push(R(e,s)),d}n(q,"renderProcessWidget");function D(i,e,o,s){if(o<=1)return s("\u256D");let d=o-2,c=`\u2500 ${i} `,g=` ${e} \u2500`,a="\u2500".repeat(Math.max(0,d-A(c)-A(g)));return s(`\u256D${T(`${c}${a}${g}`,d).padEnd(d,"\u2500")}\u256E`)}n(D,"borderTop");function b(i,e,o){if(e<=1)return o("\u2502");let s=e-2,d=T(i,s);return`${o("\u2502")}${d}${" ".repeat(Math.max(0,s-A(d)))}${o("\u2502")}`}n(b,"borderLine");function R(i,e){return e(i<=1?"\u2570":`\u2570${"\u2500".repeat(i-2)}\u256F`)}n(R,"borderBottom");async function L(i){let e=w(i),o=await M(S()),s=new I(e,K(o.preferences?.["processes.activity"]),i);i.on("session_start",(d,c)=>s.bind(c)),i.on("session_shutdown",()=>s.dispose())}n(L,"registerAgentIdeProcesses");function K(i){return i==="compact"||i==="off"?i:"detailed"}n(K,"activityMode");export{L as default};
@@ -0,0 +1,2 @@
1
+ import{a as H}from"./chunk-GUTQ3PWL.js";import{m as S}from"./chunk-5VSE5X5R.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{createHash as ue}from"node:crypto";import{readFile as z}from"node:fs/promises";import f from"node:path";import{spawn as ee}from"node:child_process";import D from"node:path";import{createInterface as te}from"node:readline";import{existsSync as Y}from"node:fs";import Z from"node:os";import F from"node:path";function O(e=process.env.PI_CODING_AGENT_DIR??F.join(Z.homedir(),".pi","agent"),t=process.platform){let n=F.join(e,"bin",t==="win32"?"rg.exe":"rg");return Y(n)?n:"rg"}a(O,"resolveRipgrepExecutable");async function A(e,t,n){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let r=D.resolve(t,oe(e.path??".")),o=["--json","--no-config","--no-ignore-parent","--color=never","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],..._(e.include).flatMap(i=>["--glob",i]),..._(e.exclude).flatMap(i=>["--glob",`!${i}`]),"--",e.query,r];if(e.regex!==!0)return k(["--fixed-strings",...o],n);try{return await k(["--engine","auto",...o],n)}catch(i){if(!ne(i))throw i;return k(["--engine","default",...o],n)}}a(A,"searchText");function k(e,t){return new Promise((n,r)=>{let o=ee(O(),e,{stdio:["ignore","pipe","pipe"]}),i=te({input:o.stdout}),s=[],l="",c,u=a(()=>{o.kill()},"abort"),d=a(()=>{t?.removeEventListener("abort",u),i.close()},"cleanup");o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{l+=m}),i.on("line",m=>{if(!(c!==void 0||m.length===0))try{let h=JSON.parse(m);if(h.type!=="match")return;for(let b of re(h))s.push(b)}catch(h){c=h,o.kill()}}),o.once("error",m=>{d(),r(m)}),o.once("close",m=>{if(d(),t?.aborted===!0){let h=new Error("Search was aborted.");h.name="AbortError",r(h);return}if(c!==void 0){r(new Error("Unable to parse ripgrep search output.",{cause:c}));return}if(m!==0&&m!==1){r(new Error(l.trim()||`ripgrep exited with code ${String(m)}.`));return}s.sort(ie),n({matches:s,complete:!0})}),t?.addEventListener("abort",u,{once:!0}),t?.aborted===!0&&u()})}a(k,"runRipgrep");function ne(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}a(ne,"isPcre2MatchLimitError");function re(e){let t=e.data.path.text,n=e.data.lines.text;if(t===void 0||n===void 0||!Number.isSafeInteger(e.data.line_number))return[];let r=n.replace(/(?:\r\n|\n)$/u,""),o=Buffer.from(n),i=[];for(let s of e.data.submatches){if(s.start<0||s.end<=s.start||s.end>o.length)continue;let l=o.subarray(0,s.start).toString("utf8").length,c=o.subarray(0,s.end).toString("utf8").length;i.push({source:D.resolve(t),lineNumber:e.data.line_number,startColumn:l,endColumn:c,matchedText:r.slice(l,c),lineText:r})}return i}a(re,"matchesFromEvent");function _(e){if(e===void 0)return[];let t=[],n=0,r="";for(let o of e){if(o==="{"?n+=1:o==="}"&&(n=Math.max(0,n-1)),n===0&&(o===","||/\s/u.test(o))){r.length>0&&(t.push(r),r="");continue}r+=o}return r.length>0&&t.push(r),t}a(_,"splitGlobList");function oe(e){return e.startsWith("@")?e.slice(1):e}a(oe,"stripFilePrefix");function ie(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}a(ie,"compareMatches");function N(e,t=!1){let n=M(e);if(!C(n))return t?e:B(e);let r=E(new v(e,n).parse(),t);return`^${r.condition}.*?\\K(${r.match})`}a(N,"compileSearchQuery");function Q(e){if(C(M(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(B).join("|")})`:void 0}a(Q,"compileSearchFallbackQuery");function C(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}a(C,"containsBooleanSyntax");var v=class{static{a(this,"BooleanQueryParser")}#t;#r;#i=0;constructor(t,n){this.#t=t,this.#r=n}parse(){let t=this.#s(),n=this.#e();if(n.type!=="end"){let r=n.type==="right"?"unexpected ')'.":`unexpected ${ae(n)}.`;throw p(n.offset,r)}return t}#s(){let t=this.#n();for(;this.#e().type==="or";){let n=this.#o(),r=this.#c(`after ${n.value}`);t={kind:"or",left:t,right:this.#a(r)}}return t}#n(){return this.#a(this.#c())}#a(t){let n=t;for(;;){let r=this.#e();if(r.type==="and"||r.type==="not"){this.#o();let o=this.#c(`after ${r.value}`);n={kind:r.type,left:n,right:o};continue}if(r.type==="term"||r.type==="left"){n={kind:"and",left:n,right:this.#c()};continue}return n}}#c(t){let n=this.#e();if(n.type==="term")return this.#o(),{kind:"term",value:n.value,quoted:n.quoted};if(n.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw p(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw p(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw p(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw p(n.offset,`expected a term${r}.`)}#e(){return this.#r[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function M(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&se(e,n)){t.push({type:"left",value:r,offset:n}),n+=1;continue}if(r===")"){t.push({type:"right",value:r,offset:n}),n+=1;continue}if(W(e,n)){let s=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+s),offset:n}),n+=s;continue}if(r==="'"||r==='"'){let s=n,l=r,c="";for(n+=1;n<e.length&&e.charAt(n)!==l;)e.charAt(n)==="\\"&&(e.charAt(n+1)===l||e.charAt(n+1)==="\\")&&(n+=1),c+=e.charAt(n++);if(n>=e.length)throw p(s,`unterminated ${l==="'"?"single":"double"}-quoted term.`);if(n+=1,c.length===0)throw p(s,"quoted terms must not be empty.");t.push({type:"term",value:c,offset:s,quoted:!0});continue}let o=n;for(;n<e.length;){let s=e.charAt(n);if(/\s/u.test(s)||s===")"||W(e,n))break;s==="\\"&&n+1<e.length?n+=2:s==="["||s==="("?n=$(e,n)??n+1:n+=1}let i=e.slice(o,n);t.push({type:ce(i),value:i,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}a(M,"tokenize");function W(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}a(W,"isBooleanPipe");function $(e,t){let n=e.charAt(t)==="["?"]":")",r=t+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===n)return r+1;if(n===")"&&(o==="("||o==="[")){let i=$(e,r);if(i===void 0)return;r=i}else r+=1}}}a($,"regexBlockEnd");function se(e,t){let n=$(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:C(M(r))}a(se,"isBooleanGroup");function ce(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}a(ce,"operatorType");function ae(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}a(ae,"quoteToken");function p(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(p,"syntaxError");function E(e,t){if(e.kind==="term"){let o=t&&!e.quoted?e.value:B(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let n=E(e.left,t),r=E(e.right,t);return e.kind==="or"?{condition:`(?:${n.condition}|${r.condition})`,match:`(?:${n.match}|${r.match})`}:e.kind==="not"?{condition:`${n.condition}(?!${r.condition})`,match:n.match}:{condition:`${n.condition}${r.condition}`,match:`(?:${n.match}|${r.match})`}}a(E,"compileExpression");function B(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}a(B,"escapeRegex");function Be(e){let t=N(e.query),n=N(e.query,!0),r=Q(e.query),o=[];return n!==t&&o.push({query:n,mode:"regex"}),r!==void 0&&r!==t&&r!==n&&o.push({query:r,mode:"words"}),{...e,query:t,regex:!0,fallbacks:o}}a(Be,"createSearchRecipe");async function P(e,t,n){let r=e.query,o=await A(e,t,n),i=[];for(let s of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await A({...e,query:s.query,regex:!0},t,n),r=s.query,i.push(s.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(l){if(s.mode!=="regex"||!le(l)||n?.aborted)throw l;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:i}}a(P,"runSearchRecipe");function le(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}a(le,"isRegexSyntaxError");var de=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,U=4;function We(e,t,n,r){return K(e,t,n,r).slice(0,U)}a(We,"createSearchSessionId");function K(e,t,n,r){let o=n===void 0?pe(t.map(c=>c.source)):f.resolve(n),i=t.map(c=>({match:c,source:f.relative(o,f.resolve(c.source))})).sort((c,u)=>c.source.localeCompare(u.source)||L(c.match,u.match)).map(({match:c,source:u})=>[u,c.lineNumber,c.startColumn,c.endLineNumber??c.lineNumber,c.endColumn,c.matchedText,c.lineText]),{limit:s,...l}=V(r??{query:e,regex:!0},o);return ue("sha256").update(JSON.stringify([e,o,l,i])).digest("hex").toUpperCase()}a(K,"createSearchSessionIdentity");function he(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let n=U;n<=e.length;n+=1){let r=e.slice(0,n);if(!t.has(r))return r}throw new Error("Could not allocate a unique search session id.")}a(he,"allocateSearchSessionId");function V(e,t){return{query:e.query,path:f.resolve(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,fallbacks:e.fallbacks??[]}}a(V,"normalizeRecipe");var R=class extends Error{static{a(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},q=class{constructor(t=K){this.createIdentity=t}static{a(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(t,n,r,o,i,s={query:t,regex:!0},l){let c=n.map(j=>({...j,source:f.resolve(j.source)})).sort(L),u=await J(c,i),d=this.createIdentity(t,c,o,s),h=this.#r.get(d)??he(d,new Set(this.#t.keys())),b={id:h,query:t,matches:c,complete:r,contentBySource:u,recipe:s,...l!==void 0&&{refresh:l},cwd:f.resolve(o)};return this.#r.set(d,h),this.#t.set(h,b),b}async registerIfCurrent(t,n,r,o,i,s,l){try{return await this.register(t,n,r,o,i,s,l)}catch(c){if(c instanceof R)return;throw c}}async observeAfterEdit(t,n){let r=new Set(t.flatMap(i=>{let s=typeof i=="string"?w(i):void 0;return s===void 0?[]:[s.id]})),o=[];for(let i of r){let s=this.#t.get(i);if(s===void 0)continue;let l={sessionId:i,query:s.recipe.originalQuery??s.query,scope:V(s.recipe,s.cwd)};try{let c=s.refresh===void 0?await P(s.recipe,s.cwd,n):await s.refresh(n);o.push({...l,matches:c.matches.length,complete:c.complete,notices:c.notices})}catch(c){o.push({...l,error:c instanceof Error?c.message:String(c)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
2
+ `),renderFull(t){return t},renderCompact(t){let n=w(t);return n===void 0?"selected result":n.selector==="all"?n.mode==="match"?"all matches":"all lines":n.mode==="match"?`match ${String(n.selector)}`:`line ${String(n.selector)}`},tryResolve:a((t,n)=>this.#i(t,n.source,n.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:a((t,n)=>this.#s(t,n.cwd),"tryResolve")}}async#i(t,n,r){let o=w(t);if(o===void 0)return{kind:"not-handled"};let i=this.#t.get(o.id);if(i===void 0)return x();if(o.selector==="all"&&!i.complete)return y();let s=f.resolve(n),l=i;if(o.selector==="all"){if(i.refreshedComplete?.complete===!0)l=i.refreshedComplete;else if(i.refreshedComplete!==void 0&&(l=await this.#n(i,r),!l.complete))return y()}let c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await I(s,r);if(d===void 0)return x(g(u[0]).lineNumber);if(o.selector==="all"&&d!==l.contentBySource.get(s)){if(l=await this.#n(i,r),!l.complete)return y();c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==i.contentBySource.get(s))return x(g(u[0]).lineNumber);let m=S(s,d);return{kind:"resolved",anchor:new H(t,s,u.map(h=>G(m,h,o.mode)))}}async#s(t,n){let r=w(t);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return x();if(r.selector==="all"&&!o.complete)return y();let i=o;if(r.selector==="all"){if(o.refreshedComplete?.complete===!0)i=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(i=await this.#n(o),!i.complete))return y();let u=new Set(T(i,r.selector,r.mode).map(d=>d.source));for(let d of u)if(await I(d)!==i.contentBySource.get(d)){if(i=await this.#n(o),!i.complete)return y();break}}let s=T(i,r.selector,r.mode);if(r.selector!=="all"){let u=s[0]?.source;if(u!==void 0&&await I(u)!==i.contentBySource.get(u))return x(s[0]?.lineNumber)}let l=new Map;for(let u of s){let d=l.get(u.source)??[];d.push(G(S(u.source,i.contentBySource.get(u.source)??u.lineText),u,r.mode)),l.set(u.source,d)}let c=[...l].map(([u,d])=>({source:u,ranges:d,expectedContent:i.contentBySource.get(u)}));return c.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:c}}async#n(t,n){let r=t.refresh===void 0?await P(t.recipe,t.cwd,n):await t.refresh(n),o=r.matches.map(s=>({...s,source:f.resolve(s.source)})).sort(L),i={matches:o,complete:r.complete,contentBySource:await J(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:i}),i}};function w(e){let t=de.exec(e);if(t!==null)return{id:g(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}a(w,"parseSearchAnchor");function T(e,t,n){let r=t==="all"?e.matches:[e.matches[t-1]].filter(fe);if(n==="match"||t!=="all")return r;let o=new Set;return r.flatMap(i=>{let s=S(i.source,e.contentBySource.get(i.source)??i.lineText),l=X(i);return s.lines.slice(i.lineNumber-1,l).flatMap(c=>{let u=`${i.source}\0${String(c.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...i,lineNumber:c.lineNumber,endLineNumber:c.lineNumber,startColumn:0,endColumn:c.content.length,lineText:c.content,matchedText:c.content}])})})}a(T,"selectMatches");function fe(e){return e!==void 0}a(fe,"isMatch");function X(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(X,"lastContainingLine");function G(e,t,n){if(n==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let r=X(t),o=g(e.lines[r-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:r+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}a(G,"selectionRange");function me(e,t){let n=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,n).map(r=>{let o=r.lineNumber===t.lineNumber?t.startColumn:0,i=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,i)+(r.lineNumber===n?"":r.lineEnding)}).join("")}a(me,"matchedSourceText");async function J(e,t){let n=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await z(r,{encoding:"utf8",...t!==void 0&&{signal:t}}),i=S(r,o);for(let s of e.filter(l=>l.source===r))if(i.lines[s.lineNumber-1]?.content!==s.lineText||me(i,s)!==s.matchedText)throw new R(r);n.set(r,o)}return n}a(J,"snapshotContents");async function I(e,t){try{return await z(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(I,"readCurrent");function x(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}a(x,"staleAnchor");function y(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}a(y,"missingCompleteAnchor");function pe(e){if(e.length===0)return".";let t=f.dirname(f.resolve(g(e[0])));for(let n of e.slice(1)){let r=f.resolve(n);for(;!ge(t,r);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}a(pe,"commonSourceDirectory");function ge(e,t){let n=f.relative(e,t);return n!==".."&&!n.startsWith(`..${f.sep}`)&&!f.isAbsolute(n)}a(ge,"isWithin");function L(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}a(L,"compareMatches");export{O as a,Be as b,P as c,We as d,K as e,he as f,R as g,q as h};
@@ -0,0 +1,26 @@
1
+ import{a as re,b as ie,c as oe}from"./chunk-ESPNEJHK.js";import{a as ne}from"./chunk-M5IVSCR2.js";import{a as Z}from"./chunk-L7JMDDSD.js";import{a as z,b as J}from"./chunk-O6LE42GK.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as K}from"./chunk-6CZO43OH.js";import{a as Y,b as V}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as te}from"./chunk-ZTYWHL2F.js";import{a as Q,b as ee}from"./chunk-7UGNGK7Y.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Fe from"node:path";import{stripVTControlCharacters as je}from"node:util";import{truncateLine as Ge}from"@earendil-works/pi-coding-agent";import{Text as x}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as ae,formatSize as Ue,truncateTail as We}from"@earendil-works/pi-coding-agent";function I(t){return We(t,{maxBytes:se-4096,maxLines:ae-32})}a(I,"terminalOutputTail");function P(t){let e=I(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
+ `)}
3
+ output:${r.length===0?" (empty)":`
4
+ ${r}`}`;let i=e.truncatedBy==="lines"?`${ae} line output budget`:`${Ue(se)} output budget`,s=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
+ `)}
6
+ output:
7
+ ${s}${r.length===0?"":`
8
+ ${r}`}`}a(P,"formatAgentTerminalSnapshot");var He=500;function le(t,e,n,r,i){let s=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${$(n)} \xB7 ${s}`)}`;return new x(`${o}
9
+ ${i.fg("accent",O(r.family))} ${t}`,0,0)}a(le,"renderRunCall");function ue(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new x(r.join(`
10
+ `),0,0)}a(ue,"renderTerminalActionResult");function E(t,e,n,r,i){let s=[Ye(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(o=>` ${i.fg("dim",o)}`)),new x(s.join(`
11
+ `),0,0)}a(E,"renderTerminalAction");function S(t,e,n,r){let i=Be(t,R,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new x(i.join(`
12
+ `),0,0)}a(S,"renderTerminalResult");function ce(t,e,n){if(e)return S(t,!0,n);let r=_(t.output??"",R),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(s=>` ${n.fg("dim",s)}`)];return i.push(D(t,(s,o)=>n.fg(s,o))),new x(i.join(`
13
+ `),0,0)}a(ce,"renderRunResult");function de(t,e){let n=a((o,l)=>e?.fg(o,l)??l,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${$(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",O(t.shellFamily))} ${M(t.command,84)}`],s=qe(t.output,2);return s.length>0&&i.push(...s.map(o=>` ${n("dim",M(o,90))}`)),i.push(D(t,n)),i.join(`
14
+ `)}a(de,"renderActiveTerminal");function Be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":$(t.cwd),o=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",O(o))} ${t.command??""}`],u=_(t.output??"",e);return u.omission!==void 0&&l.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&l.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),l.push(D(t,(c,d)=>n.fg(c,d))),l}a(Be,"terminalCardLines");function qe(t,e){return _(t,e).lines}a(qe,"outputTail");function _(t,e){let n=I(je(t).replaceAll("\r","")),r=n.content.split(`
15
+ `).map(u=>Ge(u.trimEnd(),He).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),l=s+o;return{lines:r.slice(s),...n.truncated||l>0?{omission:l>0?`\u2026 ${l} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(_,"outputWindow");function D(t,e){let n=t.status??"running",r=Xe(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,Ve(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}a(D,"statusLine");function Xe(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Xe,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function Ye(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":$(t.cwd),i=t.background===!0?"background":"wait",s=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}a(Ye,"terminalIdentity");function $(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Fe.sep}`))?`~${t.slice(e.length)}`:t}a($,"shortCwd");function M(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(M,"oneLine");function Ve(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Ve,"formatElapsed");function me(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:a(n=>de(e,n).split(`
16
+ `),"renderSummary"),renderDetail:a(n=>S(e,!0,n),"renderDetail"),sendInput:a(n=>t.write(e.source,n),"sendInput"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(me,"terminalProcessProvider");var Ke="#d8dee9",N="#111418",ze=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function U(t,e,n){let r=t.get(e);if(r===void 0)throw new Error(`Unknown terminal session ${e}`);await r.screenReady;let{createCanvas:i}=await import("@napi-rs/canvas"),s=Math.max(0,Math.min(r.rows-1,n?.start??0)),o=Math.max(1,Math.min(r.rows-s,n?.count??r.rows)),l=i(r.cols*9+24,o*18+24),u=l.getContext("2d");u.fillStyle=N,u.fillRect(0,0,l.width,l.height),u.textBaseline="top";let c=r.screen.buffer.active,d=Math.max(0,c.baseY);for(let m=0;m<o;m+=1){let p=c.getLine(d+s+m);if(p!==void 0)for(let f=0;f<r.cols;f+=1){let h=p.getCell(f);h===void 0||h.getWidth()===0||Je(u,h,f,m)}}return r.status==="running"&&c.cursorY>=s&&c.cursorY<s+o&&(u.fillStyle="rgba(216, 222, 233, 0.75)",u.fillRect(12+c.cursorX*9,12+(c.cursorY-s)*18+18-2,9,2)),l.toBuffer("image/png").toString("base64")}a(U,"renderTerminalScreen");function Je(t,e,n,r){let i=pe(e,"foreground"),s=pe(e,"background");e.isInverse()&&([i,s]=[s,i]);let o=12+n*9,l=12+r*18;s!==N&&(t.fillStyle=s,t.fillRect(o,l,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,o,l),e.isUnderline()&&t.fillRect(o,l+18-2,9*Math.max(1,e.getWidth()),1))}a(Je,"drawCell");function pe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ke:N;let i=n?t.isFgRGB():t.isBgRGB(),s=n?t.getFgColor():t.getBgColor();return i?`#${s.toString(16).padStart(6,"0")}`:Ze(s)}a(pe,"cellColor");function Ze(t){let e=ze[t];if(e!==void 0)return e;if(t>=232){let l=8+(t-232)*10;return fe(l,l,l)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),s=n%6,o=a(l=>l===0?0:55+l*40,"channel");return fe(o(r),o(i),o(s))}a(Ze,"ansiColor");function fe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(fe,"rgb");var W="\0pi-terminal-write\0",F="\0pi-terminal-keys\0";async function Se(t,e){let n=new Map,r=new Map,i={protocol:Y,apiVersion:V,id:"terminal",setup(o){o.addResolver({resolver:Qe(e),preserveTruncatedOutput:!0,renderResult(l,u,c){let d=l.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return S(m===void 0?p:{...p,output:e.screenTail(m).join(`
17
+ `)},u.expanded,c,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(l){let u=l.request.path;if(u===void 0||!y(u)||l.request.views?.includes("image")!==!0)return{kind:"continue",context:l};let c=e.get(u);if(c===void 0)return{kind:"return",result:ge(u,`Unknown terminal session ${u}`)};try{return e.markInspected(u),{kind:"return",result:{content:[{type:"image",data:await U(e,u),mimeType:"image/png"}],details:{source:c.source,resolvedBy:"terminal"}}}}catch(d){return{kind:"return",result:ge(u,d instanceof Error?d.message:String(d))}}}}),o.describe('shell:<session> \u2014 terminal session status and a bounded output tail with a full-log path when truncated. Use views: ["image"] to read the current virtual terminal screen as a PNG.'),o.addPromptGuideline("Use read with a returned shell:<session> source to inspect terminal status and output. Add the image view when cursor movement, ANSI layout, or a full-screen terminal interface matters.")}},s={protocol:z,apiVersion:J,id:"terminal",setup(o){o.addResolver({resolver:et(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(ye(l.input,e,n),await he(l.input,e,r),tt(l,W)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await he(l.input,e,r),ye(l.input,e,n),nt(l)),"handler")});for(let l of["write","insert","delete"])o.addToolRenderer({tool:l,matches:a((u,c)=>st(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),E(f.snapshot??{},l,we(l,m),[],c)},renderResult(u,c,d){let m=ot(u.details);return ue(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([K(t,i),Z(t,s)]),t.on("tool_result",async(o,l)=>{if(!w(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:o.details,isError:!0};if(o.toolName==="delete"&&typeof u=="string"&&y(u)){let X=e.get(u);if(X===void 0)return;let Ne=e.snapshot(X);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:Ne,action:"delete",input:"session",changedLines:[]},isError:!1}),L=>({content:[{type:"text",text:L instanceof Error?L.message:String(L)}],details:{source:u,deleted:!1},isError:!0}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,v=we(h,o.input),b=e.screenChangeRegion(d,m,6),q=[{type:"text",text:`Sent ${v} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&q.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:q,details:{source:d.source,action:h,status:d.status,snapshot:f,input:v,changedLines:b.lines},isError:o.isError}})}a(Se,"registerTerminalResources");function Qe(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:rt(r)}]}}}}}}a(Qe,"createReadResolver");function et(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=it(r),s=i.indexOf(W),o=i.indexOf(F);if(s>=0){t.write(n.source,i.slice(s+W.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(et,"createInputResolver");function tt(t,e){return!w(t.input)||!Te(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(tt,"transformWriteInput");function nt(t){if(!w(t.input)||!Te(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${F}${typeof t.input.text=="string"?t.input.text:""}`}}}a(nt,"transformInsertInput");function rt(t){return P(t)}a(rt,"formatSnapshot");function it(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(it,"singleText");function ge(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(ge,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Te(t){return typeof t=="string"&&y(t)}a(Te,"isShellSourceValue");function ot(t){if(!w(t)||!w(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(ot,"terminalActionDetails");async function he(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(he,"rememberScreen");function ye(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(ye,"rememberOutputEnd");function we(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(we,"terminalInputLabel");function st(t,e){if(!w(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return w(n)&&typeof n.source=="string"&&y(n.source)}a(st,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Re(t,e){await te(t,{protocol:Q,apiVersion:ee,id:"terminal",setup(r){r.addResolver({resolver:at(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."),r.addPromptGuideline("Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.")}})}a(Re,"registerTerminalSearch");function at(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=lt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=j(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
18
+ `)}
19
+
20
+ ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,s=H(i)?j(i.payload):j(void 0),o=E(s.snapshot,"search",JSON.stringify(s.query),s.matches.slice(-6).map(l=>`${l.lineNumber}: ${l.lineText}`),r);return new G(o,n.expanded===!0,r)}}}a(at,"terminalSearchResolver");var be=12,G=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{a(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=be)return n;let r=be-1;return[...n.slice(0,r),this.theme.fg("muted",`\u2026 ${String(n.length-r)} visual rows omitted \xB7 ctrl+o to expand`)]}invalidate(){this.content.invalidate()}};function lt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[s,o]of t.output.replaceAll("\r","").split(`
21
+ `).entries()){let l=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=l.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||ut(l,c,d))&&r.push({source:t.source,lineNumber:s+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(lt,"findTerminalMatches");function ut(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(ut,"isWordBoundary");function j(t){if(!ct(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function ct(t){return H(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&H(t.snapshot)&&typeof t.snapshot.source=="string"}a(ct,"isTerminalSearchPayload");function H(t){return typeof t=="object"&&t!==null}a(H,"isRecord");import{spawn as dt}from"node:child_process";import{closeSync as mt,mkdirSync as pt,openSync as ft,rmSync as gt,writeSync as ht}from"node:fs";import yt from"node:os";import xe from"node:path";import{createRequire as wt}from"node:module";import{randomUUID as St}from"node:crypto";import{stripVTControlCharacters as Tt}from"node:util";var Ee=wt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),ve=1e6,bt=100,Rt=30,xt=2e3,A=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=Et){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get($t(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Mt(n);this.#i.set(n,ft(r,"a",384));let i=e.cols??bt,s=e.rows??Rt,o=Pt(i,s),l=a(p=>{},"resolveCompletion"),u=new Promise(p=>{l=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:s,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=Ee("node-pty"),f={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:kt(At())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:It(p)};return this.#e.set(n,f),this.#s(n),l(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{T(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return T(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,s)=>{let o=a(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",o),i(l)},s)})}async waitForForeground(e,n){let r=this.required(e);if(T(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(s=>{let o=!1,l,u=a(p=>{o||(p!==void 0&&T(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!vt(r)){l=void 0;return}l??=Date.now(),Date.now()-l>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,s;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=40)return;await B(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),s=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),l=-1;for(let d=0;d<=e.rows-s;d+=1){let m=0;for(let p=d;p<d+s;p+=1){let f=n[p]??"",h=i[p]??"",v=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(v||b)&&(m+=1)}m>l&&(l=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+s).map((d,m)=>{if(o+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),s=[];for(let o=0;o<e.rows;o+=1){let l=r.getLine(i+o)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&s.push(l)}return s.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Ct(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await Pe(r,!1),await Promise.race([r.completion.then(()=>!0),B(xt).then(()=>!1)])||(await Pe(r,!0),await Promise.race([r.completion,B(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),gt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],s=Math.max(0,r.baseY);for(let o=s;o<s+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!T(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Tt(n),i=this.#i.get(e.id);if(i!==void 0&&ht(i,r),e.output+=r,e.output.length>ve){let s=e.output.length-ve;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(mt(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function vt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(vt,"looksInteractive");function Pt(t,e){let{Terminal:n}=Ee("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(Pt,"createScreen");function Et(){return St().replaceAll("-","").slice(0,12)}a(Et,"defaultSessionId");function $t(t){return t.startsWith("shell:")?t.slice(6):t}a($t,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function At(){return process.env}a(At,"processEnvironment");function kt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(kt,"cleanEnvironment");function Ct(t){return t.split(/[\s,]+/u).filter(Boolean).map(Lt).join("")}a(Ct,"encodeTerminalKeys");function Lt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),s=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return s?`\x1B${m}`:m}let l={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!s&&!o&&l[n]!==void 0)return l[n];if(s&&!i&&!o&&l[n]!==void 0)return`\x1B${l[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!s&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(s?2:0)+(i?4:0)}${c}`;if(s&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(Lt,"encodeTerminalKey");async function Pe(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=dt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(Pe,"terminateProcessTree");function B(t){return new Promise(e=>setTimeout(e,t))}a(B,"delay");function It(t){return t instanceof Error?t.message:String(t)}a(It,"errorMessage");function Mt(t){let e=xe.join(yt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return pt(e,{recursive:!0,mode:448}),xe.join(e,`${t}.log`)}a(Mt,"createOutputLog");import _t from"node:os";import $e from"node:path";function Ae(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=$e.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||_t.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=$e.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a(Ae,"resolveShellProfile");function ke(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(ke,"shellSyntaxGuidance");import Ce from"node:path";import{stripVTControlCharacters as Dt}from"node:util";import{defineTool as Ot}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Nt=g.Object({command:g.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:g.Optional(g.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:g.Optional(g.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:g.Optional(g.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:g.Optional(g.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:g.Optional(g.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function Le(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(Ot({name:i,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Write commands for ${n.displayName}; commands are not translated between shell languages.`,`Use ${i} with background for servers, watchers, and long builds. After a session enters background, do not poll it continuously; continue other work or wait for completion. Keep short tasks in the foreground. Enable periodic or verbose output for long-running commands. Use the returned shell: source with read, write, insert, and delete.`],description:`Use ${i} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions are treated as potentially stale after two minutes and wake an idle agent for inspection. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${ke(n)}`,parameters:Nt,async execute(s,o,l,u,c){r.bind(c);let d=o.cwd===void 0?c.cwd:Ce.resolve(c.cwd,o.cwd),m=e.start({command:o.command,background:o.background??!1,cwd:d,shell:n,...o.cols===void 0?{}:{cols:o.cols},...o.rows===void 0?{}:{rows:o.rows}});if(o.background===!0&&m.status!=="failed")return await Ut(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),k(e.snapshot(m));if(m.status==="failed")return k(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(o.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),k(e.snapshot(p.session))},renderCall(s,o){let l=typeof s.command=="string"?s.command:"",u=typeof s.cwd=="string"?Ce.resolve(process.cwd(),s.cwd):process.cwd();return le(l,s.background===!0,u,n,o)},renderResult(s,o,l){return ce(s.details,o.expanded,l)}}))}a(Le,"registerTerminalTools");function k(t){return{content:[{type:"text",text:P(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(k,"terminalResult");async function Ut(t,e,n){await new Promise(r=>{let i=!1,s,o=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(s),o(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(k(c)),(Dt(c.output).replaceAll("\r","").split(`
22
+ `).filter(m=>m.length>0).length>=R||c.status!=="running")&&l()},"publish");o=t.onDidChange(c=>{c.id===e.id&&u()}),s=setTimeout(l,2e3),u()})}a(Ut,"captureInitialBackgroundPreview");import{Box as Ie,Container as Me}from"@earendil-works/pi-tui";var Wt=120,Ft=12e4,C=class{constructor(e,n,r=Ft){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:s},o)=>{let l=_e(i.details)?i.details:void 0,u=new Me;l!==void 0&&u.addChild(S(l,s,o,"stale \xB7 inspect session"));let c=new Ie(1,1,d=>o.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:s},o)=>{let l=new Me;for(let c of jt(i.details))l.addChild(S(c,s,o));let u=new Ie(1,1,c=>o.bg("toolSuccessBg",c));return u.addChild(l),u}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{a(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:Ht(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.#t.set(e.id,setTimeout(()=>this.#n(e),this.staleIntervalMs))}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:Gt(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},Wt)))}};function jt(t){return!Oe(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(_e)}a(jt,"completionSnapshots");function _e(t){return Oe(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}a(_e,"isTerminalSessionSnapshot");function Gt(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
23
+ ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,s=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${De(n.elapsedMs)}
24
+ ${s||"(no output)"}`}).join(`
25
+ `)}`}a(Gt,"formatCompletionMessage");function Ht(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${De(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
26
+ ${e||"(no output)"}`}a(Ht,"formatStaleMessage");function De(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(De,"formatElapsed");function Oe(t){return typeof t=="object"&&t!==null}a(Oe,"isRecord");async function Bt(t){let e=ie("terminal")??new A,n=Ae(),r=new C(t,e),i=ne(t).add(me(e));await Promise.all([Se(t,e),Re(t,e)]),Le(t,e,n,r),t.on("session_start",(s,o)=>r.bind(o)),t.on("agent_settled",(s,o)=>r.onAgentSettled(o)),t.on("session_shutdown",async s=>{if(r.dispose(),i(),s.reason!=="quit"){re("terminal",e);return}oe("terminal",e),await e.dispose()})}a(Bt,"registerTerminal");export{Bt as default};
@@ -1,2 +1,2 @@
1
- import"./chunk-NNCZYO4Q.js";import{d as N}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as E}from"./chunk-6CZO43OH.js";import{a as A,b}from"./chunk-OBNING2A.js";import{d as O}from"./chunk-WGGIQ7IJ.js";import"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as D,g as w,h as k,i as P,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-HKMBQLEK.js";import{a as y,b as I}from"./chunk-Z3VC3S2T.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import S from"node:path";var T="diagnostics",V=N({kind:"code-view",label:"Diagnostics"});async function q(c){let n,t=l((o,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(o,{cwd:f,...e})},"collect"),i={protocol:y,apiVersion:4,id:"diagnostics",setup(o){n=o.readDiagnostics}},r=new WeakMap,s=new WeakMap,a=new WeakMap,d=new WeakMap,M={protocol:A,apiVersion:b,id:"diagnostics",setup(o){o.addResolver({resolver:W(t,s),renderResult:V});let f=v();o.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),o.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=s.get(g);return u&&r.set(e.request,u),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),o.addHandler({stage:"post-read",handler(e){let g=r.get(e.request);if(g&&e.result)return{kind:"continue",context:{...e,result:{...e.result,details:{...e.result.details,diagnosticCheck:g}}}};let u=a.get(e.request),h=u&&d.get(u),p=e.result,R=p?.content[0];return!h||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${h}
1
+ import{d as O}from"./chunk-FEDVTZJG.js";import"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as N}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as E}from"./chunk-6CZO43OH.js";import{a as A,b}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as D,g as w,h as k,i as P,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-HKMBQLEK.js";import{a as y,b as I}from"./chunk-Z3VC3S2T.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import S from"node:path";var T="diagnostics",V=N({kind:"code-view",label:"Diagnostics"});async function q(c){let n,t=l((o,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(o,{cwd:f,...e})},"collect"),i={protocol:y,apiVersion:4,id:"diagnostics",setup(o){n=o.readDiagnostics}},r=new WeakMap,s=new WeakMap,a=new WeakMap,d=new WeakMap,M={protocol:A,apiVersion:b,id:"diagnostics",setup(o){o.addResolver({resolver:W(t,s),renderResult:V});let f=v();o.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),o.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=s.get(g);return u&&r.set(e.request,u),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),o.addHandler({stage:"post-read",handler(e){let g=r.get(e.request);if(g&&e.result)return{kind:"continue",context:{...e,result:{...e.result,details:{...e.result.details,diagnosticCheck:g}}}};let u=a.get(e.request),h=u&&d.get(u),p=e.result,R=p?.content[0];return!h||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${h}
2
2
  ${R.text}`},...p.content.slice(1)]}}}}}),o.describe('diagnostics:<path> \u2014 lint and language-server diagnostics. views: ["diagnostics"] \u2014 diagnostics alongside source text. Diagnostic sources name the actual reporting tools. Automatic notices include findings only and wake an idle agent after the notification buffer (five seconds by default); silence does not prove the file is clean. Use an explicit diagnostic read to check readiness. Pending results and snapshots are not completed checks; an empty snapshot does not prove the file is clean.'),o.addPromptGuideline("Use read with `diagnostics:<path>` or the `diagnostics` view for per-file diagnostics instead of running equivalent checks through Bash. Project builds and tests remain separate verification.")}};await Promise.all([C(c,i),E(c,M)])}l(q,"registerDiagnostics");function W(c,n){return{id:"diagnostics",tryResolve(t,i){return Promise.resolve(_(t,i.cwd,c,n,{signal:i.signal,...i.audience==="script"&&{mode:"complete"}}))}}}l(W,"createDiagnosticResolver");function _(c,n,t,i,r){let s;try{s=m(c,T,n)}catch(a){return{kind:"failed",error:a}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:D(T,s),async read(){let a=await t(s,n,r),d=w(s,a.content,a.results);return i.set(d,d.diagnosticCheck),[d]}}}}l(_,"resolveDiagnosticSource");function j(c,n){return{id:"diagnostics",async present(t,i){if(i.purpose!=="read"||!S.isAbsolute(t.source))return t;let r=i.audience==="script"&&!i.requestedViews?.includes("diagnostics");if(r&&O(t.source))return t;let s=await c(t.source,i.cwd,{signal:i.signal,...i.audience==="script"&&{mode:r?"snapshot":"complete"}}).catch(a=>{if(i.signal?.throwIfAborted(),!r)throw a});if(s===void 0||r&&s.content!==t.content)return t;if(s.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,P(s.results)),k(t,s.results)}}}l(j,"createDiagnosticPresenter");export{q as default};
package/dist/entry-10.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-U2JKHKLK.js";import"./chunk-J4RTW44E.js";import"./chunk-NNCZYO4Q.js";import"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as g}from"./chunk-6CZO43OH.js";import{a as f,b as y}from"./chunk-OBNING2A.js";import"./chunk-IQD6PON5.js";import"./chunk-WGGIQ7IJ.js";import{a as l}from"./chunk-L7JMDDSD.js";import{a as s,b as c}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function x(n,e){return u(e),g(n,{protocol:f,apiVersion:y,id:`hook/before-read/${e.id}`,setup(t){t.addResourceGuard({id:e.id,async guard(o){let r=await e.run(o);return r.decision==="allow"?{kind:"accepted"}:{kind:"rejected",reason:r.reason}}})}})}d(x,"connectBeforeReadHook");function A(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/before-edit/${e.id}`,setup(t){t.addMutationGuard({id:e.id,async guard(o,r){let a=await e.run({cwd:r.cwd,intent:r.intent??"edit",resources:o.resources.map(i=>({resourceSource:i.source,existed:i.existed,before:i.before,after:i.after,changes:i.changes})),...r.signal!==void 0&&{signal:r.signal}});return a.decision==="allow"?{kind:"accepted"}:{kind:"rejected",rejection:{code:"MUTATION_REJECTED",reason:a.reason,message:`Edit blocked by hook ${e.id}: ${a.reason}`,effect:"not-applied"}}}})}})}d(A,"connectBeforeEditHook");function m(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/after-edit/${e.id}`,setup(t){t.onDidEdit(async o=>{if(o.postProcessing!=="deferred")try{return await e.run(o)}catch(r){return{feedback:`After-edit hook ${e.id} failed after the edit was saved: ${r instanceof Error?r.message:String(r)}`,tone:"error"}}})}})}d(m,"connectAfterEditHook");function u(n){if(n.id.trim().length===0||typeof n.run!="function")throw new TypeError("A file hook needs a non-empty id and run function")}d(u,"assertHook");export{m as connectAfterEditHook,A as connectBeforeEditHook,x as connectBeforeReadHook};
1
+ import"./chunk-IQD6PON5.js";import"./chunk-FEDVTZJG.js";import{a as l}from"./chunk-L7JMDDSD.js";import{a as s,b as c}from"./chunk-O6LE42GK.js";import"./chunk-U2JKHKLK.js";import"./chunk-22CLOM2D.js";import"./chunk-NNCZYO4Q.js";import"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as g}from"./chunk-6CZO43OH.js";import{a as f,b as y}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function x(n,e){return u(e),g(n,{protocol:f,apiVersion:y,id:`hook/before-read/${e.id}`,setup(t){t.addResourceGuard({id:e.id,async guard(o){let r=await e.run(o);return r.decision==="allow"?{kind:"accepted"}:{kind:"rejected",reason:r.reason}}})}})}d(x,"connectBeforeReadHook");function A(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/before-edit/${e.id}`,setup(t){t.addMutationGuard({id:e.id,async guard(o,r){let a=await e.run({cwd:r.cwd,intent:r.intent??"edit",resources:o.resources.map(i=>({resourceSource:i.source,existed:i.existed,before:i.before,after:i.after,changes:i.changes})),...r.signal!==void 0&&{signal:r.signal}});return a.decision==="allow"?{kind:"accepted"}:{kind:"rejected",rejection:{code:"MUTATION_REJECTED",reason:a.reason,message:`Edit blocked by hook ${e.id}: ${a.reason}`,effect:"not-applied"}}}})}})}d(A,"connectBeforeEditHook");function m(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/after-edit/${e.id}`,setup(t){t.onDidEdit(async o=>{if(o.postProcessing!=="deferred")try{return await e.run(o)}catch(r){return{feedback:`After-edit hook ${e.id} failed after the edit was saved: ${r instanceof Error?r.message:String(r)}`,tone:"error"}}})}})}d(m,"connectAfterEditHook");function u(n){if(n.id.trim().length===0||typeof n.run!="function")throw new TypeError("A file hook needs a non-empty id and run function")}d(u,"assertHook");export{m as connectAfterEditHook,A as connectBeforeEditHook,x as connectBeforeReadHook};
package/dist/entry-11.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-U2JKHKLK.js";import{a as k,b as l,c as m,d as n,e as o,f as p,g as q}from"./chunk-J4RTW44E.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as h}from"./chunk-6CZO43OH.js";import{a,b,c,d,e,f,g}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{i as COMPACT_READ_ROWS,b as READ_API_VERSION,c as READ_CORE_READY_EVENT,d as READ_PLUGIN_REGISTER_EVENT,a as READ_PROTOCOL,h as connectReadPlugin,j as createReadResultRenderer,p as isFragmentResolverRegistration,e as isReadCoreReady,q as isReadFragmentResolution,n as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,o as isReadViewRegistration,m as isResourceResolverRegistration,l as isTextTargetResolverRegistration,k as readParameters};
1
+ import{a}from"./chunk-K5G4FDXD.js";import"./chunk-EI7MMDWY.js";export{a as sameFilePath};
package/dist/entry-12.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-S3ZPXWX7.js";import"./chunk-EI7MMDWY.js";export{j as CONTENT_API_VERSION,l as CONTENT_CONVERTER_REGISTER_EVENT,k as CONTENT_HOST_READY_EVENT,i as CONTENT_PROTOCOL,d as UnsupportedContentError,u as connectContentConverter,s as createContentHost,g as createContentRunner,r as isAgentContent,b as isContentConversionAttempt,x as isContentConversionContext,a as isContentConverter,c as isContentConverterRegistration,q as isContentConverterRegistrationRequest,n as isContentHostReady,t as isContentInput,p as isContentTarget,e as isResource,m as isResourceResolutionAttempt,f as isResourceResolver,o as renderContentDescription,h as targetsEqual};
1
+ import"./chunk-U2JKHKLK.js";import{a as k,b as l,c as m,d as n,e as o,f as p,g as q}from"./chunk-22CLOM2D.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as h}from"./chunk-6CZO43OH.js";import{a,b,c,d,e,f,g}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{i as COMPACT_READ_ROWS,b as READ_API_VERSION,c as READ_CORE_READY_EVENT,d as READ_PLUGIN_REGISTER_EVENT,a as READ_PROTOCOL,h as connectReadPlugin,j as createReadResultRenderer,p as isFragmentResolverRegistration,e as isReadCoreReady,q as isReadFragmentResolution,n as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,o as isReadViewRegistration,m as isResourceResolverRegistration,l as isTextTargetResolverRegistration,k as readParameters};
package/dist/entry-13.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-ROXXK6TW.js";import{a}from"./chunk-KII2JQC5.js";import{a as x}from"./chunk-ZTYWHL2F.js";import{a as o,b as r,c as e,d as f,e as m,f as p,g as t}from"./chunk-7UGNGK7Y.js";import"./chunk-EI7MMDWY.js";export{r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,a as searchSchema};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-S3ZPXWX7.js";import"./chunk-EI7MMDWY.js";export{j as CONTENT_API_VERSION,l as CONTENT_CONVERTER_REGISTER_EVENT,k as CONTENT_HOST_READY_EVENT,i as CONTENT_PROTOCOL,d as UnsupportedContentError,u as connectContentConverter,s as createContentHost,g as createContentRunner,r as isAgentContent,b as isContentConversionAttempt,x as isContentConversionContext,a as isContentConverter,c as isContentConverterRegistration,q as isContentConverterRegistrationRequest,n as isContentHostReady,t as isContentInput,p as isContentTarget,e as isResource,m as isResourceResolutionAttempt,f as isResourceResolver,o as renderContentDescription,h as targetsEqual};
package/dist/entry-14.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s}from"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as TextAnchor,r as attachTextAnchorRenderer,j as createTextContentConverter,g as createTextDocument,e as getTextAnchorRenderer,a as getTextSourceLine,t as isTextAnchorRecoveryOutcome,p as isTextAnchorResolutionAttempt,m as isTextAnchorResolver,c as isTextLinePresenter,d as isTextPresenterRegistration,n as isTextTargetResolutionAttempt,k as isTextualMediaType,i as renderPresentedTextDocument,x as renderPresentedTextRows,f as renderTextAnchor,h as renderTextDocument,s as restoreText,q as storeText,l as textFromAgentContent,b as withTextSourceLine};
1
+ import"./chunk-ROXXK6TW.js";import{a}from"./chunk-KII2JQC5.js";import{a as x}from"./chunk-ZTYWHL2F.js";import{a as o,b as r,c as e,d as f,e as m,f as p,g as t}from"./chunk-7UGNGK7Y.js";import"./chunk-EI7MMDWY.js";export{r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,a as searchSchema};
package/dist/entry-15.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-IQD6PON5.js";import{l as o}from"./chunk-WGGIQ7IJ.js";import{a as n}from"./chunk-L7JMDDSD.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,n as connectTextEditorPlugin,o as connectTextEditorPostEditHandler,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s}from"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as TextAnchor,r as attachTextAnchorRenderer,j as createTextContentConverter,g as createTextDocument,e as getTextAnchorRenderer,a as getTextSourceLine,t as isTextAnchorRecoveryOutcome,p as isTextAnchorResolutionAttempt,m as isTextAnchorResolver,c as isTextLinePresenter,d as isTextPresenterRegistration,n as isTextTargetResolutionAttempt,k as isTextualMediaType,i as renderPresentedTextDocument,x as renderPresentedTextRows,f as renderTextAnchor,h as renderTextDocument,s as restoreText,q as storeText,l as textFromAgentContent,b as withTextSourceLine};
@@ -0,0 +1 @@
1
+ import"./chunk-IQD6PON5.js";import{m as o}from"./chunk-FEDVTZJG.js";import{a as n}from"./chunk-L7JMDDSD.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,n as connectTextEditorPlugin,o as connectTextEditorPostEditHandler,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
package/dist/entry-18.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-MGCHOGQD.js";import"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{a as connectDoctorPlugin};
1
+ import"./chunk-K4ZMRDEI.js";
package/dist/entry-19.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-WZI4YC2O.js";import"./chunk-EI7MMDWY.js";export{b as hasProjectMarker,a as inspectRecipeEvidence};
1
+ import{a}from"./chunk-MGCHOGQD.js";import"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{a as connectDoctorPlugin};
package/dist/entry-20.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-N34ATN52.js";import"./chunk-EI7MMDWY.js";export{d as isExecutableAvailable,b as normalizeProcessEnvironment,e as probeExecutable,a as projectExecutableDirectories,c as projectProcessEnvironment};
1
+ import{a,b}from"./chunk-WZI4YC2O.js";import"./chunk-EI7MMDWY.js";export{b as hasProjectMarker,a as inspectRecipeEvidence};
package/dist/entry-21.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{b as DOCTOR_API_VERSION,c as DOCTOR_CORE_READY_EVENT,d as DOCTOR_PLUGIN_REGISTER_EVENT,a as DOCTOR_PROTOCOL,e as isDoctorCoreReady,f as isDoctorPluginRegistrationRequest};
1
+ import{a,b,c,d,e}from"./chunk-N34ATN52.js";import"./chunk-EI7MMDWY.js";export{d as isExecutableAvailable,b as normalizeProcessEnvironment,e as probeExecutable,a as projectExecutableDirectories,c as projectProcessEnvironment};
package/dist/entry-22.js CHANGED
@@ -1,2 +1 @@
1
- import"./chunk-NNCZYO4Q.js";import{d as v}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as R}from"./chunk-6CZO43OH.js";import{a as y,b as p}from"./chunk-OBNING2A.js";import{a as w}from"./chunk-L7JMDDSD.js";import{a as h,b as F}from"./chunk-O6LE42GK.js";import{a as g,u as m}from"./chunk-S3ZPXWX7.js";import{r as f}from"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{readdirSync as x,realpathSync as H,statSync as S}from"node:fs";import{mkdir as k,readFile as D,writeFile as O}from"node:fs/promises";import b from"node:path";import{fileURLToPath as I,pathToFileURL as _}from"node:url";function T(e){return P("read",e)}o(T,"createFilesystemReadResolver");function C(e){return P("write",e)}o(C,"createFilesystemWriteResolver");function P(e,s){return{id:"filesystem",tryResolve(t,i){return Promise.resolve(L(t,i,e,s))}}}o(P,"createFilesystemResolver");function L(e,s,t,i){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!W(e))return{kind:"not-handled"};if(s.signal?.aborted===!0)return{kind:"failed",error:E()};let r=e.startsWith("file://")?H(I(new URL(e))):b.resolve(s.cwd,e),l=_(r).href,c=(()=>{try{return S(r).isDirectory()}catch{return!1}})(),n=o(async({signal:d})=>c?U(r,d):V(r,i,d),"read");return t==="read"||c?{kind:"resolved",resource:{source:r,link:l,read:n}}:{kind:"resolved",resource:{source:r,link:l,read:n,async write(d,u){a(u.signal);let A=f(d);await k(b.dirname(r),{recursive:!0}),a(u.signal),await O(r,A,{encoding:"utf8",...u.signal!==void 0&&{signal:u.signal}})}}}}o(L,"resolveFilesystemSource");function U(e,s){a(s);let t=x(e,{withFileTypes:!0}),i=[`\u{1F4C1} ${e}/`];t.length>0&&i.push("");for(let r of t){let l=r.isDirectory()?"\u{1F4C1}":r.isFile()?"\u{1F4C4}":"\u{1F517}";i.push(` ${l} ${r.name}`)}return[{type:"text",text:i.join(`
2
- `)}]}o(U,"readDirectoryContent");async function V(e,s,t){a(t);let i=await D(e,{encoding:null,...t!==void 0&&{signal:t}});return a(t),s.convert({source:e,bytes:i},t===void 0?{}:{signal:t})}o(V,"readFilesystemContent");function W(e){return/^[A-Za-z]:[\\/]/u.test(e)||e.startsWith("file://")?!0:!/^[A-Za-z][A-Za-z\d+.-]*:/u.test(e)}o(W,"isFilesystemSource");function a(e){if(e?.aborted===!0)throw E()}o(a,"throwIfAborted");function E(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(E,"abortError");var z={provider:"filesystem",capability:"read"},Z={provider:"filesystem",capability:"write"},$=v({kind:"source",nativeResources:!0});async function j(e){let s=m(e,z),t=m(e,Z),i=T(s),r=C(t),l={protocol:y,apiVersion:p,id:"filesystem",setup(n){n.addResolver({resolver:i,renderResult:$}),n.describe(()=>g("File path \u2014 file content; directory path \u2014 entry listing. Relative, absolute and file:// paths accepted.",s.listDescriptions())),n.addPromptGuideline("Use read with paths relative to the current working directory for project files. Use read with absolute paths for files elsewhere on the system.")}},c={protocol:h,apiVersion:F,id:"filesystem",setup(n){n.addResolver({resolver:r})}};await Promise.all([R(e,l),w(e,c)])}o(j,"registerFilesystemPlugin");export{j as default};
1
+ import{a,b,c,d,e,f}from"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{b as DOCTOR_API_VERSION,c as DOCTOR_CORE_READY_EVENT,d as DOCTOR_PLUGIN_REGISTER_EVENT,a as DOCTOR_PROTOCOL,e as isDoctorCoreReady,f as isDoctorPluginRegistrationRequest};
package/dist/entry-23.js CHANGED
@@ -1 +1,2 @@
1
- import{a as r}from"./chunk-QIJMV2P2.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:100};async function i(o){await e(o,n)}t(i,"registerFilesystemImage");export{i as default};
1
+ import{a as w}from"./chunk-L7JMDDSD.js";import{a as h,b as F}from"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as v}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as R}from"./chunk-6CZO43OH.js";import{a as y,b as p}from"./chunk-OBNING2A.js";import{a as g,u as m}from"./chunk-S3ZPXWX7.js";import{r as f}from"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{readdirSync as x,realpathSync as H,statSync as S}from"node:fs";import{mkdir as k,readFile as D,writeFile as O}from"node:fs/promises";import b from"node:path";import{fileURLToPath as I,pathToFileURL as _}from"node:url";function T(e){return P("read",e)}o(T,"createFilesystemReadResolver");function C(e){return P("write",e)}o(C,"createFilesystemWriteResolver");function P(e,s){return{id:"filesystem",tryResolve(t,i){return Promise.resolve(L(t,i,e,s))}}}o(P,"createFilesystemResolver");function L(e,s,t,i){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!W(e))return{kind:"not-handled"};if(s.signal?.aborted===!0)return{kind:"failed",error:E()};let r=e.startsWith("file://")?H(I(new URL(e))):b.resolve(s.cwd,e),l=_(r).href,c=(()=>{try{return S(r).isDirectory()}catch{return!1}})(),n=o(async({signal:d})=>c?U(r,d):V(r,i,d),"read");return t==="read"||c?{kind:"resolved",resource:{source:r,link:l,read:n}}:{kind:"resolved",resource:{source:r,link:l,read:n,async write(d,u){a(u.signal);let A=f(d);await k(b.dirname(r),{recursive:!0}),a(u.signal),await O(r,A,{encoding:"utf8",...u.signal!==void 0&&{signal:u.signal}})}}}}o(L,"resolveFilesystemSource");function U(e,s){a(s);let t=x(e,{withFileTypes:!0}),i=[`\u{1F4C1} ${e}/`];t.length>0&&i.push("");for(let r of t){let l=r.isDirectory()?"\u{1F4C1}":r.isFile()?"\u{1F4C4}":"\u{1F517}";i.push(` ${l} ${r.name}`)}return[{type:"text",text:i.join(`
2
+ `)}]}o(U,"readDirectoryContent");async function V(e,s,t){a(t);let i=await D(e,{encoding:null,...t!==void 0&&{signal:t}});return a(t),s.convert({source:e,bytes:i},t===void 0?{}:{signal:t})}o(V,"readFilesystemContent");function W(e){return/^[A-Za-z]:[\\/]/u.test(e)||e.startsWith("file://")?!0:!/^[A-Za-z][A-Za-z\d+.-]*:/u.test(e)}o(W,"isFilesystemSource");function a(e){if(e?.aborted===!0)throw E()}o(a,"throwIfAborted");function E(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(E,"abortError");var z={provider:"filesystem",capability:"read"},Z={provider:"filesystem",capability:"write"},$=v({kind:"source",nativeResources:!0});async function j(e){let s=m(e,z),t=m(e,Z),i=T(s),r=C(t),l={protocol:y,apiVersion:p,id:"filesystem",setup(n){n.addResolver({resolver:i,renderResult:$}),n.describe(()=>g("File path \u2014 file content; directory path \u2014 entry listing. Relative, absolute and file:// paths accepted.",s.listDescriptions())),n.addPromptGuideline("Use read with paths relative to the current working directory for project files. Use read with absolute paths for files elsewhere on the system.")}},c={protocol:h,apiVersion:F,id:"filesystem",setup(n){n.addResolver({resolver:r})}};await Promise.all([R(e,l),w(e,c)])}o(j,"registerFilesystemPlugin");export{j as default};
package/dist/entry-24.js CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./chunk-BHSO2MDK.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:200};async function i(o){await e(o,n)}t(i,"registerFilesystemPdf");export{i as default};
1
+ import{a as r}from"./chunk-QIJMV2P2.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:100};async function i(o){await e(o,n)}t(i,"registerFilesystemImage");export{i as default};
package/dist/entry-25.js CHANGED
@@ -1 +1 @@
1
- import{v as t}from"./chunk-S3ZPXWX7.js";import{p as i}from"./chunk-5VSE5X5R.js";import{a as r}from"./chunk-EI7MMDWY.js";var o=i(),n={target:{provider:"filesystem",capability:"read"},converter:o,priority:300},s={target:{provider:"filesystem",capability:"write"},converter:o,priority:300};async function a(e){await Promise.all([t(e,n),t(e,s)])}r(a,"registerFilesystemText");export{a as default};
1
+ import{a as r}from"./chunk-BHSO2MDK.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:200};async function i(o){await e(o,n)}t(i,"registerFilesystemPdf");export{i as default};
package/dist/entry-26.js CHANGED
@@ -1 +1 @@
1
- import{b as e,c as o}from"./chunk-25CZ5ZIU.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as AstScopeManager,e as parseDocument};
1
+ import{v as t}from"./chunk-S3ZPXWX7.js";import{p as i}from"./chunk-5VSE5X5R.js";import{a as r}from"./chunk-EI7MMDWY.js";var o=i(),n={target:{provider:"filesystem",capability:"read"},converter:o,priority:300},s={target:{provider:"filesystem",capability:"write"},converter:o,priority:300};async function a(e){await Promise.all([t(e,n),t(e,s)])}r(a,"registerFilesystemText");export{a as default};
package/dist/entry-27.js CHANGED
@@ -1,12 +1 @@
1
- import{b as B,c as V}from"./chunk-25CZ5ZIU.js";import{a as E}from"./chunk-MGCHOGQD.js";import{a as O,b as L}from"./chunk-T6LX2RX5.js";import"./chunk-NNCZYO4Q.js";import{d as $}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as M}from"./chunk-6CZO43OH.js";import{a as k,b as P}from"./chunk-OBNING2A.js";import{a as D}from"./chunk-ZTYWHL2F.js";import{a as H,b as j}from"./chunk-7UGNGK7Y.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as I,b as C,c as N}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{a as S,b as R,c as w,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import"./chunk-KINKBPPX.js";import{j as T}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as x}from"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as te}from"node:fs/promises";var ne={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},y=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),G={protocol:O,apiVersion:1,id:"ast",setup(a){a.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(r=>y.has(r))?await T({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),a.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let r of e.detectedLanguageIds){let t=ne[r];if(t!==void 0){n.push({status:"skip",message:`${r} AST is unavailable: ${t}`});continue}if(!y.has(r))continue;let s=e.files.find(o=>re(o,r));if(s!==void 0)try{let o=await te(s,"utf8"),i=await B(s,e.cwd,o.replaceAll(`\r
2
- `,`
3
- `).split(`
4
- `));n.push(i===void 0?{status:"fail",message:`${r} parser did not return a tree`}:{status:"pass",message:`${r} parser loaded`,detail:s})}catch(o){n.push({status:"fail",message:`${r}: ${o instanceof Error?o.message:String(o)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),a.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(r=>y.has(r)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await x("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function re(a,e){let n=a.slice(a.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}d(re,"matchesLanguage");var se,ae;function F(a){return{id:"ast",tryResolve(e,n){return Promise.resolve(oe(e,n,a))}}}d(F,"createAstOutlineResolver");function oe(a,e,n){let r;try{r=S(a,"ast")}catch(o){return{kind:"failed",error:o}}if(r===void 0)return{kind:"not-handled"};let t;try{t=R(r.path,e.cwd)}catch(o){return{kind:"failed",error:o}}return{kind:"resolved",resource:{source:w("ast",t),async read({signal:o}){o?.throwIfAborted();let i=await(ae??=import("./chunk-5QQABP47.js")),c=await(n??(se??=new i.AstOutlineManager)).readFileOutline(t,e.cwd);return o?.throwIfAborted(),[i.formatAstOutline(c)]}}}}d(oe,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as ie,DEFAULT_MAX_LINES as ce,truncateHead as A}from"@earendil-works/pi-coding-agent";var b=d(async(a,e,n)=>{let{source:r,resolvedBy:t,lines:s,totalLines:o,startLine:i}=a.details;if(!(r===void 0||t!=="filesystem"||s===void 0||s.length!==o||i!==void 0&&i!==1))try{let{AstOutlineManager:l,isSupportedOutlinePath:c}=await import("./chunk-5QQABP47.js");if(!c(r))return;let u=d(m=>[`AST overview of ${m.path}, source lines 1-${m.totalLines}: the requested text exceeded the read buffer.`,"Source line numbers are on the left. Detail is reduced to fit the buffer; omitted bodies are not exact source text. Read a small source range when needed.",...m.renderedLines.map(g=>`${g.sourceLine?.lineNumber??"\u2026"} | ${g.text}`)].join(`
5
- `),"format");e.signal?.throwIfAborted();let p=await new l(12).readDocumentOutline(r,e.cwd,s.map(m=>m.content),m=>(e.signal?.throwIfAborted(),!A(u(m),n).truncated)),f=u(p);return A(f,n).truncated?void 0:{content:[{type:"text",text:f}],details:{source:r,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function z(){return async a=>{let{state:e,result:n}=a,r=n?.content.length===1?n.content[0]:void 0;if(a.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||r?.type!=="text"||!A(r.text).truncated)return{kind:"continue",context:a};let t=await b({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},a.resolverContext,{maxBytes:ie,maxLines:ce});return t===void 0?{kind:"continue",context:a}:{kind:"return",result:t}}}d(z,"createAstOverflowHandler");var X="pi-agent-ast";function K(a){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let r=await a.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),t=de(e.lines,r);return t===e.lines?e:{...e,lines:t}}catch{return e}}}}d(K,"createAstScopePresenter");function U(){return a=>{let e=a.state,n=a.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:a};let r=n.details.lines;if(r===void 0)return{kind:"continue",context:a};let t=new Map(e.text.lines.map(u=>[u.lineNumber,u])),s=new Set(r.map(u=>u.lineNumber)),o=new Map;for(let u of r){let p=t.get(u.lineNumber),f=q(p);for(let m of f?.boundaries??[]){if(s.has(m.endLine))continue;let g=t.get(m.endLine);g!==void 0&&o.set(m.endLine,g)}}if(o.size===0)return{kind:"continue",context:a};let i=[...o.values()].sort((u,p)=>u.lineNumber-p.lineNumber),l=[...r,...i],c=le(n,l,r.at(-1));return{kind:"continue",context:{...a,result:c}}}}d(U,"createAstScopePostReadHandler");function de(a,e){if(e.length===0)return a;let n=new Map,r=new Map;for(let t of e){let s=n.get(t.startLine)??[];s.push(t.beginAnchor.value),n.set(t.startLine,s);let o=r.get(t.startLine)??[];o.push({endLine:t.endLine,beginAnchor:t.beginAnchor.value,endAnchor:t.endScopeAnchor.value}),r.set(t.startLine,o);let i=n.get(t.endLine)??[];i.push(t.endScopeAnchor.value),n.set(t.endLine,i)}return a.map(t=>{let s=n.get(t.lineNumber),o=r.get(t.lineNumber);return s===void 0&&o===void 0?t:{...t,...s!==void 0&&{anchors:[...new Set([...t.anchors??[],...s])],presentation:{...t.presentation,suffix:`${t.presentation?.suffix??""}${s.map(i=>` <!-- ${i} -->`).join("")}`}},metadata:{...t.metadata,[X]:{...q(t),...o!==void 0&&{boundaries:o}}}}})}d(de,"addScopeMarkers");function q(a){let e=a?.metadata?.[X];if(!(typeof e!="object"||e===null))return e}d(q,"getAstScopeMetadata");function le(a,e,n){let r=a.content.length===1?a.content[0]:void 0;if(r?.type!=="text"||a.details.lines===void 0)return a;let t=e.slice(a.details.lines.length);if(t.length===0)return a;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:t[0]?.lineEnding!==void 0&&t[0].lineEnding.length>0?t[0].lineEnding:`
6
- `,o=t.map((c,u)=>{let f=u===t.length-1?c.lineEnding:c.lineEnding||s,m=c.presentation?.prefix??"",g=c.presentation?.suffix??"";return`${m}${c.content}${g}${f}`}).join(""),i=/(?:\r\n|\r|\n)$/.test(r.text)?"":s,l=`${r.text}${i}${o}`;return{...a,content:[{...r,text:l}],details:{...a.details,lines:e}}}d(le,"appendTextLines");var J=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function Y(a){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return J.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!J.test(e))return{kind:"not-handled"};try{let t=(await a.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return t===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:t.beginAnchor.value===e?t.beginAnchor:t.endScopeAnchor}}catch(r){return{kind:"failed",error:r}}}}}d(Y,"createAstScopeAnchorResolver");import{spawn as ue}from"node:child_process";import{readFile as pe,stat as W}from"node:fs/promises";import h from"node:path";function Q(a){return{id:"ast",async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let r=e.query.slice(4).trim();if(r.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let t=d(async i=>{let l=Date.now(),c=await me(r,e,n.cwd,i);c.sort((p,f)=>h.resolve(n.cwd,p.file).localeCompare(h.resolve(n.cwd,f.file))||p.range.byteOffset.start-f.range.byteOffset.start||p.range.byteOffset.end-f.range.byteOffset.end);let u=c.slice(0,e.limit??100);return{raw:u,matches:await fe(u,n.cwd,l,i),complete:c.length<=(e.limit??100)}},"collect"),s=await t(n.signal),o=await a({request:e,matches:s.matches,complete:s.complete,refresh:t},n);return{kind:"resolved",payload:{pattern:r,matches:s.raw.map((i,l)=>({...i,selection:s.matches[l]})),complete:s.complete,sessionId:o.id}}},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n};let r=n.matches.flatMap((t,s)=>[`SEARCH#${n.sessionId}:${String(s+1)}:match ${t.file}:${String(t.range.start.line+1)}:${String(t.range.start.column+1)} ${t.language}`,` ${t.lines.trim()}`]);return n.complete&&r.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),n.complete||r.push("Result limit reached."),{content:[{type:"text",text:r.join(`
7
- `)}],details:n}}}}d(Q,"createAstSearchResolver");async function fe(a,e,n,r){let t=new Map;for(let s of a){let o=h.resolve(e,s.file);if(t.has(o))continue;let i=await W(o),l=await pe(o,{signal:r}),c=await W(o);if(i.mtimeMs>n||i.mtimeMs!==c.mtimeMs||i.size!==c.size)throw new Error("AST source changed during search. Run the structural query again.");t.set(o,l)}return a.map(s=>{let o=h.resolve(e,s.file),i=t.get(o);if(i===void 0)throw new Error("Missing AST source snapshot");let{start:l,end:c}=s.range.byteOffset;if(!Number.isInteger(l)||!Number.isInteger(c)||l<0||c<l||c>i.length||i.subarray(l,c).toString("utf8")!==s.text)throw new Error("AST range does not match its source snapshot. Search again.");let u=i.subarray(0,l).toString("utf8"),p=i.subarray(0,c).toString("utf8"),f=u.split(`
8
- `).length;return{source:o,lineNumber:f,endLineNumber:p.split(`
9
- `).length,startColumn:u.length-u.lastIndexOf(`
10
- `)-1,endColumn:p.length-p.lastIndexOf(`
11
- `)-1,matchedText:s.text,lineText:i.toString("utf8").split(`
12
- `)[f-1]?.replace(/\r$/u,"")??""}})}d(fe,"selectionMatches");function me(a,e,n,r){let t=["run","--pattern",a,"--json=compact","--no-ignore","parent"];for(let s of Z(e.include))t.push("--globs",s);for(let s of Z(e.exclude))t.push("--globs",`!${s}`);return t.push(e.path??"."),new Promise((s,o)=>{let i=ue("ast-grep",t,{cwd:n,stdio:["ignore","pipe","pipe"]}),l="",c="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",p=>l+=p),i.stderr.on("data",p=>c+=p);let u=d(()=>{i.kill("SIGTERM")},"abort");r?.addEventListener("abort",u,{once:!0}),i.once("error",o),i.once("close",p=>{if(r?.removeEventListener("abort",u),r?.aborted===!0){o(r.reason instanceof Error?r.reason:new Error("AST search aborted"));return}if(p!==0&&p!==1){o(new Error(c.trim()||`ast-grep exited with code ${String(p)}`));return}try{let f=JSON.parse(l.length===0?"[]":l);if(!Array.isArray(f))throw new TypeError("ast-grep returned non-array JSON");s(f)}catch(f){o(f instanceof Error?f:new Error(String(f)))}})})}d(me,"runAstGrep");function Z(a){return a?.split(",").map(e=>e.trim()).filter(Boolean)??[]}d(Z,"splitGlobs");var ge=$({kind:"code-view",label:"AST"});async function ee(a){let e=new V,n=K(e),r={protocol:k,apiVersion:P,id:"ast",setup(s){s.addResolver({resolver:F(),renderResult:ge}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:v()}),s.addView({view:"ast",presenter:n});let o=z();s.addOutputReducer(b);let i=U();s.addHandler({stage:"post-read",async handler(l){let c=await o(l);return c.kind==="return"?c:i(c.context)}}),s.describe('ast:<path> \u2014 compact declaration outline. views: ["ast"] \u2014 scope boundaries alongside source text. Oversized code reads may return an outline with source line numbers; offset/limit read a smaller source range.')}},t={protocol:I,apiVersion:C,id:"ast",setup(s){s.addAnchorResolver({resolver:Y(e),kind:N,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([M(a,r),E(a,G),_(a,t),D(a,{protocol:H,apiVersion:j,id:"ast-search",setup(s){s.addResolver({resolver:Q(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use captures in Apply to compute replacement text; these edits do not update imports or references.")}})])}d(ee,"registerAst");export{ee as default};
1
+ import{b as e,c as o}from"./chunk-25CZ5ZIU.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as AstScopeManager,e as parseDocument};