pi-agent-ide 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (342) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +81 -23
  3. package/assets/gallery/apply-editing.png +0 -0
  4. package/assets/gallery/debugging.png +0 -0
  5. package/assets/gallery/read-web.png +0 -0
  6. package/assets/gallery/search-replace.png +0 -0
  7. package/assets/gallery/terminal.png +0 -0
  8. package/assets/gallery/tool-editing.png +0 -0
  9. package/dist/chunk-22CLOM2D.js +1 -0
  10. package/dist/{chunk-LY6U5EAD.js → chunk-2527OQ4Y.js} +1 -1
  11. package/dist/chunk-3XJ3KDPZ.js +16 -0
  12. package/dist/chunk-5JELU6RV.js +7 -0
  13. package/dist/chunk-DDKHZZDO.js +5 -0
  14. package/dist/chunk-FEDVTZJG.js +1 -0
  15. package/dist/chunk-HSM6R7IB.js +27 -0
  16. package/dist/chunk-K5G4FDXD.js +1 -0
  17. package/dist/chunk-M5IVSCR2.js +1 -0
  18. package/dist/chunk-OYWIZII6.js +1 -0
  19. package/dist/chunk-P7XO5CIP.js +2 -0
  20. package/dist/chunk-PCZH7GOX.js +26 -0
  21. package/dist/{chunk-DQXPQOF7.js → chunk-SQ7ZTGOP.js} +1 -1
  22. package/dist/entry-10.js +1 -1
  23. package/dist/entry-11.js +1 -1
  24. package/dist/entry-12.js +1 -1
  25. package/dist/entry-13.js +1 -1
  26. package/dist/entry-14.js +1 -1
  27. package/dist/entry-15.js +1 -1
  28. package/dist/entry-16.js +1 -0
  29. package/dist/entry-18.js +1 -1
  30. package/dist/entry-19.js +1 -1
  31. package/dist/entry-20.js +1 -1
  32. package/dist/entry-21.js +1 -1
  33. package/dist/entry-22.js +1 -2
  34. package/dist/entry-23.js +2 -1
  35. package/dist/entry-24.js +1 -1
  36. package/dist/entry-25.js +1 -1
  37. package/dist/entry-26.js +1 -1
  38. package/dist/entry-27.js +1 -12
  39. package/dist/entry-28.js +12 -1
  40. package/dist/entry-29.js +1 -1
  41. package/dist/entry-30.js +1 -1
  42. package/dist/entry-31.js +1 -1
  43. package/dist/entry-32.js +1 -4
  44. package/dist/entry-33.js +3 -8
  45. package/dist/entry-34.js +9 -1
  46. package/dist/entry-35.js +1 -1
  47. package/dist/entry-36.js +1 -1
  48. package/dist/entry-37.js +1 -1
  49. package/dist/entry-38.js +1 -1
  50. package/dist/entry-39.js +1 -1
  51. package/dist/entry-40.js +1 -1
  52. package/dist/entry-41.js +1 -18
  53. package/dist/entry-42.js +18 -1
  54. package/dist/entry-43.js +1 -1
  55. package/dist/entry-44.js +1 -1
  56. package/dist/entry-45.js +1 -1
  57. package/dist/entry-46.js +1 -7
  58. package/dist/entry-47.js +7 -11
  59. package/dist/entry-48.js +11 -1
  60. package/dist/entry-49.js +1 -1
  61. package/dist/entry-50.js +1 -1
  62. package/dist/entry-51.js +1 -1
  63. package/dist/entry-52.js +1 -1
  64. package/dist/entry-53.js +1 -1
  65. package/dist/entry-54.js +1 -1
  66. package/dist/entry-55.js +1 -1
  67. package/dist/entry-56.js +1 -0
  68. package/dist/entry-57.js +0 -1
  69. package/dist/entry-58.js +1 -0
  70. package/dist/entry-59.js +0 -1
  71. package/dist/entry-60.js +1 -1
  72. package/dist/entry-61.js +1 -1
  73. package/dist/entry-62.js +1 -1
  74. package/dist/entry-63.js +1 -1
  75. package/dist/entry-64.js +1 -1
  76. package/dist/entry-65.js +1 -0
  77. package/dist/entry-66.js +0 -1
  78. package/dist/entry-67.js +1 -0
  79. package/dist/entry-68.js +0 -1
  80. package/dist/entry-69.js +1 -1
  81. package/dist/entry-70.js +1 -1
  82. package/dist/entry-71.js +1 -203
  83. package/dist/entry-72.js +254 -25
  84. package/dist/entry-73.js +30 -2
  85. package/dist/entry-74.js +2 -1
  86. package/dist/entry-75.js +1 -1
  87. package/dist/entry-76.js +1 -1
  88. package/dist/entry-77.js +3 -3
  89. package/dist/entry-78.js +3 -1
  90. package/dist/entry-79.js +1 -1
  91. package/dist/entry-80.js +1 -1
  92. package/dist/entry-81.js +1 -0
  93. package/dist/pi-agent-ide.js +3 -3
  94. package/docs/configuration.md +3 -1
  95. package/docs/development.md +0 -6
  96. package/docs/tools.md +12 -0
  97. package/node_modules/pi-agent-doctor/package.json +6 -6
  98. package/node_modules/pi-agent-doctor/runtime/entry-22.js +1 -0
  99. package/node_modules/pi-agent-filesystem/package.json +7 -7
  100. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  101. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  102. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  103. package/node_modules/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  104. package/node_modules/pi-agent-ide-ast/package.json +12 -11
  105. package/node_modules/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  106. package/node_modules/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  107. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  108. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  109. package/node_modules/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  110. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  111. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  112. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  113. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +3 -1
  114. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  115. package/node_modules/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  116. package/node_modules/pi-agent-image/package.json +3 -3
  117. package/node_modules/pi-agent-invariant/package.json +2 -2
  118. package/node_modules/pi-agent-pdf/package.json +3 -3
  119. package/node_modules/pi-agent-read/package.json +11 -11
  120. package/node_modules/pi-agent-read/runtime/entry-41.js +0 -1
  121. package/node_modules/pi-agent-read/runtime/entry-42.js +2 -0
  122. package/node_modules/pi-agent-read/src/api/read-parameters.ts +2 -2
  123. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  124. package/node_modules/pi-agent-resource/package.json +2 -2
  125. package/node_modules/pi-agent-search/package.json +7 -7
  126. package/node_modules/pi-agent-search/runtime/entry-46.js +0 -1
  127. package/node_modules/pi-agent-search-text/package.json +9 -9
  128. package/node_modules/pi-agent-search-text/runtime/entry-48.js +1 -0
  129. package/node_modules/pi-agent-search-text/src/resolvers.ts +32 -27
  130. package/node_modules/pi-agent-search-text/src/search-session.ts +27 -1
  131. package/node_modules/pi-agent-text/package.json +3 -3
  132. package/node_modules/pi-agent-text/runtime/entry-50.js +1 -0
  133. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  134. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  135. package/node_modules/pi-agent-text-anchor-exact/index.ts +3 -3
  136. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  137. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  138. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  139. package/node_modules/pi-agent-text-anchor-exact/src/config.ts +2 -2
  140. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  141. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  142. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  143. package/node_modules/pi-agent-text-editor/package.json +25 -25
  144. package/node_modules/pi-agent-text-editor/runtime/entry-71.js +0 -1
  145. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  146. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  147. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  148. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  149. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  150. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  151. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  152. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  153. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  154. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  155. package/node_modules/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  156. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  157. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  158. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  159. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  160. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  161. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  162. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  163. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  164. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  165. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  166. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  167. package/node_modules/pi-agent-tool-ui/runtime/entry-76.js +1 -0
  168. package/node_modules/pi-agent-web/package.json +7 -7
  169. package/node_modules/pi-agent-web/src/resolver.ts +128 -1
  170. package/node_modules/pi-agent-web-html/package.json +3 -3
  171. package/node_modules/pi-agent-web-image/package.json +4 -4
  172. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  173. package/node_modules/pi-agent-web-text/package.json +4 -4
  174. package/node_modules/pi-agent-web-text/runtime/entry-81.js +2 -0
  175. package/package.json +44 -39
  176. package/src/api/path-identity.ts +15 -0
  177. package/src/composite/builtin-extensions.ts +7 -2
  178. package/src/composite/module-labels.ts +4 -0
  179. package/src/composite/module-settings.ts +34 -14
  180. package/src/composite/preferences.ts +46 -3
  181. package/src/composite/selection.ts +5 -1
  182. package/src/doctor/inventory.ts +7 -2
  183. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  185. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  186. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  187. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  188. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-23.js +2 -0
  189. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  190. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  191. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  192. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  193. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  194. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-81.js +2 -0
  195. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-77.js +2 -0
  196. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +128 -1
  197. package/src/extensions/pi-agent-read/package.json +11 -11
  198. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  199. package/src/extensions/pi-agent-read/runtime/entry-42.js +2 -0
  200. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
  201. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  202. package/src/extensions/pi-agent-search/package.json +7 -7
  203. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  204. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-48.js +1 -0
  205. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-49.js +1 -0
  206. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +32 -27
  207. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +27 -1
  208. package/src/extensions/pi-agent-search/runtime/entry-46.js +0 -1
  209. package/src/extensions/pi-agent-search/runtime/entry-47.js +2 -0
  210. package/src/extensions/pi-agent-text-editor/package.json +25 -25
  211. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  212. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  213. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +3 -3
  214. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  215. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  216. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  217. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/config.ts +2 -2
  218. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  219. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  220. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  221. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  222. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  223. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  224. package/src/extensions/pi-agent-text-editor/runtime/entry-71.js +0 -1
  225. package/src/extensions/pi-agent-text-editor/runtime/entry-72.js +2 -0
  226. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  227. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  228. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  229. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  230. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  231. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  232. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  233. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  234. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  235. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  236. package/src/extensions/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  237. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  238. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  239. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  240. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  241. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  242. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  243. package/src/pi-agent-ide.ts +15 -2
  244. package/src/plugins/pi-agent-ide-ast/package.json +12 -11
  245. package/src/plugins/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  246. package/src/plugins/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  247. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  248. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  249. package/src/plugins/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  250. package/src/plugins/pi-agent-ide-debugger/index.ts +3 -9
  251. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +31 -0
  252. package/src/plugins/pi-agent-ide-debugger/src/breakpoint-view.ts +3 -1
  253. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +24 -23
  254. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -2
  255. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +55 -17
  256. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -22
  257. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  258. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  259. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  260. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +3 -1
  261. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  262. package/src/plugins/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  263. package/src/plugins/pi-agent-ide-processes/src/registry.ts +6 -0
  264. package/src/plugins/pi-agent-ide-processes/src/ui.ts +28 -11
  265. package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
  266. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +2 -0
  267. package/src/plugins/pi-agent-ide-terminal/src/search.ts +32 -2
  268. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +5 -4
  269. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
  270. package/src/plugins/pi-agent-ide-terminal/src/types.ts +3 -1
  271. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +1 -1
  272. package/src/plugins/pi-agent-ide-vision/index.ts +232 -0
  273. package/src/plugins/pi-agent-ide-vision/src/vision.ts +530 -0
  274. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +30 -0
  275. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +33 -0
  276. package/dist/chunk-5PLV4HLG.js +0 -1
  277. package/dist/chunk-BGUSBUUD.js +0 -26
  278. package/dist/chunk-G725MARR.js +0 -16
  279. package/dist/chunk-HKXDP2FD.js +0 -7
  280. package/dist/chunk-J4RTW44E.js +0 -1
  281. package/dist/chunk-QH4ZUDOD.js +0 -1
  282. package/dist/chunk-WGGIQ7IJ.js +0 -1
  283. package/dist/chunk-ZG2MWXCR.js +0 -2
  284. package/dist/chunk-ZUMN6U77.js +0 -27
  285. package/dist/entry-17.js +0 -1
  286. package/docs/evaluation.md +0 -14
  287. package/node_modules/pi-agent-doctor/runtime/entry-17.js +0 -1
  288. package/node_modules/pi-agent-filesystem/runtime/entry-22.js +0 -2
  289. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  290. package/node_modules/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  291. package/node_modules/pi-agent-image/runtime/entry-34.js +0 -1
  292. package/node_modules/pi-agent-resource/runtime/entry-42.js +0 -1
  293. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  294. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  295. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  296. package/node_modules/pi-agent-text-editor/runtime/entry-55.js +0 -1
  297. package/node_modules/pi-agent-tool-call-interception/runtime/entry-74.js +0 -1
  298. package/node_modules/pi-agent-web/runtime/entry-76.js +0 -2
  299. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  300. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-22.js +0 -2
  301. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-77.js +0 -2
  302. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +0 -2
  303. package/src/extensions/pi-agent-read/runtime/entry-37.js +0 -1
  304. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +0 -2
  305. package/src/extensions/pi-agent-search/runtime/entry-43.js +0 -1
  306. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  307. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  308. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  309. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  310. package/src/extensions/pi-agent-text-editor/runtime/entry-55.js +0 -1
  311. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  312. package/src/plugins/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  313. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-23.js +0 -0
  314. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  315. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  316. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  317. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  318. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  319. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
  320. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-35.js +0 -0
  321. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-36.js +0 -0
  322. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-37.js +0 -0
  323. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-43.js +0 -0
  324. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-47.js +0 -0
  325. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-49.js +0 -0
  326. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-72.js +0 -0
  327. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  328. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-75.js +0 -0
  329. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-77.js +0 -0
  330. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  331. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  332. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  333. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  334. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  335. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  336. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  337. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  338. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  339. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  340. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  341. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  342. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
@@ -1,26 +0,0 @@
1
- import{a as ne,b as re,c as ie}from"./chunk-ESPNEJHK.js";import{a as te}from"./chunk-5PLV4HLG.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as V}from"./chunk-6CZO43OH.js";import{a as X,b as Y}from"./chunk-OBNING2A.js";import{a as ee}from"./chunk-ZTYWHL2F.js";import{a as Z,b as Q}from"./chunk-7UGNGK7Y.js";import{a as J}from"./chunk-L7JMDDSD.js";import{a as K,b as z}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Ue from"node:path";import{stripVTControlCharacters as We}from"node:util";import{truncateLine as Fe}from"@earendil-works/pi-coding-agent";import{Text as x}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as oe,formatSize as Oe,truncateTail as Ne}from"@earendil-works/pi-coding-agent";function I(t){return Ne(t,{maxBytes:se-4096,maxLines:oe-32})}a(I,"terminalOutputTail");function v(t){let e=I(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(s=>s!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
- `)}
3
- output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${oe} line output budget`:`${Oe(se)} output budget`,o=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
- `)}
6
- output:
7
- ${o}${r.length===0?"":`
8
- ${r}`}`}a(v,"formatAgentTerminalSnapshot");var je=500;function ae(t,e,n,r,i){let o=e?"background":"wait",s=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${E(n)} \xB7 ${o}`)}`;return new x(`${s}
9
- ${i.fg("accent",O(r.family))} ${t}`,0,0)}a(ae,"renderRunCall");function le(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new x(r.join(`
10
- `),0,0)}a(le,"renderTerminalActionResult");function $(t,e,n,r,i){let o=[qe(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&o.push(...r.map(s=>` ${i.fg("dim",s)}`)),new x(o.join(`
11
- `),0,0)}a($,"renderTerminalAction");function S(t,e,n,r){let i=Ge(t,R,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new x(i.join(`
12
- `),0,0)}a(S,"renderTerminalResult");function ue(t,e,n){if(e)return S(t,!0,n);let r=_(t.output??"",R),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(o=>` ${n.fg("dim",o)}`)];return i.push(D(t,(o,s)=>n.fg(o,s))),new x(i.join(`
13
- `),0,0)}a(ue,"renderRunResult");function ce(t,e){let n=a((s,l)=>e?.fg(s,l)??l,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${E(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",O(t.shellFamily))} ${M(t.command,84)}`],o=He(t.output,2);return o.length>0&&i.push(...o.map(s=>` ${n("dim",M(s,90))}`)),i.push(D(t,n)),i.join(`
14
- `)}a(ce,"renderActiveTerminal");function Ge(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",o=t.cwd===void 0?"workspace":E(t.cwd),s=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${o} \xB7 ${i}`)}`,`${n.fg("accent",O(s))} ${t.command??""}`],u=_(t.output??"",e);return u.omission!==void 0&&l.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&l.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),l.push(D(t,(c,d)=>n.fg(c,d))),l}a(Ge,"terminalCardLines");function He(t,e){return _(t,e).lines}a(He,"outputTail");function _(t,e){let n=I(We(t).replaceAll("\r","")),r=n.content.split(`
15
- `).map(u=>Fe(u.trimEnd(),je).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,o=Math.max(0,r.length-i),s=Math.max(0,n.totalLines-n.outputLines),l=o+s;return{lines:r.slice(o),...n.truncated||l>0?{omission:l>0?`\u2026 ${l} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(_,"outputWindow");function D(t,e){let n=t.status??"running",r=Be(n),i=n==="completed"?"success":n==="running"?"accent":"error",o=[`${r} ${n}`,Xe(t.elapsedMs??0)];return t.waitReason!==void 0&&o.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&o.push(`reason ${t.completionReason}`),t.exitCode!==void 0?o.push(`exit ${t.exitCode}`):t.signal!==void 0&&o.push(`signal ${t.signal}`),e(i,o.join(" \xB7 "))}a(D,"statusLine");function Be(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Be,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function qe(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":E(t.cwd),i=t.background===!0?"background":"wait",o=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${o}`)}`}a(qe,"terminalIdentity");function E(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Ue.sep}`))?`~${t.slice(e.length)}`:t}a(E,"shortCwd");function M(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(M,"oneLine");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Xe,"formatElapsed");function de(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",renderSummary:a(n=>ce(e,n).split(`
16
- `),"renderSummary"),renderDetail:a(n=>S(e,!0,n),"renderDetail"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(de,"terminalProcessProvider");var Ye="#d8dee9",N="#111418",Ve=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function U(t,e,n){let r=t.get(e);if(r===void 0)throw new Error(`Unknown terminal session ${e}`);await r.screenReady;let{createCanvas:i}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(r.rows-1,n?.start??0)),s=Math.max(1,Math.min(r.rows-o,n?.count??r.rows)),l=i(r.cols*9+24,s*18+24),u=l.getContext("2d");u.fillStyle=N,u.fillRect(0,0,l.width,l.height),u.textBaseline="top";let c=r.screen.buffer.active,d=Math.max(0,c.baseY);for(let m=0;m<s;m+=1){let p=c.getLine(d+o+m);if(p!==void 0)for(let f=0;f<r.cols;f+=1){let h=p.getCell(f);h===void 0||h.getWidth()===0||Ke(u,h,f,m)}}return r.status==="running"&&c.cursorY>=o&&c.cursorY<o+s&&(u.fillStyle="rgba(216, 222, 233, 0.75)",u.fillRect(12+c.cursorX*9,12+(c.cursorY-o)*18+18-2,9,2)),l.toBuffer("image/png").toString("base64")}a(U,"renderTerminalScreen");function Ke(t,e,n,r){let i=me(e,"foreground"),o=me(e,"background");e.isInverse()&&([i,o]=[o,i]);let s=12+n*9,l=12+r*18;o!==N&&(t.fillStyle=o,t.fillRect(s,l,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,s,l),e.isUnderline()&&t.fillRect(s,l+18-2,9*Math.max(1,e.getWidth()),1))}a(Ke,"drawCell");function me(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ye:N;let i=n?t.isFgRGB():t.isBgRGB(),o=n?t.getFgColor():t.getBgColor();return i?`#${o.toString(16).padStart(6,"0")}`:ze(o)}a(me,"cellColor");function ze(t){let e=Ve[t];if(e!==void 0)return e;if(t>=232){let l=8+(t-232)*10;return pe(l,l,l)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),o=n%6,s=a(l=>l===0?0:55+l*40,"channel");return pe(s(r),s(i),s(o))}a(ze,"ansiColor");function pe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(pe,"rgb");var W="\0pi-terminal-write\0",F="\0pi-terminal-keys\0";async function we(t,e){let n=new Map,r=new Map,i={protocol:X,apiVersion:Y,id:"terminal",setup(s){s.addResolver({resolver:Je(e),preserveTruncatedOutput:!0,renderResult(l,u,c){let d=l.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return S(m===void 0?p:{...p,output:e.screenTail(m).join(`
17
- `)},u.expanded,c,"read terminal")}}),s.addHandler({stage:"pre-read",async handler(l){let u=l.request.path;if(u===void 0||!y(u)||l.request.views?.includes("image")!==!0)return{kind:"continue",context:l};let c=e.get(u);if(c===void 0)return{kind:"return",result:fe(u,`Unknown terminal session ${u}`)};try{return e.markInspected(u),{kind:"return",result:{content:[{type:"image",data:await U(e,u),mimeType:"image/png"}],details:{source:c.source,resolvedBy:"terminal"}}}}catch(d){return{kind:"return",result:fe(u,d instanceof Error?d.message:String(d))}}}}),s.describe('shell:<session> \u2014 terminal session status and a bounded output tail with a full-log path when truncated. Use views: ["image"] to read the current virtual terminal screen as a PNG.'),s.addPromptGuideline("Use read with a returned shell:<session> source to inspect terminal status and output. Add the image view when cursor movement, ANSI layout, or a full-screen terminal interface matters.")}},o={protocol:K,apiVersion:z,id:"terminal",setup(s){s.addResolver({resolver:Ze(e)}),s.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(he(l.input,e,n),await ge(l.input,e,r),Qe(l,W)),"handler")}),s.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await ge(l.input,e,r),he(l.input,e,n),et(l)),"handler")});for(let l of["write","insert","delete"])s.addToolRenderer({tool:l,matches:a((u,c)=>it(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),$(f.snapshot??{},l,ye(l,m),[],c)},renderResult(u,c,d){let m=rt(u.details);return le(m.action,m.changedLines,d)}});s.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),s.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),s.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([V(t,i),J(t,o)]),t.on("tool_result",async(s,l)=>{if(!w(s.input))return;let u=s.input.path;if(s.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:s.details,isError:!0};if(s.toolName==="delete"&&typeof u=="string"&&y(u)){let q=e.get(u);if(q===void 0)return;let De=e.snapshot(q);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:De,action:"delete",input:"session",changedLines:[]},isError:!1}),L=>({content:[{type:"text",text:L instanceof Error?L.message:String(L)}],details:{source:u,deleted:!1},isError:!0}))}if(s.toolName!=="write"&&s.toolName!=="insert"||s.isError)return;let c=s.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=s.toolName,P=ye(h,s.input),b=e.screenChangeRegion(d,m,6),B=[{type:"text",text:`Sent ${P} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&B.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:B,details:{source:d.source,action:h,status:d.status,snapshot:f,input:P,changedLines:b.lines},isError:s.isError}})}a(we,"registerTerminalResources");function Je(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:tt(r)}]}}}}}}a(Je,"createReadResolver");function Ze(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=nt(r),o=i.indexOf(W),s=i.indexOf(F);if(o>=0){t.write(n.source,i.slice(o+W.length));return}if(s>=0){t.sendKeys(n.source,i.slice(s+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(Ze,"createInputResolver");function Qe(t,e){return!w(t.input)||!Se(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(Qe,"transformWriteInput");function et(t){if(!w(t.input)||!Se(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${F}${typeof t.input.text=="string"?t.input.text:""}`}}}a(et,"transformInsertInput");function tt(t){return v(t)}a(tt,"formatSnapshot");function nt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(nt,"singleText");function fe(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(fe,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Se(t){return typeof t=="string"&&y(t)}a(Se,"isShellSourceValue");function rt(t){if(!w(t)||!w(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(rt,"terminalActionDetails");async function ge(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(ge,"rememberScreen");function he(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(he,"rememberOutputEnd");function ye(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(ye,"terminalInputLabel");function it(t,e){if(!w(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return w(n)&&typeof n.source=="string"&&y(n.source)}a(it,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Te(t,e){await ee(t,{protocol:Z,apiVersion:Q,id:"terminal",setup(r){r.addResolver({resolver:st(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."),r.addPromptGuideline("Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.")}})}a(Te,"registerTerminalSearch");function st(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=ot(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=j(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
18
- `)}
19
-
20
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,o=G(i)?j(i.payload):j(void 0);return $(o.snapshot,"search",JSON.stringify(o.query),o.matches.slice(-6).map(s=>`${s.lineNumber}: ${s.lineText}`),r)}}}a(st,"terminalSearchResolver");function ot(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[o,s]of t.output.replaceAll("\r","").split(`
21
- `).entries()){let l=e.caseSensitive===!0?s:s.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=l.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||at(l,c,d))&&r.push({source:t.source,lineNumber:o+1,startColumn:c,endColumn:d,matchedText:s.slice(c,d),lineText:s}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(ot,"findTerminalMatches");function at(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(at,"isWordBoundary");function j(t){if(!lt(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function lt(t){return G(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&G(t.snapshot)&&typeof t.snapshot.source=="string"}a(lt,"isTerminalSearchPayload");function G(t){return typeof t=="object"&&t!==null}a(G,"isRecord");import{spawn as ut}from"node:child_process";import{closeSync as ct,mkdirSync as dt,openSync as mt,rmSync as pt,writeSync as ft}from"node:fs";import gt from"node:os";import be from"node:path";import{createRequire as ht}from"node:module";import{randomUUID as yt}from"node:crypto";import{stripVTControlCharacters as wt}from"node:util";var Pe=ht(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Re=1e6,St=100,Tt=30,bt=2e3,A=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#s=!1;constructor(e=Pt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(vt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#s)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Lt(n);this.#i.set(n,mt(r,"a",384));let i=e.cols??St,o=e.rows??Tt,s=xt(i,o),l=a(p=>{},"resolveCompletion"),u=new Promise(p=>{l=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:o,fullOutputPath:r,screen:s,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=Pe("node-pty"),f={name:"xterm-256color",cols:i,rows:o,cwd:e.cwd,env:Et($t())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:Ct(p)};return this.#e.set(n,f),this.#o(n),l(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{T(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#o(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return T(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,o)=>{let s=a(()=>{this.stop(r.source,"cancelled").then(i,o)},"onAbort");n?.addEventListener("abort",s,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",s),i(l)},o)})}async waitForForeground(e,n){let r=this.required(e);if(T(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(o=>{let s=!1,l,u=a(p=>{s||(p!==void 0&&T(r.status)&&(p=void 0),s=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,r.waitReason=p,this.#n(r)),o({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Rt(r)){l=void 0;return}l??=Date.now(),Date.now()-l>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,o;for(;Date.now()<r;){let s=e.outputStart+e.output.length;if(s!==i)i=s,o=Date.now(),await e.screenReady;else if(o!==void 0&&Date.now()-o>=40)return;await H(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),o=Math.max(1,Math.min(e.rows,r)),s=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(o/2)),l=-1;for(let d=0;d<=e.rows-o;d+=1){let m=0;for(let p=d;p<d+o;p+=1){let f=n[p]??"",h=i[p]??"",P=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(P||b)&&(m+=1)}m>l&&(l=m,s=d)}let u=e.screen.buffer.active;return{lines:i.slice(s,s+o).map((d,m)=>{if(s+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:s}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),o=[];for(let s=0;s<e.rows;s+=1){let l=r.getLine(i+s)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&o.push(l)}return o.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(At(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await xe(r,!1),await Promise.race([r.completion.then(()=>!0),H(bt).then(()=>!1)])||(await xe(r,!0),await Promise.race([r.completion,H(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#o(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#o(n.id),pt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],o=Math.max(0,r.baseY);for(let s=o;s<o+n.rows;s+=1)i.push(r.getLine(s)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#s){this.#s=!0,await Promise.all([...this.#e.values()].filter(e=>!T(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#o(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=wt(n),i=this.#i.get(e.id);if(i!==void 0&&ft(i,r),e.output+=r,e.output.length>Re){let o=e.output.length-Re;e.output=e.output.slice(o),e.outputStart+=o}e.screenReady=e.screenReady.then(()=>new Promise(o=>{e.screen.write(n,o)})),this.#n(e)}#o(e){let n=this.#i.get(e);n!==void 0&&(ct(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Rt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(Rt,"looksInteractive");function xt(t,e){let{Terminal:n}=Pe("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(xt,"createScreen");function Pt(){return yt().replaceAll("-","").slice(0,12)}a(Pt,"defaultSessionId");function vt(t){return t.startsWith("shell:")?t.slice(6):t}a(vt,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function $t(){return process.env}a($t,"processEnvironment");function Et(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(Et,"cleanEnvironment");function At(t){return t.split(/[\s,]+/u).filter(Boolean).map(kt).join("")}a(At,"encodeTerminalKeys");function kt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),o=r.has("alt")||r.has("meta"),s=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return o?`\x1B${m}`:m}let l={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!o&&!s&&l[n]!==void 0)return l[n];if(o&&!i&&!s&&l[n]!==void 0)return`\x1B${l[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!o&&!s?`\x1B[${c}`:`\x1B[1;${1+(s?1:0)+(o?2:0)+(i?4:0)}${c}`;if(o&&!i&&n.length===1)return`\x1B${s?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(kt,"encodeTerminalKey");async function xe(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=ut("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(xe,"terminateProcessTree");function H(t){return new Promise(e=>setTimeout(e,t))}a(H,"delay");function Ct(t){return t instanceof Error?t.message:String(t)}a(Ct,"errorMessage");function Lt(t){let e=be.join(gt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return dt(e,{recursive:!0,mode:448}),be.join(e,`${t}.log`)}a(Lt,"createOutputLog");import It from"node:os";import ve from"node:path";function $e(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",o=ve.win32.basename(i).toLowerCase();return o==="cmd"||o==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(s=>["/d","/s","/c",s],"commandArgs")}:{executable:i,displayName:o.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(s=>["-NoLogo","-NoProfile","-Command",s],"commandArgs")}}let n=e.SHELL?.trim()||It.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=ve.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a($e,"resolveShellProfile");function Ee(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(Ee,"shellSyntaxGuidance");import Ae from"node:path";import{stripVTControlCharacters as Mt}from"node:util";import{defineTool as _t}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Dt=g.Object({command:g.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:g.Optional(g.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:g.Optional(g.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:g.Optional(g.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:g.Optional(g.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:g.Optional(g.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function ke(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(_t({name:i,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Write commands for ${n.displayName}; commands are not translated between shell languages.`,`Use ${i} with background for servers, watchers, and long builds. Foreground waits become background after timeoutSeconds (60 by default), on a stable interactive prompt, or when the turn is aborted. A background session with no output for two minutes wakes an idle agent so it can be inspected. Sessions survive extension reloads and keep the same shell: source. Large output returns a bounded tail and a fullOutput file path. Use the returned shell: source with read, write, insert, and delete.`],description:`Use ${i} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort; completion is delivered automatically and wakes the agent. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${Ee(n)}`,parameters:Dt,async execute(o,s,l,u,c){r.bind(c);let d=s.cwd===void 0?c.cwd:Ae.resolve(c.cwd,s.cwd),m=e.start({command:s.command,background:s.background??!1,cwd:d,shell:n,...s.cols===void 0?{}:{cols:s.cols},...s.rows===void 0?{}:{rows:s.rows}});if(s.background===!0&&m.status!=="failed")return await Ot(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),k(e.snapshot(m));if(m.status==="failed")return k(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(s.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),k(e.snapshot(p.session))},renderCall(o,s){let l=typeof o.command=="string"?o.command:"",u=typeof o.cwd=="string"?Ae.resolve(process.cwd(),o.cwd):process.cwd();return ae(l,o.background===!0,u,n,s)},renderResult(o,s,l){return ue(o.details,s.expanded,l)}}))}a(ke,"registerTerminalTools");function k(t){return{content:[{type:"text",text:v(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(k,"terminalResult");async function Ot(t,e,n){await new Promise(r=>{let i=!1,o,s=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(o),s(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(k(c)),(Mt(c.output).replaceAll("\r","").split(`
22
- `).filter(m=>m.length>0).length>=R||c.status!=="running")&&l()},"publish");s=t.onDidChange(c=>{c.id===e.id&&u()}),o=setTimeout(l,2e3),u()})}a(Ot,"captureInitialBackgroundPreview");import{Box as Ce,Container as Le}from"@earendil-works/pi-tui";var Nt=120,Ut=12e4,C=class{constructor(e,n,r=Ut){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:o},s)=>{let l=Ie(i.details)?i.details:void 0,u=new Le;l!==void 0&&u.addChild(S(l,o,s,"stale \xB7 inspect session"));let c=new Ce(1,1,d=>s.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:o},s)=>{let l=new Le;for(let c of Wt(i.details))l.addChild(S(c,o,s));let u=new Ce(1,1,c=>s.bg("toolSuccessBg",c));return u.addChild(l),u}),this.#u=[n.onDidChange(i=>this.#o(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{a(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#s=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#o(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait aborted; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#s=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#o(e,n=!1){if(this.#l(e.id),this.#s||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#s||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:jt(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.#t.set(e.id,setTimeout(()=>this.#n(e),this.staleIntervalMs))}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#s||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#s||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:Ft(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},Nt)))}};function Wt(t){return!_e(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Ie)}a(Wt,"completionSnapshots");function Ie(t){return _e(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}a(Ie,"isTerminalSessionSnapshot");function Ft(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
23
- ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,o=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Me(n.elapsedMs)}
24
- ${o||"(no output)"}`}).join(`
25
- `)}`}a(Ft,"formatCompletionMessage");function jt(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Me(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
26
- ${e||"(no output)"}`}a(jt,"formatStaleMessage");function Me(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Me,"formatElapsed");function _e(t){return typeof t=="object"&&t!==null}a(_e,"isRecord");async function Gt(t){let e=re("terminal")??new A,n=$e(),r=new C(t,e),i=te(t).add(de(e));await Promise.all([we(t,e),Te(t,e)]),ke(t,e,n,r),t.on("session_start",(o,s)=>r.bind(s)),t.on("agent_settled",(o,s)=>r.onAgentSettled(s)),t.on("session_shutdown",async o=>{if(r.dispose(),i(),o.reason==="reload"){ne("terminal",e);return}ie("terminal",e),await e.dispose()})}a(Gt,"registerTerminal");export{Gt as default};
@@ -1,16 +0,0 @@
1
- import{a as b,d as A}from"./chunk-ITSNK5YG.js";import{a as $}from"./chunk-J4RTW44E.js";import{b as F,d as v}from"./chunk-526E364R.js";import{f as M}from"./chunk-YHUTTZC6.js";import{a as f}from"./chunk-EI7MMDWY.js";import N from"node:path";import{truncateHead as L,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 _=O.Union([O.String({minLength:1}),$]),I=O.Object({before:_,after:_},{additionalProperties:!1});async function ne(e,i,c){if(!re.Check(I,i))throw Object.assign(new Error("Use before and after source strings or read request objects"),{code:"INVALID_ARGUMENTS"});let n=i,r=f(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"),a=await r(n.before),s=await r(n.after),o=b(a.source,a.content,s.content,s.source);return{kind:"diff",ok:!0,equal:a.content===s.content,before:a,after:s,...o}}f(ne,"executeDiff");function B(e,i){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,i));return{source:e.source??i,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
- `)}}f(B,"comparisonText");function R(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="diff"&&"ok"in e&&e.ok===!0}f(R,"isDiffOutcome");function E(e,i=process.cwd()){let c=f(r=>N.isAbsolute(r)?N.relative(i,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]})]}}f(E,"diffPresentation");function T(e){return e.equal?`No differences: ${e.before.source} \u2192 ${e.after.source}`:e.diff}f(T,"diffText");function Pe(e){return{content:[{type:"text",text:T(e)}],details:{}}}f(Pe,"diffReadResult");function ke(e,i,c){e.registerTool({name:"diff",label:"Diff",parameters:I,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,a,s){let o=n.details;if(o?.comparison?.equal)return new S(T(o.comparison),0,0);let l=i.getToolRenderer("diff")?.renderResult;return l?l(n,r,a,s):new S(n.content.filter(t=>t.type==="text").map(t=>t.text).join(`
4
- `),0,0)},async execute(n,r,a,s,o){let l=c();if(l===void 0)throw new Error("Diff requires the read extension");let t=await ne(l,r,{cwd:o.cwd,signal:a}),p=T(t),y=L(p).truncated?await l.saveTemporary(p):void 0,d=y===void 0?"":`
5
- Full diff: ${y}`;return{content:[{type:"text",text:y===void 0?p:L(p,{maxLines:te-2,maxBytes:ee-Buffer.byteLength(d)}).content+d}],details:{...E(t,o.cwd),comparison:t,temporarySource:y}}}})}f(ke,"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","apply","result"]);function V(e,i=q.parse(e)){let c=[];i.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 a=r.node.parent;for(;a?.parent&&!["VariableDeclaration","ParamList","Block","Script"].includes(a.name);)a=a.parent;let s=a?.name==="VariableDeclaration"&&a.firstChild?.name==="var",o=new Set(["Script","FunctionDeclaration","FunctionExpression","ArrowFunction",...s?[]:["Block"]]),l=r.node.parent;for(l?.name==="FunctionDeclaration"&&(l=l.parent);l?.parent&&!o.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 i.iterate({enter(r){if(r.name!=="CallExpression")return;let a=r.node.firstChild;if(a?.name!=="VariableName")return;let s=e.slice(a.from,a.to);if(!oe.has(s)||c.some(t=>t.name===s&&t.from<=r.from&&t.to>=r.to))return;let o=r.node.getChild("ArgList")?.getChild("ObjectExpression"),l=Object.create(null);if(!o){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 o?.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 d=t.lastChild;if(!d||d.type.isError||d.name===":")continue;let m=e.slice(d.from,d.to),u=m.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(m);l[y]={text:u.length>160&&!h?`${u.slice(0,100)}\u2026${u.slice(-40)} (${m.length} source chars)`:u,literal:["String","Number","BooleanLiteral","Null"].includes(d.name)&&d.lastChild?.type.isError!==!0}}return n.push({name:s,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}f(V,"parseApplyCalls");function ie(e,i=V(e),c,n=r=>r){let r=0,a=[],s=f(o=>n(o.split(`
6
- `).map(l=>l.length>200?l.slice(0,200)+"\u2026":l).join(`
7
- `)),"codePreview");for(let o of i)a.push(s(e.slice(r,o.from))),a.push(c?.(o)??`${o.name}(${o.path?o.path.literal?o.path.text:`\u2039${o.path.text}\u203A`:"\u2026"})`),r=o.to;return a.push(s(e.slice(r))),a.join("")}f(ie,"compactApplySource");function J(e,i){let c="",n="",r=[];return a=>{if(a===c)return n;let s=0;for(;s<c.length&&s<a.length&&c[s]===a[s];)s++;r=U.applyChanges(r,[{fromA:s,toA:c.length,fromB:s,toB:a.length}]);let o=q.parse(a,r);return r=U.addTree(o),n=ie(a,V(a,o),e,i),c=a,n}}f(J,"createApplySourceProjection");import{lstat as G,unlink as ae}from"node:fs/promises";import Y from"node:path";import z from"fs-extra";import{Type as x}from"typebox";import{Value as se}from"typebox/value";var P=x.String({minLength:1,description:"Local regular file path, relative to cwd or absolute."}),le=x.Object({path:P},{additionalProperties:!1}),ce=x.Object({path:P,target:P,overwrite:x.Optional(x.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))},{additionalProperties:!1});function k(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="file-operation"}f(k,"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(i=>i!==void 0).join(`
8
- `)}f(D,"formatFileOperation");async function Be(e,i,c,n){let r=!1,a,s;try{let o=e==="delete"?le:ce;if(!se.Check(o,i))throw Object.assign(new Error("Invalid file operation arguments"),{code:"INVALID_ARGUMENTS"});let l=i;a=Y.resolve(c,l.path),s=l.target===void 0?void 0:Y.resolve(c,l.target),n?.throwIfAborted();let t=await pe(a);if(s!==void 0){let p=await fe(s);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(a===s||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 ae(a):s!==void 0&&(e==="copy"?await z.copy(a,s,{overwrite:l.overwrite===!0,errorOnExist:!0}):await z.move(a,s,{overwrite:l.overwrite===!0})),{kind:"file-operation",operation:e,ok:!0,effect:"applied",path:a,...s===void 0?{}:{target:s}}}catch(o){return{kind:"file-operation",operation:e,ok:!1,effect:r?"unknown":"not-applied",...a===void 0?{}:{path:a},...s===void 0?{}:{target:s},error:{code:o!==null&&typeof o=="object"&&"code"in o?String(o.code):"FILE_OPERATION_FAILED",message:o instanceof Error?o.message:String(o)}}}}f(Be,"executeFileOperation");async function pe(e){let i=await G(e);if(!i.isFile()||i.isSymbolicLink())throw Object.assign(new Error("Source must be a regular file"),{code:"INVALID_FILE_TYPE"});return i}f(pe,"regularFile");async function fe(e){try{return await G(e)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&i.code==="ENOENT")return;throw i}}f(fe,"optionalStat");import{Text as de}from"@earendil-works/pi-tui";function K(e){let i=e.select(),c=e.mutationValues().filter(ue);return i.files.map(n=>{let r=c.flatMap(o=>o.files.filter(l=>l.source===n.source).map(l=>({outcome:o,changed:l}))),a=e.mutationPresentation(n.source)?.data,s=a?.afterContent===n.after?a: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:s?.afterDocument,resultPresentation:s?.resultPresentation,scopeMarkers:s?.scopeMarkers,hints:s?.hints,warnings:s?.warnings,diffStatuses:s?.diffStatuses,diffs:[b(n.source,n.before??"",n.after??"").diff],operations:r.map(({outcome:o,changed:l})=>({operation:o.operation==="remove"?"delete":o.operation,changes:l.changes.length})),formatting:s?.formatting??r.at(-1)?.changed.formatting})})}f(K,"finalApplyMutations");function ue(e){return e!==null&&typeof e=="object"&&"operation"in e&&"files"in e&&Array.isArray(e.files)&&"effect"in e}f(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 rt(e,i,c,n=process.cwd()){let r=e.select(),a=[...r.automatic,...r.explicit.filter(t=>t.kind==="operation")].filter(t=>R(t.value)&&!t.value.equal),s=a.flatMap(t=>R(t.value)?[E(t.value,n)]:[]),o=new Set(a.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:s,cwd:n,blocks:[...i.content.filter(p=>!o.has(p)).flatMap(p=>p.type==="text"?[{text:H(p.text),read:t.find(g=>g.content.includes(p))}]:[])]}}let l=K(e);return{...l.length>0?{mutations:{results:l}}:{},comparisons:s,cwd:n,blocks:[...r.explicit.flatMap(t=>t.kind==="operation"&&R(t.value)&&!t.value.equal?[]:k(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})=>k(t)?[{text:D(t)}]:t!==null&&typeof t=="object"&&"kind"in t&&t.kind==="index-operation"?p?.content.flatMap(g=>g.type==="text"?[{text:g.text}]:[])??[]:t===null||typeof t!="object"||!("errors"in t)||!Array.isArray(t.errors)?[]:t.errors.flatMap(g=>g!==null&&typeof g=="object"&&"message"in g&&typeof g.message=="string"?[{text:g.message}]:[])),...c===void 0?[]:[{text:c instanceof Error?c.message:JSON.stringify(c)}]]}}f(rt,"createApplyDisplay");function j(e,i,c,n,r,a,s=!1){let o=Math.max(1,c);if(o<5)return e.split(`
9
- `).flatMap(u=>W(u,o));let l=o-4,t=f(u=>i.fg("borderMuted",u),"border"),g=me(` ${n==="call"?"Apply \xB7 JavaScript":"Result"} `,o-4,""),y=[t(`${n==="call"?"\u256D":"\u251C"}\u2500`)+i.fg(s?"error":"accent",g)+t(`${"\u2500".repeat(Math.max(0,o-X(g)-3))}${n==="call"?"\u256E":"\u2524"}`)],d=`${t("\u2502")}${" ".repeat(o-2)}${t("\u2502")}`;for(let u of e.split(`
10
- `)){let h=a==="diff"?i.fg(u.startsWith("+")?"toolDiffAdded":u.startsWith("-")?"toolDiffRemoved":"toolDiffContext",u):a?Z(u,a).join(`
11
- `):i.fg("toolOutput",u);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(d),r&&y.push(t(`\u2570${"\u2500".repeat(o-2)}\u256F`));let m=i.getBgAnsi("toolPendingBg");return y.map(u=>m+M(u,m)+"\x1B[0m")}f(j,"applyFrameRows");function ge(e){return(i,c,n)=>{let r=n.state,a=r.projectSource??=J(e?o=>e(o,c):void 0,e?o=>Z(o,"javascript").join(`
12
- `):void 0),s=i!==null&&typeof i=="object"&&"source"in i&&typeof i.source=="string"?i.source:"";return{invalidate(){},render(o){return j(r.codeView||n.expanded?r.displaySource??s:ye(a(r.displaySource??s)),c,o,"call",!r.applyResultReady,r.codeView||n.expanded||!e?"javascript":void 0)}}}}f(ge,"createApplyCallRenderer");function ye(e,i=F){let c=e.split(`
13
- `);if(c.length<=i)return e;let n=Math.max(2,i-1),r=Math.ceil(n/2),a=Math.floor(n/2),s=c.length-r-a;return[...c.slice(0,r),`\u2026 ${s} lines omitted \u2026`,...c.slice(-a)].join(`
14
- `)}f(ye,"compactApplyPreview");var nt=ge();function he(e){return(i,c,n,r)=>{r.state.applyResultReady=!0;let a=i.details;r.state.displaySource=a?.displaySource;let s=a?.display,o=s?.blocks??[{text:r.isError?"Apply failed":"Apply finished"}],l=v({kind:"source"}),t=o.map(d=>l(d.read??{content:[{type:"text",text:d.text}],details:we(d.text)},c,n,{...r,isError:!1,lastComponent:void 0})),p=s?.mutations,g=(s?.comparisons??[]).flatMap(d=>[e?.(d,n,c.expanded,s?.cwd??process.cwd())??new de((d.results??[]).flatMap(u=>u.data.diffs??[]).join(`
15
- `),0,0)]),y=p===void 0?void 0:e?.(p,n,c.expanded,s?.cwd??process.cwd());return{invalidate(){y?.invalidate();for(let d of g)d.invalidate()},render(d){let m=[];for(let u of t){let h=u.render(Math.max(1,d-4));h.length!==0&&(m.length>0&&m.push(""),m.push(...h))}for(let u of g)m.length>0&&m.push(""),m.push(...u.render(Math.max(1,d-4)));if(y!==void 0){let u=y.render(Math.max(1,d-4));m.length>0&&u.length>0&&m.push(""),m.push(...u)}else p!==void 0&&m.push(...(p.results??[]).map(u=>u.path??"Changed file"));return m.length===0&&o.length>0&&o.every(u=>u.read?.details.diagnosticCheck?.complete&&u.read.details.diagnosticCheck.count===0)?j("",n,d,"result",!0).slice(-1):j(m.length===0?"No output":m.join(`
16
- `),n,d,"result",!0,void 0,r.isError)}}}}f(he,"createApplyResultRenderer");function H(e){if(/^(?:Undo transaction:|Undo available)/u.test(e.trim()))return"";try{let i=JSON.parse(e);return JSON.stringify(C(i),null,2)}catch{return e.replace(/APPLY#[0-9A-F]{12}/gu,"Apply transaction")}}f(H,"redactApplyReceipts");function C(e){return Array.isArray(e)?e.map(C):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([i])=>i!=="transaction").map(([i,c])=>[i,C(c)]))}f(C,"redactTransactionKeys");function we(e){try{let i=JSON.parse(e);return i!==null&&typeof i=="object"?{source:"result.json"}:{}}catch{return{}}}f(we,"jsonDetails");var ot=he();export{ne as a,Pe as b,ke as c,Be as d,K as e,rt as f,ge as g,nt as h,he as i,ot as j};
@@ -1,7 +0,0 @@
1
- import"./chunk-3YK4XMWB.js";import{a as J,b as V,c as U,d as q,f as z}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 c}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(r=>r.recipe.formatter!==void 0),i=t.filter(r=>r.recipe.linter!==void 0),s=t.filter(r=>r.recipe.lsp!==void 0);if(o.length>0){let r=h(n,"formatters"),a=await S(r,{version:1,formatters:{}}),u=P(a,"formatters");for(let l of o)u[l.recipe.id]??=l.recipe.formatter;await R(r,a)&&e.push(r)}if(i.length>0){let r=h(n,"linters"),a=await S(r,{version:1,linters:{}}),u=P(a,"linters");for(let l of i)u[l.recipe.id]??=l.recipe.linter;await R(r,a)&&e.push(r)}if(s.length>0){let r=h(n,"lsp-servers"),a=await S(r,{version:1,servers:{}}),u=P(a,"servers");for(let l of s){let d=O(l.recipe.lsp);u[l.recipe.id]??={command:d.command,transport:"stdio",rootMarkers:d.rootMarkers,...d.initializationOptions!==void 0&&{initializationOptions:d.initializationOptions},...d.settings!==void 0&&{settings:d.settings},...d.requireRootMarker!==void 0&&{requireRootMarker:d.requireRootMarker},languages:Object.fromEntries(Object.entries(d.languageIds).map(([p,f])=>[p,{extensions:f,...d.fileNames?.[p]&&{fileNames:d.fileNames[p]}}])),capabilities:["diagnostics"]}}await R(r,a)&&e.push(r)}return e}c(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}}c(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}c(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)}c(R,"writeJson");var C=class{static{c(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,s=[],r=[],a=[],u=[],l={addLanguage:c(d=>{b(d,s,t.id,"language",()=>i)},"addLanguage"),addToolRecipe:c(d=>{b(d,r,t.id,"tool recipe",()=>i)},"addToolRecipe"),addSetupCheck:c(d=>{b(d,a,t.id,"setup check",()=>i)},"addSetupCheck"),addCheck:c(d=>{b(d,u,t.id,"check",()=>i)},"addCheck")};try{await t.setup(l)}finally{i=!1}W(this.languages,s,"language"),W(this.recipes,r,"tool recipe"),this.languages.push(...s),this.recipes.push(...r),this.setupChecks.push(...a),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 s=await i.value.inspect(t);e.push(...(s.selections??[]).map(r=>({...r,pluginId:i.pluginId}))),o.push(...(s.actions??[]).map(r=>({...r,pluginId:i.pluginId})))}catch{}return{selections:e,actions:o}}c(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}c(X,"runContributedChecks");function W(n,t,e){for(let o of t){let i=n.find(s=>s.value.id===o.value.id)?.pluginId;if(i!==void 0)throw new Error(`${e} ${o.value.id} is already owned by doctor plugin ${i}`)}}c(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(s=>s.value.id===n.id))throw new Error(`Doctor plugin ${e} registered ${o} ${n.id} twice`);t.push({pluginId:e,value:n})}c(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(a=>a.value)),s=await ce(n),r=[];for(let a of e){let u=a.value;if(u.languages.every(v=>!t.has(v)))continue;let l=[],d=1,p=i.get(u.id),f=p?.config;f!==void 0&&(d+=6,l.push(`project config: ${f}`)),s.has(`${u.kind}:${u.id}`)&&(d+=6,l.push("Pi Agent IDE config"));let w=p?.dependency;w!==void 0&&(d+=4,l.push(`project dependency: ${w}`));let m=await ae(n,u.executables,o);m!==void 0&&(d+=3,l.push(`executable: ${m}`)),r.push({pluginId:a.pluginId,recipe:u,score:d,evidence:l,...m&&{executable:m}})}return r.sort((a,u)=>u.score-a.score||a.recipe.id.localeCompare(u.recipe.id))}c(Y,"discoverRecipeCandidates");function K(n,t,e=[]){let o=new Map,i=new Map(e.map(s=>[`${s.kind}:${s.languageId}`,s.toolId]));for(let s of t)for(let r of["formatter","linter","lsp"]){let a=i.get(`${r}:${s}`),u=a===void 0?4:7,l=n.filter(p=>p.recipe.kind===r&&p.recipe.languages.includes(s)&&p.executable!==void 0&&p.recipe.id!==a&&p.score>=u),d=l[0];d!==void 0&&(l.filter(p=>p.score===d.score).length>1||o.set(`${d.recipe.kind}:${d.recipe.id}`,d))}return[...o.values()]}c(K,"selectSuggestedRecipes");async function ae(n,t,e){for(let o of t)if(await N(o,n,e))return o}c(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 s=JSON.parse(await se(h(n,e),"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s[o];if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let u of Object.keys(a))t.add(`${i}:${u}`)}catch{}return t}c(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)}}c(Q,"collectProjectFiles");function Z(n,t){let e=new Map;for(let o of t){let i=new Set(o.extensions.map(a=>a.toLowerCase())),s=new Set(o.fileNames),r=n.filter(a=>!a.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")&&(i.has(y.extname(a).toLowerCase())||s.has(y.basename(a))));r.length>0&&e.set(o.id,r)}return e}c(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}c(k,"walk");function ee(n){return n.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")}c(ee,"isManagedIdeConfig");async function $(n,t,e=process.env,o){o?.throwIfAborted();let i=await Q(t,o);o?.throwIfAborted();let s=Z(i,n.languages.map(p=>p.value)),r=new Set(s.keys()),a={cwd:t,files:i,detectedLanguageIds:r,detectedLanguages:s,env:e},[u,l]=await Promise.all([Y(t,r,n.recipes,e),H(n,a)]),d=new Map;for(let p of r)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=c(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`;d.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:s,candidates:u,selections:l.selections,actions:[...l.actions,...d.values()],suggestions:K(u,r,l.selections)}}c($,"inspectDoctorSetup");async function I(n,t,e=process.env){let o=await $(n,t,e),i=new Set(o.detectedLanguages.keys()),s={cwd:t,files:o.files,detectedLanguageIds:i,detectedLanguages:o.detectedLanguages,env:e},r=await X(n,s),a=[{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:a},...r]}}c(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()}c(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"))}c(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
- `)}c(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(()=>{})}c(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(s=>`\u2022 ${s.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
- `)}}}}c(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(r=>n.detectedLanguages.has(r)).join(", "),s={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} ${s}`}});return[...t,...e].sort((o,i)=>o.id.localeCompare(i.id))}c(we,"setupItems");function De(n){return me("sha256").update(n.map(t=>`${t.id}\0${t.message}`).join("\0")).digest("hex").slice(0,12)}c(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(q,i=>{if(!z(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:c(async(i,s)=>{await t.waitForPlugins();let r=await I(t.snapshot(),s.cwd);A(n,D(r));let a=new Set(i.trim().split(/\s+/u).filter(Boolean));if(r.suggestions.length>0&&!a.has("--no-apply")&&(a.has("--apply")||s.hasUI&&await s.ui.confirm("Apply suggested configuration?","Add detected tools to .pi/pi-agent-ide/. Existing entries and native tool settings are kept."))){let d=await G(s.cwd,r.suggestions),p=d.length===0?"Pi Agent IDE configs are already up to date":`Updated ${d.length} Pi Agent IDE config ${d.length===1?"file":"files"}`;s.ui.notify(p,"info"),r=await I(t.snapshot(),s.cwd),A(n,D(r))}if(!j(r)&&!a.has("--agent"))return;(a.has("--agent")||s.hasUI&&await s.ui.confirm("Ask the agent to finish setup?","The agent will receive this redacted report and relevant plugin recipes."))&&(e=s.cwd,n.sendUserMessage(te(r)))},"handler")}),n.on("agent_end",async(i,s)=>{let r=e;if(r===void 0)return;e=void 0;let a=await I(t.snapshot(),r,process.env);A(n,`Doctor recheck after agent setup
6
-
7
- ${D(a)}`),j(a)?s.ui.notify("Pi Agent IDE setup still needs attention","warning"):s.ui.notify("Pi Agent IDE setup is ready","info")}),n.events.emit(U,{protocol:J,apiVersion:1}),await t.waitForPlugins()}c(oe,"registerDoctor");function A(n,t){n.sendMessage({customType:"pi-agent-ide-doctor",content:t,display:!0},{triggerTurn:!1})}c(A,"sendReport");export{oe as default};
@@ -1 +0,0 @@
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."})),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."})),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())}),y=e.Object({id:e.String({pattern:"\\S"}),priority:e.Optional(e.Number()),resolve:a}),c=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 h(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(h,"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(c,t)}o(C,"isReadViewRegistration");function k(t){return i.Check(y,t)}o(k,"isFragmentResolverRegistration");function P(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(P,"isReadFragmentResolution");function m(t){return typeof t=="object"&&t!==null}o(m,"isRecord");export{l as a,h as b,O as c,S as d,C as e,k as f,P as g};
@@ -1 +0,0 @@
1
- import{a as w}from"./chunk-5PLV4HLG.js";import{a as C,b as E}from"./chunk-EJ5OACQM.js";import{a as n}from"./chunk-EI7MMDWY.js";import{DynamicBorder as $}from"@earendil-works/pi-coding-agent";import{Container as W,Key as S,matchesKey as M,SelectList as _,Text as m,truncateToWidth as D,visibleWidth as I}from"@earendil-works/pi-tui";var v=class{constructor(e,s,i){this.registry=e;this.activityMode=s;e.onDidChange(()=>this.#s()),i.registerCommand("agent-ide-processes",{description:"Show active terminal and debugger processes created by Agent IDE",handler:n(async(r,d)=>{if(this.bind(d),d.mode!=="tui"){d.ui.notify("The Agent IDE process overlay requires the TUI.","info");return}await this.#r(d)},"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 s=this.#n();if(this.activityMode==="off"||s.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: ${s.length}`);return}e.ui.setStatus("agent-ide-processes",void 0),e.ui.setWidget("agent-ide-processes",(i,r)=>({invalidate(){},render:n(d=>k(s,d,r),"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 s=n(()=>{},"disposeRefresh"),i,r;try{r=await e.ui.custom((u,c,O,x)=>{let y=this.#n(),f="list",g,P=n(l=>{let a=y.map(o=>({value:o.source,label:`${o.status} ${o.kind} ${o.title}`,description:o.description})),p=new _(a,Math.min(a.length,12),{selectedPrefix:n(o=>c.fg("accent",o),"selectedPrefix"),selectedText:n(o=>c.fg("accent",o),"selectedText"),description:n(o=>c.fg("muted",o),"description"),scrollInfo:n(o=>c.fg("dim",o),"scrollInfo"),noMatch:n(o=>c.fg("warning",o),"noMatch")}),b=a.findIndex(o=>o.value===l);return b>=0&&p.setSelectedIndex(b),p.onSelect=o=>{g=y.find(R=>R.source===o.value),f="detail",u.requestRender()},p.onCancel=()=>x(null),p},"createList"),h=P(),A=n(()=>{let l=g?.source??h.getSelectedItem()?.value;y=this.#n(),g=f==="list"?void 0:y.find(a=>a.source===l),h=P(l),u.requestRender()},"refresh");return s=this.registry.onDidChange(A),i=setInterval(A,1e3),{invalidate:n(()=>h.invalidate(),"invalidate"),render(l){let a=new W;return a.addChild(new $(p=>c.fg("accent",p))),f==="list"?(a.addChild(new m(c.fg("accent",c.bold("Agent IDE processes")),1,0)),a.addChild(h),a.addChild(new m(c.fg("dim","enter view \xB7 d stop \xB7 esc close"),1,0))):g===void 0?a.addChild(new m(c.fg("warning","Process is no longer active."),1,0)):(a.addChild(g.renderDetail(c)),a.addChild(new m(c.fg(f==="confirm"?"warning":"dim",f==="confirm"?"Stop this process? y confirm \xB7 n/esc cancel":"esc back \xB7 d stop"),1,0))),a.addChild(new $(p=>c.fg("accent",p))),a.render(l)},handleInput(l){f==="list"?l==="d"?(g=y.find(a=>a.source===h.getSelectedItem()?.value),g!==void 0&&(f="confirm")):h.handleInput(l):f==="detail"?M(l,S.escape)?f="list":l==="d"&&(f="confirm"):l==="y"&&g!==void 0?x({source:g.source}):(l==="n"||M(l,S.escape))&&(f="detail"),u.requestRender()}}},{overlay:!0,overlayOptions:{width:"75%",maxHeight:"80%",minWidth:52}})}finally{s(),i!==void 0&&clearInterval(i)}if(r===null)return;let d=this.#n().find(u=>u.source===r.source);d!==void 0&&await d.stop()}}};function k(t,e,s){if(t.length===0)return[];let i=n(d=>s.fg("accent",d),"accent"),r=[q("Agent IDE Processes",`${t.length} active`,e,i)];for(let[d,u]of t.entries()){for(let c of u.renderSummary(s))r.push(T(` ${c} `,e,i));d<t.length-1&&r.push(T("",e,i))}return r.push(L(e,i)),r}n(k,"renderProcessWidget");function q(t,e,s,i){if(s<=1)return i("\u256D");let r=s-2,d=`\u2500 ${t} `,u=` ${e} \u2500`,c="\u2500".repeat(Math.max(0,r-I(d)-I(u)));return i(`\u256D${D(`${d}${c}${u}`,r).padEnd(r,"\u2500")}\u256E`)}n(q,"borderTop");function T(t,e,s){if(e<=1)return s("\u2502");let i=e-2,r=D(t,i);return`${s("\u2502")}${r}${" ".repeat(Math.max(0,i-I(r)))}${s("\u2502")}`}n(T,"borderLine");function L(t,e){return e(t<=1?"\u2570":`\u2570${"\u2500".repeat(t-2)}\u256F`)}n(L,"borderBottom");async function B(t){let e=w(t),s=await E(C()),i=new v(e,K(s.preferences?.["processes.activity"]),t);t.on("session_start",(r,d)=>i.bind(d)),t.on("session_shutdown",()=>i.dispose())}n(B,"registerAgentIdeProcesses");function K(t){return t==="compact"||t==="off"?t:"detailed"}n(K,"activityMode");export{B as default};
@@ -1 +0,0 @@
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 l=new m,u=new m;function E(t){let e=u.getStore();e?e.push(t):t()}o(E,"afterPostEditScope");async function T(t){if(u.getStore())return t();let e=[];try{return await u.run(e,t)}finally{for(let r of e)r()}}o(T,"collectPostEditNotifications");function b(t,e){let r=l.getStore();return r?(r.set(t,e),!0):!1}o(b,"deferPostEdit");function h(t){return l.getStore()?.has(t)??!1}o(h,"hasDeferredPostEdit");function v(){let t=new Map;return{run(e){return l.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(v,"createPostEditScope");import{Type as n}from"typebox";import{Value as c}from"typebox/value";var w=`${p}/post-edit/register`;function A(t){return c.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(A,"isFormattingContribution");function M(t){return c.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(M,"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 c.Check(y,t)}o(S,"isTextPostEditHandlerRegistration");function _(t){return c.Check(P,t)}o(_,"isTextPostEditHandlerRegistrationRequest");function j(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(j,"isTextMutationResultContributionData");function I(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(I,"connectTextEditorPostEditHandler");export{E as a,T as b,b as c,h as d,v as e,w as f,A as g,M as h,S as i,_ as j,j as k,I as l};
@@ -1,2 +0,0 @@
1
- import{a as j}from"./chunk-GUTQ3PWL.js";import{m as S}from"./chunk-5VSE5X5R.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{createHash as le}from"node:crypto";import{readFile as J}from"node:fs/promises";import f from"node:path";import{spawn as Z}from"node:child_process";import _ from"node:path";import{createInterface as ee}from"node:readline";import{existsSync as X}from"node:fs";import Y from"node:os";import H from"node:path";function F(e=process.env.PI_CODING_AGENT_DIR??H.join(Y.homedir(),".pi","agent"),t=process.platform){let n=H.join(e,"bin",t==="win32"?"rg.exe":"rg");return X(n)?n:"rg"}a(F,"resolveRipgrepExecutable");async function R(e,t,n){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let r=_.resolve(t,re(e.path??".")),o=["--json","--no-config","--no-ignore-parent","--color=never","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...O(e.include).flatMap(i=>["--glob",i]),...O(e.exclude).flatMap(i=>["--glob",`!${i}`]),"--",e.query,r];if(e.regex!==!0)return k(["--fixed-strings",...o],n);try{return await k(["--engine","auto",...o],n)}catch(i){if(!te(i))throw i;return k(["--engine","default",...o],n)}}a(R,"searchText");function k(e,t){return new Promise((n,r)=>{let o=Z(F(),e,{stdio:["ignore","pipe","pipe"]}),i=ee({input:o.stdout}),s=[],l="",c,u=a(()=>{o.kill()},"abort"),d=a(()=>{t?.removeEventListener("abort",u),i.close()},"cleanup");o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{l+=m}),i.on("line",m=>{if(!(c!==void 0||m.length===0))try{let h=JSON.parse(m);if(h.type!=="match")return;for(let b of ne(h))s.push(b)}catch(h){c=h,o.kill()}}),o.once("error",m=>{d(),r(m)}),o.once("close",m=>{if(d(),t?.aborted===!0){let h=new Error("Search was aborted.");h.name="AbortError",r(h);return}if(c!==void 0){r(new Error("Unable to parse ripgrep search output.",{cause:c}));return}if(m!==0&&m!==1){r(new Error(l.trim()||`ripgrep exited with code ${String(m)}.`));return}s.sort(oe),n({matches:s,complete:!0})}),t?.addEventListener("abort",u,{once:!0}),t?.aborted===!0&&u()})}a(k,"runRipgrep");function te(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}a(te,"isPcre2MatchLimitError");function ne(e){let t=e.data.path.text,n=e.data.lines.text;if(t===void 0||n===void 0||!Number.isSafeInteger(e.data.line_number))return[];let r=n.replace(/(?:\r\n|\n)$/u,""),o=Buffer.from(n),i=[];for(let s of e.data.submatches){if(s.start<0||s.end<=s.start||s.end>o.length)continue;let l=o.subarray(0,s.start).toString("utf8").length,c=o.subarray(0,s.end).toString("utf8").length;i.push({source:_.resolve(t),lineNumber:e.data.line_number,startColumn:l,endColumn:c,matchedText:r.slice(l,c),lineText:r})}return i}a(ne,"matchesFromEvent");function O(e){if(e===void 0)return[];let t=[],n=0,r="";for(let o of e){if(o==="{"?n+=1:o==="}"&&(n=Math.max(0,n-1)),n===0&&(o===","||/\s/u.test(o))){r.length>0&&(t.push(r),r="");continue}r+=o}return r.length>0&&t.push(r),t}a(O,"splitGlobList");function re(e){return e.startsWith("@")?e.slice(1):e}a(re,"stripFilePrefix");function oe(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}a(oe,"compareMatches");function E(e,t=!1){let n=C(e);if(!N(n))return t?e:$(e);let r=v(new A(e,n).parse(),t);return`^${r.condition}.*?\\K(${r.match})`}a(E,"compileSearchQuery");function W(e){if(N(C(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map($).join("|")})`:void 0}a(W,"compileSearchFallbackQuery");function N(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}a(N,"containsBooleanSyntax");var A=class{static{a(this,"BooleanQueryParser")}#t;#r;#i=0;constructor(t,n){this.#t=t,this.#r=n}parse(){let t=this.#s(),n=this.#e();if(n.type!=="end"){let r=n.type==="right"?"unexpected ')'.":`unexpected ${ce(n)}.`;throw p(n.offset,r)}return t}#s(){let t=this.#n();for(;this.#e().type==="or";){let n=this.#o(),r=this.#c(`after ${n.value}`);t={kind:"or",left:t,right:this.#a(r)}}return t}#n(){return this.#a(this.#c())}#a(t){let n=t;for(;;){let r=this.#e();if(r.type==="and"||r.type==="not"){this.#o();let o=this.#c(`after ${r.value}`);n={kind:r.type,left:n,right:o};continue}if(r.type==="term"||r.type==="left"){n={kind:"and",left:n,right:this.#c()};continue}return n}}#c(t){let n=this.#e();if(n.type==="term")return this.#o(),{kind:"term",value:n.value,quoted:n.quoted};if(n.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw p(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw p(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw p(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw p(n.offset,`expected a term${r}.`)}#e(){return this.#r[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function C(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&ie(e,n)){t.push({type:"left",value:r,offset:n}),n+=1;continue}if(r===")"){t.push({type:"right",value:r,offset:n}),n+=1;continue}if(D(e,n)){let s=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+s),offset:n}),n+=s;continue}if(r==="'"||r==='"'){let s=n,l=r,c="";for(n+=1;n<e.length&&e.charAt(n)!==l;)e.charAt(n)==="\\"&&(e.charAt(n+1)===l||e.charAt(n+1)==="\\")&&(n+=1),c+=e.charAt(n++);if(n>=e.length)throw p(s,`unterminated ${l==="'"?"single":"double"}-quoted term.`);if(n+=1,c.length===0)throw p(s,"quoted terms must not be empty.");t.push({type:"term",value:c,offset:s,quoted:!0});continue}let o=n;for(;n<e.length;){let s=e.charAt(n);if(/\s/u.test(s)||s===")"||D(e,n))break;s==="\\"&&n+1<e.length?n+=2:s==="["||s==="("?n=M(e,n)??n+1:n+=1}let i=e.slice(o,n);t.push({type:se(i),value:i,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}a(C,"tokenize");function D(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}a(D,"isBooleanPipe");function M(e,t){let n=e.charAt(t)==="["?"]":")",r=t+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===n)return r+1;if(n===")"&&(o==="("||o==="[")){let i=M(e,r);if(i===void 0)return;r=i}else r+=1}}}a(M,"regexBlockEnd");function ie(e,t){let n=M(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:N(C(r))}a(ie,"isBooleanGroup");function se(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}a(se,"operatorType");function ce(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}a(ce,"quoteToken");function p(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(p,"syntaxError");function v(e,t){if(e.kind==="term"){let o=t&&!e.quoted?e.value:$(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let n=v(e.left,t),r=v(e.right,t);return e.kind==="or"?{condition:`(?:${n.condition}|${r.condition})`,match:`(?:${n.match}|${r.match})`}:e.kind==="not"?{condition:`${n.condition}(?!${r.condition})`,match:n.match}:{condition:`${n.condition}${r.condition}`,match:`(?:${n.match}|${r.match})`}}a(v,"compileExpression");function $(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}a($,"escapeRegex");function $e(e){let t=E(e.query),n=E(e.query,!0),r=W(e.query),o=[];return n!==t&&o.push({query:n,mode:"regex"}),r!==void 0&&r!==t&&r!==n&&o.push({query:r,mode:"words"}),{...e,query:t,regex:!0,fallbacks:o}}a($e,"createSearchRecipe");async function B(e,t,n){let r=e.query,o=await R(e,t,n),i=[];for(let s of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await R({...e,query:s.query,regex:!0},t,n),r=s.query,i.push(s.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(l){if(s.mode!=="regex"||!ae(l)||n?.aborted)throw l;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:i}}a(B,"runSearchRecipe");function ae(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}a(ae,"isRegexSyntaxError");var ue=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,z=4;function De(e,t,n,r){return U(e,t,n,r).slice(0,z)}a(De,"createSearchSessionId");function U(e,t,n,r){let o=n===void 0?me(t.map(c=>c.source)):f.resolve(n),i=t.map(c=>({match:c,source:f.relative(o,f.resolve(c.source))})).sort((c,u)=>c.source.localeCompare(u.source)||I(c.match,u.match)).map(({match:c,source:u})=>[u,c.lineNumber,c.startColumn,c.endLineNumber??c.lineNumber,c.endColumn,c.matchedText,c.lineText]),{limit:s,...l}=K(r??{query:e,regex:!0},o);return le("sha256").update(JSON.stringify([e,o,l,i])).digest("hex").toUpperCase()}a(U,"createSearchSessionIdentity");function de(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let n=z;n<=e.length;n+=1){let r=e.slice(0,n);if(!t.has(r))return r}throw new Error("Could not allocate a unique search session id.")}a(de,"allocateSearchSessionId");function K(e,t){return{query:e.query,path:f.resolve(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,fallbacks:e.fallbacks??[]}}a(K,"normalizeRecipe");var Q=class{constructor(t=U){this.createIdentity=t}static{a(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(t,n,r,o,i,s={query:t,regex:!0},l){let c=n.map(L=>({...L,source:f.resolve(L.source)})).sort(I),u=await G(c,i),d=this.createIdentity(t,c,o,s),h=this.#r.get(d)??de(d,new Set(this.#t.keys())),b={id:h,query:t,matches:c,complete:r,contentBySource:u,recipe:s,...l!==void 0&&{refresh:l},cwd:f.resolve(o)};return this.#r.set(d,h),this.#t.set(h,b),b}async observeAfterEdit(t,n){let r=new Set(t.flatMap(i=>{let s=typeof i=="string"?w(i):void 0;return s===void 0?[]:[s.id]})),o=[];for(let i of r){let s=this.#t.get(i);if(s===void 0)continue;let l={sessionId:i,query:s.recipe.originalQuery??s.query,scope:K(s.recipe,s.cwd)};try{let c=s.refresh===void 0?await B(s.recipe,s.cwd,n):await s.refresh(n);o.push({...l,matches:c.matches.length,complete:c.complete,notices:c.notices})}catch(c){o.push({...l,error:c instanceof Error?c.message:String(c)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
2
- `),renderFull(t){return t},renderCompact(t){let n=w(t);return n===void 0?"selected result":n.selector==="all"?n.mode==="match"?"all matches":"all lines":n.mode==="match"?`match ${String(n.selector)}`:`line ${String(n.selector)}`},tryResolve:a((t,n)=>this.#i(t,n.source,n.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:a((t,n)=>this.#s(t,n.cwd),"tryResolve")}}async#i(t,n,r){let o=w(t);if(o===void 0)return{kind:"not-handled"};let i=this.#t.get(o.id);if(i===void 0)return x();if(o.selector==="all"&&!i.complete)return y();let s=f.resolve(n),l=i;if(o.selector==="all"){if(i.refreshedComplete?.complete===!0)l=i.refreshedComplete;else if(i.refreshedComplete!==void 0&&(l=await this.#n(i,r),!l.complete))return y()}let c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await P(s,r);if(d===void 0)return x(g(u[0]).lineNumber);if(o.selector==="all"&&d!==l.contentBySource.get(s)){if(l=await this.#n(i,r),!l.complete)return y();c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==i.contentBySource.get(s))return x(g(u[0]).lineNumber);let m=S(s,d);return{kind:"resolved",anchor:new j(t,s,u.map(h=>q(m,h,o.mode)))}}async#s(t,n){let r=w(t);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return x();if(r.selector==="all"&&!o.complete)return y();let i=o;if(r.selector==="all"){if(o.refreshedComplete?.complete===!0)i=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(i=await this.#n(o),!i.complete))return y();let u=new Set(T(i,r.selector,r.mode).map(d=>d.source));for(let d of u)if(await P(d)!==i.contentBySource.get(d)){if(i=await this.#n(o),!i.complete)return y();break}}let s=T(i,r.selector,r.mode);if(r.selector!=="all"){let u=s[0]?.source;if(u!==void 0&&await P(u)!==i.contentBySource.get(u))return x(s[0]?.lineNumber)}let l=new Map;for(let u of s){let d=l.get(u.source)??[];d.push(q(S(u.source,i.contentBySource.get(u.source)??u.lineText),u,r.mode)),l.set(u.source,d)}let c=[...l].map(([u,d])=>({source:u,ranges:d,expectedContent:i.contentBySource.get(u)}));return c.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:c}}async#n(t,n){let r=t.refresh===void 0?await B(t.recipe,t.cwd,n):await t.refresh(n),o=r.matches.map(s=>({...s,source:f.resolve(s.source)})).sort(I),i={matches:o,complete:r.complete,contentBySource:await G(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:i}),i}};function w(e){let t=ue.exec(e);if(t!==null)return{id:g(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}a(w,"parseSearchAnchor");function T(e,t,n){let r=t==="all"?e.matches:[e.matches[t-1]].filter(he);if(n==="match"||t!=="all")return r;let o=new Set;return r.flatMap(i=>{let s=S(i.source,e.contentBySource.get(i.source)??i.lineText),l=V(i);return s.lines.slice(i.lineNumber-1,l).flatMap(c=>{let u=`${i.source}\0${String(c.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...i,lineNumber:c.lineNumber,endLineNumber:c.lineNumber,startColumn:0,endColumn:c.content.length,lineText:c.content,matchedText:c.content}])})})}a(T,"selectMatches");function he(e){return e!==void 0}a(he,"isMatch");function V(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(V,"lastContainingLine");function q(e,t,n){if(n==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let r=V(t),o=g(e.lines[r-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:r+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}a(q,"selectionRange");function fe(e,t){let n=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,n).map(r=>{let o=r.lineNumber===t.lineNumber?t.startColumn:0,i=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,i)+(r.lineNumber===n?"":r.lineEnding)}).join("")}a(fe,"matchedSourceText");async function G(e,t){let n=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await J(r,{encoding:"utf8",...t!==void 0&&{signal:t}}),i=S(r,o);for(let s of e.filter(l=>l.source===r))if(i.lines[s.lineNumber-1]?.content!==s.lineText||fe(i,s)!==s.matchedText)throw new Error(`Search result in ${r} changed before its anchors were registered.`);n.set(r,o)}return n}a(G,"snapshotContents");async function P(e,t){try{return await J(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(P,"readCurrent");function x(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}a(x,"staleAnchor");function y(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}a(y,"missingCompleteAnchor");function me(e){if(e.length===0)return".";let t=f.dirname(f.resolve(g(e[0])));for(let n of e.slice(1)){let r=f.resolve(n);for(;!pe(t,r);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}a(me,"commonSourceDirectory");function pe(e,t){let n=f.relative(e,t);return n!==".."&&!n.startsWith(`..${f.sep}`)&&!f.isAbsolute(n)}a(pe,"isWithin");function I(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}a(I,"compareMatches");export{F as a,$e as b,B as c,De as d,U as e,de as f,Q as g};
@@ -1,27 +0,0 @@
1
- import{a as ae,b as oe,c as ie}from"./chunk-ESPNEJHK.js";import{a as ne}from"./chunk-5PLV4HLG.js";import{a as K}from"./chunk-MGCHOGQD.js";import{a as W,b as z}from"./chunk-T6LX2RX5.js";import{c as Q}from"./chunk-YHUTTZC6.js";import{a as Y}from"./chunk-6CZO43OH.js";import{a as X,b as Z}from"./chunk-OBNING2A.js";import{a as re}from"./chunk-L7JMDDSD.js";import{a as ee,b as te}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{d as E,e as y}from"./chunk-N34ATN52.js";import{a as i}from"./chunk-EI7MMDWY.js";import S from"node:path";import{access as et}from"node:fs/promises";import{StringEnum as tt}from"@earendil-works/pi-ai";import{defineTool as rt}from"@earendil-works/pi-coding-agent";import{Type as D}from"typebox";import{access as $}from"node:fs/promises";var se=[{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"}],N=[{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"],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"],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"],install:"Run go install github.com/go-delve/delve/cmd/dlv@v1.25.2."}},{id:"elixir-ls-debug-adapter",name:"ElixirLS debug adapter",kind:"debugger",languages:["elixir"],executables:["elixir","mix"],dependencies:["Elixir 1.14.5","Erlang/OTP 25.3.2.21","ElixirLS 0.29.3"],documentation:"https://github.com/elixir-lsp/elixir-ls",debugger:{runtimeExecutables:["elixir","mix"],adapterExecutables:["debug_adapter.sh"],platforms:["linux"],install:"Install Erlang/OTP 25.3.2.21, Elixir 1.14.5, and the ElixirLS 0.29.3 release at /opt/pi-debug-adapters/elixir-ls."}},{id:"vsc-debugger",name:"vscDebugger",kind:"debugger",languages:["r"],executables:["R"],dependencies:["R 4.3.3","R6 2.5.1","jsonlite 1.8.8","vscDebugger 0.5.2"],documentation:"https://manuelhentschel.github.io/vscDebugger/",debugger:{runtimeExecutables:["R"],adapterExecutables:["R"],platforms:["linux"],install:"Install R 4.3.3 and vscDebugger 0.5.2 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"],install:"Install .NET SDK 8 and NetCoreDbg 3.2.0-1092."}},{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"],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"],install:"Install Lua, 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"],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.1"],documentation:"https://github.com/ruby/debug",debugger:{runtimeExecutables:["ruby"],adapterExecutables:["rdbg"],platforms:["linux"],install:"Install Ruby and debug gem 1.11.1."}},{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"],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"],install:"Install Node 24 and js-debug-dap v1.117.0 from the official release archive."}}];function L(r){return N.find(e=>e.languages.includes(r))}i(L,"debuggerRecipeForLanguage");var de="/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js",ue="/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh",le={protocol:W,apiVersion:1,id:"debugger",setup(r){for(let e of N)r.addToolRecipe(e);r.addSetupCheck({id:"effective-config",inspect:Ae}),r.addCheck({id:"adapters",title:"Debug adapters",run:Te})}};async function Ae(r){let e=new Map([...r.detectedLanguageIds].map(L).filter(a=>a!==void 0).map(a=>[a.id,a])),t=[...r.detectedLanguageIds].flatMap(a=>{let o=L(a);return o===void 0?[]:[{kind:"debugger",languageId:a,toolId:o.id}]}),n=[];for(let a of se)a.status==="planned"&&r.detectedLanguageIds.has(a.language)&&n.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 e.values()){let o=a.debugger;if(o===void 0)continue;if(process.platform!=="linux"||!o.platforms.includes("linux")){n.push({id:`debugger-${a.id}-platform`,category:"unsupported-platform",message:`${a.name} does not support the Linux debugger recipe`});continue}let s=await Ie(o.runtimeExecutables,r.cwd,r.env);if(s!==void 0){n.push({id:`debugger-${a.id}-runtime`,category:"missing-runtime",message:`Runtime ${s} is unavailable. ${o.install}`});continue}if(!await $e(a.id,r.cwd,r.env)){n.push({id:`debugger-${a.id}-adapter`,category:"missing-adapter",message:`${a.name} is not installed. ${o.install}`});continue}await Ce(a.id,r.cwd,r.env)||n.push({id:`debugger-${a.id}-startup`,category:"adapter-startup",message:`${a.name} is installed but cannot start. ${o.install}`})}return{selections:t,actions:n}}i(Ae,"inspectDebuggerSetup");async function Te(r){let e=[...new Map([...r.detectedLanguageIds].map(L).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 ce(t.id,r.cwd,r.env);return{status:n.ok?"pass":"fail",message:`${t.name}: ${n.ok?"available":"unavailable"}`,detail:n.detail}}))}i(Te,"checkDebuggerAdapters");async function Ie(r,e,t){for(let n of r)if(!await E(n,e,t))return n}i(Ie,"firstMissingExecutable");async function $e(r,e,t){if(r==="elixir-ls-debug-adapter")try{return await $(t.PI_ELIXIR_LS_DEBUG_PATH??ue),!0}catch{return!1}if(r==="vsc-debugger")return(await y(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 $(t.PI_JS_DEBUG_PATH??de),!0}catch{return!1}if(r.startsWith("lldb-dap"))return await E(t.PI_LLDB_DAP_PATH??"lldb-dap-18",e,t)||await E("lldb-dap",e,t);if(r==="delve")return E(t.PI_DELVE_PATH??"dlv",e,t);if(r==="kotlin-debug-adapter")return E(t.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",e,t);if(r==="julia-debug-adapter")try{return await $(`${t.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia"}/Project.toml`),!0}catch{return!1}return r==="dart-debug-adapter"?E(t.PI_DART_PATH??"dart",e,t):(await y("python3",["-c","import importlib.util; raise SystemExit(importlib.util.find_spec('debugpy') is None)"],e,t)).ok}i($e,"adapterInstalled");async function Ce(r,e,t){return(await ce(r,e,t)).ok}i(Ce,"adapterAvailable");async function ce(r,e,t){if(r==="elixir-ls-debug-adapter")return I(t.PI_ELIXIR_LS_DEBUG_PATH??ue,e,t);if(r==="vsc-debugger")return y(t.PI_R_PATH??"R",["--vanilla","--quiet","-e","library(vscDebugger); cat(as.character(packageVersion('vscDebugger')))"],e,t);if(r==="dart-debug-adapter")return y(t.PI_DART_PATH??"dart",["--version"],e,t);if(r==="debugpy")return y("python3",["-c","import debugpy; print(debugpy.__version__)"],e,t);if(r==="delve")return y(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 y(t.PI_JULIA_PATH??"julia",[`--project=${a}`,"--startup-file=no","-e","using DebugAdapter"],e,t)}if(r==="kotlin-debug-adapter"){let a=await y(t.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",["--help"],e,t);return a.ok?y("java",["-version"],e,t):a}if(r==="netcoredbg"){let a=await y(t.PI_NETCOREDBG_PATH??"netcoredbg",["--version"],e,t);return a.ok?y("dotnet",["--version"],e,t):a}if(r.startsWith("lldb-dap")){let a=t.PI_LLDB_DAP_PATH??(await E("lldb-dap-18",e,t)?"lldb-dap-18":"lldb-dap");return y(a,["--version"],e,t)}if(r==="rdbg")return y(t.PI_RUBY_DEBUG_PATH??"rdbg",["--version"],e,t);if(r==="vscode-php-debug"){let a=await y(t.PI_PHP_PATH??"php",["-r","exit(extension_loaded('xdebug') ? 0 : 1);"],e,t);return a.ok?I(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 y(t.PI_LUA_PATH??"lua",["-v"],e,t);return a.ok?I(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 y(t.PI_BASH_PATH??"bash",["--version"],e,t);return a.ok?I(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 y(t.PI_PWSH_PATH??"pwsh",["--version"],e,t),o=t.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";return a.ok?I(`${o}/PowerShellEditorServices/Start-EditorServices.ps1`,e,t):a}let n=t.PI_JS_DEBUG_PATH??de;try{await $(n)}catch{return{ok:!1,detail:`${n} does not exist`}}return y(process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1]); console.log(process.version)",n],e,t)}i(ce,"probeAdapter");async function I(r,e,t){try{await $(r)}catch{return{ok:!1,detail:`${r} does not exist`}}return y(process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1])",r],e,t)}i(I,"probeAdapterFile");import Be from"node:path";import{fileURLToPath as Le}from"node:url";function pe(r){return{id:"debug-breakpoints",present(e,t){let n=r.get(t.source),a=r.sourceFile(t.source)??qe(e.source,t.cwd);if(a===void 0)return e;let o=r.breakpointsForFile(a,n?.source);if(o.length===0)return e;let s=je(o);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??""}${He(l)}`,compactSuffix:`${d.presentation?.compactSuffix??""}${Fe(l)}`}}})}}}}i(pe,"createBreakpointPresenter");function je(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(je,"groupByLine");function qe(r,e){if(r.startsWith("file://"))return Le(r);if(!/^[a-z][a-z\d+.-]*:/iu.test(r))return Be.resolve(e,r)}i(qe,"filesystemSource");function He(r){return r.map(e=>` ${e.verified?"\u25CF":"\u25CB"} breakpoint ${e.source} (${e.verified?"verified":"pending"})`).join("")}i(He,"renderAgentBreakpoints");function Fe(r){let t=r.filter(a=>a.verified).length===r.length?"\u25CF":"\u25CB",n=r.length===1?"breakpoint":`${r.length} breakpoints`;return` ${t} ${n}`}i(Fe,"renderUserBreakpoints");import j from"node:path";import{Text as M}from"@earendil-works/pi-tui";function G(r,e,t,n){return new M(`${n.fg("toolTitle",r)} ${n.fg("muted",`\xB7 ${ye(e,t)}`)}
2
- ${n.fg("accent","\u25C6 configure debugger")}`,0,0)}i(G,"renderDebugCall");function ge(r,e,t){return new M(`${fe(r,t)}
3
- ${t.fg("accent",Ue(e))}`,0,0)}i(ge,"renderDebugActionCall");function C(r,e,t){return new M(Oe(r,e,t).join(`
4
- `),0,0)}i(C,"renderDebugResult");function be(r,e){let t=[fe(r,e),me(r.status,e)];return r.stop?.frame!==void 0&&t.push(` ${e.fg("warning","\u25CF")} ${r.stop.frame.name} ${e.fg("muted",`\xB7 ${he(r.stop)}`)}`),t}i(be,"renderActiveDebugger");function Oe(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 ${he(r.stop)}`)}`));for(let o of r.stop.sourceLines){let s=o.current?t.fg("warning",">"):t.fg("dim","\u2502"),d=o.current?"text":"dim";n.push(`${s} ${String(o.lineNumber).padStart(4)} ${t.fg(d,o.content)}`)}let a=e?r.stop.variables:r.stop.variables.slice(0,6);if(a.length>0){n.push(t.fg("muted","Locals"));for(let o of a)n.push(` ${t.fg("accent",o.name.padEnd(16))} ${t.fg("toolOutput",o.value)}${o.type===void 0?"":t.fg("dim",` ${o.type}`)}`);a.length<r.stop.variables.length&&n.push(t.fg("muted",` \u2026 ${r.stop.variables.length-a.length} more`))}return n}if(n.push(me(r.status,t)),r.breakpoints.length>0){let a=r.breakpoints.filter(o=>o.verified).length;n.push(t.fg("muted",`${r.breakpoints.length} breakpoint${r.breakpoints.length===1?"":"s"} \xB7 ${a} verified`))}return n}i(Oe,"debugResultLines");function fe(r,e){return`${e.fg("toolTitle",r.options.adapter)} ${e.fg("muted",`\xB7 ${ye(r.options.program,r.options.cwd)}`)}`}i(fe,"debugIdentity");function Ue(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(Ue,"actionLabel");function me(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(me,"statusLine");function he(r){let e=r.frame?.source?.path??r.frame?.source?.name??"unknown";return`${j.basename(e)}:${r.frame?.line??"?"}`}i(he,"shortFrame");function ye(r,e){let t=j.relative(e,r),n=".".repeat(2),a=t===n||t.startsWith(`${n}${j.sep}`);return t.length>0&&!a?t:j.basename(r)}i(ye,"shortPath");function J(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(J,"debuggerSnapshotFromResult");function ve(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=>be(e,t),"renderSummary"),renderDetail:i(t=>C(e,!0,t),"renderDetail"),stop:i(()=>r.delete(e.source),"stop")})),"list")}}i(ve,"debuggerProcessProvider");import{spawn as B}from"node:child_process";import{randomBytes as De}from"node:crypto";import{rmSync as Ge}from"node:fs";import{mkdtemp as Je,readFile as Ee,rm as Ve}from"node:fs/promises";import xe from"node:net";import{tmpdir as We}from"node:os";import m from"node:path";import{spawn as Ne}from"node:child_process";import Me from"node:net";var P=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",a=>this.#t(a)),e.once("error",a=>this.#c(a)),e.once("close",()=>this.#c(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",a=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(a)}),n.once("error",a=>this.#c(a)),n.once("exit",(a,o)=>{this.#c(new Error(`Debug adapter exited${a===null?"":` with code ${a}`}${o===null?"":` (${o})`}`))}))}static start(e,t,n){let a=Ne(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,a)=>{let o=Me.createConnection({port:e,host:t}),s=i(d=>a(d),"fail");o.once("error",s),o.once("connect",()=>{o.off("error",s),n(new r(o,o))})})}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 a=this.#p++,o={seq:a,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(a),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(a),c(),l(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#o.set(a,{resolve:i(p=>d(p),"resolve"),reject:l,cleanup:c}),n.signal?.addEventListener("abort",b,{once:!0})});return this.#d(o),s}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let a=new Set(e),o=this.#b.findIndex(s=>a.has(s.event));return o>=0?Promise.resolve(this.#b.splice(o,1)[0]):this.#s!==void 0?Promise.reject(this.#s):new Promise((s,d)=>{let l={events:a,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"),a=/^Content-Length:\s*(\d+)$/imu.exec(n);if(a===null){this.#c(new Error("Debug adapter sent a frame without Content-Length"));return}let o=Number(a[1]),s=t+4;if(this.#r.length<s+o)return;let d=this.#r.subarray(s,s+o).toString("utf8");this.#r=this.#r.subarray(s+o);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 H=class{static{i(this,"DebugSessionManager")}#a=new Map;#u=new Set;create(e){let t=De(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){let n=m.resolve(e);return this.list().filter(a=>t===void 0||a.source===t).flatMap(a=>[...a.breakpoints.values()]).filter(a=>m.resolve(a.file)===n)}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}`)):Ee(t,"utf8")}async addBreakpoint(e,t,n){let a=this.get(e),o=this.sourceFile(e);if(a===void 0||o===void 0)throw new Error(`Unknown debug source ${e}`);if(a.status==="terminated")throw new Error("Cannot add a breakpoint to a terminated session");let s=De(5).toString("hex"),d={id:s,source:`${a.source}/breakpoint/${s}`,file:o,line:t,verified:!1};return a.breakpoints.set(s,d),a.client!==void 0&&await this.#d(a,a.client,o,n),this.#e(a),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 Je(m.join(We(),"pi-powershell-debug-")));let a=Qe(e.options,e.adapterTemporaryDirectory),o=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):P.start(a.command,a.args,e.options.cwd);e.client=o,e.controlClient=o,e.clients=[o],e.options.adapter==="node"&&(e.targetReady=new Promise(s=>{e.resolveTargetReady=s})),e.status="running",this.#e(e);try{e.options.adapter!=="r"&&await we(o,a.adapterID,t);let s=o.waitForAnyEvent(["initialized"],3e4,t),d=o.request(a.request,a.launch,{signal:t});await s,await this.#n(e,o,t);let l=o.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??[o])u.close();e.adapterProcess?.kill(),await V(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??[o])d.close();throw e.adapterProcess?.kill(),await V(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 a=x(e),o=e.stop.threadId;return await a.request(t,{threadId:o},{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 a=/\/breakpoint\/([a-f\d]{10})$/u.exec(e);if(a!==null){let o=n.breakpoints.get(a[1]);if(o===void 0)throw new Error(`Unknown debug breakpoint ${e}`);n.breakpoints.delete(o.id),n.client!==void 0&&n.status!=="terminated"&&await this.#d(n,n.client,o.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 o of n.clients??[n.client])o.close();n.adapterProcess?.kill()}await V(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();e.adapterProcess?.kill(),e.adapterTemporaryDirectory!==void 0&&Ge(e.adapterTemporaryDirectory,{recursive:!0,force:!0})}this.#a.clear()}async#o(e){let t=await q(),n=process.env.PI_RUBY_DEBUG_PATH??"rdbg";return e.adapterProcess=B(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"]}),await Se(e.adapterProcess,"Debugger can attach via TCP/IP","rdbg"),P.connect(t)}async#b(e){let t=await q(),n=process.env.PI_DELVE_PATH??"dlv";return e.adapterProcess=B(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 Se(e.adapterProcess,"DAP server listening","Delve"),P.connect(t)}async#i(e){let t=await q(),n=process.env.PI_JULIA_PATH??"julia",a=process.env.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia",o='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=B(n,["--startup-file=no","--history-file=no",`--project=${a}`,"-e",o,String(t)],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),Pe(e.adapterProcess,`DebugAdapter.jl:${String(t)}`),await new Promise(s=>setTimeout(s,25)),ke(t,"DebugAdapter.jl")}async#f(e){let t=xe.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 a=new Promise((d,l)=>{t.once("connection",u=>{t.close();let c=P.fromSocket(u,2);c.onEvent(b=>this.#r(e,b)),d(c)}),t.once("error",l)}),o=process.env.PI_R_PATH??"R";e.rPromptInputs=[],e.rAtBrowserPrompt=!1,e.rStarted=!1,e.adapterProcess=B(o,["--vanilla","--quiet"],{cwd:e.options.cwd,env:process.env,stdio:["pipe","pipe","pipe"]}),Pe(e.adapterProcess,`vscDebugger:${String(n.port)}`),this.#p(e);let s=Xe({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
- `),Ze(a,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=_(t.body),a=typeof n.reason=="string"?n.reason:"",o=typeof n.text=="string"?n.text:"";if(!(a!=="writeToStdin"||o.length===0)){if(n.when==="browserPrompt"&&e.rAtBrowserPrompt===!0){e.rAtBrowserPrompt=!1,e.adapterProcess?.stdin?.write(`${o}
11
- `);return}e.rPromptInputs?.push(o)}}#p(e){let t="";e.adapterProcess?.stdout?.on("data",n=>{for(t+=n.toString("utf8");;){let a=/Browse\[\d+\]> /u.exec(t),o=/(?:^|\r?\n)__PI_R_PROMPT__(?:\r?\n|$)/u.exec(t),s=a?.index??Number.POSITIVE_INFINITY,d=o?.index??Number.POSITIVE_INFINITY;if(!Number.isFinite(s)&&!Number.isFinite(d)){t=t.slice(-128);return}if(s<d){t=t.slice(s+(a?.[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+(o?.[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 q(),n=process.env.PI_JS_DEBUG_PATH??"/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js";e.adapterProcess=B(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 Ye(e.adapterProcess);let a=await ke(t);return a.onReverseRequest(this.#g(e,t)),a}#g(e,t){return async n=>{if(n.command!=="startDebugging")throw new Error(`Client does not support reverse request ${n.command}`);let a=_(n.arguments),o=_(a.configuration),s=await P.connect(t);e.clients?.push(s),s.onReverseRequest(this.#g(e,t)),await we(s,"pwa-node");let d=s.waitForEvent("initialized"),l=s.request(typeof a.request=="string"?a.request:"launch",{...o,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[m.join(m.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 a=new Set([...e.breakpoints.values()].map(o=>o.file));for(let o of a)await this.#d(e,t,o,n)}async#d(e,t,n,a){let o=[...e.breakpoints.values()].filter(d=>d.file===n),s=await t.request("setBreakpoints",{source:{path:n,name:m.basename(n)},breakpoints:o.map(({line:d})=>({line:d})),sourceModified:!1},{signal:a});for(let[d,l]of o.entries())l.verified=s.breakpoints?.[d]?.verified===!0}async#t(e,t){let n=await x(e).waitForAnyEvent(["stopped","terminated","exited","loadedSource","breakpoint","custom"],3e4,t),a=_(n.body);if(n.event==="custom"&&e.options.adapter==="r"){await this.#t(e,t);return}if(n.event==="loadedSource"){let o=_(a.source),s=typeof o.path=="string"?m.resolve(o.path):void 0,d=s===void 0?void 0:[...e.breakpoints.values()].find(l=>m.resolve(l.file)===s)?.file;d!==void 0&&await this.#d(e,x(e),d,t),await this.#t(e,t);return}if(n.event==="breakpoint"){let o=_(a.breakpoint),s=_(o.source);for(let d of e.breakpoints.values())o.verified===!0&&typeof o.line=="number"&&o.line===d.line&&typeof s.path=="string"&&m.resolve(s.path)===m.resolve(d.file)&&(d.verified=!0);await this.#t(e,t);return}if(a.reason==="exit"){e.status="terminated",e.stop=void 0,this.#e(e);return}if(e.options.adapter==="node"&&a.reason==="entry"){await this.#n(e,x(e),t);let o=typeof a.threadId=="number"?a.threadId:1;await x(e).request("continue",{threadId:o},{signal:t}),await this.#t(e,t);return}if((e.options.adapter==="dart"||e.options.adapter==="kotlin")&&a.reason==="entry"){let o=x(e);if(await this.#n(e,o,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,o,t)}let s=typeof a.threadId=="number"?a.threadId:1;await o.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(o=>m.resolve(o.file)===m.resolve(e.stop?.frame?.source?.path??"")&&o.line===e.stop?.frame?.line)){let o=e.stop.threadId;e.stopGeneration--,e.stop=void 0,e.status="running",await x(e).request("continue",{threadId:o},{signal:t}),await this.#t(e,t);return}e.options.adapter==="shell"&&this.#e(e)}async#m(e,t,n=!0){let a=x(e),o=_(t.body),s=(await a.request("threads")).threads?.[0]?.id,d=typeof o.threadId=="number"?o.threadId:s;if(d===void 0)throw new Error("Debugger stopped without a thread");let l=(await Ke(a,d,e.options.adapter==="dart")).stackFrames?.[0];if(l?.source?.path!==void 0)for(let c of e.breakpoints.values())m.resolve(c.file)===m.resolve(l.source.path)&&c.line===l.line&&(c.verified=!0);let u=[];if(l!==void 0){let c=(await a.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 a.request("variables",{variablesReference:p.variablesReference,start:0,count:100});u.push(...g.variables??[])}}e.stopGeneration++,e.stop={generation:e.stopGeneration,reason:typeof o.reason=="string"?o.reason:"stopped",threadId:d,...l===void 0?{}:{frame:l},variables:u,sourceLines:l===void 0?[]:await ze(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 ze(r){let e=r.source?.path;if(e===void 0)return[];try{let t=(await Ee(e,"utf8")).split(/\r?\n/u),n=Math.max(1,r.line-2),a=Math.min(t.length,r.line+2);return t.slice(n-1,a).map((o,s)=>({lineNumber:n+s,content:o,current:n+s===r.line}))}catch{return[]}}i(ze,"sourceWindow");async function Ke(r,e,t){let n=Date.now()+1e3,a;do{try{let o=await r.request("stackTrace",{threadId:e});if(!t||(o.stackFrames?.length??0)>0)return o;a=new Error("Debugger stack is not ready")}catch(o){if(a=o,!t)throw o}await new Promise(o=>setTimeout(o,25))}while(Date.now()<n);throw a instanceof Error?a:new Error("Could not read debugger stack")}i(Ke,"requestStackTrace");function F(r){let e=[`Session: ${r.source}`,`Adapter: ${r.options.adapter}`,`Program: ${m.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} ${m.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(F,"renderDebugSession");function x(r){if(r.client===void 0)throw new Error("Debug adapter is not running");return r.client}i(x,"requiredClient");function _(r){return typeof r=="object"&&r!==null?r:{}}i(_,"asRecord");function Xe(r){let e=JSON.stringify(r);return`Content-Length: ${Buffer.byteLength(e,"utf8")}\r
16
- \r
17
- ${e}`}i(Xe,"dapFrame");function we(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(we,"initializeClient");function q(){return new Promise((r,e)=>{let t=xe.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(a=>a===void 0?r(n.port):e(a))})})}i(q,"availablePort");function Pe(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(Pe,"traceAdapterProcess");function Ze(r,e,t){return new Promise((n,a)=>{let o=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),s=i(()=>{clearTimeout(o),e.off("error",d),e.off("exit",l)},"cleanup"),d=i(u=>{s(),t.close(),e.killed||e.kill(),a(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(Ze,"waitForRAdapterConnection");function Se(r,e,t){return new Promise((n,a)=>{let o=[r.stdout,r.stderr].filter(u=>u!==null),s=setTimeout(()=>a(new Error(`Timed out starting ${t} server`)),5e3),d=i(()=>{clearTimeout(s);for(let u of o)u.off("data",l)},"cleanup"),l=i(u=>{u.toString("utf8").includes(e)&&(d(),n())},"onData");for(let u of o)u.on("data",l);r.once("error",u=>{d(),a(u)}),r.once("exit",u=>{d(),a(new Error(`${t} server exited with code ${String(u)}`))})})}i(Se,"waitForAdapterReady");function Ye(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let a=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),o=i(s=>{s.toString("utf8").includes("Debug server listening")&&(clearTimeout(a),n.off("data",o),e())},"onData");n.on("data",o),r.once("error",t),r.once("exit",s=>t(new Error(`js-debug server exited with code ${s}`)))})}i(Ye,"waitForJsDebugReady");async function ke(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await P.connect(r)}catch(a){t=a,await new Promise(o=>setTimeout(o,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}i(ke,"connectWithRetry");async function V(r){r.adapterTemporaryDirectory!==void 0&&(await Ve(r.adapterTemporaryDirectory,{recursive:!0,force:!0}),r.adapterTemporaryDirectory=void 0)}i(V,"removeAdapterTemporaryDirectory");function Qe(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")return{command:"python3",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??"/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:process.env.PI_LLDB_DAP_PATH??"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:m.dirname(m.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??m.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:m.join(n,"bashdb_dir/bashdb"),pathBashdbLib:m.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",`& '${m.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${m.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${m.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:[m.join(m.dirname(r.program),"**","*.js")]}}}i(Qe,"adapterRecipe");var nt=D.Object({adapter:tt(["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:D.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:D.Optional(D.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:D.Optional(D.Array(D.String(),{description:"Arguments passed to the debugged program."})),mainClass:D.Optional(D.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:D.Optional(D.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function at(r){let e=oe("debugger")??new H,t=new Map,n=_e(e,"debugger-source"),a=_e(e,"debugger-input"),o=ne(r).add(ve(e)),s=pe(e),d={protocol:X,apiVersion:Z,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:"",h=e.get(f),v=e.sourceFile(f);if(h===void 0||v===void 0)throw new Error("Debugger source header lost its session");let w=S.relative(h.options.cwd,v),k=Array.isArray(g.views)?g.views.filter(U=>typeof U=="string"):[],R=typeof g.offset=="number"?g.offset:1,T=typeof g.limit=="number"?g.limit:void 0,O=T===void 0?String(R):`${R}-${R+T-1}`;return Q(p.lastComponent,{tool:"debug file",primary:{text:`${w}:${O}`,color:"accent",underline:!0},qualifiers:k.length===0?[]:[{text:`views ${k.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},...k.length===0?[]:[{label:"views",value:k.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. Set adapter to elixir for Elixir or r for R. 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:ee,apiVersion:te,id:"debugger",setup(u){u.addResolver({resolver:a}),u.tool("insert").addSemanticHandler({matches:i(c=>ot(c,e),"matches"),execute:i(async(c,b)=>{let p=b,g=Re(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"),h=await e.addBreakpoint(p.path,f.lineNumber,c.signal);return{source:h.source,summary:`Breakpoint ${h.source} created at ${S.relative(g.options.cwd,h.file)}:${h.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:h.file,line:h.line,verified:h.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 st(e,g,p.text,c.signal),{source:g.source,summary:F(g),data:ut(e,g,p.text)}},"execute")}),u.tool("delete").addSemanticHandler({matches:i(c=>it(c,e),"matches"),execute:i(async(c,b)=>{let p=b.path,g=Re(e,p),f=e.snapshot(g);t.set(p,f);let h=p.includes("/breakpoint/");await e.delete(p,c.signal);let v=h?e.snapshot(g):{...f,status:"terminated"};return{source:p,summary:`Deleted ${p}.`,data:{kind:h?"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)):J(A(b)&&"details"in b?b.details:b)!==void 0},renderCall(b,p,g){let f=b,h=f.path===void 0?void 0:e.get(f.path),v=f.path===void 0?void 0:t.get(f.path),w=g.state;h!==void 0?w.snapshot=e.snapshot(h):v!==void 0&&(w.snapshot=v);let k=w.snapshot;if(k===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:e.breakpoint(f.path)??k.breakpoints.find(U=>U.source===f.path),T=f.path===void 0?void 0:e.sourceFile(f.path),O=c==="delete"?R===void 0?"delete-session":`delete-breakpoint ${S.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&T!==void 0?`breakpoint ${S.basename(T)}:${ct(f)}`:f.text??"debug action";return ge(k,O,p)},renderResult(b,p,g){let f=J(b.details);if(f===void 0)throw new Error("Debugger result is missing its session");return C(f,p.expanded,g)}})}};await Promise.all([K(r,le),Y(r,d)]),await re(r,l),r.registerTool(rt({name:"debug",label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",promptGuidelines:["Use the returned debug source resource rather than the filesystem path when setting breakpoints; its anchors are checked against fresh text without editing that text.","Use java for Java, kotlin for Kotlin, lldb-dap for C, C++, Rust, Swift, or Zig, and julia for Julia.","Use lldb-dap for C, C++, Rust, Swift, or Zig; use julia for Julia.","Use elixir for Elixir; use r for R."],description:"Use debug to create a configured local debugger session. This does not launch the program yet. Sessions survive extension reloads and keep the same debug: resources. Read the returned debug source, set breakpoints with insert, then start and control execution by inserting commands on the session resource.",parameters:nt,async execute(u,c,b,p,g){let f=S.resolve(g.cwd,c.cwd??"."),h=S.resolve(f,c.program);try{await et(h);let v=e.create({adapter:c.adapter,program:h,sourceFile:S.resolve(f,c.source??c.program),args:c.args??[],cwd:f,...c.mainClass===void 0?{}:{mainClass:c.mainClass}}),w=dt(e,v);return{content:[{type:"text",text:`${F(v)}
20
- Source: ${w.sourceResource}
21
- Breakpoints: ${w.breakpointsResource}
22
-
23
- Next: read ${w.sourceResource} with views ["anchors"], then insert a breakpoint at an anchor.`}],details:w}}catch(v){return{content:[{type:"text",text:v instanceof Error?v.message:String(v)}],details:{adapter:c.adapter,program:h,cwd:f,status:"failed"},isError:!0}}},renderCall(u,c){let b=S.resolve(process.cwd(),typeof u.cwd=="string"?u.cwd:"."),p=S.resolve(b,typeof u.program=="string"?u.program:"program");return G(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 C(p,c.expanded,b);let g=u.details;return G(g.adapter,g.program,g.cwd,b)}})),r.on("session_shutdown",u=>{if(o(),u.reason==="reload"){ae("debugger",e);return}ie("debugger",e),e.dispose()})}i(at,"registerDebugger");function _e(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 a=r.sourceFile(t);if(a!==void 0)return[pt(a,await r.readSource(t))];if(t===`${n.source}/breakpoints`)return[{type:"text",text:lt(n)}];let o=r.breakpoint(t);if(t!==n.source&&o===void 0)throw new Error(`Unknown debug resource ${t}`);return[{type:"text",text:o===void 0?F(n):`Breakpoint: ${o.source}
24
- File: ${o.file}
25
- Line: ${o.line}
26
- Status: ${o.verified?"verified":"pending"}`}]}}})}}}i(_e,"createDebugResourceResolver");function ot(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(ot,"matchesDebugInsert");function it(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(it,"matchesDebugDelete");async function st(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(st,"executeSessionCommand");function dt(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:a,verified:o})=>({source:t,file:n,line:a,verified:o})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(dt,"debugDetails");function ut(r,e,t){return{kind:"debug-command",command:t,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:n,file:a,line:o,verified:s})=>({source:n,file:a,line:o,verified:s})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(ut,"debugActionData");function lt(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(lt,"renderBreakpointList");function Re(r,e){let t=r.get(e);if(t===void 0)throw new Error(`Unknown debug session ${e}`);return t}i(Re,"requiredSession");function ct(r){let e=A(r)&&typeof r.anchor=="string"?r.anchor:void 0;return/^(\d+)#/u.exec(e??"")?.[1]??e??"selected line"}i(ct,"breakpointLine");function A(r){return typeof r=="object"&&r!==null}i(A,"isRecord");function pt(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(pt,"debugSourceContent");export{at as default};
package/dist/entry-17.js DELETED
@@ -1 +0,0 @@
1
- import"./chunk-K4ZMRDEI.js";
@@ -1,14 +0,0 @@
1
- # Evaluation
2
-
3
- Pi Agent IDE is still experimental. Evaluation compares it with vanilla Pi instead of assuming that richer tools always improve agent behavior.
4
-
5
- Current studies use repeatable coding tasks and editing gyms. They inspect:
6
-
7
- - task completion and correctness;
8
- - tool calls and failed tool calls;
9
- - input, output, and cache tokens;
10
- - unnecessary reads and repeated searches;
11
- - edit retries and recovery from stale context;
12
- - cases where specialized tools make a task harder.
13
-
14
- Results depend on the model, prompt, repository, and task. A result from one suite is evidence about that suite, not a universal performance claim.
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-17.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../dist/entry-22.js";
2
- export { default } from "../../../dist/entry-22.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-26.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-28.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-34.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-42.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../dist/entry-50.js";
2
- export { default } from "../../../dist/entry-50.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-51.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-53.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-55.js";
@@ -1 +0,0 @@
1
- export * from "../../../dist/entry-74.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../dist/entry-76.js";
2
- export { default } from "../../../dist/entry-76.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../../../dist/entry-23.js";
2
- export { default } from "../../../../../../../../dist/entry-23.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../dist/entry-22.js";
2
- export { default } from "../../../../../../dist/entry-22.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../../../dist/entry-77.js";
2
- export { default } from "../../../../../../../../dist/entry-77.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../dist/entry-76.js";
2
- export { default } from "../../../../../../dist/entry-76.js";
@@ -1 +0,0 @@
1
- export * from "../../../../dist/entry-37.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../dist/entry-47.js";
2
- export { default } from "../../../../../../dist/entry-47.js";
@@ -1 +0,0 @@
1
- export * from "../../../../dist/entry-43.js";
@@ -1,2 +0,0 @@
1
- export * from "../../../../../../dist/entry-50.js";
2
- export { default } from "../../../../../../dist/entry-50.js";