pi-agent-ide 0.5.1 → 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 (322) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +10 -4
  3. package/dist/chunk-22CLOM2D.js +1 -0
  4. package/dist/{chunk-LY6U5EAD.js → chunk-2527OQ4Y.js} +1 -1
  5. package/dist/chunk-3XJ3KDPZ.js +16 -0
  6. package/dist/chunk-5JELU6RV.js +7 -0
  7. package/dist/chunk-DDKHZZDO.js +5 -0
  8. package/dist/chunk-FEDVTZJG.js +1 -0
  9. package/dist/chunk-HSM6R7IB.js +27 -0
  10. package/dist/chunk-K5G4FDXD.js +1 -0
  11. package/dist/chunk-M5IVSCR2.js +1 -0
  12. package/dist/chunk-OYWIZII6.js +1 -0
  13. package/dist/{chunk-7ALCBKCW.js → chunk-PCZH7GOX.js} +11 -11
  14. package/dist/{chunk-DQXPQOF7.js → chunk-SQ7ZTGOP.js} +1 -1
  15. package/dist/entry-10.js +1 -1
  16. package/dist/entry-11.js +1 -1
  17. package/dist/entry-12.js +1 -1
  18. package/dist/entry-13.js +1 -1
  19. package/dist/entry-14.js +1 -1
  20. package/dist/entry-15.js +1 -1
  21. package/dist/entry-16.js +1 -0
  22. package/dist/entry-18.js +1 -1
  23. package/dist/entry-19.js +1 -1
  24. package/dist/entry-20.js +1 -1
  25. package/dist/entry-21.js +1 -1
  26. package/dist/entry-22.js +1 -2
  27. package/dist/entry-23.js +2 -1
  28. package/dist/entry-24.js +1 -1
  29. package/dist/entry-25.js +1 -1
  30. package/dist/entry-26.js +1 -1
  31. package/dist/entry-27.js +1 -12
  32. package/dist/entry-28.js +12 -1
  33. package/dist/entry-29.js +1 -1
  34. package/dist/entry-30.js +1 -1
  35. package/dist/entry-31.js +1 -1
  36. package/dist/entry-32.js +1 -4
  37. package/dist/entry-33.js +3 -8
  38. package/dist/entry-34.js +9 -1
  39. package/dist/entry-35.js +1 -1
  40. package/dist/entry-36.js +1 -1
  41. package/dist/entry-37.js +1 -1
  42. package/dist/entry-38.js +1 -1
  43. package/dist/entry-39.js +1 -1
  44. package/dist/entry-40.js +1 -1
  45. package/dist/entry-41.js +1 -18
  46. package/dist/entry-42.js +18 -1
  47. package/dist/entry-43.js +1 -1
  48. package/dist/entry-44.js +1 -1
  49. package/dist/entry-45.js +1 -1
  50. package/dist/entry-46.js +1 -7
  51. package/dist/entry-47.js +7 -11
  52. package/dist/entry-48.js +11 -1
  53. package/dist/entry-49.js +1 -1
  54. package/dist/entry-50.js +1 -1
  55. package/dist/entry-51.js +1 -1
  56. package/dist/entry-52.js +1 -1
  57. package/dist/entry-53.js +1 -1
  58. package/dist/entry-54.js +1 -1
  59. package/dist/entry-55.js +1 -1
  60. package/dist/entry-56.js +1 -0
  61. package/dist/entry-57.js +0 -1
  62. package/dist/entry-58.js +1 -0
  63. package/dist/entry-59.js +0 -1
  64. package/dist/entry-60.js +1 -1
  65. package/dist/entry-61.js +1 -1
  66. package/dist/entry-62.js +1 -1
  67. package/dist/entry-63.js +1 -1
  68. package/dist/entry-64.js +1 -1
  69. package/dist/entry-65.js +1 -0
  70. package/dist/entry-66.js +0 -1
  71. package/dist/entry-67.js +1 -0
  72. package/dist/entry-68.js +0 -1
  73. package/dist/entry-69.js +1 -1
  74. package/dist/entry-70.js +1 -1
  75. package/dist/entry-71.js +1 -203
  76. package/dist/entry-72.js +254 -25
  77. package/dist/entry-73.js +30 -2
  78. package/dist/entry-74.js +2 -1
  79. package/dist/entry-75.js +1 -1
  80. package/dist/entry-76.js +1 -3
  81. package/dist/entry-77.js +3 -3
  82. package/dist/entry-78.js +3 -1
  83. package/dist/entry-79.js +1 -1
  84. package/dist/entry-80.js +1 -1
  85. package/dist/entry-81.js +1 -0
  86. package/dist/pi-agent-ide.js +3 -3
  87. package/docs/configuration.md +3 -1
  88. package/docs/tools.md +12 -0
  89. package/node_modules/pi-agent-doctor/package.json +6 -6
  90. package/node_modules/pi-agent-doctor/runtime/entry-22.js +1 -0
  91. package/node_modules/pi-agent-filesystem/package.json +7 -7
  92. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  93. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  94. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  95. package/node_modules/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  96. package/node_modules/pi-agent-ide-ast/package.json +12 -11
  97. package/node_modules/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  98. package/node_modules/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  99. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  100. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  101. package/node_modules/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  102. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  103. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  104. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  105. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +3 -1
  106. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  107. package/node_modules/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  108. package/node_modules/pi-agent-image/package.json +3 -3
  109. package/node_modules/pi-agent-invariant/package.json +2 -2
  110. package/node_modules/pi-agent-pdf/package.json +3 -3
  111. package/node_modules/pi-agent-read/package.json +11 -11
  112. package/node_modules/pi-agent-read/runtime/entry-41.js +0 -1
  113. package/node_modules/pi-agent-read/runtime/entry-42.js +2 -0
  114. package/node_modules/pi-agent-read/src/api/read-parameters.ts +2 -2
  115. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  116. package/node_modules/pi-agent-resource/package.json +2 -2
  117. package/node_modules/pi-agent-search/package.json +7 -7
  118. package/node_modules/pi-agent-search/runtime/entry-46.js +0 -1
  119. package/node_modules/pi-agent-search-text/package.json +9 -9
  120. package/node_modules/pi-agent-search-text/runtime/entry-48.js +1 -0
  121. package/node_modules/pi-agent-text/package.json +3 -3
  122. package/node_modules/pi-agent-text/runtime/entry-50.js +1 -0
  123. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  124. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  125. package/node_modules/pi-agent-text-anchor-exact/index.ts +3 -3
  126. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  127. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  128. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  129. package/node_modules/pi-agent-text-anchor-exact/src/config.ts +2 -2
  130. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  131. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  132. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  133. package/node_modules/pi-agent-text-editor/package.json +25 -25
  134. package/node_modules/pi-agent-text-editor/runtime/entry-71.js +0 -1
  135. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  136. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  137. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  138. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  139. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  140. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  141. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  142. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  143. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  144. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  145. package/node_modules/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  146. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  147. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  148. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  149. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  150. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  151. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  152. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  153. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  154. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  155. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  156. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  157. package/node_modules/pi-agent-tool-ui/runtime/entry-76.js +1 -0
  158. package/node_modules/pi-agent-web/package.json +7 -7
  159. package/node_modules/pi-agent-web-html/package.json +3 -3
  160. package/node_modules/pi-agent-web-image/package.json +4 -4
  161. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  162. package/node_modules/pi-agent-web-text/package.json +4 -4
  163. package/node_modules/pi-agent-web-text/runtime/entry-81.js +2 -0
  164. package/package.json +43 -38
  165. package/src/api/path-identity.ts +15 -0
  166. package/src/composite/builtin-extensions.ts +7 -2
  167. package/src/composite/module-labels.ts +4 -0
  168. package/src/composite/module-settings.ts +34 -14
  169. package/src/composite/preferences.ts +46 -3
  170. package/src/composite/selection.ts +5 -1
  171. package/src/doctor/inventory.ts +7 -2
  172. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  173. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  174. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  175. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  176. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  177. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-23.js +2 -0
  178. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  179. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  180. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  181. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  182. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  183. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-81.js +2 -0
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-77.js +2 -0
  185. package/src/extensions/pi-agent-read/package.json +11 -11
  186. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  187. package/src/extensions/pi-agent-read/runtime/entry-42.js +2 -0
  188. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
  189. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  190. package/src/extensions/pi-agent-search/package.json +7 -7
  191. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  192. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-48.js +1 -0
  193. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-49.js +1 -0
  194. package/src/extensions/pi-agent-search/runtime/entry-46.js +0 -1
  195. package/src/extensions/pi-agent-search/runtime/entry-47.js +2 -0
  196. package/src/extensions/pi-agent-text-editor/package.json +25 -25
  197. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  198. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  199. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +3 -3
  200. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  201. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  202. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  203. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/config.ts +2 -2
  204. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  205. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  206. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  207. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  208. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  209. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  210. package/src/extensions/pi-agent-text-editor/runtime/entry-71.js +0 -1
  211. package/src/extensions/pi-agent-text-editor/runtime/entry-72.js +2 -0
  212. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  213. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  214. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  215. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  216. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  217. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  218. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  219. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  220. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  221. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  222. package/src/extensions/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  223. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  224. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  225. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  226. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  227. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  228. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  229. package/src/pi-agent-ide.ts +15 -2
  230. package/src/plugins/pi-agent-ide-ast/package.json +12 -11
  231. package/src/plugins/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  232. package/src/plugins/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  233. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  234. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  235. package/src/plugins/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  236. package/src/plugins/pi-agent-ide-debugger/index.ts +2 -8
  237. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +31 -0
  238. package/src/plugins/pi-agent-ide-debugger/src/breakpoint-view.ts +3 -1
  239. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +24 -23
  240. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -2
  241. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +55 -17
  242. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -22
  243. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  244. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  245. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  246. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +3 -1
  247. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  248. package/src/plugins/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  249. package/src/plugins/pi-agent-ide-processes/src/registry.ts +4 -0
  250. package/src/plugins/pi-agent-ide-processes/src/ui.ts +18 -9
  251. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +1 -0
  252. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +1 -0
  253. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
  254. package/src/plugins/pi-agent-ide-terminal/src/types.ts +1 -0
  255. package/src/plugins/pi-agent-ide-vision/index.ts +232 -0
  256. package/src/plugins/pi-agent-ide-vision/src/vision.ts +530 -0
  257. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +30 -0
  258. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +33 -0
  259. package/dist/chunk-5PLV4HLG.js +0 -1
  260. package/dist/chunk-G725MARR.js +0 -16
  261. package/dist/chunk-HKXDP2FD.js +0 -7
  262. package/dist/chunk-IRECDTJG.js +0 -27
  263. package/dist/chunk-J4RTW44E.js +0 -1
  264. package/dist/chunk-NZYDMBM6.js +0 -1
  265. package/dist/chunk-WGGIQ7IJ.js +0 -1
  266. package/dist/entry-17.js +0 -1
  267. package/node_modules/pi-agent-doctor/runtime/entry-17.js +0 -1
  268. package/node_modules/pi-agent-filesystem/runtime/entry-22.js +0 -2
  269. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  270. package/node_modules/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  271. package/node_modules/pi-agent-image/runtime/entry-34.js +0 -1
  272. package/node_modules/pi-agent-resource/runtime/entry-42.js +0 -1
  273. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  274. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  275. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  276. package/node_modules/pi-agent-text-editor/runtime/entry-55.js +0 -1
  277. package/node_modules/pi-agent-tool-call-interception/runtime/entry-74.js +0 -1
  278. package/node_modules/pi-agent-web/runtime/entry-76.js +0 -2
  279. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  280. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-22.js +0 -2
  281. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-77.js +0 -2
  282. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +0 -2
  283. package/src/extensions/pi-agent-read/runtime/entry-37.js +0 -1
  284. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +0 -2
  285. package/src/extensions/pi-agent-search/runtime/entry-43.js +0 -1
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  289. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  290. package/src/extensions/pi-agent-text-editor/runtime/entry-55.js +0 -1
  291. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  292. package/src/plugins/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  293. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-23.js +0 -0
  294. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  295. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  296. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  297. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  298. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  299. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
  300. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-35.js +0 -0
  301. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-36.js +0 -0
  302. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-37.js +0 -0
  303. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-43.js +0 -0
  304. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-47.js +0 -0
  305. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-49.js +0 -0
  306. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-72.js +0 -0
  307. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  308. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-75.js +0 -0
  309. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-77.js +0 -0
  310. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  311. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  312. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  313. /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
  314. /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
  315. /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
  316. /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
  317. /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
  318. /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
  319. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  320. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  321. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  322. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 — 2026-09-16
4
+
5
+ ### Agent vision
6
+
7
+ - Let agents discover running processes and read process metadata.
8
+ - Let agents inspect application windows, full displays, and rendered web pages as images. Agent-owned windows are available by default; arbitrary windows and full displays require separate opt-in settings.
9
+ - Add image sequences for observing changing interfaces and media over time.
10
+ - Let agents choose sequence duration, frame interval, image scale, normalized image regions, and grid cells.
11
+ - Add executable allowlists for desktop applications that agents may inspect without unrestricted window access.
12
+ - Support Linux and macOS capture through `node-screenshots`, plus visible Windows-host windows and displays from WSL.
13
+
14
+ ### Apply
15
+
16
+ - Keep successful independent changes when another operation in the same transaction fails, and report the outcome of each operation.
17
+ - Add selection-set replacements, removals, copies, and moves for exact matches and structural-search results.
18
+ - Add whole-file create, copy, move, and delete operations to Apply scripts.
19
+ - Refresh open files after `flush()`, preserve line endings for line-based edits, and skip post-processing for files that were subsequently moved or deleted.
20
+
21
+ ### Windows
22
+
23
+ - Add native Windows support for Agent IDE debugger workflows, filesystem identity, language detection, command launchers, and executable discovery.
24
+ - Improve debugger support across the Windows language toolchains that are available on the machine.
25
+
26
+ ### Settings
27
+
28
+ - Add editable settings for sequence duration, frame interval, image scale, and allowed executable names.
29
+
30
+ ## 0.5.1 — 2026-09-14
31
+
32
+ ### Sessions and processes
33
+
34
+ - Keep active terminal and debugger resources alive across extension reloads, so agents can reconnect to the same `shell:` and `debug:` sessions.
35
+ - Add terminal input mode to the process panel. Press `i` in a terminal detail view to send text and keys, and press Escape to return to the normal view.
36
+ - Keep foreground terminal waits running in the background when an agent turn is interrupted instead of reporting them as aborted.
37
+ - Bound terminal-search output in the TUI while keeping the complete search result available to the agent.
38
+
39
+ ### Reading and search
40
+
41
+ - Return a bounded hex and ASCII preview for unsupported HTTP binary responses instead of downloading the full body or failing without useful content.
42
+ - Preserve native image reads when a server reports a generic binary content type for a known image URL.
43
+ - Keep search results when a file or terminal log changes during the search. Stale results remain visible, but unsafe anchors are omitted.
44
+
3
45
  ## 0.5.0 — 2026-09-13
4
46
 
5
47
  ### Debugging
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <h1 align="center">Pi Agent IDE</h1>
6
6
 
7
- <p align="center">IDE capabilities for coding agents in <a href="https://pi.dev/">Pi</a>.</p>
7
+ <p align="center">Pi Agent IDE is an agent-native IDE extension for the <a href="https://pi.dev/">Pi coding agent</a>. It adds guarded editing, code search, AST/LSP navigation, persistent terminals, debugging, transactional changes, and observability tools.</p>
8
8
 
9
9
  <p align="center">
10
10
  <a href="https://www.npmjs.com/package/pi-agent-ide"><img src="https://img.shields.io/npm/v/pi-agent-ide" alt="npm version"></a>
@@ -12,7 +12,7 @@
12
12
  <a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI status"></a>
13
13
  <a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgist.githubusercontent.com%2Falexshpunt%2F0d28d39557e2a9976c4548e7737c102d%2Fraw%2Funit.json" alt="Unit test count"></a>
14
14
  <a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgist.githubusercontent.com%2Falexshpunt%2F0d28d39557e2a9976c4548e7737c102d%2Fraw%2Fintegration.json" alt="Integration test count"></a>
15
- <a href="https://alexshpunt-benchmark-explorer.static.hf.space/?filter.harness=pi-agent-ide"><img src="https://img.shields.io/badge/Explicit%20Edit%20Benchmark-v0.5.1%20%E2%80%A2%20not%20tested-lightgrey?style=flat-square" alt="Explicit Edit Benchmark: pi-agent-ide v0.5.1 is not tested yet"></a>
15
+ <a href="https://huggingface.co/spaces/alexshpunt/benchmark-explorer?card=harness%3Api-agent-ide%40latest"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fhuggingface.co%2Fdatasets%2Falexshpunt%2Fexplicit-edit-benchmark%2Fresolve%2Fmain%2Fbadges%2Fpi-agent-ide.json" alt="Explicit Edit Benchmark score"></a>
16
16
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/pi-agent-ide" alt="MIT license"></a>
17
17
  </p>
18
18
 
@@ -40,7 +40,7 @@ The project started as another take on hash-based editing. It later brought back
40
40
 
41
41
  The agent should express what it wants to do without choosing a different tool for every implementation behind it.
42
42
 
43
- `read` is the main interface to the environment. It reads text, source code, raw bytes, web pages, images, PDFs, terminal sessions, debugger sessions, and diagnostics. The same interface can ask for AST structure, language-server information, anchors, or other views. The agent chooses the information it needs while the parsing, conversion, and resource handling stay behind one facade.
43
+ `read` is the main interface to the environment. It reads text, source code, raw bytes, web pages, images, PDFs, terminal sessions, debugger sessions, diagnostics, running processes, application windows, and full displays. The same interface can ask for AST structure, language-server information, anchors, or other views. The agent chooses the information it needs while the parsing, conversion, and resource handling stay behind one facade.
44
44
 
45
45
  `search` follows the same rule. It searches files, text, symbols, syntax trees, and supported live resources through one interface.
46
46
 
@@ -52,6 +52,8 @@ The shell remains available, but it behaves like part of an IDE. The agent can s
52
52
 
53
53
  Debugger sessions are also addressable resources. The agent can set breakpoints, inspect source and variables, step through a program, and reconnect after a reload. Formatting, diagnostics, AST views, language-server views, terminal output, and debugger state work through the same resource model. This support is currently focused on Linux and WSL.
54
54
 
55
+ Agent vision uses that resource model instead of adding a separate screenshot workflow. The agent can discover a process, inspect its metadata, read an application window, capture a full display, or render a web page through `read`. Image and sequence views support downscaling, normalized regions, and grid-cell selection, so the model can inspect a useful area without loading every source pixel. Window and display access is guarded by ownership, executable allowlists, and separate opt-in settings.
56
+
55
57
  ### Extensible by protocol
56
58
 
57
59
  The visible tools stay small because their internals are protocols. HTTP reads, filesystem reads, terminal and debugger resources, file formats, AST views, language-server views, converters, search backends, anchors, formatters, and diagnostics can be added or replaced independently.
@@ -76,6 +78,10 @@ Daily use and judgement still matter, but features should not be built on vibes
76
78
 
77
79
  The [Explicit Edit Benchmark](https://github.com/alexshpunt/explicit-edit-benchmark) was created for this purpose. It measures how easily agents can use editing tools on exact, deterministic tasks. These tasks are especially useful for smaller models and models with limited reasoning, where tool design has a larger effect on reliability.
78
80
 
81
+ Version 0.5.1 scores **93.8%** on `gpt-5.6-luna` with low reasoning: 224 of the 226 tasks solved
82
+ in the end, 208 of them on the first attempt. The full observation, including the two tasks it
83
+ did not solve, is in the [published data](https://huggingface.co/datasets/alexshpunt/explicit-edit-benchmark).
84
+
79
85
  Agent results are stochastic and no benchmark captures everything. We publish the score we actually get and build broader statistics instead of selecting only favorable runs.
80
86
 
81
87
  Pi Agent IDE is experimental and under active development. Interfaces and behavior may change.
@@ -126,7 +132,7 @@ If something breaks, behaves badly, or does not fit your workflow, please [open
126
132
 
127
133
  | Document | Contents |
128
134
  | ------------------------------------------ | -------------------------------------------------------------------- |
129
- | [Tools and workflow](./docs/tools.md) | Read, search, editing, anchors, and feedback |
135
+ | [Tools and workflow](./docs/tools.md) | Read, vision, search, editing, anchors, and feedback |
130
136
  | [Architecture](./docs/architecture.md) | Module boundaries, protocols, and the umbrella extension |
131
137
  | [Configuration](./docs/configuration.md) | Run doctor, configure project tools and search, or disable built-ins |
132
138
  | [File hooks](./docs/user-hooks.md) | Inspect, change, or deny reads and edits |
@@ -0,0 +1 @@
1
+ import{d as s}from"./chunk-S3ZPXWX7.js";import{a as o}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";import{Type as n}from"typebox";var l=n.Object({path:n.Optional(n.String({description:"What to read: a file or directory path, URL, returned temp: or SEARCH# reference, or one of the source forms listed in the description. Supply a path; an empty call cannot select a source."})),offset:n.Optional(n.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor or a SEARCH selection, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:n.Optional(n.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:n.Optional(n.Array(n.String(),{description:`Optional additions to the returned text. Use the views listed in the tool description. Combine views when needed, for example ["anchors", "ast"] for source text with editable line references and scope boundaries. Omit for the source's default presentation.`}))});var a=e.Function([],e.Unknown()),u=e.Object({resolver:e.Unknown(),matchesCall:e.Optional(a),renderCall:e.Optional(a),priority:e.Optional(e.Number()),renderResult:e.Optional(a),preserveTruncatedOutput:e.Optional(e.Boolean())}),R=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),c=e.Object({id:e.String({pattern:"\\S"}),priority:e.Optional(e.Number()),resolve:a}),y=e.Object({view:e.String({pattern:"\\S"}),includes:e.Optional(e.Array(e.String({pattern:"\\S"}))),presenter:e.Object({id:e.String(),present:a}),priority:e.Optional(e.Number())}),p=e.Object({resolvedBy:e.String({pattern:"\\S"}),contentKind:e.Union([e.Literal("text"),e.Literal("any")])}),g=e.Union([e.Object({stage:e.Literal("pre-read"),handler:a}),e.Object({stage:e.Literal("read"),when:p,handler:a}),e.Object({stage:e.Literal("post-read"),handler:a})]);function T(t){if(!i.Check(R,t))return!1;let r=t,d=r.resolver;return typeof d.id=="string"&&d.id.length>0&&typeof d.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}o(T,"isTextTargetResolverRegistration");function O(t){if(!i.Check(u,t))return!1;let r=t;return s(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("matchesCall"in r)||typeof r.matchesCall=="function")&&(!("renderCall"in r)||typeof r.renderCall=="function")&&"matchesCall"in r=="renderCall"in r&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}o(O,"isResourceResolverRegistration");function S(t){return i.Check(g,t)}o(S,"isReadHandlerRegistration");function C(t){return i.Check(y,t)}o(C,"isReadViewRegistration");function k(t){return i.Check(c,t)}o(k,"isFragmentResolverRegistration");function w(t){return m(t)?t.kind==="not-handled"?!0:t.kind==="failed"?typeof t.message=="string"&&t.message.length>0:t.kind==="resolved"&&typeof t.originLine=="number":!1}o(w,"isReadFragmentResolution");function m(t){return typeof t=="object"&&t!==null}o(m,"isRecord");export{l as a,T as b,O as c,S as d,C as e,k as f,w as g};
@@ -1,4 +1,4 @@
1
- import{a as j,l as M}from"./chunk-WGGIQ7IJ.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as N,b as O}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{a as C,b as R,c as A,d as $,g as F}from"./chunk-Z3VC3S2T.js";import{a as k}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";var h=[],y=[],P=[];function b(n,t,e){if(t.some(i=>i.name===e))throw new Error(`[pi-agent-ide] ${n} "${e}" is already registered. Use a unique name.`)}c(b,"assertUniqueName");function q(n){let t=new Set;for(let e of n){let i=`${e.kind}:${e.name}`;if(t.has(i))throw new Error(`[pi-agent-ide] ${e.kind} "${e.name}" is registered twice by one plugin.`);switch(t.add(i),e.kind){case"compiler":{b(e.kind,y,e.name);break}case"formatter":{b(e.kind,h,e.name);break}case"linter":{b(e.kind,P,e.name);break}}}for(let e of n)switch(e.kind){case"compiler":{y.push(e);break}case"formatter":{h.push(e);break}case"linter":{P.push(e);break}}}c(q,"registerTools");async function L(n,t){let e=[];for(let i of n)try{await i.detect(t)&&e.push(i)}catch(o){console.error(`[pi-agent-ide] detect failed for "${i.name}":`,o)}return e.sort((i,o)=>o.priority-i.priority),H(e),e}c(L,"filterActive");function H(n){let t=new Map;for(let e of n)for(let i of e.extensions){let o=`${i}@${e.priority}`,a=t.get(o);if(a!==void 0)throw new Error(`[pi-agent-ide] priority conflict: tools "${a}" and "${e.name}" both claim "${i}" at priority ${e.priority}.`);t.set(o,e.name)}}c(H,"assertNoPriorityConflicts");async function G(n){let[t,e]=await Promise.all([L(h,n),L(y.filter(i=>i.syntaxOnly===!0),n)]);return{ctx:n,formatters:t,compilers:e,linters:[]}}c(G,"warmupFormatting");function T(){h.length=0,y.length=0,P.length=0}c(T,"resetRegistry");import{readFile as D}from"node:fs/promises";import g from"node:path";var v=class{constructor(t,e={}){this.sources=t;this.options=e}static{c(this,"DiagnosticStore")}files=new Map;dirty=new Set;sent=new Map;queue=[];running=0;disposed=!1;changeListeners=new Set;onDidChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}schedule(t,e,{cwd:i}){this.disposed||this.ensure(t,e,i)}async read(t,{cwd:e,mode:i,signal:o}){o?.throwIfAborted(),this.assertActive();let a=g.resolve(e,t),s=await D(a,"utf8");this.assertActive();let r=this.ensure(a,s,e);i==="complete"?await this.waitComplete(r,o):i!=="snapshot"&&await K(Promise.all(r.jobs),this.options.readWaitMs??5e3),o?.throwIfAborted(),this.assertActive();let d=await D(a,"utf8");this.assertActive();let l=this.ensure(a,d,e);if(i==="complete"&&l!==r)throw Object.assign(new Error("File changed during diagnostics"),{code:"DIAGNOSTICS_STALE"});return{filePath:a,content:l.content,results:[...l.results.values()]}}async waitComplete(t,e){let i=e?AbortSignal.any([e,t.controller.signal]):t.controller.signal;i.throwIfAborted();let o=[];await new Promise((a,s)=>{let r=c(m=>s(Object.assign(new Error(m),{code:m,details:[...t.results.values()]})),"fail"),d=c(()=>{let m=[...t.results.values()];m.some(w=>w.status==="unavailable")?r("DIAGNOSTICS_UNAVAILABLE"):m.every(w=>w.status==="ready")&&a()},"check"),l=c(()=>s(i.reason),"abort"),f=this.onDidChange(d),u=setTimeout(()=>r("DIAGNOSTICS_TIMEOUT"),this.options.checkTimeoutMs??3e4);i.addEventListener("abort",l,{once:!0});let p=c(()=>{clearTimeout(u),f(),i.removeEventListener("abort",l)},"cleanup");Promise.resolve().then(d),o.push(p)}).finally(()=>{for(let a of o)a()})}async takeNotifications(t){let e=[];for(let i of[...this.dirty]){if(i.cwd!==g.resolve(t)||(this.dirty.delete(i),!await this.isCurrent(i)))continue;let o=[...i.results.values()].filter(d=>d.status!=="pending"&&d.status!=="unavailable"&&d.diagnostics.length>0),a=this.key(i.filePath,i.cwd),s=JSON.stringify(o);if(this.sent.get(a)===s||(this.sent.set(a,s),o.length===0))continue;let r=o.map(d=>{let l=["error","warning","info","hint"].flatMap(f=>{let u=d.diagnostics.filter(p=>p.severity===f).length;return u>0?[`${u} ${f}`]:[]});return`${d.source} ${l.join(", ")}${d.status==="snapshot"?" (snapshot; completion unknown)":d.status==="unversioned"?" (unversioned)":""}`}).join("; ");e.push({filePath:g.relative(t,i.filePath),results:o,text:`${JSON.stringify(g.relative(t,i.filePath))}: ${r}.`})}return e}dispose(){this.disposed=!0,this.changeListeners.clear();for(let t of this.files.values())t.controller.abort();this.files.clear(),this.dirty.clear(),this.sent.clear(),this.pump()}key(t,e){return JSON.stringify([g.resolve(e),g.resolve(e,t)])}ensure(t,e,i){let o=this.key(t,i),a=this.files.get(o);if(a?.content===e)return a;a?.controller.abort(),a&&this.dirty.delete(a);let s={cwd:g.resolve(i),filePath:g.resolve(i,t),content:e,controller:new AbortController,results:new Map,jobs:[],publications:new Map};this.files.set(o,s),this.sources.length===0&&s.results.set("diagnostics",{source:"diagnostics",status:"unavailable",diagnostics:[],reason:"No diagnostic sources registered"}),this.dirty.add(s);for(let r of this.sources){s.results.set(r.id,{source:r.id,status:"pending",diagnostics:[]});let d=new Promise(l=>{this.queue.push(async()=>{try{await this.check(s,r)}finally{l()}})});s.jobs.push(d)}return queueMicrotask(()=>this.pump()),s}pump(){for(;this.running<(this.options.concurrency??4)&&this.queue.length>0;){let t=this.queue.shift();if(!t)break;this.running++,t().finally(()=>{this.running--,this.pump()})}}active(t){return!this.disposed&&!t.controller.signal.aborted}assertActive(){if(this.disposed)throw new Error("Diagnostics session has ended")}async isCurrent(t){if(!this.active(t))return!1;let e=await D(t.filePath,"utf8").catch(()=>{});return this.active(t)&&e===t.content}async publish(t,e,i){let o=(t.publications.get(e)??0)+1;if(t.publications.set(e,o),!await this.isCurrent(t)||t.publications.get(e)!==o)return;let a={...i,source:i.source??e};if(JSON.stringify(t.results.get(e))===JSON.stringify(a))return;t.results.set(e,a),this.dirty.add(t);let s=[...t.results.values()].some(r=>r.status!=="pending"&&r.status!=="unavailable"&&r.diagnostics.length>0);s||this.sent.delete(this.key(t.filePath,t.cwd));for(let r of this.changeListeners)r(t.cwd,s)}async check(t,e){if(!await this.isCurrent(t))return;let i=new AbortController,o=AbortSignal.any([i.signal,t.controller.signal]);if(o.aborted)return;let a,s;try{let r=new Promise((l,f)=>{s=c(()=>f(o.reason),"onAbort"),o.addEventListener("abort",s,{once:!0}),a=setTimeout(()=>i.abort(new Error("Diagnostic check timed out")),this.options.checkTimeoutMs??3e4)}),d=await Promise.race([e.diagnose(t.filePath,{cwd:t.cwd,content:t.content,signal:o,publish:c(l=>{o.aborted||this.publish(t,e.id,l)},"publish")}),r]);await this.publish(t,e.id,d)}catch(r){await this.publish(t,e.id,{status:"unavailable",diagnostics:[],reason:r instanceof Error?r.message:String(r)})}finally{clearTimeout(a),s&&o.removeEventListener("abort",s)}}};async function K(n,t){let e;try{await Promise.race([n,new Promise(i=>{e=setTimeout(i,t)})])}finally{clearTimeout(e)}}c(K,"waitAtMost");function V(){let n=new Map,t=[],e=new v(t),i=Promise.resolve();return{diagnostics:e,registerPlugin(o){if(o.id.trim().length===0)return Promise.reject(new Error("Plugin ID must not be empty"));let a=n.get(o.id);if(a!==void 0)return a;let s=i.then(async()=>{let r=[],d=[],l=!0,f={addTool(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);Z(u),r.push(u)},addDiagnosticSource(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);tt(u),d.push(u)},readDiagnostics(u,p){return e.read(u,p)}};try{await o.setup(f)}catch(u){throw l=!1,u}l=!1,Q(t,d),q(r),t.push(...d)});return n.set(o.id,s),i=s.catch(()=>{}),s.catch(()=>{n.delete(o.id)}),s},async waitForPendingPlugins(){await Promise.all(n.values())}}}c(V,"createIdeCore");function Q(n,t){let e=new Set(n.map(i=>i.id));for(let i of t){if(e.has(i.id))throw new Error(`Diagnostic source ${i.id} is already registered`);e.add(i.id)}}c(Q,"assertUniqueDiagnosticSources");function Z(n){if(!U(n))throw new TypeError("IDE tool must be an object");let t=n.kind,e=t==="compiler"?n.compile:t==="formatter"?n.format:t==="linter"?n.lint:void 0;if(e===void 0||typeof e!="function"||typeof n.detect!="function"||typeof n.name!="string"||n.name.trim().length===0||typeof n.priority!="number"||!Number.isFinite(n.priority)||!Array.isArray(n.extensions)||n.extensions.length===0||n.extensions.some(i=>typeof i!="string"||i.length===0))throw new TypeError("Invalid pi-agent-ide tool contribution")}c(Z,"assertIdeTool");function tt(n){if(!U(n)||typeof n.id!="string"||n.id.trim().length===0||typeof n.diagnose!="function")throw new TypeError("Invalid pi-agent-ide diagnostic source contribution")}c(tt,"assertDiagnosticSource");function U(n){return typeof n=="object"&&n!==null}c(U,"isRecord");function J(n,t,e=console.error){let i=new Map,o=!1,a=Promise.resolve();return{schedule(s){if(o||i.has(s))return;let r=setTimeout(()=>{i.delete(s),a=a.then(async()=>{o||await n(s)}).catch(e)},t);i.set(s,r)},dispose(){o=!0;for(let s of i.values())clearTimeout(s);i.clear()}}}c(J,"createDiagnosticDelivery");import{Text as Y}from"@earendil-works/pi-tui";var S="ide-diagnostic-summary";function W(n){return{filePath:n.filePath,sources:n.results.map(t=>{let e={error:0,warning:0,info:0,hint:0};for(let i of t.diagnostics)e[i.severity]++;return{source:t.source,status:t.status,counts:e}})}}c(W,"diagnosticEntryData");function E(n,t,e=!1){return{render(i){let o=n.sources.filter(r=>r.status!=="pending"&&r.status!=="unavailable"&&Object.values(r.counts).some(d=>d>0));if(o.length===0)return[];let a=o.map(r=>`${x(r.counts,t)} ${t.fg("dim",`(${I(r.source)})`)}`+(r.status==="ready"?"":` \xB7 ${t.fg("dim",r.status)}`)).join(" \xB7 "),s=[`${t.fg("accent","Diagnostics")} ${t.fg("toolTitle",I(n.filePath))} \xB7 ${a}`];if(e)for(let r of o)s.push(` ${t.fg("dim",I(r.source))} \xB7 ${x(r.counts,t)} \xB7 ${t.fg("dim",r.status)}`);return new Y(s.join(`
1
+ import{a as j,m as M}from"./chunk-FEDVTZJG.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as N,b as O}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{a as C,b as R,c as A,d as $,g as F}from"./chunk-Z3VC3S2T.js";import{a as k}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";var h=[],y=[],P=[];function b(n,t,e){if(t.some(i=>i.name===e))throw new Error(`[pi-agent-ide] ${n} "${e}" is already registered. Use a unique name.`)}c(b,"assertUniqueName");function q(n){let t=new Set;for(let e of n){let i=`${e.kind}:${e.name}`;if(t.has(i))throw new Error(`[pi-agent-ide] ${e.kind} "${e.name}" is registered twice by one plugin.`);switch(t.add(i),e.kind){case"compiler":{b(e.kind,y,e.name);break}case"formatter":{b(e.kind,h,e.name);break}case"linter":{b(e.kind,P,e.name);break}}}for(let e of n)switch(e.kind){case"compiler":{y.push(e);break}case"formatter":{h.push(e);break}case"linter":{P.push(e);break}}}c(q,"registerTools");async function L(n,t){let e=[];for(let i of n)try{await i.detect(t)&&e.push(i)}catch(o){console.error(`[pi-agent-ide] detect failed for "${i.name}":`,o)}return e.sort((i,o)=>o.priority-i.priority),H(e),e}c(L,"filterActive");function H(n){let t=new Map;for(let e of n)for(let i of e.extensions){let o=`${i}@${e.priority}`,a=t.get(o);if(a!==void 0)throw new Error(`[pi-agent-ide] priority conflict: tools "${a}" and "${e.name}" both claim "${i}" at priority ${e.priority}.`);t.set(o,e.name)}}c(H,"assertNoPriorityConflicts");async function G(n){let[t,e]=await Promise.all([L(h,n),L(y.filter(i=>i.syntaxOnly===!0),n)]);return{ctx:n,formatters:t,compilers:e,linters:[]}}c(G,"warmupFormatting");function T(){h.length=0,y.length=0,P.length=0}c(T,"resetRegistry");import{readFile as D}from"node:fs/promises";import g from"node:path";var v=class{constructor(t,e={}){this.sources=t;this.options=e}static{c(this,"DiagnosticStore")}files=new Map;dirty=new Set;sent=new Map;queue=[];running=0;disposed=!1;changeListeners=new Set;onDidChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}schedule(t,e,{cwd:i}){this.disposed||this.ensure(t,e,i)}async read(t,{cwd:e,mode:i,signal:o}){o?.throwIfAborted(),this.assertActive();let a=g.resolve(e,t),s=await D(a,"utf8");this.assertActive();let r=this.ensure(a,s,e);i==="complete"?await this.waitComplete(r,o):i!=="snapshot"&&await K(Promise.all(r.jobs),this.options.readWaitMs??5e3),o?.throwIfAborted(),this.assertActive();let d=await D(a,"utf8");this.assertActive();let l=this.ensure(a,d,e);if(i==="complete"&&l!==r)throw Object.assign(new Error("File changed during diagnostics"),{code:"DIAGNOSTICS_STALE"});return{filePath:a,content:l.content,results:[...l.results.values()]}}async waitComplete(t,e){let i=e?AbortSignal.any([e,t.controller.signal]):t.controller.signal;i.throwIfAborted();let o=[];await new Promise((a,s)=>{let r=c(m=>s(Object.assign(new Error(m),{code:m,details:[...t.results.values()]})),"fail"),d=c(()=>{let m=[...t.results.values()];m.some(w=>w.status==="unavailable")?r("DIAGNOSTICS_UNAVAILABLE"):m.every(w=>w.status==="ready")&&a()},"check"),l=c(()=>s(i.reason),"abort"),f=this.onDidChange(d),u=setTimeout(()=>r("DIAGNOSTICS_TIMEOUT"),this.options.checkTimeoutMs??3e4);i.addEventListener("abort",l,{once:!0});let p=c(()=>{clearTimeout(u),f(),i.removeEventListener("abort",l)},"cleanup");Promise.resolve().then(d),o.push(p)}).finally(()=>{for(let a of o)a()})}async takeNotifications(t){let e=[];for(let i of[...this.dirty]){if(i.cwd!==g.resolve(t)||(this.dirty.delete(i),!await this.isCurrent(i)))continue;let o=[...i.results.values()].filter(d=>d.status!=="pending"&&d.status!=="unavailable"&&d.diagnostics.length>0),a=this.key(i.filePath,i.cwd),s=JSON.stringify(o);if(this.sent.get(a)===s||(this.sent.set(a,s),o.length===0))continue;let r=o.map(d=>{let l=["error","warning","info","hint"].flatMap(f=>{let u=d.diagnostics.filter(p=>p.severity===f).length;return u>0?[`${u} ${f}`]:[]});return`${d.source} ${l.join(", ")}${d.status==="snapshot"?" (snapshot; completion unknown)":d.status==="unversioned"?" (unversioned)":""}`}).join("; ");e.push({filePath:g.relative(t,i.filePath),results:o,text:`${JSON.stringify(g.relative(t,i.filePath))}: ${r}.`})}return e}dispose(){this.disposed=!0,this.changeListeners.clear();for(let t of this.files.values())t.controller.abort();this.files.clear(),this.dirty.clear(),this.sent.clear(),this.pump()}key(t,e){return JSON.stringify([g.resolve(e),g.resolve(e,t)])}ensure(t,e,i){let o=this.key(t,i),a=this.files.get(o);if(a?.content===e)return a;a?.controller.abort(),a&&this.dirty.delete(a);let s={cwd:g.resolve(i),filePath:g.resolve(i,t),content:e,controller:new AbortController,results:new Map,jobs:[],publications:new Map};this.files.set(o,s),this.sources.length===0&&s.results.set("diagnostics",{source:"diagnostics",status:"unavailable",diagnostics:[],reason:"No diagnostic sources registered"}),this.dirty.add(s);for(let r of this.sources){s.results.set(r.id,{source:r.id,status:"pending",diagnostics:[]});let d=new Promise(l=>{this.queue.push(async()=>{try{await this.check(s,r)}finally{l()}})});s.jobs.push(d)}return queueMicrotask(()=>this.pump()),s}pump(){for(;this.running<(this.options.concurrency??4)&&this.queue.length>0;){let t=this.queue.shift();if(!t)break;this.running++,t().finally(()=>{this.running--,this.pump()})}}active(t){return!this.disposed&&!t.controller.signal.aborted}assertActive(){if(this.disposed)throw new Error("Diagnostics session has ended")}async isCurrent(t){if(!this.active(t))return!1;let e=await D(t.filePath,"utf8").catch(()=>{});return this.active(t)&&e===t.content}async publish(t,e,i){let o=(t.publications.get(e)??0)+1;if(t.publications.set(e,o),!await this.isCurrent(t)||t.publications.get(e)!==o)return;let a={...i,source:i.source??e};if(JSON.stringify(t.results.get(e))===JSON.stringify(a))return;t.results.set(e,a),this.dirty.add(t);let s=[...t.results.values()].some(r=>r.status!=="pending"&&r.status!=="unavailable"&&r.diagnostics.length>0);s||this.sent.delete(this.key(t.filePath,t.cwd));for(let r of this.changeListeners)r(t.cwd,s)}async check(t,e){if(!await this.isCurrent(t))return;let i=new AbortController,o=AbortSignal.any([i.signal,t.controller.signal]);if(o.aborted)return;let a,s;try{let r=new Promise((l,f)=>{s=c(()=>f(o.reason),"onAbort"),o.addEventListener("abort",s,{once:!0}),a=setTimeout(()=>i.abort(new Error("Diagnostic check timed out")),this.options.checkTimeoutMs??3e4)}),d=await Promise.race([e.diagnose(t.filePath,{cwd:t.cwd,content:t.content,signal:o,publish:c(l=>{o.aborted||this.publish(t,e.id,l)},"publish")}),r]);await this.publish(t,e.id,d)}catch(r){await this.publish(t,e.id,{status:"unavailable",diagnostics:[],reason:r instanceof Error?r.message:String(r)})}finally{clearTimeout(a),s&&o.removeEventListener("abort",s)}}};async function K(n,t){let e;try{await Promise.race([n,new Promise(i=>{e=setTimeout(i,t)})])}finally{clearTimeout(e)}}c(K,"waitAtMost");function V(){let n=new Map,t=[],e=new v(t),i=Promise.resolve();return{diagnostics:e,registerPlugin(o){if(o.id.trim().length===0)return Promise.reject(new Error("Plugin ID must not be empty"));let a=n.get(o.id);if(a!==void 0)return a;let s=i.then(async()=>{let r=[],d=[],l=!0,f={addTool(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);Z(u),r.push(u)},addDiagnosticSource(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);tt(u),d.push(u)},readDiagnostics(u,p){return e.read(u,p)}};try{await o.setup(f)}catch(u){throw l=!1,u}l=!1,Q(t,d),q(r),t.push(...d)});return n.set(o.id,s),i=s.catch(()=>{}),s.catch(()=>{n.delete(o.id)}),s},async waitForPendingPlugins(){await Promise.all(n.values())}}}c(V,"createIdeCore");function Q(n,t){let e=new Set(n.map(i=>i.id));for(let i of t){if(e.has(i.id))throw new Error(`Diagnostic source ${i.id} is already registered`);e.add(i.id)}}c(Q,"assertUniqueDiagnosticSources");function Z(n){if(!U(n))throw new TypeError("IDE tool must be an object");let t=n.kind,e=t==="compiler"?n.compile:t==="formatter"?n.format:t==="linter"?n.lint:void 0;if(e===void 0||typeof e!="function"||typeof n.detect!="function"||typeof n.name!="string"||n.name.trim().length===0||typeof n.priority!="number"||!Number.isFinite(n.priority)||!Array.isArray(n.extensions)||n.extensions.length===0||n.extensions.some(i=>typeof i!="string"||i.length===0))throw new TypeError("Invalid pi-agent-ide tool contribution")}c(Z,"assertIdeTool");function tt(n){if(!U(n)||typeof n.id!="string"||n.id.trim().length===0||typeof n.diagnose!="function")throw new TypeError("Invalid pi-agent-ide diagnostic source contribution")}c(tt,"assertDiagnosticSource");function U(n){return typeof n=="object"&&n!==null}c(U,"isRecord");function J(n,t,e=console.error){let i=new Map,o=!1,a=Promise.resolve();return{schedule(s){if(o||i.has(s))return;let r=setTimeout(()=>{i.delete(s),a=a.then(async()=>{o||await n(s)}).catch(e)},t);i.set(s,r)},dispose(){o=!0;for(let s of i.values())clearTimeout(s);i.clear()}}}c(J,"createDiagnosticDelivery");import{Text as Y}from"@earendil-works/pi-tui";var S="ide-diagnostic-summary";function W(n){return{filePath:n.filePath,sources:n.results.map(t=>{let e={error:0,warning:0,info:0,hint:0};for(let i of t.diagnostics)e[i.severity]++;return{source:t.source,status:t.status,counts:e}})}}c(W,"diagnosticEntryData");function E(n,t,e=!1){return{render(i){let o=n.sources.filter(r=>r.status!=="pending"&&r.status!=="unavailable"&&Object.values(r.counts).some(d=>d>0));if(o.length===0)return[];let a=o.map(r=>`${x(r.counts,t)} ${t.fg("dim",`(${I(r.source)})`)}`+(r.status==="ready"?"":` \xB7 ${t.fg("dim",r.status)}`)).join(" \xB7 "),s=[`${t.fg("accent","Diagnostics")} ${t.fg("toolTitle",I(n.filePath))} \xB7 ${a}`];if(e)for(let r of o)s.push(` ${t.fg("dim",I(r.source))} \xB7 ${x(r.counts,t)} \xB7 ${t.fg("dim",r.status)}`);return new Y(s.join(`
2
2
  `),0,0).render(i)},invalidate(){}}}c(E,"renderDiagnosticEntry");function B(n){n.registerEntryRenderer(S,(t,e,i)=>{let o=k(t.data);return"files"in o?et(o.files,i,e.expanded):E(o,i,e.expanded)})}c(B,"registerDiagnosticEntryRenderer");function et(n,t,e=!1){return{render(i){let o=n.filter(d=>d.sources.some(l=>l.status!=="pending"&&l.status!=="unavailable"&&Object.values(l.counts).some(f=>f>0)));if(o.length===1&&o[0])return E(o[0],t,e).render(i);if(o.length===0)return[];let a={error:0,warning:0,info:0,hint:0},s=new Set;for(let d of o)for(let l of d.sources)if(!(l.status==="pending"||l.status==="unavailable")){s.add(l.source);for(let f of["error","warning","info","hint"])a[f]+=l.counts[f]}let r=new Y(`${t.fg("accent","Diagnostics")} \xB7 ${o.length} files \xB7 ${x(a,t)} \xB7 ${s.size} tools`,0,0).render(i);return e?[...r,...o.flatMap(d=>E(d,t,!0).render(i))]:r},invalidate(){}}}c(et,"renderDiagnosticBatch");function x(n,t){return["error","warning","info","hint"].filter(e=>n[e]>0).map(e=>{let i=n[e],o=e==="info"||i===1?e:`${e}s`,a=i>0&&(e==="error"||e==="warning")?e:"muted";return t.fg(a,`${i} ${o}`)}).join(", ")}c(x,"renderCounts");function I(n){return n.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}c(I,"plain");import X from"node:path";async function z(n){if(!X.isAbsolute(n.resourceSource))return{formatting:{status:"unavailable"}};let t;try{let e=await G({cwd:n.cwd}),i=X.extname(n.resourceSource).toLowerCase(),o=c(d=>d.extensions.includes(i)||d.extensions.includes("*"),"matches"),a=e.compilers.find(o);if(a&&(await a.compile({filePath:n.resourceSource},e.ctx)).syntaxErrors.length>0)return{formatting:{status:"skipped-syntax"}};let s=e.formatters.find(o);if(!s)return{formatting:{status:"unavailable"}};t=s.name;let r=await s.format({filePath:n.resourceSource},e.ctx);return r.formatter===null?{formatting:{status:"unavailable"}}:(t=r.formatter??s.name,{formatting:{status:r.ok?r.edits>0?"changed":"unchanged":"failed",formatter:t},...r.ok?{diffStatuses:[{text:`Formatted (${t})`,tone:"success",formatter:t}]}:{diffStatuses:[{text:`Formatting failed (${t})`,tone:"error"}]}})}catch{return{diffStatuses:[{text:"Formatting failed",tone:"error"}],formatting:{status:"failed",...t===void 0?{}:{formatter:t}}}}}c(z,"runIdePostEditGate");import it from"node:path";async function nt(n){T();let t=V();B(n);let e=n.events.on($,s=>{if(!F(s))throw new Error("Invalid pi-agent-ide plugin registration request");s.accept(t.registerPlugin(s.plugin))});n.on("session_shutdown",()=>{e(),t.diagnostics.dispose(),T()}),M(n,{id:"pi-agent-ide",handler:c(s=>n.getFlag("pi-agent-ide-no-post-processing")===!0?Promise.resolve({formatting:{status:"disabled"}}):z(s),"handler")}),n.events.emit(A,{protocol:C,apiVersion:4}),await _(n,{protocol:N,apiVersion:O,id:"ide-diagnostics",setup(s){s.onDidEdit(r=>{n.getFlag("pi-agent-ide-no-post-processing")===!0||r.postProcessing==="deferred"||it.isAbsolute(r.resourceSource)&&j(()=>t.diagnostics.schedule(r.resourceSource,r.after.content,{cwd:r.cwd}))})}});let i=!1,o=J(async s=>{let r=await t.diagnostics.takeNotifications(s);i||r.length===0||(n.sendMessage({customType:"ide-diagnostics",display:!1,content:`File diagnostics:
3
3
  ${r.map(d=>d.text).join(`
4
4
  `)}`},{triggerTurn:!0,deliverAs:"steer"}),n.appendEntry(S,{files:r.map(W)}))},n.getFlag("pi-agent-ide-no-diagnostic-buffer")===!0?0:5e3),a=t.diagnostics.onDidChange((s,r)=>{r&&o.schedule(s)});n.on("session_shutdown",()=>{i=!0,o.dispose(),a()}),await t.waitForPendingPlugins()}c(nt,"registerPiAgentIde");export{nt as default};
@@ -0,0 +1,16 @@
1
+ import{a as b,d as A}from"./chunk-ITSNK5YG.js";import{a as N}from"./chunk-22CLOM2D.js";import{b as F,d as $}from"./chunk-526E364R.js";import{f as M}from"./chunk-YHUTTZC6.js";import{a as u}from"./chunk-EI7MMDWY.js";import L from"node:path";import{truncateHead as _,DEFAULT_MAX_BYTES as ee,DEFAULT_MAX_LINES as te}from"@earendil-works/pi-coding-agent";import{Text as S}from"@earendil-works/pi-tui";import{Type as O}from"typebox";import{Value as re}from"typebox/value";var I=O.Union([O.String({minLength:1}),N]),v=O.Object({before:I,after:I},{additionalProperties:!1});async function ne(e,o,c){if(!re.Check(v,o))throw Object.assign(new Error("Use before and after source strings or read request objects"),{code:"INVALID_ARGUMENTS"});let n=o,r=u(async l=>{let t=typeof l=="string"?{path:l}:l,p=await e.read(t,c,"script");if(p.isError||p.details.failure)throw Object.assign(new Error(p.details.failure?.message??"Comparison read failed"),{code:p.details.failure?.code??"READ_FAILED",details:p.details.failure});if(p.script===void 0)throw Object.assign(new Error("Source has no comparable text data"),{code:"UNSUPPORTED_CONTENT"});return B(p.script,t.path??"source")},"resolve"),s=await r(n.before),a=await r(n.after),i=b(s.source,s.content,a.content,a.source);return{kind:"diff",ok:!0,equal:s.content===a.content,before:s,after:a,...i}}u(ne,"executeDiff");function B(e,o){if(e.kind==="text")return{source:e.source,sources:[e.source],content:e.content};if(e.kind==="resources"){let c=e.resources.map(n=>B(n,o));return{source:e.source??o,sources:c.flatMap(n=>n.sources),content:c.map(n=>n.content).join(`
2
+ `)}}if(e.kind==="bytes")throw Object.assign(new Error(`Byte sources are not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});if(e.blocks.length===0||e.blocks.some(c=>c.type!=="text"))throw Object.assign(new Error(`Source is not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});return{source:e.source,sources:[e.source],content:e.blocks.flatMap(c=>c.type==="text"?[c.text]:[]).join(`
3
+ `)}}u(B,"comparisonText");function R(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="diff"&&"ok"in e&&e.ok===!0}u(R,"isDiffOutcome");function j(e,o=process.cwd()){let c=u(r=>L.isAbsolute(r)?L.relative(o,r)||".":r,"displaySource"),n=`Diff: ${c(e.before.source)} \u2192 ${c(e.after.source)}`;return{results:[new A({ok:!0,path:n,beforeContentMap:{[n]:e.before.content},afterContent:e.after.content,diffs:[e.diff]})]}}u(j,"diffPresentation");function k(e){return e.equal?`No differences: ${e.before.source} \u2192 ${e.after.source}`:e.diff}u(k,"diffText");function Ee(e){return{content:[{type:"text",text:k(e)}],details:{}}}u(Ee,"diffReadResult");function De(e,o,c){e.registerTool({name:"diff",label:"Diff",parameters:v,promptSnippet:"Compare two text-readable sources without changing them",description:"Use diff to compare two sources without modifying them. before and after accept a source string or a read request {path, offset?, limit?, views?}. Use any source that read can resolve as text. Omit limit to compare complete resolved text; read presentation limits do not clip comparison inputs. Multiple resolved resources are joined with one newline separator in resolver order. Diff line numbers are relative to each selected text, not the original file when a window is selected. Native non-text content is rejected. Output uses the existing text diff and a shared output budget; oversized output has a full temporary reference. The same diff function is available inside Apply.",renderCall(n,r){return new S(r.fg("toolTitle",r.bold("Diff")),0,0)},renderResult(n,r,s,a){let i=n.details;if(i?.comparison?.equal)return new S(k(i.comparison),0,0);let l=o.getToolRenderer("diff")?.renderResult;return l?l(n,r,s,a):new S(n.content.filter(t=>t.type==="text").map(t=>t.text).join(`
4
+ `),0,0)},async execute(n,r,s,a,i){let l=c();if(l===void 0)throw new Error("Diff requires the read extension");let t=await ne(l,r,{cwd:i.cwd,signal:s}),p=k(t),y=_(p).truncated?await l.saveTemporary(p):void 0,f=y===void 0?"":`
5
+ Full diff: ${y}`;return{content:[{type:"text",text:y===void 0?p:_(p,{maxLines:te-2,maxBytes:ee-Buffer.byteLength(f)}).content+f}],details:{...j(t,i.cwd),comparison:t,temporarySource:y}}}})}u(De,"registerDiff");import{parser as q}from"@lezer/javascript";import{TreeFragment as U}from"@lezer/common";var oe=new Set(["read","search","diff","open","createFile","deleteFile","copyFile","moveFile","flush","result"]);function V(e,o=q.parse(e)){let c=[];o.iterate({enter(r){if(r.name==="AssignmentExpression"){let t=r.node.firstChild;t?.name==="VariableName"&&c.push({name:e.slice(t.from,t.to),from:0,to:e.length})}if(r.name!=="VariableDefinition")return;let s=r.node.parent;for(;s?.parent&&!["VariableDeclaration","ParamList","Block","Script"].includes(s.name);)s=s.parent;let a=s?.name==="VariableDeclaration"&&s.firstChild?.name==="var",i=new Set(["Script","FunctionDeclaration","FunctionExpression","ArrowFunction",...a?[]:["Block"]]),l=r.node.parent;for(l?.name==="FunctionDeclaration"&&(l=l.parent);l?.parent&&!i.has(l.name);)l=l.parent;c.push({name:e.slice(r.from,r.to),from:l?.from??0,to:l?.to??e.length})}});let n=[];return o.iterate({enter(r){if(r.name!=="CallExpression")return;let s=r.node.firstChild;if(s?.name!=="VariableName")return;let a=e.slice(s.from,s.to);if(!oe.has(a)||c.some(t=>t.name===a&&t.from<=r.from&&t.to>=r.to))return;let i=r.node.getChild("ArgList")?.getChild("ObjectExpression"),l=Object.create(null);if(!i){let t=r.node.getChild("ArgList"),p=t?e.slice(t.from+1,t.to).replace(/\)$/,""):"";p&&(l.arguments={text:p.length>160?p.slice(0,120)+"\u2026":p,literal:!1})}for(let t of i?.getChildren("Property")??[]){let p=t.firstChild,y=(p?e.slice(p.from,p.to):"").replace(/^["']|["']$/g,"");if(!/^[a-zA-Z_$][\w$]*$/.test(y)){for(let Q of["path","query","target","before","after"])delete l[Q];let w=e.slice(t.from,t.to);l[`argument@${t.from}`]={text:w.length>160?w.slice(0,160)+"\u2026":w,literal:!1};continue}let f=t.lastChild;if(!f||f.type.isError||f.name===":")continue;let g=e.slice(f.from,f.to),d=g.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),h=/^(?:["'])(?:\d+#[0-9A-F]+|CHANGE#[0-9A-F]+|begin|end|scope-(?:begin|end)-[^"']+)["']$/.test(g);l[y]={text:d.length>160&&!h?`${d.slice(0,100)}\u2026${d.slice(-40)} (${g.length} source chars)`:d,literal:["String","Number","BooleanLiteral","Null"].includes(f.name)&&f.lastChild?.type.isError!==!0}}return n.push({name:a,from:r.from,to:r.to,path:l.path,query:l.query,target:l.target,before:l.before,after:l.after,arguments:l}),!1}}),n}u(V,"parseApplyCalls");function ie(e,o=V(e),c,n=r=>r){let r=0,s=[],a=u(i=>n(i.split(`
6
+ `).map(l=>l.length>200?l.slice(0,200)+"\u2026":l).join(`
7
+ `)),"codePreview");for(let i of o)s.push(a(e.slice(r,i.from))),s.push(c?.(i)??`${i.name}(${i.path?i.path.literal?i.path.text:`\u2039${i.path.text}\u203A`:"\u2026"})`),r=i.to;return s.push(a(e.slice(r))),s.join("")}u(ie,"compactApplySource");function J(e,o){let c="",n="",r=[];return s=>{if(s===c)return n;let a=0;for(;a<c.length&&a<s.length&&c[a]===s[a];)a++;r=U.applyChanges(r,[{fromA:a,toA:c.length,fromB:a,toB:s.length}]);let i=q.parse(s,r);return r=U.addTree(i),n=ie(s,V(s,i),e,o),c=s,n}}u(J,"createApplySourceProjection");import{lstat as G,unlink as se}from"node:fs/promises";import Y from"node:path";import z from"fs-extra";import{Type as x}from"typebox";import{Value as ae}from"typebox/value";var T=x.String({minLength:1,description:"Local regular file path, relative to cwd or absolute."}),le=x.Object({path:T},{additionalProperties:!1}),ce=x.Object({path:T,target:T,overwrite:x.Optional(x.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))},{additionalProperties:!1});function E(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="file-operation"}u(E,"isFileOperationResult");function D(e){return[`${e.operation}: ${e.effect}`,e.path,e.target===void 0?void 0:`Target: ${e.target}`,e.error===void 0?void 0:`${e.error.code}: ${e.error.message}`].filter(o=>o!==void 0).join(`
8
+ `)}u(D,"formatFileOperation");async function Ue(e,o,c,n){let r=!1,s,a;try{let i=e==="delete"?le:ce;if(!ae.Check(i,o))throw Object.assign(new Error("Invalid file operation arguments"),{code:"INVALID_ARGUMENTS"});let l=o;s=Y.resolve(c,l.path),a=l.target===void 0?void 0:Y.resolve(c,l.target),n?.throwIfAborted();let t=await pe(s);if(a!==void 0){let p=await fe(a);if(p!==void 0){if(!p.isFile()||p.isSymbolicLink())throw Object.assign(new Error("Target must be a regular file"),{code:"INVALID_FILE_TYPE"});if(s===a||t.ino===p.ino&&t.dev===p.dev)throw Object.assign(new Error("Source and target are the same file"),{code:"SAME_FILE"});if(l.overwrite!==!0)throw Object.assign(new Error("Target exists; use overwrite: true to replace it"),{code:"EEXIST"})}}return n?.throwIfAborted(),r=!0,e==="delete"?await se(s):a!==void 0&&(e==="copy"?await z.copy(s,a,{overwrite:l.overwrite===!0,errorOnExist:!0}):await z.move(s,a,{overwrite:l.overwrite===!0})),{kind:"file-operation",operation:e,ok:!0,effect:"applied",path:s,...a===void 0?{}:{target:a}}}catch(i){return{kind:"file-operation",operation:e,ok:!1,effect:r?"unknown":"not-applied",...s===void 0?{}:{path:s},...a===void 0?{}:{target:a},error:{code:i!==null&&typeof i=="object"&&"code"in i?String(i.code):"FILE_OPERATION_FAILED",message:i instanceof Error?i.message:String(i)}}}}u(Ue,"executeFileOperation");async function pe(e){let o=await G(e);if(!o.isFile()||o.isSymbolicLink())throw Object.assign(new Error("Source must be a regular file"),{code:"INVALID_FILE_TYPE"});return o}u(pe,"regularFile");async function fe(e){try{return await G(e)}catch(o){if(o!==null&&typeof o=="object"&&"code"in o&&o.code==="ENOENT")return;throw o}}u(fe,"optionalStat");import{Text as de}from"@earendil-works/pi-tui";function K(e){let o=e.select(),c=e.mutationValues().filter(ue);return o.files.map(n=>{let r=c.flatMap(i=>i.files.filter(l=>l.source===n.source).map(l=>({outcome:i,changed:l}))),s=e.mutationPresentation(n.source)?.data,a=s?.afterContent===n.after?s:void 0;return new A({ok:!0,path:n.source,files:[{path:n.source,action:n.before===null?"created":"edited"}],snapshot:{content:n.before??""},beforeContentMap:{[n.source]:n.before},afterContent:n.after??"",afterDocument:a?.afterDocument,resultPresentation:a?.resultPresentation,scopeMarkers:a?.scopeMarkers,hints:a?.hints,warnings:a?.warnings,diffStatuses:a?.diffStatuses,diffs:[b(n.source,n.before??"",n.after??"").diff],operations:r.map(({outcome:i,changed:l})=>({operation:i.operation==="remove"?"delete":i.operation,changes:l.changes.length})),formatting:a?.formatting??r.at(-1)?.changed.formatting})})}u(K,"finalApplyMutations");function ue(e){return e!==null&&typeof e=="object"&&"operation"in e&&"files"in e&&Array.isArray(e.files)&&"effect"in e}u(ue,"isMutation");import{highlightCode as Z}from"@earendil-works/pi-coding-agent";import{wrapTextWithAnsi as W,visibleWidth as X,truncateToWidth as me}from"@earendil-works/pi-tui";function nt(e,o,c,n=process.cwd()){let r=e.select(),s=[...r.automatic,...r.explicit.filter(t=>t.kind==="operation")].filter(t=>R(t.value)&&!t.value.equal),a=s.flatMap(t=>R(t.value)?[j(t.value,n)]:[]),i=new Set(s.flatMap(t=>t.presentation?.content??[]));if(r.files.length===0){let t=[...r.automatic.map(p=>p.presentation),...r.explicit.map(p=>p.kind==="operation"?p.presentation:void 0)].filter(p=>p!==void 0);return{comparisons:a,cwd:n,blocks:[...o.content.filter(p=>!i.has(p)).flatMap(p=>p.type==="text"?[{text:H(p.text),read:t.find(m=>m.content.includes(p))}]:[])]}}let l=K(e);return{...l.length>0?{mutations:{results:l}}:{},comparisons:a,cwd:n,blocks:[...r.explicit.flatMap(t=>t.kind==="operation"&&R(t.value)&&!t.value.equal?[]:E(t.value)?[{text:D(t.value)}]:t.kind==="operation"?t.presentation?.content.flatMap(p=>p.type==="text"?[{text:p.text,read:t.presentation}]:[])??[]:[{text:H(typeof t.value=="string"?t.value:t.value===void 0?"undefined":JSON.stringify(t.value,null,2))}]),...r.automatic.flatMap(({value:t,presentation:p})=>{if(E(t))return[{text:D(t)}];if(t!==null&&typeof t=="object"&&"kind"in t&&t.kind==="index-operation")return p?.content.flatMap(m=>m.type==="text"?[{text:m.text}]:[])??[];if(t===null||typeof t!="object"||!("errors"in t)||!Array.isArray(t.errors))return[];if("operations"in t&&Array.isArray(t.operations)){let m=t.operations.filter(f=>f!==null&&typeof f=="object"&&"status"in f&&f.status==="applied").length;if(m===t.operations.length)return[];let y=t.operations.filter(f=>f!==null&&typeof f=="object"&&"status"in f&&f.status!=="applied").map(f=>({text:we(f)}));return[{text:`Apply partially applied: ${m} of ${t.operations.length} operations completed.`},...y]}return t.errors.flatMap(m=>m!==null&&typeof m=="object"&&"message"in m&&typeof m.message=="string"?[{text:m.message}]:[])}),...c===void 0?[]:[{text:c instanceof Error?c.message:JSON.stringify(c)}]]}}u(nt,"createApplyDisplay");function P(e,o,c,n,r,s,a=!1){let i=Math.max(1,c);if(i<5)return e.split(`
9
+ `).flatMap(d=>W(d,i));let l=i-4,t=u(d=>o.fg("borderMuted",d),"border"),m=me(` ${n==="call"?"Apply \xB7 JavaScript":"Result"} `,i-4,""),y=[t(`${n==="call"?"\u256D":"\u251C"}\u2500`)+o.fg(a?"error":"accent",m)+t(`${"\u2500".repeat(Math.max(0,i-X(m)-3))}${n==="call"?"\u256E":"\u2524"}`)],f=`${t("\u2502")}${" ".repeat(i-2)}${t("\u2502")}`;for(let d of e.split(`
10
+ `)){let h=s==="diff"?o.fg(d.startsWith("+")?"toolDiffAdded":d.startsWith("-")?"toolDiffRemoved":"toolDiffContext",d):s?Z(d,s).join(`
11
+ `):o.fg("toolOutput",d);for(let w of W(h,l))y.push(`${t("\u2502")} ${w}${" ".repeat(Math.max(0,l-X(w)))} ${t("\u2502")}`)}n==="call"&&y.push(f),r&&y.push(t(`\u2570${"\u2500".repeat(i-2)}\u256F`));let g=o.getBgAnsi("toolPendingBg");return y.map(d=>g+M(d,g)+"\x1B[0m")}u(P,"applyFrameRows");function ge(e){return(o,c,n)=>{let r=n.state,s=r.projectSource??=J(e?i=>e(i,c):void 0,e?i=>Z(i,"javascript").join(`
12
+ `):void 0),a=o!==null&&typeof o=="object"&&"source"in o&&typeof o.source=="string"?o.source:"";return{invalidate(){},render(i){return P(r.codeView||n.expanded?r.displaySource??a:ye(s(r.displaySource??a)),c,i,"call",!r.applyResultReady,r.codeView||n.expanded||!e?"javascript":void 0)}}}}u(ge,"createApplyCallRenderer");function ye(e,o=F){let c=e.split(`
13
+ `);if(c.length<=o)return e;let n=Math.max(2,o-1),r=Math.ceil(n/2),s=Math.floor(n/2),a=c.length-r-s;return[...c.slice(0,r),`\u2026 ${a} lines omitted \u2026`,...c.slice(-s)].join(`
14
+ `)}u(ye,"compactApplyPreview");var ot=ge();function he(e){return(o,c,n,r)=>{r.state.applyResultReady=!0;let s=o.details;r.state.displaySource=s?.displaySource;let a=s?.display,i=a?.blocks??[{text:r.isError?"Apply failed":"Apply finished"}],l=$({kind:"source"}),t=i.map(f=>l(f.read??{content:[{type:"text",text:f.text}],details:xe(f.text)},c,n,{...r,isError:!1,lastComponent:void 0})),p=a?.mutations,m=(a?.comparisons??[]).flatMap(f=>[e?.(f,n,c.expanded,a?.cwd??process.cwd())??new de((f.results??[]).flatMap(d=>d.data.diffs??[]).join(`
15
+ `),0,0)]),y=p===void 0?void 0:e?.(p,n,c.expanded,a?.cwd??process.cwd());return{invalidate(){y?.invalidate();for(let f of m)f.invalidate()},render(f){let g=[];for(let d of t){let h=d.render(Math.max(1,f-4));h.length!==0&&(g.length>0&&g.push(""),g.push(...h))}for(let d of m)g.length>0&&g.push(""),g.push(...d.render(Math.max(1,f-4)));if(y!==void 0){let d=y.render(Math.max(1,f-4));g.length>0&&d.length>0&&g.push(""),g.push(...d)}else p!==void 0&&g.push(...(p.results??[]).map(d=>d.path??"Changed file"));return g.length===0&&i.length>0&&i.every(d=>d.read?.details.diagnosticCheck?.complete&&d.read.details.diagnosticCheck.count===0)?P("",n,f,"result",!0).slice(-1):P(g.length===0?"No output":g.join(`
16
+ `),n,f,"result",!0,void 0,r.isError)}}}}u(he,"createApplyResultRenderer");function we(e){if(e===null||typeof e!="object")return String(e);let o="index"in e?Number(e.index)+1:"?",c="kind"in e?String(e.kind):"operation",n="status"in e?String(e.status):"unknown",r="error"in e&&e.error!==null&&typeof e.error=="object"?`: ${"code"in e.error?String(e.error.code):"ERROR"}: ${"message"in e.error?String(e.error.message):"Operation failed"}`:"";return`Operation ${o} (${c}): ${n}${r}`}u(we,"formatDisplayOutcome");function H(e){if(/^(?:Undo transaction:|Undo available)/u.test(e.trim()))return"";try{let o=JSON.parse(e);return JSON.stringify(C(o),null,2)}catch{return e.replace(/APPLY#[0-9A-F]{12}/gu,"Apply transaction")}}u(H,"redactApplyReceipts");function C(e){return Array.isArray(e)?e.map(C):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([o])=>o!=="transaction").map(([o,c])=>[o,C(c)]))}u(C,"redactTransactionKeys");function xe(e){try{let o=JSON.parse(e);return o!==null&&typeof o=="object"?{source:"result.json"}:{}}catch{return{}}}u(xe,"jsonDetails");var it=he();export{ne as a,Ee as b,De as c,Ue as d,K as e,nt as f,ge as g,ot as h,he as i,it as j};
@@ -0,0 +1,7 @@
1
+ import"./chunk-3YK4XMWB.js";import{a as J,b as V,c as z,d as U,f as q}from"./chunk-T6LX2RX5.js";import{d as L,e as h}from"./chunk-M5MJP7Z2.js";import{a as E}from"./chunk-WZI4YC2O.js";import{d as N}from"./chunk-N34ATN52.js";import{a as O}from"./chunk-ZC65Z3CK.js";import{a as _,b as F,c as M}from"./chunk-JMVDFOTQ.js";import{a as d}from"./chunk-EI7MMDWY.js";import{mkdir as ie,readFile as B,writeFile as re}from"node:fs/promises";async function G(n,t){await ie(L(n),{recursive:!0});let e=[],o=t.filter(s=>s.recipe.formatter!==void 0),i=t.filter(s=>s.recipe.linter!==void 0),r=t.filter(s=>s.recipe.lsp!==void 0);if(o.length>0){let s=h(n,"formatters"),c=await S(s,{version:1,formatters:{}}),u=P(c,"formatters");for(let l of o)u[l.recipe.id]??=l.recipe.formatter;await R(s,c)&&e.push(s)}if(i.length>0){let s=h(n,"linters"),c=await S(s,{version:1,linters:{}}),u=P(c,"linters");for(let l of i)u[l.recipe.id]??=l.recipe.linter;await R(s,c)&&e.push(s)}if(r.length>0){let s=h(n,"lsp-servers"),c=await S(s,{version:1,servers:{}}),u=P(c,"servers");for(let l of r){let a=O(l.recipe.lsp);u[l.recipe.id]??={command:a.command,transport:"stdio",rootMarkers:a.rootMarkers,...a.initializationOptions!==void 0&&{initializationOptions:a.initializationOptions},...a.settings!==void 0&&{settings:a.settings},...a.requireRootMarker!==void 0&&{requireRootMarker:a.requireRootMarker},languages:Object.fromEntries(Object.entries(a.languageIds).map(([p,f])=>[p,{extensions:f,...a.fileNames?.[p]&&{fileNames:a.fileNames[p]}}])),capabilities:["diagnostics"]}}await R(s,c)&&e.push(s)}return e}d(G,"writeSuggestedConfigs");async function S(n,t){try{let e=JSON.parse(await B(n,"utf8"));if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${n} must contain an object`);return e}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return t;throw e}}d(S,"readObject");function P(n,t){let e=n[t];if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} must be an object`);return e}d(P,"objectMember");async function R(n,t){let e=`${JSON.stringify(t,null,2)}
2
+ `;return await B(n,"utf8").catch(()=>{})===e?!1:(await re(n,e,"utf8"),!0)}d(R,"writeJson");var C=class{static{d(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(t){let e=this.plugins.get(t.id);if(e!==void 0)return e;let o=this.queue.then(async()=>{let i=!0,r=[],s=[],c=[],u=[],l={addLanguage:d(a=>{b(a,r,t.id,"language",()=>i)},"addLanguage"),addToolRecipe:d(a=>{b(a,s,t.id,"tool recipe",()=>i)},"addToolRecipe"),addSetupCheck:d(a=>{b(a,c,t.id,"setup check",()=>i)},"addSetupCheck"),addCheck:d(a=>{b(a,u,t.id,"check",()=>i)},"addCheck")};try{await t.setup(l)}finally{i=!1}W(this.languages,r,"language"),W(this.recipes,s,"tool recipe"),this.languages.push(...r),this.recipes.push(...s),this.setupChecks.push(...c),this.checks.push(...u)});return this.plugins.set(t.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(t.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function H(n,t){let e=[],o=[];for(let i of n.setupChecks)try{let r=await i.value.inspect(t);e.push(...(r.selections??[]).map(s=>({...s,pluginId:i.pluginId}))),o.push(...(r.actions??[]).map(s=>({...s,pluginId:i.pluginId})))}catch{}return{selections:e,actions:o}}d(H,"runContributedSetupChecks");async function X(n,t){let e=[];for(let o of n.checks)try{e.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(t)})}catch(i){e.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:i instanceof Error?i.message:String(i)}]})}return e}d(X,"runContributedChecks");function W(n,t,e){for(let o of t){let i=n.find(r=>r.value.id===o.value.id)?.pluginId;if(i!==void 0)throw new Error(`${e} ${o.value.id} is already owned by doctor plugin ${i}`)}}d(W,"assertAvailable");function b(n,t,e,o,i){if(!i())throw new Error(`Doctor plugin ${e} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(t.some(r=>r.value.id===n.id))throw new Error(`Doctor plugin ${e} registered ${o} ${n.id} twice`);t.push({pluginId:e,value:n})}d(b,"add");import fe from"node:path";import{readFile as se}from"node:fs/promises";async function Y(n,t,e,o=process.env){let i=await E(n,e.map(c=>c.value)),r=await ce(n),s=[];for(let c of e){let u=c.value;if(u.languages.every(v=>!t.has(v)))continue;let l=[],a=1,p=i.get(u.id),f=p?.config;f!==void 0&&(a+=6,l.push(`project config: ${f}`)),r.has(`${u.kind}:${u.id}`)&&(a+=6,l.push("Pi Agent IDE config"));let w=p?.dependency;w!==void 0&&(a+=4,l.push(`project dependency: ${w}`));let m=await ae(n,u.executables,o);m!==void 0&&(a+=3,l.push(`executable: ${m}`)),s.push({pluginId:c.pluginId,recipe:u,score:a,evidence:l,...m&&{executable:m}})}return s.sort((c,u)=>u.score-c.score||c.recipe.id.localeCompare(u.recipe.id))}d(Y,"discoverRecipeCandidates");function K(n,t,e=[]){let o=new Map,i=new Map(e.map(r=>[`${r.kind}:${r.languageId}`,r.toolId]));for(let r of t)for(let s of["formatter","linter","lsp"]){let c=i.get(`${s}:${r}`),u=c===void 0?4:7,l=n.filter(p=>p.recipe.kind===s&&p.recipe.languages.includes(r)&&p.executable!==void 0&&p.recipe.id!==c&&p.score>=u),a=l[0];a!==void 0&&(l.filter(p=>p.score===a.score).length>1||o.set(`${a.recipe.kind}:${a.recipe.id}`,a))}return[...o.values()]}d(K,"selectSuggestedRecipes");async function ae(n,t,e){for(let o of t)if(await N(o,n,e))return o}d(ae,"firstExecutable");async function ce(n){let t=new Set;for(let[e,o,i]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{let r=JSON.parse(await se(h(n,e),"utf8"));if(typeof r!="object"||r===null||Array.isArray(r))continue;let c=r[o];if(typeof c=="object"&&c!==null&&!Array.isArray(c))for(let u of Object.keys(c))t.add(`${i}:${u}`)}catch{}return t}d(ce,"managedRecipeIds");import{execFile as de}from"node:child_process";import{readdir as ue}from"node:fs/promises";import y from"node:path";import{promisify as le}from"node:util";var pe=le(de),ge=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Q(n,t){t?.throwIfAborted();try{let o=(await pe("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:t})).stdout.split("\0").filter(Boolean).map(i=>y.resolve(n,i)).filter(i=>!ee(i));return t?.throwIfAborted(),o.length>0?o:await k(n,t)}catch{return t?.throwIfAborted(),k(n,t)}}d(Q,"collectProjectFiles");function Z(n,t,e=process.platform){let o=new Map,i=e==="win32"?y.win32:y;for(let r of t){let s=new Set(r.extensions.map(a=>a.toLowerCase())),c=d(a=>e==="win32"?a.toLowerCase():a,"normalizeName"),u=new Set(r.fileNames?.map(c)),l=n.filter(a=>!a.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")&&(s.has(i.extname(a).toLowerCase())||u.has(c(i.basename(a)))));l.length>0&&o.set(r.id,l)}return o}d(Z,"detectProjectLanguages");async function k(n,t){t?.throwIfAborted();let e=[];for(let o of await ue(n,{withFileTypes:!0})){if(o.isDirectory()&&ge.has(o.name))continue;let i=y.join(n,o.name);ee(i)||(o.isDirectory()?e.push(...await k(i,t)):o.isFile()&&e.push(i))}return e}d(k,"walk");function ee(n){return n.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")}d(ee,"isManagedIdeConfig");async function $(n,t,e=process.env,o){o?.throwIfAborted();let i=await Q(t,o);o?.throwIfAborted();let r=Z(i,n.languages.map(p=>p.value)),s=new Set(r.keys()),c={cwd:t,files:i,detectedLanguageIds:s,detectedLanguages:r,env:e},[u,l]=await Promise.all([Y(t,s,n.recipes,e),H(n,c)]),a=new Map;for(let p of s)for(let f of["formatter","linter","lsp"]){if(l.selections.some(g=>g.languageId===p&&g.kind===f))continue;let w=u.filter(g=>g.recipe.kind===f&&g.recipe.languages.includes(p)),m=d(g=>g.score-(g.executable===void 0?0:3),"nativeScore"),v=Math.max(1,...w.map(m));for(let g of w){if(g.executable!==void 0||m(g)!==v||v<=1)continue;let T=`${f}-${g.recipe.id}-unavailable`;a.set(T,{id:T,pluginId:g.pluginId,message:`Native project setup selects ${g.recipe.id}, but its executable is unavailable. Install ${g.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:t,files:i,detectedLanguages:r,candidates:u,selections:l.selections,actions:[...l.actions,...a.values()],suggestions:K(u,s,l.selections)}}d($,"inspectDoctorSetup");async function I(n,t,e=process.env){let o=await $(n,t,e),i=new Set(o.detectedLanguages.keys()),r={cwd:t,files:o.files,detectedLanguageIds:i,detectedLanguages:o.detectedLanguages,env:e},s=await X(n,r),c=[{status:"pass",message:`Project: ${t}`},o.files.length>0?{status:"pass",message:`${o.files.length} project files inspected`}:{status:"warn",message:"No project files found"},i.size>0?{status:"pass",message:`Detected: ${[...i].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...o,sections:[{title:"Project",pluginId:"doctor",findings:c},...s]}}d(I,"runDoctor");function D(n){let t=["Pi Agent IDE doctor",""];for(let e of n.sections){t.push(`${e.title} (${e.pluginId})`);for(let o of e.findings)t.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&t.push(` \`${o.detail}\``);t.push("")}if(n.actions.length>0){t.push("Setup needs attention");for(let e of n.actions)t.push(` ${e.message} [${e.pluginId}]`);t.push("")}if(n.suggestions.length>0){t.push("Suggested configuration");for(let e of n.suggestions){let o=e.evidence.length>0?` \u2014 ${e.evidence.join(", ")}`:"";t.push(` ${e.recipe.kind.padEnd(9)} ${e.recipe.id} [${e.pluginId}]${o}`)}t.push("")}return t.join(`
3
+ `).trimEnd()}d(D,"formatDoctorReport");function j(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(t=>t.findings.some(e=>e.status==="fail"))}d(j,"doctorNeedsWork");function te(n){let t=n.candidates.map(e=>({owner:e.pluginId,id:e.recipe.id,kind:e.recipe.kind,languages:e.recipe.languages,evidence:e.evidence,documentation:e.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",D(n),"","Relevant registered recipes:",JSON.stringify(t,null,2),"",`Project root: ${fe.resolve(n.cwd)}`].join(`
4
+ `)}d(te,"buildDoctorAgentPrompt");import{createHash as me}from"node:crypto";var he="doctor",x=3;function ne(n,t){let e=_(n,ye(t));e!==void 0&&e.catch(()=>{})}d(ne,"registerDoctorTipProvider");function ye(n){return{protocol:F,apiVersion:M,id:he,async getTip(t){let e=await n(t),o=we(e);if(o.length===0)return;let i=o.slice(0,x).map(r=>`\u2022 ${r.message}`);return o.length>x&&i.push(`\u2022 ${o.length-x} more`),{id:`doctor-setup-${De(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...i,"Run /pi-agent-ide-doctor"].join(`
5
+ `)}}}}d(ye,"createDoctorTipProvider");function we(n){let t=n.actions.map(o=>({id:`action:${o.pluginId}:${o.id}`,message:o.message})),e=n.suggestions.map(o=>{let i=o.recipe.languages.filter(s=>n.detectedLanguages.has(s)).join(", "),r={debugger:"debugging",formatter:"formatting",linter:"linting",lsp:"language support"}[o.recipe.kind];return{id:`suggestion:${o.pluginId}:${o.recipe.kind}:${o.recipe.id}`,message:`Use ${o.recipe.name} for ${i} ${r}`}});return[...t,...e].sort((o,i)=>o.id.localeCompare(i.id))}d(we,"setupItems");function De(n){return me("sha256").update(n.map(t=>`${t.id}\0${t.message}`).join("\0")).digest("hex").slice(0,12)}d(De,"fingerprint");async function oe(n){let t=new C;ne(n,async i=>(await t.waitForPlugins(),$(t.snapshot(),i.cwd,process.env,i.signal)));let e,o=n.events.on(U,i=>{if(!q(i))throw new Error("Invalid doctor plugin registration request");i.accept(t.registerPlugin(i.plugin))});n.on("session_shutdown",o),n.registerCommand("pi-agent-ide-doctor",{description:"Check and configure Pi Agent IDE for this project",handler:d(async(i,r)=>{await t.waitForPlugins();let s=await I(t.snapshot(),r.cwd);A(n,D(s));let c=new Set(i.trim().split(/\s+/u).filter(Boolean));if(s.suggestions.length>0&&!c.has("--no-apply")&&(c.has("--apply")||r.hasUI&&await r.ui.confirm("Apply suggested configuration?","Add detected tools to .pi/pi-agent-ide/. Existing entries and native tool settings are kept."))){let a=await G(r.cwd,s.suggestions),p=a.length===0?"Pi Agent IDE configs are already up to date":`Updated ${a.length} Pi Agent IDE config ${a.length===1?"file":"files"}`;r.ui.notify(p,"info"),s=await I(t.snapshot(),r.cwd),A(n,D(s))}if(!j(s)&&!c.has("--agent"))return;(c.has("--agent")||r.hasUI&&await r.ui.confirm("Ask the agent to finish setup?","The agent will receive this redacted report and relevant plugin recipes."))&&(e=r.cwd,n.sendUserMessage(te(s)))},"handler")}),n.on("agent_end",async(i,r)=>{let s=e;if(s===void 0)return;e=void 0;let c=await I(t.snapshot(),s,process.env);A(n,`Doctor recheck after agent setup
6
+
7
+ ${D(c)}`),j(c)?r.ui.notify("Pi Agent IDE setup still needs attention","warning"):r.ui.notify("Pi Agent IDE setup is ready","info")}),n.events.emit(z,{protocol:J,apiVersion:1}),await t.waitForPlugins()}d(oe,"registerDoctor");function A(n,t){n.sendMessage({customType:"pi-agent-ide-doctor",content:t,display:!0},{triggerTurn:!1})}d(A,"sendReport");export{oe as default};
@@ -0,0 +1,5 @@
1
+ import{a as L}from"./chunk-M5IVSCR2.js";import{a as U}from"./chunk-6CZO43OH.js";import{a as M,b as $}from"./chunk-OBNING2A.js";import{a as k}from"./chunk-ZTYWHL2F.js";import{a as O,b as T}from"./chunk-7UGNGK7Y.js";import{a as c}from"./chunk-EI7MMDWY.js";import{execFile as Z}from"node:child_process";import ee from"node:os";import{promisify as ne}from"node:util";import{createCanvas as _,loadImage as te}from"@napi-rs/canvas";var p=ne(Z),I=20*1024*1024,B={durationSeconds:2,intervalSeconds:.5,scale:.5},W=new Set;function F(e){let n=D({mode:"sequence",durationSeconds:Number(e.durationSeconds??2),intervalSeconds:Number(e.intervalSeconds??.5),scale:Number(e.scale??.5)});B={durationSeconds:n.durationSeconds,intervalSeconds:n.intervalSeconds,scale:n.scale},W=new Set((e.allowedExecutables??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}c(F,"configureVision");function y(){return B}c(y,"getVisionDefaults");function H(e){let n=e.includes("\\")?e.slice(e.lastIndexOf("\\")+1):e,r=n.trim().split(/\s+/u)[0]??"",t=r.slice(r.lastIndexOf("/")+1);return W.has((e.includes("\\")?n:t).toLowerCase())}c(H,"isExecutableAllowed");function j(e,n){let r=e?.filter(a=>/^(?:image|sequence)(?::|$)/u.test(a))??[];if(r.length===0)return;if(r.length>1)throw new Error("Use only one image or sequence view");let t=r[0],i=t.indexOf(":"),s=t.slice(0,i<0?void 0:i),o={};if(i>=0&&re(t.slice(i+1),o),s==="image"&&(o.duration!==void 0||o.interval!==void 0))throw new Error("duration and interval are supported only by the sequence view");return D({mode:s,durationSeconds:o.duration??n.durationSeconds,intervalSeconds:o.interval??n.intervalSeconds,scale:o.scale??n.scale,...o.region===void 0?{}:{region:o.region}})}c(j,"parseVisionView");function re(e,n){if(e.length===0)throw new Error("View parameters cannot be empty");let r=e.split(",");for(let t=0;t<r.length;t+=1){let i=r[t],s=i.indexOf("=");if(s<=0)throw new Error(`Invalid view parameter ${i}`);let o=i.slice(0,s),a=i.slice(s+1);if(o==="region"){let l=[a,r[t+1],r[t+2],r[t+3]].map(Number);if(l.some(m=>!Number.isFinite(m)))throw new Error("region requires x,y,width,height values");n.region={x:l[0],y:l[1],width:l[2],height:l[3]},t+=3;continue}if(o!=="duration"&&o!=="interval"&&o!=="scale")throw new Error(`Unknown view parameter ${o}`);let d=Number(a);if(!Number.isFinite(d))throw new Error(`View parameter ${o} must be a number`);if(n[o]!==void 0)throw new Error(`Duplicate view parameter ${o}`);n[o]=d}}c(re,"parseViewParameters");function G(e){if(!e.startsWith("display:"))return;if(e==="display:")return 0;let n=/^display:#(\d+)$/u.exec(e);if(n===null)throw new Error("Display sources use display: or display:#N with a zero-based index");let r=Number(n[1]);if(!Number.isSafeInteger(r))throw new Error("Display sources use display: or display:#N with a zero-based index");return r}c(G,"parseDisplaySource");async function E(e){let n=new Map(e.list().flatMap(i=>i.pid===void 0?[]:[[i.pid,i]]));if(process.platform!=="linux"&&process.platform!=="darwin")return[...n].map(([i,s])=>({pid:i,command:s.description,owned:!0,source:s.source}));let{stdout:r}=await p("ps",["-eo","pid=,ppid=,lstart=,args="],{maxBuffer:4*1024*1024}),t=r.split(`
2
+ `).flatMap(i=>{let s=/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/u.exec(i);if(s===null)return[];let o=Number(s[1]),a=n.get(o);return[{pid:o,parentPid:Number(s[2]),started:s[3],command:s[4]??"",owned:a!==void 0,...a===void 0?{}:{source:a.source}}]});return x()?[...t,...await oe()]:t}c(E,"listProcesses");async function oe(){try{let{stdout:e}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command","Get-Process | Select-Object Id,ProcessName,Path,StartTime | ConvertTo-Json -Compress"],{maxBuffer:4194304}),n=JSON.parse(e);return(Array.isArray(n)?n:[n]).flatMap(t=>{if(typeof t!="object"||t===null||!("Id"in t)||typeof t.Id!="number")return[];let i="ProcessName"in t&&typeof t.ProcessName=="string"?t.ProcessName:"Windows process",s="Path"in t&&typeof t.Path=="string"?t.Path:void 0,o="StartTime"in t&&typeof t.StartTime=="string"?t.StartTime:void 0;return[{pid:t.Id,command:s??i,owned:!1,...o===void 0?{}:{started:o}}]})}catch{return[]}}c(oe,"listWindowsProcesses");async function A(e,n){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Process PID must be a positive integer");let r=(await E(n)).find(t=>t.pid===e);if(r===void 0)throw new Error(`Process ${e} is not running`);return r}c(A,"readProcess");function D(e){let n=e.scale??1;if(!(n>0&&n<=1))throw new Error("Image scale must be greater than 0 and at most 1");let r=e.durationSeconds??0,t=e.intervalSeconds??1;if(e.mode==="sequence"){if(!(r>0&&r<=10))throw new Error("Sequence duration must be greater than 0 and at most 10 seconds");if(!(t>0))throw new Error("Sequence interval must be greater than 0 seconds");if(Math.floor(r/t)+1>20)throw new Error("Sequence capture is limited to 20 frames")}if(e.region!==void 0){let{x:i,y:s,width:o,height:a}=e.region;if(i<0||s<0||o<=0||a<=0||i+o>1||s+a>1)throw new Error("Image region x,y,width,height must fit within normalized bounds 0..1")}if(e.cellIndex!==void 0&&e.cellSize===void 0)throw new Error("Image offset requires limit to set the square grid cell size");if(e.cellSize!==void 0&&(!Number.isSafeInteger(e.cellSize)||e.cellSize<=0))throw new Error("Image limit must be a positive integer pixel size");if(e.cellIndex!==void 0&&(!Number.isSafeInteger(e.cellIndex)||e.cellIndex<0))throw new Error("Image offset must be a zero-based cell index");return e}c(D,"validateVisionOptions");async function b(e,n,r){let t=D(n),i=t.mode==="image"?1:Math.floor(t.durationSeconds/t.intervalSeconds)+1,s=[],o=0;for(let a=0;a<i;a+=1){r?.throwIfAborted(),a>0&&await de(t.intervalSeconds*1e3,r);let d=await e();if(o+=d.byteLength,o>I)throw new Error("Captured images exceed the 20MB aggregate limit");for(let l of await ie(d,t))s.push({type:"image",data:Buffer.from(l).toString("base64"),mimeType:"image/png"})}return s}c(b,"captureImages");async function ie(e,n){let r=await te(e),t=n.region??{x:0,y:0,width:1,height:1},i=Math.round(t.x*r.width),s=Math.round(t.y*r.height),o=Math.max(1,Math.round(t.width*r.width)),a=Math.max(1,Math.round(t.height*r.height)),d=n.scale??1,l=Math.max(1,Math.round(o*d)),m=Math.max(1,Math.round(a*d)),w=_(l,m);if(w.getContext("2d").drawImage(r,i,s,o,a,0,0,l,m),n.cellSize===void 0)return[await w.encode("png")];let u=Math.ceil(l/n.cellSize),f=Math.ceil(m/n.cellSize),h=n.cellIndex??0;if(h>=u*f)throw new Error(`Image cell offset ${h} exceeds the ${u}x${f} grid`);let K=h%u,Q=Math.floor(h/u),C=K*n.cellSize,V=Q*n.cellSize,P=Math.min(n.cellSize,l-C),S=Math.min(n.cellSize,m-V),q=_(P,S);return q.getContext("2d").drawImage(w,C,V,P,S,0,0,P,S),[await q.encode("png")]}c(ie,"selectImage");function J(){return{async captureWindow(e,n){if(n?.throwIfAborted(),x())return se(e,n);if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Window capture is unsupported on ${process.platform}`);let{Window:r}=await import("node-screenshots"),t;try{t=r.all()}catch(o){throw new Error(`Desktop window enumeration is unavailable: ${z(o)}`,{cause:o})}let i=t.find(o=>{try{return o.pid()===e}catch{return!1}});if(i===void 0)throw new Error(`No capturable desktop window belongs to PID ${e}`);let s=await i.captureImage();return n?.throwIfAborted(),new Uint8Array(await s.toPng())},async captureDisplay(e,n){if(n?.throwIfAborted(),x())return ae(e,n);if(process.platform!=="linux"&&process.platform!=="darwin"&&process.platform!=="win32")throw new Error(`Display capture is unsupported on ${process.platform}`);let{Monitor:r}=await import("node-screenshots"),t;try{t=r.all()}catch(o){throw new Error(`Desktop display enumeration is unavailable: ${z(o)}`,{cause:o})}let i=t[e];if(i===void 0)throw new Error(`Display index ${e} is unavailable; found ${t.length} display(s)`);let s=await i.captureImage();return n?.throwIfAborted(),new Uint8Array(await s.toPng())},async captureUrl(e,n){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Web screenshots require an HTTP(S) URL");let{chromium:r}=await import("playwright-core"),t=await ce(),i=await r.launch({executablePath:t,headless:!0,chromiumSandbox:!1,timeout:3e4}),s=c(()=>{i.close()},"abort");n?.addEventListener("abort",s,{once:!0});try{let o=await i.newPage({viewport:{width:1280,height:720}});return await o.goto(e.href,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle",{timeout:1500}).catch(()=>{}),n?.throwIfAborted(),new Uint8Array(await o.screenshot({type:"png",fullPage:!0}))}finally{n?.removeEventListener("abort",s),await i.close().catch(()=>{})}}}}c(J,"createCaptureBackend");async function se(e,n){let r=new URL("windows-window-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await p("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-ProcessId",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(se,"captureWslWindow");async function ae(e,n){let r=new URL("windows-display-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await p("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-DisplayIndex",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(ae,"captureWslDisplay");function x(){return process.platform==="linux"&&(process.env.WSL_DISTRO_NAME!==void 0||ee.release().toLowerCase().includes("microsoft"))}c(x,"isWsl");async function ce(){let e=process.env.PI_AGENT_IDE_BROWSER_PATH;if(e!==void 0)return e;let{stdout:n}=await p("bash",["-lc","command -v google-chrome-stable || command -v google-chrome || command -v chromium || command -v chromium-browser"]),r=n.trim();if(r.length===0)throw new Error("No Chrome or Chromium executable was found; set PI_AGENT_IDE_BROWSER_PATH");return r}c(ce,"resolveBrowser");function de(e,n){return new Promise((r,t)=>{let i=setTimeout(r,e),s=c(()=>{clearTimeout(i),t(n?.reason??new Error("Capture aborted"))},"abort");n?.addEventListener("abort",s,{once:!0}),i.unref()})}c(de,"delay");function z(e){return e instanceof Error?e.message:String(e)}c(z,"errorMessage");async function ue(e,n){let r=n?.preferences??{};F({durationSeconds:r["vision.sequenceDurationSeconds"],intervalSeconds:r["vision.sequenceIntervalSeconds"],scale:r["vision.imageScale"],allowedExecutables:r["vision.allowedExecutables"]});let t=L(e),i=J();await Promise.all([U(e,{protocol:M,apiVersion:$,id:"vision",setup(s){for(let a of["image","sequence"])s.addView({view:a,presenter:{id:`vision-${a}`,present:c(d=>d,"present")}});s.addHandler({stage:"pre-read",async handler(a){let d=a.request.path;if(d===void 0)return{kind:"continue",context:a};let l=G(d);if(l!==void 0){if(e.getFlag("pi-agent-ide-vision-displays")!==!0)return g(d,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");try{let u=await b(()=>i.captureDisplay(l,a.resolverContext.signal),R(a.request),a.resolverContext.signal);return v(d,u)}catch(u){return g(d,N(u))}}let m=X(d,"process:");if(m!==void 0){let u=await A(m,t);return v(d,[{type:"text",text:Y(u)}])}let w=X(d,"window:");if(w!==void 0){let u=await A(w,t);if(!u.owned&&!H(u.command)&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)return g(d,`Window capture for PID ${w} is denied because the process is neither Agent IDE-owned nor allowlisted by executable name. Enable --pi-agent-ide-vision-arbitrary-windows to allow it.`);try{let f=await b(()=>i.captureWindow(w,a.resolverContext.signal),R(a.request),a.resolverContext.signal);return v(d,f)}catch(f){return g(d,N(f))}}if(/^https?:\/\//iu.test(d)&&le(a.request)){let u=new URL(d);try{let f=await b(()=>i.captureUrl(u,a.resolverContext.signal),R(a.request),a.resolverContext.signal);return v(u.href,f)}catch(f){return g(u.href,N(f))}}return{kind:"continue",context:a}}});let o=y();s.describe(`Process metadata: process:PID. Visual capture: window:PID and display: or display:#N. HTTP(S) sources accept image and sequence screenshots. Use named view parameters such as sequence:duration=2,interval=0.5,scale=0.5 and image:scale=0.5,region=0.25,0.25,0.5,0.5. Duration is limited to 10 seconds and sequences to 20 frames. Defaults: duration=${o.durationSeconds}, interval=${o.intervalSeconds}, scale=${o.scale}. Region uses normalized x,y,width,height and runs before scaling. For captures, limit is a square grid cell size in output pixels and offset is one zero-based row-major cell index; limit without offset selects cell 0, while offset without limit is invalid. Omit both for the bounded transformed image.`),s.addPromptGuideline("Use search with process:<query> before reading process:PID or window:PID. Capture arbitrary desktop windows and full displays only when their dedicated flags are enabled; Agent IDE-owned terminal processes are allowed by default. Use a bounded sequence view only when one image is insufficient; set named duration, interval, scale and region parameters when the defaults do not fit. Use limit and offset to select one image grid cell.")}}),k(e,{protocol:O,apiVersion:T,id:"vision-processes",setup(s){s.addResolver({priority:-100,resolver:{id:"processes",async tryResolve(o){let a=/^process:(.*)$/isu.exec(o.query);if(a===null)return{kind:"not-handled"};let d=(a[1]??"").trim().toLowerCase();return{kind:"resolved",payload:(await E(t)).filter(m=>d.length===0||String(m.pid)===d||m.command.toLowerCase().includes(d)).slice(0,Math.min(o.limit??50,100))}},format(o){let a=o;return{content:[{type:"text",text:a.length===0?"No matching processes.":a.map(Y).join(`
3
+
4
+ `)}],details:{count:a.length,processes:a}}}}}),s.describe("process:<query> finds running processes by PID or command for process:PID metadata reads and guarded window:PID capture."),s.addPromptGuideline("Use process:<query> to discover a PID before selecting a process or window source.")}})])}c(ue,"registerVision");function X(e,n){if(!e.startsWith(n))return;let r=e.slice(n.length);if(!/^\d+$/u.test(r))throw new Error(`${n} sources require a numeric PID`);return Number(r)}c(X,"prefixedPid");function R(e){return{...j(e.views,y())??{mode:"image",...y()},...e.limit===void 0?{}:{cellSize:e.limit},...e.offset===void 0?{}:{cellIndex:e.offset}}}c(R,"options");function le(e){return e.views?.some(n=>/^(?:image|sequence)(?::|$)/u.test(n))===!0}c(le,"requestsScreenshot");function v(e,n){return{kind:"return",result:{content:n,details:{source:e,resolvedBy:"vision"}}}}c(v,"returned");function g(e,n){return{kind:"return",result:{content:[{type:"text",text:n}],details:{source:e,resolvedBy:"vision",failure:{code:"READ_FAILED",source:e,resolverId:"vision",message:n}},isError:!0}}}c(g,"failed");function N(e){return e instanceof Error?e.message:String(e)}c(N,"errorMessage");function Y(e){return[`PID: ${e.pid}`,`Command: ${e.command}`,`Owned by Agent IDE: ${e.owned?"yes":"no"}`,...e.parentPid===void 0?[]:[`Parent PID: ${e.parentPid}`],...e.started===void 0?[]:[`Started: ${e.started}`],...e.source===void 0?[]:[`Agent IDE source: ${e.source}`]].join(`
5
+ `)}c(Y,"formatProcess");export{ue as default};
@@ -0,0 +1 @@
1
+ import{a as p,e as f,k as g}from"./chunk-O6LE42GK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as m}from"node:async_hooks";var c=new m,l=new m;function E(t){let e=l.getStore();e?e.push(t):t()}o(E,"afterPostEditScope");async function T(t){if(l.getStore())return t();let e=[];try{return await l.run(e,t)}finally{for(let r of e)r()}}o(T,"collectPostEditNotifications");function b(t,e){let r=c.getStore();return r?(r.set(t,e),!0):!1}o(b,"deferPostEdit");function h(t){return c.getStore()?.has(t)??!1}o(h,"hasDeferredPostEdit");function v(t){c.getStore()?.delete(t)}o(v,"forgetDeferredPostEdit");function k(){let t=new Map;return{run(e){return c.run(t,e)},forget(e){t.delete(e)},async finish(e){let r=[...t.values()];t.clear();let d=[],i=[];if(await T(async()=>{for(let a of r)try{let s=await a();d.push(s),e?.(s)}catch(s){i.push(s)}}),i.length>0)throw new AggregateError(i,`Some final post-processing failed; completed edits remain applied. ${i.map(a=>a instanceof Error?a.message:String(a)).join("; ")}`);return d}}}o(k,"createPostEditScope");import{Type as n}from"typebox";import{Value as u}from"typebox/value";var w=`${p}/post-edit/register`;function M(t){return u.Check(n.Object({formatting:n.Object({status:n.Union(["disabled","unavailable","skipped-syntax","unchanged","changed","failed","not-reported","deferred"].map(e=>n.Literal(e))),formatter:n.Optional(n.String())})}),t)}o(M,"isFormattingContribution");function _(t){return u.Check(n.Object({diffStatuses:n.Array(n.Object({text:n.String({minLength:1}),formatter:n.Optional(n.String()),tone:n.Optional(n.Union(["muted","success","warning","error"].map(e=>n.Literal(e))))}))}),t)}o(_,"isDiffStatusContribution");var x=n.Function([],n.Unknown()),y=n.Object({id:n.String({minLength:1}),handler:x}),P=n.Object({registration:y,accept:x});function S(t){return u.Check(y,t)}o(S,"isTextPostEditHandlerRegistration");function j(t){return u.Check(P,t)}o(j,"isTextPostEditHandlerRegistrationRequest");function I(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.hints)&&typeof e.scopeMarkers=="object"&&e.scopeMarkers!==null&&Array.isArray(e.warnings)}o(I,"isTextMutationResultContributionData");function F(t,e){if(!S(e))throw new TypeError("Invalid text editor post-edit handler registration");let r,d=o(()=>{let a={registration:e,accept(s){if(r!==void 0)throw new Error(`Post-edit handler ${e.id} was accepted more than once`);r=s}};return t.events.emit(w,a),r!==void 0},"announce"),i=o(()=>{},"unsubscribeReady");i=t.events.on(f,a=>{if(!g(a))throw new Error("Invalid pi-agent-text-editor core readiness event");if(!d())throw new Error("pi-agent-text-editor core announced readiness without accepting the post-edit handler");i()}),t.on("session_shutdown",()=>{i(),r?.()}),d()&&i()}o(F,"connectTextEditorPostEditHandler");export{E as a,T as b,b as c,h as d,v as e,k as f,w as g,M as h,_ as i,S as j,j as k,I as l,F as m};
@@ -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};