pi-agent-ide 0.6.1 → 0.6.3

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 (222) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +82 -30
  3. package/assets/summary/debugging.png +0 -0
  4. package/assets/summary/editing.png +0 -0
  5. package/assets/summary/read.png +0 -0
  6. package/assets/summary/search-and-replace.png +0 -0
  7. package/assets/summary/search.png +0 -0
  8. package/assets/summary/settings.png +0 -0
  9. package/assets/summary/terminal.png +0 -0
  10. package/assets/summary/thumbs/debugging.png +0 -0
  11. package/assets/summary/thumbs/editing.png +0 -0
  12. package/assets/summary/thumbs/read.png +0 -0
  13. package/assets/summary/thumbs/search-and-replace.png +0 -0
  14. package/assets/summary/thumbs/search.png +0 -0
  15. package/assets/summary/thumbs/settings.png +0 -0
  16. package/assets/summary/thumbs/terminal.png +0 -0
  17. package/assets/summary/thumbs/user_terminal.png +0 -0
  18. package/assets/summary/user_terminal.png +0 -0
  19. package/dist/{chunk-4KUFOHWP.js → chunk-3E2NTWCN.js} +1 -1
  20. package/dist/chunk-7WCZOO5I.js +1 -0
  21. package/dist/chunk-CEX3VOJ7.js +2 -0
  22. package/dist/{chunk-2527OQ4Y.js → chunk-HMLH43ZS.js} +1 -1
  23. package/dist/chunk-LVWMWWWF.js +28 -0
  24. package/dist/{chunk-HKMBQLEK.js → chunk-QDLTO5PH.js} +1 -1
  25. package/dist/{chunk-Z3VC3S2T.js → chunk-QIK2E64R.js} +1 -1
  26. package/dist/chunk-T7CZIACQ.js +27 -0
  27. package/dist/chunk-VXD6FZP5.js +5 -0
  28. package/dist/entry-1.js +1 -1
  29. package/dist/entry-2.js +1 -1
  30. package/dist/entry-31.js +8 -7
  31. package/dist/entry-34.js +1 -1
  32. package/dist/entry-36.js +1 -1
  33. package/dist/entry-37.js +1 -1
  34. package/dist/entry-51.js +9 -10
  35. package/dist/entry-53.js +1 -1
  36. package/dist/entry-54.js +1 -1
  37. package/dist/entry-55.js +1 -1
  38. package/dist/entry-56.js +1 -1
  39. package/dist/entry-57.js +1 -1
  40. package/dist/entry-58.js +1 -1
  41. package/dist/entry-59.js +1 -1
  42. package/dist/entry-60.js +1 -0
  43. package/dist/entry-61.js +1 -1
  44. package/dist/entry-63.js +1 -1
  45. package/dist/entry-64.js +0 -1
  46. package/dist/entry-65.js +1 -1
  47. package/dist/entry-66.js +1 -1
  48. package/dist/entry-67.js +1 -1
  49. package/dist/entry-68.js +1 -1
  50. package/dist/entry-69.js +1 -0
  51. package/dist/entry-70.js +1 -1
  52. package/dist/entry-72.js +1 -1
  53. package/dist/entry-73.js +0 -1
  54. package/dist/entry-74.js +1 -1
  55. package/dist/entry-75.js +1 -315
  56. package/dist/entry-76.js +1 -30
  57. package/dist/entry-77.js +324 -2
  58. package/dist/entry-78.js +30 -1
  59. package/dist/entry-79.js +2 -1
  60. package/dist/entry-80.js +1 -3
  61. package/dist/entry-81.js +1 -3
  62. package/dist/entry-82.js +3 -1
  63. package/dist/entry-83.js +3 -1
  64. package/dist/entry-84.js +1 -1
  65. package/dist/entry-85.js +1 -0
  66. package/dist/entry-86.js +1 -0
  67. package/dist/pi-agent-ide.js +1 -1
  68. package/docs/agent-guides/apply.md +1 -1
  69. package/docs/agent-guides/debugger.md +1 -1
  70. package/docs/agent-guides/editing.md +4 -0
  71. package/docs/agent-guides/terminal.md +1 -1
  72. package/node_modules/pi-agent-doctor/package.json +1 -1
  73. package/node_modules/pi-agent-documentation/package.json +1 -1
  74. package/node_modules/pi-agent-filesystem/package.json +6 -6
  75. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  76. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  77. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  78. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  79. package/node_modules/pi-agent-ide-ast/package.json +10 -9
  80. package/node_modules/pi-agent-ide-ast/src/search-presentation.ts +117 -0
  81. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +20 -2
  82. package/node_modules/pi-agent-ide-changes/package.json +7 -7
  83. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  84. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  85. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  86. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  87. package/node_modules/pi-agent-image/package.json +2 -2
  88. package/node_modules/pi-agent-invariant/package.json +1 -1
  89. package/node_modules/pi-agent-pdf/package.json +2 -2
  90. package/node_modules/pi-agent-read/package.json +7 -7
  91. package/node_modules/pi-agent-resource/package.json +1 -1
  92. package/node_modules/pi-agent-search/package.json +4 -4
  93. package/node_modules/pi-agent-search-text/package.json +14 -6
  94. package/node_modules/pi-agent-search-text/runtime/entry-54.js +1 -0
  95. package/node_modules/pi-agent-search-text/src/persisted-result.ts +9 -7
  96. package/node_modules/pi-agent-search-text/src/search-renderer.ts +10 -4
  97. package/node_modules/pi-agent-search-text/src/search-result.ts +8 -1
  98. package/node_modules/pi-agent-text/package.json +3 -3
  99. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  100. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  101. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  102. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-60.js +2 -0
  103. package/node_modules/pi-agent-text-editor/package.json +26 -26
  104. package/node_modules/pi-agent-text-editor/runtime/entry-75.js +0 -1
  105. package/node_modules/pi-agent-text-editor/runtime/entry-76.js +1 -0
  106. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +1 -1
  107. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +20 -11
  108. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +52 -11
  109. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +7 -4
  110. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +24 -3
  111. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  112. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  113. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  114. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-79.js +2 -0
  115. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  116. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +1 -0
  117. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  118. package/node_modules/pi-agent-tool-ui/runtime/entry-81.js +1 -0
  119. package/node_modules/pi-agent-web/package.json +7 -7
  120. package/node_modules/pi-agent-web-html/package.json +3 -3
  121. package/node_modules/pi-agent-web-image/package.json +4 -4
  122. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  123. package/node_modules/pi-agent-web-pdf/runtime/entry-85.js +2 -0
  124. package/node_modules/pi-agent-web-text/package.json +4 -4
  125. package/node_modules/pi-agent-web-text/runtime/entry-86.js +2 -0
  126. package/package.json +35 -35
  127. package/src/api/plugin-protocol.ts +10 -4
  128. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  129. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  130. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  131. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  132. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  133. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  134. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  135. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  136. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  137. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-85.js +2 -0
  138. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  139. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-86.js +2 -0
  140. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +2 -0
  141. package/src/extensions/pi-agent-read/package.json +7 -7
  142. package/src/extensions/pi-agent-search/package.json +4 -4
  143. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -6
  144. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +1 -0
  145. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-54.js +1 -0
  146. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/persisted-result.ts +9 -7
  147. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +10 -4
  148. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +8 -1
  149. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  150. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  151. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  152. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  153. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-59.js +1 -0
  154. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-60.js +2 -0
  155. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  156. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  157. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  158. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-79.js +2 -0
  159. package/src/extensions/pi-agent-text-editor/runtime/entry-75.js +0 -1
  160. package/src/extensions/pi-agent-text-editor/runtime/entry-76.js +1 -0
  161. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +2 -0
  162. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +1 -1
  163. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +20 -11
  164. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +52 -11
  165. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +7 -4
  166. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +24 -3
  167. package/src/plugins/pi-agent-ide-ast/package.json +10 -9
  168. package/src/plugins/pi-agent-ide-ast/src/search-presentation.ts +117 -0
  169. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +20 -2
  170. package/src/plugins/pi-agent-ide-changes/package.json +7 -7
  171. package/src/plugins/pi-agent-ide-debugger/index.ts +32 -10
  172. package/src/plugins/pi-agent-ide-debugger/src/renderer.ts +10 -1
  173. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +39 -0
  174. package/src/plugins/pi-agent-ide-debugger/src/ui.ts +42 -5
  175. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  176. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  177. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  178. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  179. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +88 -9
  180. package/src/plugins/pi-agent-ide-terminal/src/screen-image.ts +6 -2
  181. package/src/plugins/pi-agent-ide-vision/index.ts +2 -1
  182. package/src/plugins/pi-agent-ide-vision/src/vision.ts +17 -3
  183. package/assets/gallery/apply-editing.png +0 -0
  184. package/assets/gallery/debugging.png +0 -0
  185. package/assets/gallery/read-web.png +0 -0
  186. package/assets/gallery/search-replace.png +0 -0
  187. package/assets/gallery/terminal.png +0 -0
  188. package/assets/gallery/tool-editing.png +0 -0
  189. package/dist/chunk-4LDOV7QS.js +0 -28
  190. package/dist/chunk-I6Y3W4X6.js +0 -27
  191. package/dist/chunk-YEQOQMU7.js +0 -5
  192. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-54.js +0 -2
  193. package/node_modules/pi-agent-text-editor/runtime/entry-60.js +0 -1
  194. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-76.js +0 -2
  195. package/node_modules/pi-agent-tool-call-interception/runtime/entry-78.js +0 -1
  196. package/node_modules/pi-agent-tool-ui/runtime/entry-79.js +0 -1
  197. package/node_modules/pi-agent-web/runtime/entry-80.js +0 -2
  198. package/node_modules/pi-agent-web-html/runtime/entry-81.js +0 -2
  199. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-81.js +0 -2
  200. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-82.js +0 -2
  201. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-80.js +0 -2
  202. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-54.js +0 -2
  203. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-55.js +0 -1
  204. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-76.js +0 -2
  205. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-77.js +0 -2
  206. package/src/extensions/pi-agent-text-editor/runtime/entry-59.js +0 -1
  207. package/src/extensions/pi-agent-text-editor/runtime/entry-60.js +0 -1
  208. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-53.js +0 -0
  209. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-55.js +0 -0
  210. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-56.js +0 -0
  211. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-57.js +0 -0
  212. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-58.js +0 -0
  213. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-59.js +0 -0
  214. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-77.js +0 -0
  215. /package/node_modules/{pi-agent-web-image → pi-agent-web}/runtime/entry-82.js +0 -0
  216. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-83.js +0 -0
  217. /package/node_modules/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-84.js +0 -0
  218. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-83.js +0 -0
  219. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-84.js +0 -0
  220. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-56.js +0 -0
  221. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-57.js +0 -0
  222. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-58.js +0 -0
@@ -0,0 +1,27 @@
1
+ import{a as le,b as ce,c as pe}from"./chunk-ESPNEJHK.js";import{a as ue}from"./chunk-M5IVSCR2.js";import{e as Q,f as ee}from"./chunk-T7I2VX3J.js";import{a as te}from"./chunk-MGCHOGQD.js";import{a as Y,b as Z}from"./chunk-T6LX2RX5.js";import{a as de}from"./chunk-L7JMDDSD.js";import{a as ie,b as se}from"./chunk-O6LE42GK.js";import{a as I}from"./chunk-K5G4FDXD.js";import{c as oe}from"./chunk-YHUTTZC6.js";import{a as ae}from"./chunk-6CZO43OH.js";import{a as re,b as ne}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{d as S,e as y}from"./chunk-N34ATN52.js";import{a as i}from"./chunk-EI7MMDWY.js";import x from"node:path";import{access as dt}from"node:fs/promises";import{StringEnum as ut}from"@earendil-works/pi-ai";import{defineTool as lt}from"@earendil-works/pi-coding-agent";import{Type as D}from"typebox";import{access as j}from"node:fs/promises";async function $(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}i($,"resolvePythonDebuggerCommand");var ge=[{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"}],J=[{id:"dart-debug-adapter",name:"Dart debug adapter",kind:"debugger",languages:["dart"],executables:["dart"],dependencies:["Dart SDK 3.13.3"],documentation:"https://github.com/dart-lang/sdk/tree/main/third_party/pkg/dap",debugger:{runtimeExecutables:["dart"],adapterExecutables:["dart"],platforms:["linux","win32"],install:"Install Dart SDK 3.13.3 from the official Dart archive."}},{id:"debugpy",name:"debugpy",kind:"debugger",languages:["python"],executables:["python3"],dependencies:["debugpy"],documentation:"https://github.com/microsoft/debugpy",debugger:{runtimeExecutables:["python3"],adapterExecutables:["python3"],platforms:["linux","win32"],install:"Install Python 3 and debugpy for that interpreter."}},{id:"delve",name:"Delve",kind:"debugger",languages:["go"],executables:["dlv"],dependencies:["github.com/go-delve/delve/cmd/dlv@v1.25.2"],documentation:"https://github.com/go-delve/delve/tree/master/Documentation/api/dap",debugger:{runtimeExecutables:["go"],adapterExecutables:["dlv"],platforms:["linux","win32"],install:"Install Go and Delve. Native Windows support requires amd64."}},{id:"elixir-ls-debug-adapter",name:"ElixirLS debug adapter",kind:"debugger",languages:["elixir"],executables:["elixir","mix"],dependencies:["Elixir","Erlang/OTP","ElixirLS 0.31.1"],documentation:"https://github.com/elixir-lsp/elixir-ls",debugger:{runtimeExecutables:["elixir","mix"],adapterExecutables:["debug_adapter.sh","debug_adapter.bat"],platforms:["linux","win32"],install:"Install compatible Erlang/OTP and Elixir releases plus ElixirLS 0.31.1. Use debug_adapter.bat on Windows."}},{id:"vsc-debugger",name:"vscDebugger",kind:"debugger",languages:["r"],executables:["R"],dependencies:["R 4.5.3","R6 2.6.1","jsonlite 2.0.0","vscDebugger 0.5.9"],documentation:"https://manuelhentschel.github.io/vscDebugger/",debugger:{runtimeExecutables:["R"],adapterExecutables:["R"],platforms:["linux","win32"],install:"Install R 4.5.3 and vscDebugger 0.5.9 for that R installation."}},{id:"julia-debug-adapter",name:"DebugAdapter.jl",kind:"debugger",languages:["julia"],executables:["julia"],dependencies:["Julia 1.13.0","DebugAdapter.jl 3.2.1"],documentation:"https://github.com/julia-vscode/DebugAdapter.jl",debugger:{runtimeExecutables:["julia"],adapterExecutables:["julia"],platforms:["linux"],install:"Install Julia 1.13.0 and add DebugAdapter.jl 3.2.1 to /opt/pi-debug-adapters/julia."}},{id:"kotlin-debug-adapter",name:"Kotlin Debug Adapter",kind:"debugger",languages:["java","kotlin"],executables:["kotlin-debug-adapter"],dependencies:["fwcd/kotlin-debug-adapter 0.4.4","Temurin JDK 21.0.8+9","Kotlin compiler 2.2.20 for Kotlin builds"],documentation:"https://github.com/fwcd/kotlin-debug-adapter",debugger:{runtimeExecutables:["java"],adapterExecutables:["kotlin-debug-adapter"],platforms:["linux"],install:"Install Temurin JDK 21.0.8+9 and fwcd/kotlin-debug-adapter 0.4.4. Compile the target with debug information before launching it."}},{id:"netcoredbg",name:"NetCoreDbg",kind:"debugger",languages:["csharp"],executables:["netcoredbg"],dependencies:["Samsung/netcoredbg 3.2.0-1092",".NET SDK 8"],documentation:"https://github.com/Samsung/netcoredbg",debugger:{runtimeExecutables:["dotnet"],adapterExecutables:["netcoredbg"],platforms:["linux","win32"],install:"Install .NET SDK 8 and NetCoreDbg 3.2.0-1092. On Windows, ensure the selected dotnet SDK is on PATH."}},{id:"lldb-dap",name:"lldb-dap",kind:"debugger",languages:["c","cpp","rust"],executables:["lldb-dap-18","lldb-dap"],dependencies:["lldb-18"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:[],adapterExecutables:["lldb-dap-18","lldb-dap"],platforms:["linux"],install:"Install LLDB 18 and compile the target with debug information."}},{id:"lldb-dap-swift",name:"lldb-dap for Swift",kind:"debugger",languages:["swift"],executables:["lldb-dap"],dependencies:["Swift 6.3.3 toolchain"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:["swiftc"],adapterExecutables:["lldb-dap"],platforms:["linux"],install:"Install the official Swift 6.3.3 Linux toolchain, which includes swiftc and lldb-dap."}},{id:"lldb-dap-zig",name:"lldb-dap for Zig",kind:"debugger",languages:["zig"],executables:["lldb-dap-18","lldb-dap"],dependencies:["Zig 0.15.2","lldb-18"],documentation:"https://lldb.llvm.org/use/lldbdap.html",debugger:{runtimeExecutables:["zig"],adapterExecutables:["lldb-dap-18","lldb-dap"],platforms:["linux","win32"],install:"Install Zig 0.15.2 and LLDB 18, then compile the target in Debug mode with the LLVM backend (-fllvm) so LLDB can inspect locals."}},{id:"local-lua-debugger",name:"Local Lua Debugger",kind:"debugger",languages:["lua"],executables:["lua","node"],dependencies:["local-lua-debugger-vscode 0.3.3"],documentation:"https://github.com/tomblind/local-lua-debugger-vscode",debugger:{runtimeExecutables:["lua","node"],adapterExecutables:["debugAdapter.js"],platforms:["linux","win32"],install:"Install Lua 5.3, Node 24, and local-lua-debugger-vscode 0.3.3."}},{id:"powershell-editor-services-debug",name:"PowerShell Editor Services",kind:"debugger",languages:["powershell"],executables:["pwsh"],dependencies:["PowerShellEditorServices 4.7.0"],documentation:"https://github.com/PowerShell/PowerShellEditorServices",debugger:{runtimeExecutables:["pwsh"],adapterExecutables:["Start-EditorServices.ps1"],platforms:["linux","win32"],install:"Install PowerShell 7.4.13 and PowerShellEditorServices 4.7.0."}},{id:"rdbg",name:"rdbg",kind:"debugger",languages:["ruby"],executables:["rdbg"],dependencies:["debug gem 1.11.0 or newer"],documentation:"https://github.com/ruby/debug",debugger:{runtimeExecutables:["ruby"],adapterExecutables:["rdbg","rdbg.bat"],platforms:["linux","win32"],install:"Install Ruby and debug gem 1.11.0 or newer."}},{id:"vscode-bash-debug",name:"Bash Debug",kind:"debugger",languages:["shell"],executables:["bash","node"],dependencies:["Bash Debug 0.3.9"],documentation:"https://github.com/rogalmic/vscode-bash-debug",debugger:{runtimeExecutables:["bash","node"],adapterExecutables:["bashDebug.js"],platforms:["linux"],install:"Install Bash, Node 24, and Bash Debug 0.3.9."}},{id:"vscode-php-debug",name:"PHP Debug",kind:"debugger",languages:["php"],executables:["php","node"],dependencies:["PHP Debug 1.40.1","Xdebug"],documentation:"https://github.com/xdebug/vscode-php-debug",debugger:{runtimeExecutables:["php","node"],adapterExecutables:["phpDebug.js"],platforms:["linux","win32"],install:"Install PHP with Xdebug, Node 24, and PHP Debug 1.40.1."}},{id:"vscode-js-debug",name:"vscode-js-debug",kind:"debugger",languages:["javascript","typescript"],executables:["node"],dependencies:["@vscode/js-debug"],documentation:"https://github.com/microsoft/vscode-js-debug",debugger:{runtimeExecutables:["node"],adapterExecutables:["dapDebugServer.js"],platforms:["linux","win32"],install:"Install Node 24 and js-debug-dap v1.117.0 from the official release archive."}}];function H(r){return J.find(e=>e.languages.includes(r))}i(H,"debuggerRecipeForLanguage");var be="/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js",fe="/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh",me={protocol:Y,apiVersion:1,id:"debugger",setup(r){for(let e of J)r.addToolRecipe(e);r.addSetupCheck({id:"effective-config",inspect:He}),r.addCheck({id:"adapters",title:"Debug adapters",run:Fe})}};async function He(r,e=process.platform){let t=new Map([...r.detectedLanguageIds].map(H).filter(a=>a!==void 0).map(a=>[a.id,a])),n=[...r.detectedLanguageIds].flatMap(a=>{let s=H(a);return s===void 0?[]:[{kind:"debugger",languageId:a,toolId:s.id}]}),o=[];for(let a of ge)a.status==="planned"&&r.detectedLanguageIds.has(a.language)&&o.push({id:`debugger-${a.language}-not-verified`,message:`${a.backend} is selected for ${a.language}, but its Linux debugger integration is not verified yet`});for(let a of t.values()){let s=a.debugger;if(s===void 0)continue;let d=e==="linux"||e==="darwin"||e==="win32"?e:void 0;if(d===void 0||!s.platforms.includes(d)){o.push({id:`debugger-${a.id}-platform`,category:"unsupported-platform",message:`${a.name} does not support the ${e} debugger recipe`});continue}let u=a.id==="debugpy"?await $(r.cwd,r.env,e):void 0,c=await Oe(u===void 0?s.runtimeExecutables:[u.command],r.cwd,r.env);if(c!==void 0){o.push({id:`debugger-${a.id}-runtime`,category:"missing-runtime",message:`Runtime ${c} is unavailable. ${s.install}`});continue}if(!await Ne(a.id,r.cwd,r.env,e)){o.push({id:`debugger-${a.id}-adapter`,category:"missing-adapter",message:`${a.name} is not installed. ${s.install}`});continue}await Ue(a.id,r.cwd,r.env,e)||o.push({id:`debugger-${a.id}-startup`,category:"adapter-startup",message:`${a.name} is installed but cannot start. ${s.install}`})}return{selections:n,actions:o}}i(He,"inspectDebuggerSetup");async function Fe(r){let e=[...new Map([...r.detectedLanguageIds].map(H).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 he(t.id,r.cwd,r.env);return{status:n.ok?"pass":"fail",message:`${t.name}: ${n.ok?"available":"unavailable"}`,detail:n.detail}}))}i(Fe,"checkDebuggerAdapters");async function Oe(r,e,t){for(let n of r)if(!await S(n,e,t))return n}i(Oe,"firstMissingExecutable");async function Ne(r,e,t,n=process.platform){if(r==="elixir-ls-debug-adapter")try{return await j(t.PI_ELIXIR_LS_DEBUG_PATH??fe),!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 j(t.PI_JS_DEBUG_PATH??be),!0}catch{return!1}if(r.startsWith("lldb-dap"))return await S(t.PI_LLDB_DAP_PATH??(n==="win32"?"lldb-dap":"lldb-dap-18"),e,t)||await S("lldb-dap",e,t);if(r==="delve")return S(t.PI_DELVE_PATH??"dlv",e,t);if(r==="kotlin-debug-adapter")return S(t.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",e,t);if(r==="julia-debug-adapter")try{return await j(`${t.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia"}/Project.toml`),!0}catch{return!1}if(r==="dart-debug-adapter")return S(t.PI_DART_PATH??"dart",e,t);let o=await $(e,t,n);return(await y(o.command,[...o.args,"-c","import importlib.util; raise SystemExit(importlib.util.find_spec('debugpy') is None)"],e,t)).ok}i(Ne,"adapterInstalled");async function Ue(r,e,t,n=process.platform){return(await he(r,e,t,n)).ok}i(Ue,"adapterAvailable");async function he(r,e,t,n=process.platform){if(r==="elixir-ls-debug-adapter")return L(t.PI_ELIXIR_LS_DEBUG_PATH??fe,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"){let a=await $(e,t,n);return y(a.command,[...a.args,"-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??(n==="win32"?"lldb-dap":await S("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?L(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?L(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?L(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),s=t.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";return a.ok?L(`${s}/PowerShellEditorServices/Start-EditorServices.ps1`,e,t):a}let o=t.PI_JS_DEBUG_PATH??be;try{await j(o)}catch{return{ok:!1,detail:`${o} does not exist`}}return y(process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1]); console.log(process.version)",o],e,t)}i(he,"probeAdapter");async function L(r,e,t){try{await j(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(L,"probeAdapterFile");import Me from"node:path";import{fileURLToPath as Ge}from"node:url";function ve(r){return{id:"debug-breakpoints",present(e,t){let n=r.get(t.source),o=r.sourceFile(t.source)??ye(t.source,t.cwd)??ye(e.source,t.cwd);if(o===void 0)return e;let a=r.breakpointsForFile(o,n?.source);if(a.length===0)return e;let s=Je(a);return{...e,lines:e.lines.map(d=>{let u=s.get(d.lineNumber);return u===void 0?d:{...d,presentation:{...d.presentation,suffix:`${d.presentation?.suffix??""}${We(u)}`,compactSuffix:`${d.presentation?.compactSuffix??""}${Ve(u)}`}}})}}}}i(ve,"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 ye(r,e){if(r.startsWith("file://"))return Ge(r);if(!/^[a-z][a-z\d+.-]*:/iu.test(r))return Me.resolve(e,r)}i(ye,"filesystemSource");function We(r){return r.map(e=>` ${e.verified?"\u25CF":"\u25CB"} breakpoint ${e.source} (${e.verified?"verified":"pending"})`).join("")}i(We,"renderAgentBreakpoints");function Ve(r){let t=r.filter(o=>o.verified).length===r.length?"\u25CF":"\u25CB",n=r.length===1?"breakpoint":`${r.length} breakpoints`;return` ${t} ${n}`}i(Ve,"renderUserBreakpoints");import F from"node:path";import{Text as W}from"@earendil-works/pi-tui";function V(r,e,t,n){return new W(`${n.fg("toolTitle",r)} ${n.fg("muted",`\xB7 ${Ee(e,t)}`)}
2
+ ${n.fg("accent","\u25C6 configure debugger")}`,0,0)}i(V,"renderDebugCall");function we(r,e,t){return new W(`${Pe(r,t)}
3
+ ${t.fg("accent",Ke(e))}`,0,0)}i(we,"renderDebugActionCall");function q(r,e,t,n){let o=ze(r,e,t);return n!==void 0&&o.unshift(`${t.fg("accent",n.expression)} ${t.fg("muted","=")} ${t.fg("toolOutput",n.result)}${n.type===void 0?"":t.fg("dim",` ${n.type}`)}`),new W(o.join(`
4
+ `),0,0)}i(q,"renderDebugResult");function De(r,e){let t=[Pe(r,e),Se(r.status,e)];return r.stop?.frame!==void 0&&t.push(` ${e.fg("warning","\u25CF")} ${r.stop.frame.name} ${e.fg("muted",`\xB7 ${ke(r.stop)}`)}`),t}i(De,"renderActiveDebugger");function ze(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 ${ke(r.stop)}`)}`));for(let a of r.stop.sourceLines){let s=a.current?t.fg("warning",">"):t.fg("dim","\u2502"),d=a.current?"text":"dim";n.push(`${s} ${String(a.lineNumber).padStart(4)} ${t.fg(d,a.content)}`)}let o=e?r.stop.variables:r.stop.variables.slice(0,6);if(o.length>0){n.push(t.fg("muted","Locals"));for(let a of o)n.push(` ${t.fg("accent",a.name.padEnd(16))} ${t.fg("toolOutput",a.value)}${a.type===void 0?"":t.fg("dim",` ${a.type}`)}`);o.length<r.stop.variables.length&&n.push(t.fg("muted",` \u2026 ${r.stop.variables.length-o.length} more`))}return n}if(n.push(Se(r.status,t)),r.breakpoints.length>0){let o=r.breakpoints.filter(a=>a.verified).length;n.push(t.fg("muted",`${r.breakpoints.length} breakpoint${r.breakpoints.length===1?"":"s"} \xB7 ${o} verified`))}return n}i(ze,"debugResultLines");function Pe(r,e){return`${e.fg("toolTitle",r.options.adapter)} ${e.fg("muted",`\xB7 ${Ee(r.options.program,r.options.cwd)}`)}`}i(Pe,"debugIdentity");function Ke(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("evaluate ")?`\u25C6 ${r.trim().slice(9)}`: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(Ke,"actionLabel");function Se(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(Se,"statusLine");function ke(r){let e=r.frame?.source?.path??r.frame?.source?.name??"unknown";return`${F.basename(e)}:${r.frame?.line??"?"}`}i(ke,"shortFrame");function Ee(r,e){let t=F.relative(e,r),n=".".repeat(2),o=t===n||t.startsWith(`${n}${F.sep}`);return t.length>0&&!o?t:F.basename(r)}i(Ee,"shortPath");function z(r){let e=_e(r);if(e===void 0)return;let t=e.snapshot;return typeof t=="object"&&t!==null?t:void 0}i(z,"debuggerSnapshotFromResult");function xe(r){let e=_e(r);if(e===void 0)return;let t=e.evaluation;if(!(typeof t!="object"||t===null||!("expression"in t)||typeof t.expression!="string"||!("result"in t)||typeof t.result!="string"||!("variablesReference"in t)||typeof t.variablesReference!="number"))return{expression:t.expression,result:t.result,variablesReference:t.variablesReference,..."type"in t&&typeof t.type=="string"?{type:t.type}:{}}}i(xe,"debuggerEvaluationFromResult");function _e(r){if(typeof r!="object"||r===null)return;let e=r.metadata;if(typeof e!="object"||e===null)return;let t=e.semanticAction;return typeof t=="object"&&t!==null?t:void 0}i(_e,"semanticActionFromResult");function Re(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=>De(e,t),"renderSummary"),renderDetail:i(t=>q(e,!0,t),"renderDetail"),stop:i(()=>r.delete(e.source),"stop")})),"list")}}i(Re,"debuggerProcessProvider");import C from"cross-spawn";import{randomBytes as Ae}from"node:crypto";import{rmSync as Ze}from"node:fs";import{mkdtemp as Qe,readFile as Be,rm as et}from"node:fs/promises";import Le from"node:net";import{tmpdir as tt}from"node:os";import v from"node:path";import Xe from"cross-spawn";import Ye from"node:net";var k=class r{static{i(this,"DapClient")}#a;#u;#l;#o=new Map;#b=[];#i=new Set;#f=new Set;#r=Buffer.alloc(0);#p=1;#s;#g;#n;constructor(e,t,n){this.#a=e,this.#u=t,this.#l=n,e.on("data",o=>this.#t(o)),e.once("error",o=>this.#c(o)),e.once("close",()=>this.#c(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#c(o)),n.once("exit",(o,a)=>{this.#c(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Xe(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#p=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Ye.createConnection({port:e,host:t}),s=i(d=>o(d),"fail");a.once("error",s),a.once("connect",()=>{a.off("error",s),n(new r(a,a))})})}onReverseRequest(e){this.#g=e}onEvent(e){return this.#f.add(e),()=>this.#f.delete(e)}request(e,t,n={}){if(this.#s!==void 0)return Promise.reject(this.#s);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#n=void 0);let o=this.#p++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},s=new Promise((d,u)=>{let c,l=i(()=>{c!==void 0&&clearTimeout(c),n.signal?.removeEventListener("abort",p)},"cleanup"),p=i(()=>{this.#o.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(c=setTimeout(()=>{this.#o.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#o.set(o,{resolve:i(f=>d(f),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),s}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#b.findIndex(s=>o.has(s.event));return a>=0?Promise.resolve(this.#b.splice(a,1)[0]):this.#s!==void 0?Promise.reject(this.#s):new Promise((s,d)=>{let u={events:o,resolve:i(l=>{clearTimeout(u.timer),this.#i.delete(u),s(l)},"resolve"),reject:i(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let c=i(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?c():n?.addEventListener("abort",c,{once:!0})})}close(){this.#a.destroy(),this.#u.destroy(),this.#l!==void 0&&!this.#l.killed&&this.#l.kill(),this.#c(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#u.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
5
+ \r
6
+ `),t]))}#t(e){for(this.#r=Buffer.concat([this.#r,e]);;){let t=this.#r.indexOf(`\r
7
+ \r
8
+ `);if(t<0)return;let n=this.#r.subarray(0,t).toString("ascii"),o=/^Content-Length:\s*(\d+)$/imu.exec(n);if(o===null){this.#c(new Error("Debug adapter sent a frame without Content-Length"));return}let a=Number(o[1]),s=t+4;if(this.#r.length<s+a)return;let d=this.#r.subarray(s,s+a).toString("utf8");this.#r=this.#r.subarray(s+a);try{this.#m(JSON.parse(d))}catch(u){this.#c(u instanceof Error?u:new Error(String(u)));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 N=class{static{i(this,"DebugSessionManager")}#a=new Map;#u=new Set;create(e){let t=Ae(6).toString("hex"),n={id:t,source:`debug:${t}`,options:{...e,sourceFile:e.sourceFile??e.program},breakpoints:new Map,status:"configured",stopGeneration:0};return this.#a.set(t,n),this.#e(n),n}get(e){let t=/^debug:([a-f\d]{12})(?:\/|$)/u.exec(e);return t===null?void 0:this.#a.get(t[1])}list(){return[...this.#a.values()]}snapshot(e){return{id:e.id,source:e.source,options:e.options,status:e.status,breakpoints:[...e.breakpoints.values()].map(t=>({...t})),...e.stop===void 0?{}:{stop:e.stop}}}onDidChange(e){return this.#u.add(e),()=>this.#u.delete(e)}breakpointsForFile(e,t){return this.list().filter(n=>t===void 0||n.source===t).flatMap(n=>[...n.breakpoints.values()]).filter(n=>I(n.file,e))}sourceFile(e){let t=this.get(e);return t!==void 0&&e===`${t.source}/source`?t.options.sourceFile:void 0}sourceResource(e){return`${e.source}/source`}readSource(e){let t=this.sourceFile(e);return t===void 0?Promise.reject(new Error(`Unknown debug source ${e}`)):Be(t,"utf8")}async addBreakpoint(e,t,n){let o=this.get(e),a=this.sourceFile(e);if(o===void 0||a===void 0)throw new Error(`Unknown debug source ${e}`);if(o.status==="terminated")throw new Error("Cannot add a breakpoint to a terminated session");let s=Ae(5).toString("hex"),d={id:s,source:`${o.source}/breakpoint/${s}`,file:a,line:t,verified:!1};return o.breakpoints.set(s,d),o.client!==void 0&&await this.#d(o,o.client,a,n),this.#e(o),d}breakpoint(e){let t=this.get(e);return t===void 0?void 0:[...t.breakpoints.values()].find(n=>n.source===e)}async start(e,t){return this.#l(e,t,2)}async#l(e,t,n){if(e.status!=="configured")throw new Error(`Session is already ${e.status}`);e.options.adapter==="powershell"&&(e.adapterTemporaryDirectory=await Qe(v.join(tt(),"pi-powershell-debug-")));let o=await st(e.options,e.adapterTemporaryDirectory),a=e.options.adapter==="node"?await this.#s(e):e.options.adapter==="delve"?await this.#b(e):e.options.adapter==="ruby"?await this.#o(e):e.options.adapter==="julia"?await this.#i(e):e.options.adapter==="r"?await this.#f(e):k.start(o.command,o.args,e.options.cwd);e.client=a,e.controlClient=a,e.clients=[a],e.options.adapter==="node"&&(e.targetReady=new Promise(s=>{e.resolveTargetReady=s})),e.status="running",this.#e(e);try{e.options.adapter!=="r"&&await Te(a,o.adapterID,t);let s=a.waitForAnyEvent(["initialized"],3e4,t),d=a.request(o.request,o.launch,{signal:t});await s,await this.#n(e,a,t);let u=a.request("configurationDone",void 0,{signal:t});if(e.options.adapter==="java"||e.options.adapter==="kotlin"?u.catch(()=>{}):await u,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 c of e.clients??[a])c.close();e.adapterProcess?.kill(),await X(e),e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.adapterProcess=void 0,e.status="configured";for(let c of e.breakpoints.values())c.verified=!1;return this.#e(e),await this.#l(e,t,n-1)}return e}catch(s){for(let d of e.clients??[a])d.close();throw e.adapterProcess?.kill(),await X(e),e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.adapterProcess=void 0,e.targetReady=void 0,e.resolveTargetReady=void 0,e.status="configured",this.#e(e),s}}async command(e,t,n){if(e.status!=="stopped"||e.stop===void 0)throw new Error(`Cannot ${t} while session is ${e.status}`);let o=E(e),a=e.stop.threadId;return await o.request(t,{threadId:a},{signal:n}),e.stop=void 0,e.status="running",this.#e(e),await this.#t(e,n),e}async evaluate(e,t,n){if(e.status!=="stopped"||e.stop?.frame===void 0)throw new Error(`Cannot evaluate while session is ${e.status}`);let o=t.trim();if(o.length===0)throw new Error("Debug evaluation requires an expression");let a=await E(e).request("evaluate",{expression:o,frameId:e.stop.frame.id,context:"repl"},{signal:n});if(typeof a.result!="string")throw new Error("Debug adapter returned no evaluation result");return{expression:o,result:a.result,variablesReference:a.variablesReference??0,...a.type===void 0?{}:{type:a.type}}}async delete(e,t){let n=this.get(e);if(n===void 0)throw new Error(`Unknown debug session ${e}`);let o=/\/breakpoint\/([a-f\d]{10})$/u.exec(e);if(o!==null){let a=n.breakpoints.get(o[1]);if(a===void 0)throw new Error(`Unknown debug breakpoint ${e}`);n.breakpoints.delete(a.id),n.client!==void 0&&n.status!=="terminated"&&await this.#d(n,n.client,a.file,t),this.#e(n);return}if(e!==n.source)throw new Error(`Cannot delete debug resource ${e}`);if(n.client!==void 0){(n.controlClient??n.client).request("disconnect",{terminateDebuggee:!0},{signal:t,timeoutMs:500}).catch(()=>{});for(let a of n.clients??[n.client])a.close()}await Ce(n.adapterProcess),await X(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();Ce(e.adapterProcess),e.adapterTemporaryDirectory!==void 0&&Ze(e.adapterTemporaryDirectory,{recursive:!0,force:!0})}this.#a.clear()}async#o(e){let t=await O(),n=process.env.PI_RUBY_DEBUG_PATH??"rdbg";return e.adapterProcess=C(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"]}),K(e.adapterProcess,`rdbg:${String(t)}`),await Ie(e.adapterProcess,"Debugger can attach via TCP/IP","rdbg"),k.connect(t)}async#b(e){let t=await O(),n=process.env.PI_DELVE_PATH??"dlv";return e.adapterProcess=C(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 Ie(e.adapterProcess,"DAP server listening","Delve"),k.connect(t)}async#i(e){let t=await O(),n=process.env.PI_JULIA_PATH??"julia",o=process.env.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia",a='using Sockets, DebugAdapter; server = listen(ip"127.0.0.1", parse(Int, ARGS[1])); conn = accept(server); run(DebugAdapter.DebugSession(conn)); close(server)';return e.adapterProcess=C(n,["--startup-file=no","--history-file=no",`--project=${o}`,"-e",a,String(t)],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),K(e.adapterProcess,`DebugAdapter.jl:${String(t)}`),await new Promise(s=>setTimeout(s,25)),$e(t,"DebugAdapter.jl")}async#f(e){let t=Le.createServer();await new Promise((d,u)=>{t.once("error",u),t.listen(0,"127.0.0.1",()=>d())});let n=t.address();if(n===null||typeof n=="string")throw t.close(),new Error("Could not start the vscDebugger DAP listener");let o=new Promise((d,u)=>{t.once("connection",c=>{t.close();let l=k.fromSocket(c,2);l.onEvent(p=>this.#r(e,p)),d(l)}),t.once("error",u)}),a=process.env.PI_R_PATH??"R";e.rPromptInputs=[],e.rAtBrowserPrompt=!1,e.rStarted=!1,e.adapterProcess=C(a,["--vanilla","--quiet"],{cwd:e.options.cwd,env:process.env,stdio:["pipe","pipe","pipe"]}),K(e.adapterProcess,`vscDebugger:${String(n.port)}`),this.#p(e);let s=at({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
+ `),ot(o,e.adapterProcess,t)}#r(e,t){if(process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(`[vscDebugger:event] ${JSON.stringify(t)}
10
+ `),t.event!=="custom")return;let n=R(t.body),o=typeof n.reason=="string"?n.reason:"",a=typeof n.text=="string"?n.text:"";if(!(o!=="writeToStdin"||a.length===0)){if(n.when==="browserPrompt"&&e.rAtBrowserPrompt===!0){e.rAtBrowserPrompt=!1,e.adapterProcess?.stdin?.write(`${a}
11
+ `);return}e.rPromptInputs?.push(a)}}#p(e){let t="";e.adapterProcess?.stdout?.on("data",n=>{for(t+=n.toString("utf8");;){let o=/Browse\[\d+\]> /u.exec(t),a=/(?:^|\r?\n)__PI_R_PROMPT__(?:\r?\n|$)/u.exec(t),s=o?.index??Number.POSITIVE_INFINITY,d=a?.index??Number.POSITIVE_INFINITY;if(!Number.isFinite(s)&&!Number.isFinite(d)){t=t.slice(-128);return}if(s<d){t=t.slice(s+(o?.[0].length??0));let u=e.rPromptInputs?.shift();u===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(`${u}
13
+ `)}else t=t.slice(d+(a?.[0].length??0)),e.adapterProcess?.stdin?.write(`vscDebugger::.vsc.listenForDAP(timeout=-1)
14
+ `),e.rStarted===!0&&e.client?.request("custom",{reason:"showingPrompt",which:"topLevel"}).catch(()=>{})}})}async#s(e){let t=await O(),n=process.env.PI_JS_DEBUG_PATH??"/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js";e.adapterProcess=C(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 it(e.adapterProcess);let o=await $e(t);return o.onReverseRequest(this.#g(e,t)),o}#g(e,t){return async n=>{if(n.command!=="startDebugging")throw new Error(`Client does not support reverse request ${n.command}`);let o=R(n.arguments),a=R(o.configuration),s=await k.connect(t);e.clients?.push(s),s.onReverseRequest(this.#g(e,t)),await Te(s,"pwa-node");let d=s.waitForEvent("initialized"),u=s.request(typeof o.request=="string"?o.request:"launch",{...a,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[v.join(v.dirname(e.options.program),"**","*.js")]});return await d,e.client=s,await this.#n(e,s),await s.request("configurationDone"),await u,e.resolveTargetReady?.(),{}}}async#n(e,t,n){let o=new Set([...e.breakpoints.values()].map(a=>a.file));for(let a of o)await this.#d(e,t,a,n)}async#d(e,t,n,o){let a=[...e.breakpoints.values()].filter(d=>d.file===n),s=await t.request("setBreakpoints",{source:{path:n,name:v.basename(n)},breakpoints:a.map(({line:d})=>({line:d})),sourceModified:!1},{signal:o});for(let[d,u]of a.entries())u.verified=s.breakpoints?.[d]?.verified===!0}async#t(e,t){let n=await E(e).waitForAnyEvent(["stopped","terminated","exited","loadedSource","breakpoint","custom"],3e4,t),o=R(n.body);if(n.event==="custom"&&e.options.adapter==="r"){await this.#t(e,t);return}if(n.event==="loadedSource"){let a=R(o.source),s=typeof a.path=="string"?v.resolve(a.path):void 0,d=s===void 0?void 0:[...e.breakpoints.values()].find(u=>I(u.file,s))?.file;d!==void 0&&await this.#d(e,E(e),d,t),await this.#t(e,t);return}if(n.event==="breakpoint"){let a=R(o.breakpoint),s=R(a.source);for(let d of e.breakpoints.values())a.verified===!0&&typeof a.line=="number"&&a.line===d.line&&typeof s.path=="string"&&I(s.path,d.file)&&(d.verified=!0);await this.#t(e,t);return}if(o.reason==="exit"){e.status="terminated",e.stop=void 0,this.#e(e);return}if(e.options.adapter==="node"&&o.reason==="entry"){await this.#n(e,E(e),t);let a=typeof o.threadId=="number"?o.threadId:1;await E(e).request("continue",{threadId:a},{signal:t}),await this.#t(e,t);return}if((e.options.adapter==="dart"||e.options.adapter==="kotlin")&&o.reason==="entry"){let a=E(e);if(await this.#n(e,a,t),e.options.adapter==="kotlin"){let d=Date.now()+5e3;for(;[...e.breakpoints.values()].some(u=>!u.verified)&&Date.now()<d;)await new Promise(u=>setTimeout(u,50)),await this.#n(e,a,t)}let s=typeof o.threadId=="number"?o.threadId:1;await a.request("continue",{threadId:s},{signal:t}),await this.#t(e,t);return}if(n.event!=="stopped"){e.status="terminated",e.stop=void 0,this.#e(e);return}if(await this.#m(e,n,e.options.adapter!=="shell"),e.options.adapter==="r"&&e.stop?.frame?.source?.path===void 0){e.stopGeneration--,e.stop=void 0,e.status="running",await this.#t(e,t);return}if(e.options.adapter==="shell"&&e.stop?.frame!==void 0&&![...e.breakpoints.values()].some(a=>I(a.file,e.stop?.frame?.source?.path??"")&&a.line===e.stop?.frame?.line)){let a=e.stop.threadId;e.stopGeneration--,e.stop=void 0,e.status="running",await E(e).request("continue",{threadId:a},{signal:t}),await this.#t(e,t);return}e.options.adapter==="shell"&&this.#e(e)}async#m(e,t,n=!0){let o=E(e),a=R(t.body),s=(await o.request("threads")).threads?.[0]?.id,d=typeof a.threadId=="number"?a.threadId:s;if(d===void 0)throw new Error("Debugger stopped without a thread");let u=(await nt(o,d,e.options.adapter==="dart")).stackFrames?.[0];if(u?.source?.path!==void 0)for(let l of e.breakpoints.values())I(l.file,u.source.path)&&l.line===u.line&&(l.verified=!0);let c=[];if(u!==void 0){let l=(await o.request("scopes",{frameId:u.id})).scopes??[],p=e.options.adapter==="r"?l:l.filter(f=>[f.name.toLowerCase(),f.presentationHint?.toLowerCase()].some(g=>g?.includes("local")===!0||g==="variables"));for(let f of p){let g=await o.request("variables",{variablesReference:f.variablesReference,start:0,count:100});c.push(...g.variables??[])}}e.stopGeneration++,e.stop={generation:e.stopGeneration,reason:typeof a.reason=="string"?a.reason:"stopped",threadId:d,...u===void 0?{}:{frame:u},variables:c,sourceLines:u===void 0?[]:await rt(u)},e.status="stopped",n&&this.#e(e)}#e(e){let t=this.snapshot(e);for(let n of this.#u)n(t)}};async function rt(r){let e=r.source?.path;if(e===void 0)return[];try{let t=(await Be(e,"utf8")).split(/\r?\n/u),n=Math.max(1,r.line-2),o=Math.min(t.length,r.line+2);return t.slice(n-1,o).map((a,s)=>({lineNumber:n+s,content:a,current:n+s===r.line}))}catch{return[]}}i(rt,"sourceWindow");async function nt(r,e,t){let n=Date.now()+1e3,o;do{try{let a=await r.request("stackTrace",{threadId:e});if(!t||(a.stackFrames?.length??0)>0)return a;o=new Error("Debugger stack is not ready")}catch(a){if(o=a,!t)throw a}await new Promise(a=>setTimeout(a,25))}while(Date.now()<n);throw o instanceof Error?o:new Error("Could not read debugger stack")}i(nt,"requestStackTrace");function U(r){let e=[`Session: ${r.source}`,`Adapter: ${r.options.adapter}`,`Program: ${v.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} ${v.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(U,"renderDebugSession");function E(r){if(r.client===void 0)throw new Error("Debug adapter is not running");return r.client}i(E,"requiredClient");function R(r){return typeof r=="object"&&r!==null?r:{}}i(R,"asRecord");function at(r){let e=JSON.stringify(r);return`Content-Length: ${Buffer.byteLength(e,"utf8")}\r
16
+ \r
17
+ ${e}`}i(at,"dapFrame");function Te(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(Te,"initializeClient");function O(){return new Promise((r,e)=>{let t=Le.createServer();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let n=t.address();if(n===null||typeof n=="string"){t.close(),e(new Error("Could not allocate a debug adapter port"));return}t.close(o=>o===void 0?r(n.port):e(o))})})}i(O,"availablePort");function K(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(K,"traceAdapterProcess");function ot(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),s=i(()=>{clearTimeout(a),e.off("error",d),e.off("exit",u)},"cleanup"),d=i(c=>{s(),t.close(),e.killed||e.kill(),o(c)},"fail"),u=i(c=>d(new Error(`vscDebugger exited with code ${String(c)} before connecting`)),"onExit");e.once("error",d),e.once("exit",u),r.then(c=>{s(),n(c)},d)})}i(ot,"waitForRAdapterConnection");function Ie(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(c=>c!==null),s=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=i(()=>{clearTimeout(s);for(let c of a)c.off("data",u)},"cleanup"),u=i(c=>{c.toString("utf8").includes(e)&&(d(),n())},"onData");for(let c of a)c.on("data",u);r.once("error",c=>{d(),o(c)}),r.once("exit",c=>{d(),o(new Error(`${t} server exited with code ${String(c)}`))})})}i(Ie,"waitForAdapterReady");function it(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=i(s=>{s.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",s=>t(new Error(`js-debug server exited with code ${s}`)))})}i(it,"waitForJsDebugReady");async function $e(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await k.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}i($e,"connectWithRetry");async function X(r){r.adapterTemporaryDirectory!==void 0&&(await et(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}i(X,"removeAdapterTemporaryDirectory");async function Ce(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=C("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}i(Ce,"terminateOwnedAdapterProcess");async function st(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await $(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="java"||r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:v.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:v.dirname(v.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??v.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:v.join(n,"bashdb_dir/bashdb"),pathBashdbLib:v.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",`& '${v.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${v.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${v.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:[v.join(v.dirname(r.program),"**","*.js")]}}}i(st,"adapterRecipe");var ct=D.Object({adapter:ut(["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 pt(r){ee(r,[await Q({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(l=>({tool:l,resourcePrefixes:["debug:"]}))]})]);let e=ce("debugger"),t=e!==void 0&&typeof e.evaluate=="function"?e:new N,n=new Map,o=je(t,"debugger-source"),a=je(t,"debugger-input"),s=ue(r).add(Re(t)),d=ve(t),u={protocol:re,apiVersion:ne,id:"debugger",setup(l){l.addResolver({resolver:o,matchesCall:i(p=>t.sourceFile(p)!==void 0,"matchesCall"),renderCall(p,f,g){let m=T(p)?p:{},b=typeof m.path=="string"?m.path:"",w=t.get(b),h=t.sourceFile(b);if(w===void 0||h===void 0)throw new Error("Debugger source header lost its session");let P=x.relative(w.options.cwd,h),_=Array.isArray(m.views)?m.views.filter(G=>typeof G=="string"):[],A=typeof m.offset=="number"?m.offset:1,B=typeof m.limit=="number"?m.limit:void 0,M=B===void 0?String(A):`${A}-${A+B-1}`;return oe(g.lastComponent,{tool:"debug file",primary:{text:`${P}:${M}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:b},{label:"file",value:h},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:g.expanded},f)}}),l.addView({view:"breakpoints",presenter:d}),l.describe('views: ["breakpoints"] \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped. debug:<session> \u2014 debugger state.')}},c={protocol:ie,apiVersion:se,id:"debugger",setup(l){l.addResolver({resolver:a}),l.tool("insert").addSemanticHandler({matches:i(p=>gt(p,t),"matches"),execute:i(async(p,f)=>{let g=f,m=qe(t,g.path);if(t.sourceFile(g.path)!==void 0){if(g.text!=="breakpoint"||g.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let w=await p.resolveAnchor("anchor"),h=await t.addBreakpoint(g.path,w.lineNumber,p.signal);return{source:h.source,summary:`Breakpoint ${h.source} created at ${x.relative(m.options.cwd,h.file)}:${h.line}.`,data:{kind:"debug-breakpoint",session:m.source,file:h.file,line:h.line,verified:h.verified,snapshot:t.snapshot(m)}}}if(g.path!==m.source||g.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let b=await ft(t,m,g.text,p.signal);return{source:m.source,summary:b===void 0?U(m):`${b.expression} = ${b.result}${b.type===void 0?"":` (${b.type})`}`,data:ht(t,m,g.text,b)}},"execute")}),l.tool("delete").addSemanticHandler({matches:i(p=>bt(p,t),"matches"),execute:i(async(p,f)=>{let g=f.path,m=qe(t,g),b=t.snapshot(m);n.set(g,b);let w=g.includes("/breakpoint/");await t.delete(g,p.signal);let h=w?t.snapshot(m):{...b,status:"terminated"};return{source:g,summary:`Deleted ${g}.`,data:{kind:w?"debug-breakpoint":"debug-session",deleted:!0,snapshot:h}}},"execute")}),l.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, step out, or evaluate <expression>. Delete removes a breakpoint or terminates the session.');for(let p of["insert","delete"])l.addToolRenderer({tool:p,matches(f,g){return g==="call"?T(f)&&typeof f.path=="string"&&(t.get(f.path)!==void 0||n.has(f.path)):z(T(f)&&"details"in f?f.details:f)!==void 0},renderCall(f,g,m){let b=f,w=b.path===void 0?void 0:t.get(b.path),h=b.path===void 0?void 0:n.get(b.path),P=m.state;w!==void 0?P.snapshot=t.snapshot(w):h!==void 0&&(P.snapshot=h);let _=P.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let A=b.path===void 0?void 0:t.breakpoint(b.path)??_.breakpoints.find(G=>G.source===b.path),B=b.path===void 0?void 0:t.sourceFile(b.path),M=p==="delete"?A===void 0?"delete-session":`delete-breakpoint ${x.basename(A.file)}:${A.line}`:b.text==="breakpoint"&&B!==void 0?`breakpoint ${x.basename(B)}:${vt(b)}`:b.text??"debug action";return we(_,M,g)},renderResult(f,g,m){let b=z(f.details);if(b===void 0)throw new Error("Debugger result is missing its session");let w=xe(f.details);return q(b,g.expanded,m,w)}})}};await Promise.all([te(r,me),ae(r,u)]),await de(r,c),r.registerTool(lt({name:"debug",label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:ct,async execute(l,p,f,g,m){let b=x.resolve(m.cwd,p.cwd??"."),w=x.resolve(b,p.program);try{await dt(w);let h=t.create({adapter:p.adapter,program:w,sourceFile:x.resolve(b,p.source??p.program),args:p.args??[],cwd:b,...p.mainClass===void 0?{}:{mainClass:p.mainClass}}),P=mt(t,h);return{content:[{type:"text",text:`${U(h)}
20
+ Source: ${P.sourceResource}
21
+ Breakpoints: ${P.breakpointsResource}
22
+
23
+ Next: read ${P.sourceResource} with views ["anchors"], then insert a breakpoint at an anchor.`}],details:P}}catch(h){return{content:[{type:"text",text:h instanceof Error?h.message:String(h)}],details:{adapter:p.adapter,program:w,cwd:b,status:"failed"},isError:!0}}},renderCall(l,p){let f=x.resolve(process.cwd(),typeof l.cwd=="string"?l.cwd:"."),g=x.resolve(f,typeof l.program=="string"?l.program:"program");return V(typeof l.adapter=="string"?l.adapter:"debugger",g,f,p)},renderResult(l,p,f){let g=T(l.details)?l.details.snapshot:void 0;if(typeof g=="object"&&g!==null)return q(g,p.expanded,f);let m=l.details;return V(m.adapter,m.program,m.cwd,f)}})),r.on("session_shutdown",l=>{if(s(),l.reason!=="quit"){le("debugger",t);return}pe("debugger",t),t.dispose()})}i(pt,"registerDebugger");function je(r,e){return{id:e,tryResolve(t){let n=r.get(t);return n===void 0?Promise.resolve({kind:"not-handled"}):Promise.resolve({kind:"resolved",resource:{source:t,async read(){let o=r.sourceFile(t);if(o!==void 0)return[wt(o,await r.readSource(t))];if(t===`${n.source}/breakpoints`)return[{type:"text",text:yt(n)}];let a=r.breakpoint(t);if(t!==n.source&&a===void 0)throw new Error(`Unknown debug resource ${t}`);return[{type:"text",text:a===void 0?U(n):`Breakpoint: ${a.source}
24
+ File: ${a.file}
25
+ Line: ${a.line}
26
+ Status: ${a.verified?"verified":"pending"}`}]}}})}}}i(je,"createDebugResourceResolver");function gt(r,e){if(!T(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(gt,"matchesDebugInsert");function bt(r,e){if(!T(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(bt,"matchesDebugDelete");async function ft(r,e,t,n){let o=t.trim(),a=/^evaluate\s+(.+)$/isu.exec(o);if(a!==null)return await r.evaluate(e,a[1],n);switch(o.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(ft,"executeSessionCommand");function mt(r,e){return{source:e.source,sourceResource:r.sourceResource(e),breakpointsResource:`${e.source}/breakpoints`,adapter:e.options.adapter,program:e.options.program,cwd:e.options.cwd,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:t,file:n,line:o,verified:a})=>({source:t,file:n,line:o,verified:a})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(mt,"debugDetails");function ht(r,e,t,n){return{kind:"debug-command",command:t,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:o,file:a,line:s,verified:d})=>({source:o,file:a,line:s,verified:d})),...e.stop===void 0?{}:{stop:e.stop},...n===void 0?{}:{evaluation:n},snapshot:r.snapshot(e)}}i(ht,"debugActionData");function yt(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(yt,"renderBreakpointList");function qe(r,e){let t=r.get(e);if(t===void 0)throw new Error(`Unknown debug session ${e}`);return t}i(qe,"requiredSession");function vt(r){let e=T(r)&&typeof r.anchor=="string"?r.anchor:void 0;return/^(\d+)#/u.exec(e??"")?.[1]??e??"selected line"}i(vt,"breakpointLine");function T(r){return typeof r=="object"&&r!==null}i(T,"isRecord");function wt(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(wt,"debugSourceContent");export{pt as default};
@@ -0,0 +1,5 @@
1
+ import{a as _}from"./chunk-M5IVSCR2.js";import{e as $,f as q}from"./chunk-T7I2VX3J.js";import{a as T}from"./chunk-6CZO43OH.js";import{a as O,b as U}from"./chunk-OBNING2A.js";import{a as W}from"./chunk-ZTYWHL2F.js";import{a as k,b as L}from"./chunk-7UGNGK7Y.js";import{a as c}from"./chunk-EI7MMDWY.js";import{execFile as ne}from"node:child_process";import te from"node:os";import{promisify as re}from"node:util";import{createCanvas as z,loadImage as oe}from"@napi-rs/canvas";var p=re(ne),I=20*1024*1024,F={durationSeconds:2,intervalSeconds:.5,scale:.5},H=new Set;function j(e){let n=R({mode:"sequence",durationSeconds:Number(e.durationSeconds??2),intervalSeconds:Number(e.intervalSeconds??.5),scale:Number(e.scale??.5)});F={durationSeconds:n.durationSeconds,intervalSeconds:n.intervalSeconds,scale:n.scale},H=new Set((e.allowedExecutables??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}c(j,"configureVision");function y(){return F}c(y,"getVisionDefaults");function G(e){let n=e.includes("\\")?e.slice(e.lastIndexOf("\\")+1):e,r=n.trim().split(/\s+/u)[0]??"",t=r.slice(r.lastIndexOf("/")+1);return H.has((e.includes("\\")?n:t).toLowerCase())}c(G,"isExecutableAllowed");function J(e,n){let r=e?.filter(i=>/^(?:image|sequence)(?::|$)/u.test(i))??[];if(r.length===0)return;if(r.length>1)throw new Error("Use only one image or sequence view");let t=r[0],s=t.indexOf(":"),a=t.slice(0,s<0?void 0:s),o={};if(s>=0&&ie(t.slice(s+1),o),a==="image"&&(o.duration!==void 0||o.interval!==void 0))throw new Error("duration and interval are supported only by the sequence view");return R({mode:a,durationSeconds:o.duration??n.durationSeconds,intervalSeconds:o.interval??n.intervalSeconds,scale:o.scale??n.scale,...o.region===void 0?{}:{region:o.region}})}c(J,"parseVisionView");function ie(e,n){if(e.length===0)throw new Error("View parameters cannot be empty");let r=e.split(",");for(let t=0;t<r.length;t+=1){let s=r[t],a=s.indexOf("=");if(a<=0)throw new Error(`Invalid view parameter ${s}`);let o=s.slice(0,a),i=s.slice(a+1);if(o==="region"){let l=[i,r[t+1],r[t+2],r[t+3]].map(Number);if(l.some(m=>!Number.isFinite(m)))throw new Error("region requires x,y,width,height values");n.region={x:l[0],y:l[1],width:l[2],height:l[3]},t+=3;continue}if(o!=="duration"&&o!=="interval"&&o!=="scale")throw new Error(`Unknown view parameter ${o}`);let d=Number(i);if(!Number.isFinite(d))throw new Error(`View parameter ${o} must be a number`);if(n[o]!==void 0)throw new Error(`Duplicate view parameter ${o}`);n[o]=d}}c(ie,"parseViewParameters");function X(e){if(!e.startsWith("display:"))return;if(e==="display:")return 0;let n=/^display:#(\d+)$/u.exec(e);if(n===null)throw new Error("Display sources use display: or display:#N with a zero-based index");let r=Number(n[1]);if(!Number.isSafeInteger(r))throw new Error("Display sources use display: or display:#N with a zero-based index");return r}c(X,"parseDisplaySource");async function E(e){let n=new Map(e.list().flatMap(s=>s.pid===void 0?[]:[[s.pid,s]]));if(process.platform!=="linux"&&process.platform!=="darwin")return[...n].map(([s,a])=>({pid:s,command:a.description,owned:!0,source:a.source,host:"local"}));let{stdout:r}=await p("ps",["-eo","pid=,ppid=,lstart=,args="],{maxBuffer:4*1024*1024}),t=r.split(`
2
+ `).flatMap(s=>{let a=/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/u.exec(s);if(a===null)return[];let o=Number(a[1]),i=n.get(o);return[{pid:o,parentPid:Number(a[2]),started:a[3],command:a[4]??"",owned:i!==void 0,host:"local",...i===void 0?{}:{source:i.source}}]});return x()?[...t,...await se()]:t}c(E,"listProcesses");async function se(){try{let{stdout:e}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command","Get-Process | Select-Object Id,ProcessName,Path,StartTime | ConvertTo-Json -Compress"],{maxBuffer:4194304}),n=JSON.parse(e);return(Array.isArray(n)?n:[n]).flatMap(t=>{if(typeof t!="object"||t===null||!("Id"in t)||typeof t.Id!="number")return[];let s="ProcessName"in t&&typeof t.ProcessName=="string"?t.ProcessName:"Windows process",a="Path"in t&&typeof t.Path=="string"?t.Path:void 0,o="StartTime"in t&&typeof t.StartTime=="string"?t.StartTime:void 0;return[{pid:t.Id,command:a??s,owned:!1,host:"windows",...o===void 0?{}:{started:o}}]})}catch{return[]}}c(se,"listWindowsProcesses");async function A(e,n){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Process PID must be a positive integer");let r=(await E(n)).find(t=>t.pid===e);if(r===void 0)throw new Error(`Process ${e} is not running`);return r}c(A,"readProcess");function R(e){let n=e.scale??1;if(!(n>0&&n<=1))throw new Error("Image scale must be greater than 0 and at most 1");let r=e.durationSeconds??0,t=e.intervalSeconds??1;if(e.mode==="sequence"){if(!(r>0&&r<=10))throw new Error("Sequence duration must be greater than 0 and at most 10 seconds");if(!(t>0))throw new Error("Sequence interval must be greater than 0 seconds");if(Math.floor(r/t)+1>20)throw new Error("Sequence capture is limited to 20 frames")}if(e.region!==void 0){let{x:s,y:a,width:o,height:i}=e.region;if(s<0||a<0||o<=0||i<=0||s+o>1||a+i>1)throw new Error("Image region x,y,width,height must fit within normalized bounds 0..1")}if(e.cellIndex!==void 0&&e.cellSize===void 0)throw new Error("Image offset requires limit to set the square grid cell size");if(e.cellSize!==void 0&&(!Number.isSafeInteger(e.cellSize)||e.cellSize<=0))throw new Error("Image limit must be a positive integer pixel size");if(e.cellIndex!==void 0&&(!Number.isSafeInteger(e.cellIndex)||e.cellIndex<0))throw new Error("Image offset must be a zero-based cell index");return e}c(R,"validateVisionOptions");async function b(e,n,r){let t=R(n),s=t.mode==="image"?1:Math.floor(t.durationSeconds/t.intervalSeconds)+1,a=[],o=0;for(let i=0;i<s;i+=1){r?.throwIfAborted(),i>0&&await me(t.intervalSeconds*1e3,r);let d=await e();if(o+=d.byteLength,o>I)throw new Error("Captured images exceed the 20MB aggregate limit");for(let l of await ae(d,t))a.push({type:"image",data:Buffer.from(l).toString("base64"),mimeType:"image/png"})}return a}c(b,"captureImages");async function ae(e,n){let r=await oe(e),t=n.region??{x:0,y:0,width:1,height:1},s=Math.round(t.x*r.width),a=Math.round(t.y*r.height),o=Math.max(1,Math.round(t.width*r.width)),i=Math.max(1,Math.round(t.height*r.height)),d=n.scale??1,l=Math.max(1,Math.round(o*d)),m=Math.max(1,Math.round(i*d)),w=z(l,m);if(w.getContext("2d").drawImage(r,s,a,o,i,0,0,l,m),n.cellSize===void 0)return[await w.encode("png")];let u=Math.ceil(l/n.cellSize),f=Math.ceil(m/n.cellSize),h=n.cellIndex??0;if(h>=u*f)throw new Error(`Image cell offset ${h} exceeds the ${u}x${f} grid`);let Z=h%u,ee=Math.floor(h/u),C=Z*n.cellSize,M=ee*n.cellSize,P=Math.min(n.cellSize,l-C),S=Math.min(n.cellSize,m-M),V=z(P,S);return V.getContext("2d").drawImage(w,C,M,P,S,0,0,P,S),[await V.encode("png")]}c(ae,"selectImage");function ce(e,n){return e&&n==="windows"}c(ce,"usesWindowsHostWindowCapture");function Y(){return{async captureWindow(e,n,r){if(r?.throwIfAborted(),ce(x(),n))return de(e,r);if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Window capture is unsupported on ${process.platform}`);let{Window:t}=await import("node-screenshots"),s;try{s=t.all()}catch(i){throw new Error(`Desktop window enumeration is unavailable: ${B(i)}`,{cause:i})}let a=s.find(i=>{try{return i.pid()===e}catch{return!1}});if(a===void 0)throw new Error(`No capturable desktop window belongs to PID ${e}`);let o=await a.captureImage();return r?.throwIfAborted(),new Uint8Array(await o.toPng())},async captureDisplay(e,n){if(n?.throwIfAborted(),x())return ue(e,n);if(process.platform!=="linux"&&process.platform!=="darwin"&&process.platform!=="win32")throw new Error(`Display capture is unsupported on ${process.platform}`);let{Monitor:r}=await import("node-screenshots"),t;try{t=r.all()}catch(o){throw new Error(`Desktop display enumeration is unavailable: ${B(o)}`,{cause:o})}let s=t[e];if(s===void 0)throw new Error(`Display index ${e} is unavailable; found ${t.length} display(s)`);let a=await s.captureImage();return n?.throwIfAborted(),new Uint8Array(await a.toPng())},async captureUrl(e,n){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Web screenshots require an HTTP(S) URL");let{chromium:r}=await import("playwright-core"),t=await le(),s=await r.launch({executablePath:t,headless:!0,chromiumSandbox:!1,timeout:3e4}),a=c(()=>{s.close()},"abort");n?.addEventListener("abort",a,{once:!0});try{let o=await s.newPage({viewport:{width:1280,height:720}});return await o.goto(e.href,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle",{timeout:1500}).catch(()=>{}),n?.throwIfAborted(),new Uint8Array(await o.screenshot({type:"png",fullPage:!0}))}finally{n?.removeEventListener("abort",a),await s.close().catch(()=>{})}}}}c(Y,"createCaptureBackend");async function de(e,n){let r=new URL("windows-window-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await p("wslpath",["-w",r.pathname],{signal:n}),{stdout:s}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-ProcessId",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(s)}c(de,"captureWslWindow");async function ue(e,n){let r=new URL("windows-display-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await p("wslpath",["-w",r.pathname],{signal:n}),{stdout:s}=await p("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-DisplayIndex",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(s)}c(ue,"captureWslDisplay");function x(){return process.platform==="linux"&&(process.env.WSL_DISTRO_NAME!==void 0||te.release().toLowerCase().includes("microsoft"))}c(x,"isWsl");async function le(){let e=process.env.PI_AGENT_IDE_BROWSER_PATH;if(e!==void 0)return e;let{stdout:n}=await p("bash",["-lc","command -v google-chrome-stable || command -v google-chrome || command -v chromium || command -v chromium-browser"]),r=n.trim();if(r.length===0)throw new Error("No Chrome or Chromium executable was found; set PI_AGENT_IDE_BROWSER_PATH");return r}c(le,"resolveBrowser");function me(e,n){return new Promise((r,t)=>{let s=setTimeout(r,e),a=c(()=>{clearTimeout(s),t(n?.reason??new Error("Capture aborted"))},"abort");n?.addEventListener("abort",a,{once:!0}),s.unref()})}c(me,"delay");function B(e){return e instanceof Error?e.message:String(e)}c(B,"errorMessage");async function fe(e,n){q(e,[await $({id:"vision",description:"Window, display, image, and sequence capture",triggers:[{tool:"read",resourcePrefixes:["window:","display:"]}]})]);let r=n?.preferences??{};j({durationSeconds:r["vision.sequenceDurationSeconds"],intervalSeconds:r["vision.sequenceIntervalSeconds"],scale:r["vision.imageScale"],allowedExecutables:r["vision.allowedExecutables"]});let t=_(e),s=Y();await Promise.all([T(e,{protocol:O,apiVersion:U,id:"vision",setup(a){for(let i of["image","sequence"])a.addView({view:i,presenter:{id:`vision-${i}`,present:c(d=>d,"present")}});a.addHandler({stage:"pre-read",async handler(i){let d=i.request.path;if(d===void 0)return{kind:"continue",context:i};let l=X(d);if(l!==void 0){if(e.getFlag("pi-agent-ide-vision-displays")!==!0)return g(d,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");try{let u=await b(()=>s.captureDisplay(l,i.resolverContext.signal),D(i.request),i.resolverContext.signal);return v(d,u)}catch(u){return g(d,N(u))}}let m=K(d,"process:");if(m!==void 0){let u=await A(m,t);return v(d,[{type:"text",text:Q(u)}])}let w=K(d,"window:");if(w!==void 0){let u=await A(w,t);if(!u.owned&&!G(u.command)&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)return g(d,`Window capture for PID ${w} is denied because the process is neither Agent IDE-owned nor allowlisted by executable name. Enable --pi-agent-ide-vision-arbitrary-windows to allow it.`);try{let f=await b(()=>s.captureWindow(w,u.host,i.resolverContext.signal),D(i.request),i.resolverContext.signal);return v(d,f)}catch(f){return g(d,N(f))}}if(/^https?:\/\//iu.test(d)&&we(i.request)){let u=new URL(d);try{let f=await b(()=>s.captureUrl(u,i.resolverContext.signal),D(i.request),i.resolverContext.signal);return v(u.href,f)}catch(f){return g(u.href,N(f))}}return{kind:"continue",context:i}}});let o=y();a.describe(`Process metadata: process:PID. Visual capture: window:PID and display: or display:#N. HTTP(S) sources accept image and sequence screenshots. Use named view parameters such as sequence:duration=2,interval=0.5,scale=0.5 and image:scale=0.5,region=0.25,0.25,0.5,0.5. Duration is limited to 10 seconds and sequences to 20 frames. Defaults: duration=${o.durationSeconds}, interval=${o.intervalSeconds}, scale=${o.scale}. Region uses normalized x,y,width,height and runs before scaling. For captures, limit is a square grid cell size in output pixels and offset is one zero-based row-major cell index; limit without offset selects cell 0, while offset without limit is invalid. Omit both for the bounded transformed image.`)}}),W(e,{protocol:k,apiVersion:L,id:"vision-processes",setup(a){a.addResolver({priority:-100,resolver:{id:"processes",async tryResolve(o){let i=/^process:(.*)$/isu.exec(o.query);if(i===null)return{kind:"not-handled"};let d=(i[1]??"").trim().toLowerCase();return{kind:"resolved",payload:(await E(t)).filter(m=>d.length===0||String(m.pid)===d||m.command.toLowerCase().includes(d)).slice(0,Math.min(o.limit??50,100))}},format(o){let i=o;return{content:[{type:"text",text:i.length===0?"No matching processes.":i.map(Q).join(`
3
+
4
+ `)}],details:{count:i.length,processes:i}}}}}),a.describe("process:<query> finds running processes by PID or command for process:PID metadata reads and guarded window:PID capture.")}})])}c(fe,"registerVision");function K(e,n){if(!e.startsWith(n))return;let r=e.slice(n.length);if(!/^\d+$/u.test(r))throw new Error(`${n} sources require a numeric PID`);return Number(r)}c(K,"prefixedPid");function D(e){return{...J(e.views,y())??{mode:"image",...y()},...e.limit===void 0?{}:{cellSize:e.limit},...e.offset===void 0?{}:{cellIndex:e.offset}}}c(D,"options");function we(e){return e.views?.some(n=>/^(?:image|sequence)(?::|$)/u.test(n))===!0}c(we,"requestsScreenshot");function v(e,n){return{kind:"return",result:{content:n,details:{source:e,resolvedBy:"vision"}}}}c(v,"returned");function g(e,n){return{kind:"return",result:{content:[{type:"text",text:n}],details:{source:e,resolvedBy:"vision",failure:{code:"READ_FAILED",source:e,resolverId:"vision",message:n}},isError:!0}}}c(g,"failed");function N(e){return e instanceof Error?e.message:String(e)}c(N,"errorMessage");function Q(e){return[`PID: ${e.pid}`,`Command: ${e.command}`,`Owned by Agent IDE: ${e.owned?"yes":"no"}`,...e.parentPid===void 0?[]:[`Parent PID: ${e.parentPid}`],...e.started===void 0?[]:[`Started: ${e.started}`],...e.source===void 0?[]:[`Agent IDE source: ${e.source}`]].join(`
5
+ `)}c(Q,"formatProcess");export{fe as default};
package/dist/entry-1.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-HKMBQLEK.js";import"./chunk-Z3VC3S2T.js";import"./chunk-EI7MMDWY.js";export{a as connectIdePlugin};
1
+ import{a}from"./chunk-QDLTO5PH.js";import"./chunk-QIK2E64R.js";import"./chunk-EI7MMDWY.js";export{a as connectIdePlugin};
package/dist/entry-2.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-Z3VC3S2T.js";import"./chunk-EI7MMDWY.js";export{b as IDE_API_VERSION,c as IDE_CORE_READY_EVENT,d as IDE_PLUGIN_REGISTER_EVENT,a as IDE_PROTOCOL,e as isIdeCoreReady,f as isIdePlugin,g as isIdePluginRegistrationRequest};
1
+ import{a,b,c,d,e,f,g}from"./chunk-QIK2E64R.js";import"./chunk-EI7MMDWY.js";export{b as IDE_API_VERSION,c as IDE_CORE_READY_EVENT,d as IDE_PLUGIN_REGISTER_EVENT,a as IDE_PROTOCOL,e as isIdeCoreReady,f as isIdePlugin,g as isIdePluginRegistrationRequest};
package/dist/entry-31.js CHANGED
@@ -1,12 +1,13 @@
1
- import{b as D,c as V}from"./chunk-25CZ5ZIU.js";import{a as E}from"./chunk-MGCHOGQD.js";import{a as O,b as L}from"./chunk-T6LX2RX5.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as I,b as C,c as N}from"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as $}from"./chunk-VCTK4JSN.js";import"./chunk-YHUTTZC6.js";import{a as M}from"./chunk-6CZO43OH.js";import{a as k,b as P}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as B}from"./chunk-ZTYWHL2F.js";import{a as H,b as j}from"./chunk-7UGNGK7Y.js";import{a as S,b as R,c as w,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import"./chunk-KINKBPPX.js";import{j as T}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as x}from"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as te}from"node:fs/promises";var ne={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},y=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),G={protocol:O,apiVersion:1,id:"ast",setup(a){a.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(r=>y.has(r))?await T({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),a.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let r of e.detectedLanguageIds){let t=ne[r];if(t!==void 0){n.push({status:"skip",message:`${r} AST is unavailable: ${t}`});continue}if(!y.has(r))continue;let s=e.files.find(o=>re(o,r));if(s!==void 0)try{let o=await te(s,"utf8"),i=await D(s,e.cwd,o.replaceAll(`\r
1
+ import{b as B}from"./chunk-CEX3VOJ7.js";import"./chunk-7WCZOO5I.js";import{b as V,c as F}from"./chunk-25CZ5ZIU.js";import{a as E}from"./chunk-MGCHOGQD.js";import{a as O,b as L}from"./chunk-T6LX2RX5.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as $,b as C,c as N}from"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as I}from"./chunk-VCTK4JSN.js";import"./chunk-YHUTTZC6.js";import{a as M}from"./chunk-6CZO43OH.js";import{a as P,b as k}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as j}from"./chunk-ZTYWHL2F.js";import{a as D,b as H}from"./chunk-7UGNGK7Y.js";import{a as R,b,c as w,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import"./chunk-KINKBPPX.js";import{j as T}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as x}from"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import{readFile as se}from"node:fs/promises";var ae={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},y=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),G={protocol:O,apiVersion:1,id:"ast",setup(a){a.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(r=>y.has(r))?await T({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),a.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let r of e.detectedLanguageIds){let t=ae[r];if(t!==void 0){n.push({status:"skip",message:`${r} AST is unavailable: ${t}`});continue}if(!y.has(r))continue;let s=e.files.find(o=>oe(o,r));if(s!==void 0)try{let o=await se(s,"utf8"),i=await V(s,e.cwd,o.replaceAll(`\r
2
2
  `,`
3
3
  `).split(`
4
- `));n.push(i===void 0?{status:"fail",message:`${r} parser did not return a tree`}:{status:"pass",message:`${r} parser loaded`,detail:s})}catch(o){n.push({status:"fail",message:`${r}: ${o instanceof Error?o.message:String(o)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),a.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(r=>y.has(r)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await x("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function re(a,e){let n=a.slice(a.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}d(re,"matchesLanguage");var se,ae;function F(a){return{id:"ast",tryResolve(e,n){return Promise.resolve(oe(e,n,a))}}}d(F,"createAstOutlineResolver");function oe(a,e,n){let r;try{r=S(a,"ast")}catch(o){return{kind:"failed",error:o}}if(r===void 0)return{kind:"not-handled"};let t;try{t=R(r.path,e.cwd)}catch(o){return{kind:"failed",error:o}}return{kind:"resolved",resource:{source:w("ast",t),async read({signal:o}){o?.throwIfAborted();let i=await(ae??=import("./chunk-5QQABP47.js")),l=await(n??(se??=new i.AstOutlineManager)).readFileOutline(t,e.cwd);return o?.throwIfAborted(),[i.formatAstOutline(l)]}}}}d(oe,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as ie,DEFAULT_MAX_LINES as ce,truncateHead as A}from"@earendil-works/pi-coding-agent";var b=d(async(a,e,n)=>{let{source:r,resolvedBy:t,lines:s,totalLines:o,startLine:i}=a.details;if(!(r===void 0||t!=="filesystem"||s===void 0||s.length!==o||i!==void 0&&i!==1))try{let{AstOutlineManager:c,isSupportedOutlinePath:l}=await import("./chunk-5QQABP47.js");if(!l(r))return;let u=d(m=>[`AST overview of ${m.path}, source lines 1-${m.totalLines}: the requested text exceeded the read buffer.`,"Source line numbers are on the left. Detail is reduced to fit the buffer; omitted bodies are not exact source text. Read a small source range when needed.",...m.renderedLines.map(g=>`${g.sourceLine?.lineNumber??"\u2026"} | ${g.text}`)].join(`
5
- `),"format");e.signal?.throwIfAborted();let p=await new c(12).readDocumentOutline(r,e.cwd,s.map(m=>m.content),m=>(e.signal?.throwIfAborted(),!A(u(m),n).truncated)),f=u(p);return A(f,n).truncated?void 0:{content:[{type:"text",text:f}],details:{source:r,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function z(){return async a=>{let{state:e,result:n}=a,r=n?.content.length===1?n.content[0]:void 0;if(a.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||r?.type!=="text"||!A(r.text).truncated)return{kind:"continue",context:a};let t=await b({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},a.resolverContext,{maxBytes:ie,maxLines:ce});return t===void 0?{kind:"continue",context:a}:{kind:"return",result:t}}}d(z,"createAstOverflowHandler");var X="pi-agent-ast";function K(a){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let r=await a.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),t=de(e.lines,r);return t===e.lines?e:{...e,lines:t}}catch{return e}}}}d(K,"createAstScopePresenter");function U(){return a=>{let e=a.state,n=a.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:a};let r=n.details.lines;if(r===void 0)return{kind:"continue",context:a};let t=new Map(e.text.lines.map(u=>[u.lineNumber,u])),s=new Set(r.map(u=>u.lineNumber)),o=new Map;for(let u of r){let p=t.get(u.lineNumber),f=q(p);for(let m of f?.boundaries??[]){if(s.has(m.endLine))continue;let g=t.get(m.endLine);g!==void 0&&o.set(m.endLine,g)}}if(o.size===0)return{kind:"continue",context:a};let i=[...o.values()].sort((u,p)=>u.lineNumber-p.lineNumber),c=[...r,...i],l=le(n,c,r.at(-1));return{kind:"continue",context:{...a,result:l}}}}d(U,"createAstScopePostReadHandler");function de(a,e){if(e.length===0)return a;let n=new Map,r=new Map;for(let t of e){let s=n.get(t.startLine)??[];s.push(t.beginAnchor.value),n.set(t.startLine,s);let o=r.get(t.startLine)??[];o.push({endLine:t.endLine,beginAnchor:t.beginAnchor.value,endAnchor:t.endScopeAnchor.value}),r.set(t.startLine,o);let i=n.get(t.endLine)??[];i.push(t.endScopeAnchor.value),n.set(t.endLine,i)}return a.map(t=>{let s=n.get(t.lineNumber),o=r.get(t.lineNumber);return s===void 0&&o===void 0?t:{...t,...s!==void 0&&{anchors:[...new Set([...t.anchors??[],...s])],presentation:{...t.presentation,suffix:`${t.presentation?.suffix??""}${s.map(i=>` <!-- ${i} -->`).join("")}`}},metadata:{...t.metadata,[X]:{...q(t),...o!==void 0&&{boundaries:o}}}}})}d(de,"addScopeMarkers");function q(a){let e=a?.metadata?.[X];if(!(typeof e!="object"||e===null))return e}d(q,"getAstScopeMetadata");function le(a,e,n){let r=a.content.length===1?a.content[0]:void 0;if(r?.type!=="text"||a.details.lines===void 0)return a;let t=e.slice(a.details.lines.length);if(t.length===0)return a;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:t[0]?.lineEnding!==void 0&&t[0].lineEnding.length>0?t[0].lineEnding:`
6
- `,o=t.map((l,u)=>{let f=u===t.length-1?l.lineEnding:l.lineEnding||s,m=l.presentation?.prefix??"",g=l.presentation?.suffix??"";return`${m}${l.content}${g}${f}`}).join(""),i=/(?:\r\n|\r|\n)$/.test(r.text)?"":s,c=`${r.text}${i}${o}`;return{...a,content:[{...r,text:c}],details:{...a.details,lines:e}}}d(le,"appendTextLines");var W=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function J(a){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return W.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!W.test(e))return{kind:"not-handled"};try{let t=(await a.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return t===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:t.beginAnchor.value===e?t.beginAnchor:t.endScopeAnchor}}catch(r){return{kind:"failed",error:r}}}}}d(J,"createAstScopeAnchorResolver");import ue from"cross-spawn";import{readFile as pe,stat as Y}from"node:fs/promises";import h from"node:path";function Q(a){return{id:"ast",async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let r=e.query.slice(4).trim();if(r.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let t=d(async i=>{let c=await me(r,e,n.cwd,i);c.sort((u,p)=>h.resolve(n.cwd,u.file).localeCompare(h.resolve(n.cwd,p.file))||u.range.byteOffset.start-p.range.byteOffset.start||u.range.byteOffset.end-p.range.byteOffset.end);let l=c.slice(0,e.limit??100);return{raw:l,matches:await fe(l,n.cwd,i),complete:c.length<=(e.limit??100)}},"collect"),s=await t(n.signal),o=await a({request:e,matches:s.matches,complete:s.complete,refresh:t},n);return{kind:"resolved",payload:{pattern:r,matches:s.raw.map((i,c)=>({...i,selection:s.matches[c]})),complete:s.complete,sessionId:o.id}}},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n};let r=n.matches.flatMap((t,s)=>[`SEARCH#${n.sessionId}:${String(s+1)}:match ${t.file}:${String(t.range.start.line+1)}:${String(t.range.start.column+1)} ${t.language}`,` ${t.lines.trim()}`]);return n.complete&&r.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),n.complete||r.push("Result limit reached."),{content:[{type:"text",text:r.join(`
7
- `)}],details:n}}}}d(Q,"createAstSearchResolver");async function fe(a,e,n){let r=new Map;for(let t of a){let s=h.resolve(e,t.file);if(r.has(s))continue;let o=await Y(s),i=await pe(s,{signal:n}),c=await Y(s);if(o.mtimeMs!==c.mtimeMs||o.size!==c.size)throw new Error("AST source changed during search. Run the structural query again.");r.set(s,i)}return a.map(t=>{let s=h.resolve(e,t.file),o=r.get(s);if(o===void 0)throw new Error("Missing AST source snapshot");let{start:i,end:c}=t.range.byteOffset;if(!Number.isInteger(i)||!Number.isInteger(c)||i<0||c<i||c>o.length||o.subarray(i,c).toString("utf8")!==t.text)throw new Error("AST range does not match its source snapshot. Search again.");let l=o.subarray(0,i).toString("utf8"),u=o.subarray(0,c).toString("utf8"),p=l.split(`
4
+ `));n.push(i===void 0?{status:"fail",message:`${r} parser did not return a tree`}:{status:"pass",message:`${r} parser loaded`,detail:s})}catch(o){n.push({status:"fail",message:`${r}: ${o instanceof Error?o.message:String(o)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),a.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(r=>y.has(r)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await x("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function oe(a,e){let n=a.slice(a.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}l(oe,"matchesLanguage");var ie,ce;function z(a){return{id:"ast",tryResolve(e,n){return Promise.resolve(le(e,n,a))}}}l(z,"createAstOutlineResolver");function le(a,e,n){let r;try{r=R(a,"ast")}catch(o){return{kind:"failed",error:o}}if(r===void 0)return{kind:"not-handled"};let t;try{t=b(r.path,e.cwd)}catch(o){return{kind:"failed",error:o}}return{kind:"resolved",resource:{source:w("ast",t),async read({signal:o}){o?.throwIfAborted();let i=await(ce??=import("./chunk-5QQABP47.js")),d=await(n??(ie??=new i.AstOutlineManager)).readFileOutline(t,e.cwd);return o?.throwIfAborted(),[i.formatAstOutline(d)]}}}}l(le,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as de,DEFAULT_MAX_LINES as ue,truncateHead as A}from"@earendil-works/pi-coding-agent";var S=l(async(a,e,n)=>{let{source:r,resolvedBy:t,lines:s,totalLines:o,startLine:i}=a.details;if(!(r===void 0||t!=="filesystem"||s===void 0||s.length!==o||i!==void 0&&i!==1))try{let{AstOutlineManager:c,isSupportedOutlinePath:d}=await import("./chunk-5QQABP47.js");if(!d(r))return;let u=l(m=>[`AST overview of ${m.path}, source lines 1-${m.totalLines}: the requested text exceeded the read buffer.`,"Source line numbers are on the left. Detail is reduced to fit the buffer; omitted bodies are not exact source text. Read a small source range when needed.",...m.renderedLines.map(g=>`${g.sourceLine?.lineNumber??"\u2026"} | ${g.text}`)].join(`
5
+ `),"format");e.signal?.throwIfAborted();let p=await new c(12).readDocumentOutline(r,e.cwd,s.map(m=>m.content),m=>(e.signal?.throwIfAborted(),!A(u(m),n).truncated)),f=u(p);return A(f,n).truncated?void 0:{content:[{type:"text",text:f}],details:{source:r,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function U(){return async a=>{let{state:e,result:n}=a,r=n?.content.length===1?n.content[0]:void 0;if(a.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||r?.type!=="text"||!A(r.text).truncated)return{kind:"continue",context:a};let t=await S({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},a.resolverContext,{maxBytes:de,maxLines:ue});return t===void 0?{kind:"continue",context:a}:{kind:"return",result:t}}}l(U,"createAstOverflowHandler");var X="pi-agent-ast";function K(a){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let r=await a.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),t=pe(e.lines,r);return t===e.lines?e:{...e,lines:t}}catch{return e}}}}l(K,"createAstScopePresenter");function q(){return a=>{let e=a.state,n=a.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:a};let r=n.details.lines;if(r===void 0)return{kind:"continue",context:a};let t=new Map(e.text.lines.map(u=>[u.lineNumber,u])),s=new Set(r.map(u=>u.lineNumber)),o=new Map;for(let u of r){let p=t.get(u.lineNumber),f=W(p);for(let m of f?.boundaries??[]){if(s.has(m.endLine))continue;let g=t.get(m.endLine);g!==void 0&&o.set(m.endLine,g)}}if(o.size===0)return{kind:"continue",context:a};let i=[...o.values()].sort((u,p)=>u.lineNumber-p.lineNumber),c=[...r,...i],d=fe(n,c,r.at(-1));return{kind:"continue",context:{...a,result:d}}}}l(q,"createAstScopePostReadHandler");function pe(a,e){if(e.length===0)return a;let n=new Map,r=new Map;for(let t of e){let s=n.get(t.startLine)??[];s.push(t.beginAnchor.value),n.set(t.startLine,s);let o=r.get(t.startLine)??[];o.push({endLine:t.endLine,beginAnchor:t.beginAnchor.value,endAnchor:t.endScopeAnchor.value}),r.set(t.startLine,o);let i=n.get(t.endLine)??[];i.push(t.endScopeAnchor.value),n.set(t.endLine,i)}return a.map(t=>{let s=n.get(t.lineNumber),o=r.get(t.lineNumber);return s===void 0&&o===void 0?t:{...t,...s!==void 0&&{anchors:[...new Set([...t.anchors??[],...s])],presentation:{...t.presentation,suffix:`${t.presentation?.suffix??""}${s.map(i=>` <!-- ${i} -->`).join("")}`}},metadata:{...t.metadata,[X]:{...W(t),...o!==void 0&&{boundaries:o}}}}})}l(pe,"addScopeMarkers");function W(a){let e=a?.metadata?.[X];if(!(typeof e!="object"||e===null))return e}l(W,"getAstScopeMetadata");function fe(a,e,n){let r=a.content.length===1?a.content[0]:void 0;if(r?.type!=="text"||a.details.lines===void 0)return a;let t=e.slice(a.details.lines.length);if(t.length===0)return a;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:t[0]?.lineEnding!==void 0&&t[0].lineEnding.length>0?t[0].lineEnding:`
6
+ `,o=t.map((d,u)=>{let f=u===t.length-1?d.lineEnding:d.lineEnding||s,m=d.presentation?.prefix??"",g=d.presentation?.suffix??"";return`${m}${d.content}${g}${f}`}).join(""),i=/(?:\r\n|\r|\n)$/.test(r.text)?"":s,c=`${r.text}${i}${o}`;return{...a,content:[{...r,text:c}],details:{...a.details,lines:e}}}l(fe,"appendTextLines");var J=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function Y(a){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return J.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!J.test(e))return{kind:"not-handled"};try{let t=(await a.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return t===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:t.beginAnchor.value===e?t.beginAnchor:t.endScopeAnchor}}catch(r){return{kind:"failed",error:r}}}}}l(Y,"createAstScopeAnchorResolver");import Ae from"cross-spawn";import{readFile as Se,stat as ee}from"node:fs/promises";import h from"node:path";import Z from"node:path";import{pathToFileURL as me}from"node:url";function Q(a,e,n,r,t){let s=new Map;for(let i of e){let c=s.get(i.file)??[];c.push(i),s.set(i.file,c)}let o=[...s.entries()].map(([i,c])=>ge(i,c,r));return{sessionId:t,query:a,matchCount:e.length,fileCount:o.length,complete:n,files:o}}l(Q,"createAstSearchPresentation");function ge(a,e,n){let r=new Map;e.forEach((o,i)=>{let c=o.lines.replace(/\r/gu,"").split(`
7
+ `);c.at(-1)===""&&c.pop();let d=`${a}:${String(i)}`;c.forEach((u,p)=>{let f=o.range.start.line+p+1,m=he(o,u,p,c.length);if(m===void 0)return;let g=r.get(f)??{text:u,ranges:[],logicalMatchIds:[]};g.ranges.push(m),g.logicalMatchIds.push(d),r.set(f,g)})});let t=[...r.entries()].sort(([o],[i])=>o-i).map(([o,i])=>{let c=ye(i.ranges);return{lineNumber:o,text:i.text,matchCount:c.length,ranges:c,logicalMatchIds:[...new Set(i.logicalMatchIds)]}}),s=Z.resolve(n,a);return{path:Z.relative(n,s),link:me(s).href,matchCount:e.length,lines:t}}l(ge,"createFilePresentation");function he(a,e,n,r){let t=n===0,s=n===r-1,o=t?a.range.start.column:0,i=s?a.range.end.column:e.length;if(!(i<=o))return{from:Math.min(o,e.length),to:Math.min(i,e.length)}}l(he,"highlightedRange");function ye(a){let e=[...a].sort((r,t)=>r.from-t.from||r.to-t.to),n=[];for(let r of e){let t=n.at(-1);t===void 0||r.from>t.to?n.push(r):n[n.length-1]={from:t.from,to:Math.max(t.to,r.to)}}return n}l(ye,"mergeRanges");function ne(a){return{id:"ast",renderResult:B,async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let r=e.query.slice(4).trim();if(r.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let t=l(async i=>{let c=await be(r,e,n.cwd,i);c.sort((u,p)=>h.resolve(n.cwd,u.file).localeCompare(h.resolve(n.cwd,p.file))||u.range.byteOffset.start-p.range.byteOffset.start||u.range.byteOffset.end-p.range.byteOffset.end);let d=c.slice(0,e.limit??100);return{raw:d,matches:await Re(d,n.cwd,i),complete:c.length<=(e.limit??100)}},"collect"),s=await t(n.signal),o=await a({request:e,matches:s.matches,complete:s.complete,refresh:t},n);return{kind:"resolved",payload:{pattern:r,matches:s.raw.map((i,c)=>({...i,selection:s.matches[c]})),complete:s.complete,sessionId:o.id,presentation:Q(e.query,s.raw,s.complete,n.cwd,o.id)}}},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n.presentation};let r=n.matches.flatMap((t,s)=>[`SEARCH#${n.sessionId}:${String(s+1)}:match ${t.file}:${String(t.range.start.line+1)}:${String(t.range.start.column+1)} ${t.language}`,` ${t.lines.trim()}`]);return n.complete&&r.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),n.complete||r.push("Result limit reached."),{content:[{type:"text",text:r.join(`
8
+ `)}],details:n.presentation}}}}l(ne,"createAstSearchResolver");async function Re(a,e,n){let r=new Map;for(let t of a){let s=h.resolve(e,t.file);if(r.has(s))continue;let o=await ee(s),i=await Se(s,{signal:n}),c=await ee(s);if(o.mtimeMs!==c.mtimeMs||o.size!==c.size)throw new Error("AST source changed during search. Run the structural query again.");r.set(s,i)}return a.map(t=>{let s=h.resolve(e,t.file),o=r.get(s);if(o===void 0)throw new Error("Missing AST source snapshot");let{start:i,end:c}=t.range.byteOffset;if(!Number.isInteger(i)||!Number.isInteger(c)||i<0||c<i||c>o.length||o.subarray(i,c).toString("utf8")!==t.text)throw new Error("AST range does not match its source snapshot. Search again.");let d=o.subarray(0,i).toString("utf8"),u=o.subarray(0,c).toString("utf8"),p=d.split(`
8
9
  `).length;return{source:s,lineNumber:p,endLineNumber:u.split(`
9
- `).length,startColumn:l.length-l.lastIndexOf(`
10
+ `).length,startColumn:d.length-d.lastIndexOf(`
10
11
  `)-1,endColumn:u.length-u.lastIndexOf(`
11
12
  `)-1,matchedText:t.text,lineText:o.toString("utf8").split(`
12
- `)[p-1]?.replace(/\r$/u,"")??""}})}d(fe,"selectionMatches");function me(a,e,n,r){let t=["run","--pattern",a,"--json=compact","--no-ignore","parent"];for(let s of Z(e.include))t.push("--globs",s);for(let s of Z(e.exclude))t.push("--globs",`!${s}`);return t.push(e.path??"."),new Promise((s,o)=>{let i=ue("ast-grep",t,{cwd:n,stdio:["ignore","pipe","pipe"]}),c="",l="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",p=>c+=p),i.stderr.on("data",p=>l+=p);let u=d(()=>{i.kill("SIGTERM")},"abort");r?.addEventListener("abort",u,{once:!0}),i.once("error",o),i.once("close",p=>{if(r?.removeEventListener("abort",u),r?.aborted===!0){o(r.reason instanceof Error?r.reason:new Error("AST search aborted"));return}if(p!==0&&p!==1){o(new Error(l.trim()||`ast-grep exited with code ${String(p)}`));return}try{let f=JSON.parse(c.length===0?"[]":c);if(!Array.isArray(f))throw new TypeError("ast-grep returned non-array JSON");s(f)}catch(f){o(f instanceof Error?f:new Error(String(f)))}})})}d(me,"runAstGrep");function Z(a){return a?.split(",").map(e=>e.trim()).filter(Boolean)??[]}d(Z,"splitGlobs");var ge=$({kind:"code-view",label:"AST"});async function ee(a){let e=new V,n=K(e),r={protocol:k,apiVersion:P,id:"ast",setup(s){s.addResolver({resolver:F(),renderResult:ge}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:v()}),s.addView({view:"ast",presenter:n});let o=z();s.addOutputReducer(b);let i=U();s.addHandler({stage:"post-read",async handler(c){let l=await o(c);return l.kind==="return"?l:i(l.context)}}),s.describe('ast:<path> \u2014 compact declaration outline. views: ["ast"] \u2014 scope boundaries alongside source text. Oversized code reads may return an outline with source line numbers; offset/limit read a smaller source range.')}},t={protocol:I,apiVersion:C,id:"ast",setup(s){s.addAnchorResolver({resolver:J(e),kind:N,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([M(a,r),E(a,G),_(a,t),B(a,{protocol:H,apiVersion:j,id:"ast-search",setup(s){s.addResolver({resolver:Q(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use captures in Apply to compute replacement text; these edits do not update imports or references.")}})])}d(ee,"registerAst");export{ee as default};
13
+ `)[p-1]?.replace(/\r$/u,"")??""}})}l(Re,"selectionMatches");function be(a,e,n,r){let t=["run","--pattern",a,"--json=compact","--no-ignore","parent"];for(let s of te(e.include))t.push("--globs",s);for(let s of te(e.exclude))t.push("--globs",`!${s}`);return t.push(e.path??"."),new Promise((s,o)=>{let i=Ae("ast-grep",t,{cwd:n,stdio:["ignore","pipe","pipe"]}),c="",d="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",p=>c+=p),i.stderr.on("data",p=>d+=p);let u=l(()=>{i.kill("SIGTERM")},"abort");r?.addEventListener("abort",u,{once:!0}),i.once("error",o),i.once("close",p=>{if(r?.removeEventListener("abort",u),r?.aborted===!0){o(r.reason instanceof Error?r.reason:new Error("AST search aborted"));return}if(p!==0&&p!==1){o(new Error(d.trim()||`ast-grep exited with code ${String(p)}`));return}try{let f=JSON.parse(c.length===0?"[]":c);if(!Array.isArray(f))throw new TypeError("ast-grep returned non-array JSON");s(f)}catch(f){o(f instanceof Error?f:new Error(String(f)))}})})}l(be,"runAstGrep");function te(a){return a?.split(",").map(e=>e.trim()).filter(Boolean)??[]}l(te,"splitGlobs");var we=I({kind:"code-view",label:"AST"});async function re(a){let e=new F,n=K(e),r={protocol:P,apiVersion:k,id:"ast",setup(s){s.addResolver({resolver:z(),renderResult:we}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:v()}),s.addView({view:"ast",presenter:n});let o=U();s.addOutputReducer(S);let i=q();s.addHandler({stage:"post-read",async handler(c){let d=await o(c);return d.kind==="return"?d:i(d.context)}}),s.describe('ast:<path> \u2014 compact declaration outline. views: ["ast"] \u2014 scope boundaries alongside source text. Oversized code reads may return an outline with source line numbers; offset/limit read a smaller source range.')}},t={protocol:$,apiVersion:C,id:"ast",setup(s){s.addAnchorResolver({resolver:Y(e),kind:N,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([M(a,r),E(a,G),_(a,t),j(a,{protocol:D,apiVersion:H,id:"ast-search",setup(s){s.addResolver({resolver:ne(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use captures in Apply to compute replacement text; these edits do not update imports or references.")}})])}l(re,"registerAst");export{re as default};
package/dist/entry-34.js CHANGED
@@ -1 +1 @@
1
- import{a as P}from"./chunk-MGCHOGQD.js";import{a as F,b as R}from"./chunk-T6LX2RX5.js";import{a as j}from"./chunk-HKMBQLEK.js";import{a as h,b as v}from"./chunk-Z3VC3S2T.js";import{b as C,c as w,g as k,i as x,j as g,l as u,m as E}from"./chunk-M5MJP7Z2.js";import{a as b}from"./chunk-WZI4YC2O.js";import"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as f}from"./chunk-EI7MMDWY.js";import{copyFile as $,mkdtemp as A,rm as M}from"node:fs/promises";import y from"node:path";var D=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".html",".md",".yaml",".yml",".vue",".svelte"],z=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".less",".html",".htm",".md",".markdown",".mdx",".yaml",".yml",".toml"],d=[e("dart-format",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],[".dart"],["dart","format","{file}"],"https://dart.dev/tools/dart-format"),e("zig-format",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","fmt","{file}"],"https://ziglang.org/documentation/master/"),e("styler",["r"],["Rscript"],[".Rprofile","DESCRIPTION"],[".r"],["Rscript","-e","styler::style_file(commandArgs(TRUE)[1])","{file}"],"https://styler.r-lib.org/"),e("clang-format",["c","cpp"],["clang-format"],[".clang-format","_clang-format"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-format","-i","{file}"],"https://clang.llvm.org/docs/ClangFormat.html"),e("prettier",["javascript","typescript","html","css","json","yaml","markdown","vue","svelte"],["prettier"],[".prettierrc",".prettierrc.json",".prettierrc.json5",".prettierrc.yaml",".prettierrc.yml",".prettierrc.toml",".prettierrc.js",".prettierrc.cjs",".prettierrc.mjs","prettier.config.js","prettier.config.cjs","prettier.config.mjs","prettier.config.ts","prettier.config.mts","prettier.config.cts"],D,["prettier","--write","{file}"],"https://prettier.io/docs/",["prettier"],{"package.json":["prettier"]}),e("biome",["javascript","typescript","json","css"],["biome"],["biome.json","biome.jsonc"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css"],["biome","format","--write","{file}"],"https://biomejs.dev/",["@biomejs/biome"]),e("oxfmt",["javascript","typescript","json","css","html","markdown","yaml","toml"],["oxfmt"],[".oxfmtrc.json",".oxfmtrc.jsonc","oxfmt.config.ts","oxfmt.config.mts"],z,["oxfmt","--write","{file}"],"https://oxc.rs/docs/guide/usage/formatter.html",["oxfmt"]),e("ruff-format",["python"],["ruff"],["ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","format","{file}"],"https://docs.astral.sh/ruff/formatter/",["ruff"],{"pyproject.toml":["tool.ruff"]}),e("black",["python"],["black"],[],[".py",".pyi"],["black","--quiet","{file}"],"https://black.readthedocs.io/",["black"],{"pyproject.toml":["tool.black"]}),e("gofmt",["go"],["gofmt"],["go.mod"],[".go"],["gofmt","-w","{file}"],"https://pkg.go.dev/cmd/gofmt"),e("goimports",["go"],["goimports"],["go.mod"],[".go"],["goimports","-w","{file}"],"https://pkg.go.dev/golang.org/x/tools/cmd/goimports"),e("rustfmt",["rust"],["rustfmt"],["rustfmt.toml",".rustfmt.toml","Cargo.toml"],[".rs"],["rustfmt","{file}"],"https://github.com/rust-lang/rustfmt"),e("csharpier",["csharp"],["csharpier"],[".csharpierrc",".csharpierrc.json",".csharpierrc.yaml",".csharpierrc.yml"],[".cs"],["csharpier","format","{file}"],"https://csharpier.com/"),e("google-java-format",["java"],["google-java-format"],["pom.xml","build.gradle"],[".java"],["google-java-format","--replace","{file}"],"https://github.com/google/google-java-format"),e("ktlint-format",["kotlin"],["ktlint"],[".editorconfig","build.gradle.kts"],[".kt",".kts"],["ktlint","-F","{file}"],"https://pinterest.github.io/ktlint/"),e("rubocop-format",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--fix-layout","{file}"],"https://docs.rubocop.org/"),e("pint",["php"],["pint"],["pint.json","composer.json"],[".php"],["pint","{file}"],"https://laravel.com/docs/pint"),e("swift-format",["swift"],["swift-format"],[".swift-format","Package.swift"],[".swift"],["swift-format","format","--in-place","{file}"],"https://github.com/swiftlang/swift-format"),e("stylua",["lua"],["stylua"],["stylua.toml",".stylua.toml"],[".lua"],["stylua","{file}"],"https://github.com/JohnnyMorganz/StyLua"),e("shfmt",["shell"],["shfmt"],[".editorconfig"],[".sh",".bash",".zsh"],["shfmt","-w","{file}"],"https://github.com/mvdan/sh"),e("taplo",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","format","{file}"],"https://taplo.tamasfe.dev/"),e("sqlfluff-format",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","format","{file}"],"https://docs.sqlfluff.com/"),e("terraform-fmt",["terraform"],["terraform"],[".terraform.lock.hcl"],[".tf",".tfvars"],["terraform","fmt","{file}"],"https://developer.hashicorp.com/terraform/cli/commands/fmt"),e("cmake-format",["cmake"],["cmake-format"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-format","-i","{file}"],"https://cmake-format.readthedocs.io/",void 0,void 0,["CMakeLists.txt"]),e("xmlformat",["xml"],["xmlformat"],[".xmlformat.conf"],[".xml",".xsd",".xsl"],["xmlformat","--overwrite","{file}"],"https://github.com/pamoller/xmlformatter"),e("mix-format",["elixir"],["mix"],["mix.exs",".formatter.exs"],[".ex",".exs"],["mix","format","{file}"],"https://hexdocs.pm/mix/Mix.Tasks.Format.html"),e("scalafmt",["scala"],["scalafmt"],[".scalafmt.conf"],[".scala",".sc",".sbt"],["scalafmt","{file}"],"https://scalameta.org/scalafmt/"),e("julia-format",["julia"],["julia"],[".JuliaFormatter.toml","Project.toml"],[".jl"],["julia","--startup-file=no","--history-file=no","-e","using JuliaFormatter; format_file(ARGS[1])","{file}"],"https://github.com/domluna/JuliaFormatter.jl"),e("powershell-format",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$p=$args[0];$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};[IO.File]::WriteAllText($p,(Invoke-Formatter -ScriptDefinition ([IO.File]::ReadAllText($p)) @options))',"{file}"],"https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-formatter"),e("dockfmt",["dockerfile"],["dockfmt"],["Dockerfile","Containerfile"],[".dockerfile"],["dockfmt","fmt","--write","{file}"],"https://github.com/jessfraz/dockfmt",void 0,void 0,["Dockerfile","Containerfile"])];function e(o,t,r,i,n,m,a,l,s,c){return{id:o,name:o,kind:"formatter",languages:t,executables:r,configFiles:i,documentation:a,...l&&{dependencies:l},...s&&{configSections:s},formatter:{extensions:n,...c&&{fileNames:c},run:{command:m},output:"in-place"}}}f(e,"recipe");var p=class o{constructor(t,r,i=new Map){this.formatters=t;this.availableBuiltIns=r;this.evidence=i}static{f(this,"FormatterCommandRegistry")}static async fromDirectory(t,r={}){let i=await k(t,"formatters",s=>E(s).formatters,r),n=r.environment??process.env,m=await Promise.all(i.entries.filter(s=>s.layer==="built-in").map(async s=>({id:s.id,available:await g(s.config.run,t,n)}))),a=await b(t,d),l=[...i.entries].sort((s,c)=>s.layer==="built-in"&&c.layer==="built-in"?(a.get(c.id)?.score??0)-(a.get(s.id)?.score??0):0);return new o(l,new Set(m.filter(s=>s.available&&(!r.requireBuiltInEvidence||(a.get(s.id)?.score??0)>0)).map(s=>s.id)),a)}static fromConfig(t){return new o(Object.entries(t.formatters).map(([r,i])=>({id:r,config:i,layer:"project",sourcePath:"<memory>"})),new Set)}resolve(t,r){return this.resolveEntry(t,r)?.config}resolveEntry(t,r){return x(this.formatters,this.availableBuiltIns,this.evidence,t,r)}get entries(){return this.formatters}};var T={protocol:F,apiVersion:1,id:"formatter",setup(o){for(let t of d)o.addToolRecipe(t);o.addSetupCheck({id:"effective-config",inspect:_}),o.addCheck({id:"config",title:"Formatter",async run(t){try{let r=await p.fromDirectory(t.cwd,{environment:t.env}),i=q(r,t.files,t.cwd);return i.length===0?[{status:"skip",message:"No formatter matches the inspected project files"}]:await Promise.all(i.map(async({entry:n,source:m})=>{let a=`${n.id} [${n.layer}] command ${JSON.stringify(n.config.run.command)}`,l=await A(y.join(y.dirname(m),".pi-agent-ide-doctor-")),s=y.join(l,y.basename(m));try{return await $(m,s),(await u(n.config,{projectRoot:t.cwd,filePath:s,env:t.env})).ok?{status:"pass",message:`${a}: probe passed`,detail:n.sourcePath}:{status:"fail",message:`${a}: probe failed`,detail:n.sourcePath}}catch(c){return{status:"fail",message:`${a}: ${c instanceof Error?c.message:String(c)}`,detail:n.sourcePath}}finally{await M(l,{recursive:!0,force:!0})}}))}catch(r){return[{status:"fail",message:r instanceof Error?r.message:String(r)}]}}})}};async function _(o){try{let t=await p.fromDirectory(o.cwd,{environment:o.env}),r=[],i=new Map;for(let[n,m]of o.detectedLanguages){let a=m.map(l=>t.resolveEntry(l,o.cwd)).find(l=>l!==void 0);a!==void 0&&(r.push({kind:"formatter",languageId:n,toolId:a.id}),await g(a.config.run,o.cwd,o.env)||i.set(a.id,{id:`formatter-${a.id}-unavailable`,message:`Configured formatter ${a.id} cannot run ${JSON.stringify(a.config.run.command)}`}))}return{selections:r,actions:[...i.values()]}}catch(t){return{actions:[{id:"formatter-config-invalid",message:`Formatter configuration cannot load: ${t instanceof Error?t.message:String(t)}`}]}}}f(_,"inspectFormatterSetup");function q(o,t,r){let i=new Map;for(let n of t){let m=o.resolveEntry(n,r);m!==void 0&&!i.has(m.id)&&i.set(m.id,{entry:m,source:n})}return[...i.values()]}f(q,"applicableFormatters");import L from"node:path";var S=new Map;function O(){return{kind:"formatter",name:"formatter",priority:100,extensions:["*"],detect:f(async o=>(await I(o.cwd),!0),"detect"),async format({filePath:o},t){let r=await w(t.cwd,o,"formatters",d);if(r===void 0)return{ok:!0,edits:0,formatter:null};let i=r!==L.resolve(t.cwd),m=(await I(r,i)).resolve(o,r);if(m===void 0)return{ok:!0,edits:0,formatter:null};let a=C(m.run.command);try{let l=await u(m,{projectRoot:r,filePath:o});return{ok:l.ok,edits:l.changed?1:0,formatter:a}}catch{return{ok:!1,edits:0,formatter:a}}}}}f(O,"createFormatter");async function I(o,t=!1){let r=JSON.stringify([o,t]),i=S.get(r);return i===void 0&&(i=p.fromDirectory(o,{includeGlobal:!t,requireBuiltInEvidence:!0}),S.set(r,i)),i}f(I,"loadRegistry");async function N(o){let t={kind:"formatter",name:"pi-agent-ide-formatter",priority:200,extensions:["*"],detect:f(()=>Promise.resolve(!0),"detect"),async format(i,n){return O().format(i,n)}},r={protocol:h,apiVersion:4,id:"formatter",setup(i){i.addTool(t)}};await Promise.all([j(o,r),P(o,T)])}f(N,"registerFormatter");export{N as default};
1
+ import{a as P}from"./chunk-MGCHOGQD.js";import{a as F,b as R}from"./chunk-T6LX2RX5.js";import{a as j}from"./chunk-QDLTO5PH.js";import{a as h,b as v}from"./chunk-QIK2E64R.js";import{b as C,c as w,g as k,i as x,j as g,l as u,m as E}from"./chunk-M5MJP7Z2.js";import{a as b}from"./chunk-WZI4YC2O.js";import"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as f}from"./chunk-EI7MMDWY.js";import{copyFile as $,mkdtemp as A,rm as M}from"node:fs/promises";import y from"node:path";var D=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".html",".md",".yaml",".yml",".vue",".svelte"],z=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".less",".html",".htm",".md",".markdown",".mdx",".yaml",".yml",".toml"],d=[e("dart-format",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],[".dart"],["dart","format","{file}"],"https://dart.dev/tools/dart-format"),e("zig-format",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","fmt","{file}"],"https://ziglang.org/documentation/master/"),e("styler",["r"],["Rscript"],[".Rprofile","DESCRIPTION"],[".r"],["Rscript","-e","styler::style_file(commandArgs(TRUE)[1])","{file}"],"https://styler.r-lib.org/"),e("clang-format",["c","cpp"],["clang-format"],[".clang-format","_clang-format"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-format","-i","{file}"],"https://clang.llvm.org/docs/ClangFormat.html"),e("prettier",["javascript","typescript","html","css","json","yaml","markdown","vue","svelte"],["prettier"],[".prettierrc",".prettierrc.json",".prettierrc.json5",".prettierrc.yaml",".prettierrc.yml",".prettierrc.toml",".prettierrc.js",".prettierrc.cjs",".prettierrc.mjs","prettier.config.js","prettier.config.cjs","prettier.config.mjs","prettier.config.ts","prettier.config.mts","prettier.config.cts"],D,["prettier","--write","{file}"],"https://prettier.io/docs/",["prettier"],{"package.json":["prettier"]}),e("biome",["javascript","typescript","json","css"],["biome"],["biome.json","biome.jsonc"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css"],["biome","format","--write","{file}"],"https://biomejs.dev/",["@biomejs/biome"]),e("oxfmt",["javascript","typescript","json","css","html","markdown","yaml","toml"],["oxfmt"],[".oxfmtrc.json",".oxfmtrc.jsonc","oxfmt.config.ts","oxfmt.config.mts"],z,["oxfmt","--write","{file}"],"https://oxc.rs/docs/guide/usage/formatter.html",["oxfmt"]),e("ruff-format",["python"],["ruff"],["ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","format","{file}"],"https://docs.astral.sh/ruff/formatter/",["ruff"],{"pyproject.toml":["tool.ruff"]}),e("black",["python"],["black"],[],[".py",".pyi"],["black","--quiet","{file}"],"https://black.readthedocs.io/",["black"],{"pyproject.toml":["tool.black"]}),e("gofmt",["go"],["gofmt"],["go.mod"],[".go"],["gofmt","-w","{file}"],"https://pkg.go.dev/cmd/gofmt"),e("goimports",["go"],["goimports"],["go.mod"],[".go"],["goimports","-w","{file}"],"https://pkg.go.dev/golang.org/x/tools/cmd/goimports"),e("rustfmt",["rust"],["rustfmt"],["rustfmt.toml",".rustfmt.toml","Cargo.toml"],[".rs"],["rustfmt","{file}"],"https://github.com/rust-lang/rustfmt"),e("csharpier",["csharp"],["csharpier"],[".csharpierrc",".csharpierrc.json",".csharpierrc.yaml",".csharpierrc.yml"],[".cs"],["csharpier","format","{file}"],"https://csharpier.com/"),e("google-java-format",["java"],["google-java-format"],["pom.xml","build.gradle"],[".java"],["google-java-format","--replace","{file}"],"https://github.com/google/google-java-format"),e("ktlint-format",["kotlin"],["ktlint"],[".editorconfig","build.gradle.kts"],[".kt",".kts"],["ktlint","-F","{file}"],"https://pinterest.github.io/ktlint/"),e("rubocop-format",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--fix-layout","{file}"],"https://docs.rubocop.org/"),e("pint",["php"],["pint"],["pint.json","composer.json"],[".php"],["pint","{file}"],"https://laravel.com/docs/pint"),e("swift-format",["swift"],["swift-format"],[".swift-format","Package.swift"],[".swift"],["swift-format","format","--in-place","{file}"],"https://github.com/swiftlang/swift-format"),e("stylua",["lua"],["stylua"],["stylua.toml",".stylua.toml"],[".lua"],["stylua","{file}"],"https://github.com/JohnnyMorganz/StyLua"),e("shfmt",["shell"],["shfmt"],[".editorconfig"],[".sh",".bash",".zsh"],["shfmt","-w","{file}"],"https://github.com/mvdan/sh"),e("taplo",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","format","{file}"],"https://taplo.tamasfe.dev/"),e("sqlfluff-format",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","format","{file}"],"https://docs.sqlfluff.com/"),e("terraform-fmt",["terraform"],["terraform"],[".terraform.lock.hcl"],[".tf",".tfvars"],["terraform","fmt","{file}"],"https://developer.hashicorp.com/terraform/cli/commands/fmt"),e("cmake-format",["cmake"],["cmake-format"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-format","-i","{file}"],"https://cmake-format.readthedocs.io/",void 0,void 0,["CMakeLists.txt"]),e("xmlformat",["xml"],["xmlformat"],[".xmlformat.conf"],[".xml",".xsd",".xsl"],["xmlformat","--overwrite","{file}"],"https://github.com/pamoller/xmlformatter"),e("mix-format",["elixir"],["mix"],["mix.exs",".formatter.exs"],[".ex",".exs"],["mix","format","{file}"],"https://hexdocs.pm/mix/Mix.Tasks.Format.html"),e("scalafmt",["scala"],["scalafmt"],[".scalafmt.conf"],[".scala",".sc",".sbt"],["scalafmt","{file}"],"https://scalameta.org/scalafmt/"),e("julia-format",["julia"],["julia"],[".JuliaFormatter.toml","Project.toml"],[".jl"],["julia","--startup-file=no","--history-file=no","-e","using JuliaFormatter; format_file(ARGS[1])","{file}"],"https://github.com/domluna/JuliaFormatter.jl"),e("powershell-format",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$p=$args[0];$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};[IO.File]::WriteAllText($p,(Invoke-Formatter -ScriptDefinition ([IO.File]::ReadAllText($p)) @options))',"{file}"],"https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-formatter"),e("dockfmt",["dockerfile"],["dockfmt"],["Dockerfile","Containerfile"],[".dockerfile"],["dockfmt","fmt","--write","{file}"],"https://github.com/jessfraz/dockfmt",void 0,void 0,["Dockerfile","Containerfile"])];function e(o,t,r,i,n,m,a,l,s,c){return{id:o,name:o,kind:"formatter",languages:t,executables:r,configFiles:i,documentation:a,...l&&{dependencies:l},...s&&{configSections:s},formatter:{extensions:n,...c&&{fileNames:c},run:{command:m},output:"in-place"}}}f(e,"recipe");var p=class o{constructor(t,r,i=new Map){this.formatters=t;this.availableBuiltIns=r;this.evidence=i}static{f(this,"FormatterCommandRegistry")}static async fromDirectory(t,r={}){let i=await k(t,"formatters",s=>E(s).formatters,r),n=r.environment??process.env,m=await Promise.all(i.entries.filter(s=>s.layer==="built-in").map(async s=>({id:s.id,available:await g(s.config.run,t,n)}))),a=await b(t,d),l=[...i.entries].sort((s,c)=>s.layer==="built-in"&&c.layer==="built-in"?(a.get(c.id)?.score??0)-(a.get(s.id)?.score??0):0);return new o(l,new Set(m.filter(s=>s.available&&(!r.requireBuiltInEvidence||(a.get(s.id)?.score??0)>0)).map(s=>s.id)),a)}static fromConfig(t){return new o(Object.entries(t.formatters).map(([r,i])=>({id:r,config:i,layer:"project",sourcePath:"<memory>"})),new Set)}resolve(t,r){return this.resolveEntry(t,r)?.config}resolveEntry(t,r){return x(this.formatters,this.availableBuiltIns,this.evidence,t,r)}get entries(){return this.formatters}};var T={protocol:F,apiVersion:1,id:"formatter",setup(o){for(let t of d)o.addToolRecipe(t);o.addSetupCheck({id:"effective-config",inspect:_}),o.addCheck({id:"config",title:"Formatter",async run(t){try{let r=await p.fromDirectory(t.cwd,{environment:t.env}),i=q(r,t.files,t.cwd);return i.length===0?[{status:"skip",message:"No formatter matches the inspected project files"}]:await Promise.all(i.map(async({entry:n,source:m})=>{let a=`${n.id} [${n.layer}] command ${JSON.stringify(n.config.run.command)}`,l=await A(y.join(y.dirname(m),".pi-agent-ide-doctor-")),s=y.join(l,y.basename(m));try{return await $(m,s),(await u(n.config,{projectRoot:t.cwd,filePath:s,env:t.env})).ok?{status:"pass",message:`${a}: probe passed`,detail:n.sourcePath}:{status:"fail",message:`${a}: probe failed`,detail:n.sourcePath}}catch(c){return{status:"fail",message:`${a}: ${c instanceof Error?c.message:String(c)}`,detail:n.sourcePath}}finally{await M(l,{recursive:!0,force:!0})}}))}catch(r){return[{status:"fail",message:r instanceof Error?r.message:String(r)}]}}})}};async function _(o){try{let t=await p.fromDirectory(o.cwd,{environment:o.env}),r=[],i=new Map;for(let[n,m]of o.detectedLanguages){let a=m.map(l=>t.resolveEntry(l,o.cwd)).find(l=>l!==void 0);a!==void 0&&(r.push({kind:"formatter",languageId:n,toolId:a.id}),await g(a.config.run,o.cwd,o.env)||i.set(a.id,{id:`formatter-${a.id}-unavailable`,message:`Configured formatter ${a.id} cannot run ${JSON.stringify(a.config.run.command)}`}))}return{selections:r,actions:[...i.values()]}}catch(t){return{actions:[{id:"formatter-config-invalid",message:`Formatter configuration cannot load: ${t instanceof Error?t.message:String(t)}`}]}}}f(_,"inspectFormatterSetup");function q(o,t,r){let i=new Map;for(let n of t){let m=o.resolveEntry(n,r);m!==void 0&&!i.has(m.id)&&i.set(m.id,{entry:m,source:n})}return[...i.values()]}f(q,"applicableFormatters");import L from"node:path";var S=new Map;function O(){return{kind:"formatter",name:"formatter",priority:100,extensions:["*"],detect:f(async o=>(await I(o.cwd),!0),"detect"),async format({filePath:o},t){let r=await w(t.cwd,o,"formatters",d);if(r===void 0)return{ok:!0,edits:0,formatter:null};let i=r!==L.resolve(t.cwd),m=(await I(r,i)).resolve(o,r);if(m===void 0)return{ok:!0,edits:0,formatter:null};let a=C(m.run.command);try{let l=await u(m,{projectRoot:r,filePath:o});return{ok:l.ok,edits:l.changed?1:0,formatter:a}}catch{return{ok:!1,edits:0,formatter:a}}}}}f(O,"createFormatter");async function I(o,t=!1){let r=JSON.stringify([o,t]),i=S.get(r);return i===void 0&&(i=p.fromDirectory(o,{includeGlobal:!t,requireBuiltInEvidence:!0}),S.set(r,i)),i}f(I,"loadRegistry");async function N(o){let t={kind:"formatter",name:"pi-agent-ide-formatter",priority:200,extensions:["*"],detect:f(()=>Promise.resolve(!0),"detect"),async format(i,n){return O().format(i,n)}},r={protocol:h,apiVersion:4,id:"formatter",setup(i){i.addTool(t)}};await Promise.all([j(o,r),P(o,T)])}f(N,"registerFormatter");export{N as default};
package/dist/entry-36.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as _}from"./chunk-MGCHOGQD.js";import{a as T,b as N}from"./chunk-T6LX2RX5.js";import{a as O}from"./chunk-K5G4FDXD.js";import{a as P}from"./chunk-HKMBQLEK.js";import{a as j,b as L}from"./chunk-Z3VC3S2T.js";import{b as E,c as S,g as D,i as $,j as C,k as I,n as A}from"./chunk-M5MJP7Z2.js";import{a as R}from"./chunk-WZI4YC2O.js";import"./chunk-N34ATN52.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import le from"node:path";var p=[c("dart-analyze",["dart"],["dart"],["analysis_options.yaml","pubspec.yaml"],[".dart"],["dart","analyze","--format","machine","{file}"],"regex","https://dart.dev/tools/dart-analyze","^(?<severity>[^|]+)\\|[^|]+\\|(?<code>[^|]+)\\|(?<file>[^|]+)\\|(?<line>\\d+)\\|(?<column>\\d+)\\|\\d+\\|(?<message>.*)$",void 0,[0,1,2,3]),c("zig-ast-check",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","ast-check","{file}"],"gcc","https://ziglang.org/documentation/master/"),c("lintr",["r"],["Rscript"],[".lintr","DESCRIPTION"],[".r"],["Rscript","-e","print(lintr::lint(commandArgs(TRUE)[1]))","{file}"],"regex","https://lintr.r-lib.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[^:]+): \\[(?<code>[^\\]]+)\\] (?<message>.*)$"),c("clang-tidy",["c","cpp"],["clang-tidy"],[".clang-tidy","compile_commands.json"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-tidy","{file}"],"clang","https://clang.llvm.org/extra/clang-tidy/"),c("eslint",["javascript","typescript","vue","svelte"],["eslint"],["eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","eslint.config.mts","eslint.config.cts",".eslintrc",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".eslintrc.yaml",".eslintrc.yml"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".vue",".svelte"],["eslint","--format","json","{file}"],"eslint-json","https://eslint.org/docs/latest/",void 0,["eslint"]),c("oxlint",["javascript","typescript"],["oxlint"],[".oxlintrc.json",".oxlintrc.jsonc","oxlint.config.ts","oxlint.config.mts"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],["oxlint","--format","sarif","{file}"],"sarif","https://oxc.rs/docs/guide/usage/linter.html",void 0,["oxlint"]),c("ruff",["python"],["ruff"],["pyproject.toml","ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","check","--output-format","concise","{file}"],"regex","https://docs.astral.sh/ruff/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<code>\\S+) (?<message>.+)$",["ruff"]),c("golangci-lint",["go"],["golangci-lint"],[".golangci.yml",".golangci.yaml","go.mod"],[".go"],["golangci-lint","run","--output.text.path=","--output.checkstyle.path=stdout","--show-stats=false","./..."],"checkstyle","https://golangci-lint.run/"),c("clippy",["rust"],["cargo"],["Cargo.toml","clippy.toml"],[".rs"],["cargo","clippy","--message-format","short"],"gcc","https://doc.rust-lang.org/clippy/"),c("dotnet-format",["csharp"],["dotnet"],[".editorconfig","global.json"],[".cs"],["dotnet","format","--verify-no-changes","--include","{relativeFile}"],"regex","https://learn.microsoft.com/dotnet/core/tools/dotnet-format","^(?<file>.+)\\((?<line>\\d+),(?<column>\\d+)\\): (?<severity>error|warning) (?<code>[^:]+): (?<message>.*?)(?: \\[.*\\])?$",void 0,[0,2]),c("checkstyle",["java"],["checkstyle"],["checkstyle.xml","pom.xml"],[".java"],["checkstyle","-c","checkstyle.xml","-f","xml","{file}"],"checkstyle","https://checkstyle.org/"),c("detekt",["kotlin"],["detekt"],["detekt.yml","build.gradle.kts"],[".kt",".kts"],["detekt","--input","{file}","--config","detekt.yml"],"regex","https://detekt.dev/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<message>.*?) \\[(?<code>[^\\]]+)\\]$",void 0,[0,2]),c("rubocop",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--format","clang","{file}"],"regex","https://docs.rubocop.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?:\\[Correctable\\] )?(?<code>[^:]+): (?<message>.*)$"),c("phpcs",["php"],["phpcs"],["phpcs.xml","phpcs.xml.dist","composer.json"],[".php"],["phpcs","--report=checkstyle","{file}"],"checkstyle","https://github.com/PHPCSStandards/PHP_CodeSniffer",void 0,void 0,[0,1,2,3]),c("swiftlint",["swift"],["swiftlint"],[".swiftlint.yml","Package.swift"],[".swift"],["swiftlint","lint","--quiet","--reporter","checkstyle","{file}"],"checkstyle","https://github.com/realm/SwiftLint",void 0,void 0,[0,2]),c("scalafix",["scala"],["scalafix"],[".scalafix.conf"],[".scala",".sc"],["scalafix","--check","--files","{file}"],"gcc","https://scalacenter.github.io/scalafix/",void 0,void 0,[0,2,64,66]),c("credo",["elixir"],["mix"],["mix.exs",".credo.exs"],[".ex",".exs"],["mix","credo","--strict","--format","flycheck","--files-included","{file}"],"regex","https://hexdocs.pm/credo/","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?<message>.+)$",void 0,Array.from({length:32},(t,e)=>e)),c("psscriptanalyzer",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};Invoke-ScriptAnalyzer -Path $args[0] @options | ForEach-Object {"$($_.ScriptPath):$($_.Line):$($_.Column): $($_.Severity): $($_.Message) [$($_.RuleName)]"}',"{file}"],"regex","https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-scriptanalyzer","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>\\w+): (?<message>.+) \\[(?<code>[^\\]]+)\\]$",void 0,[0]),c("luacheck",["lua"],["luacheck"],[".luacheckrc"],[".lua"],["luacheck","--formatter","plain","--codes","--no-color","{file}"],"regex","https://github.com/lunarmodules/luacheck","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): \\((?<code>(?<severity>[WE])\\d+)\\) (?<message>.+)$",void 0,[0,1,2]),c("shellcheck",["shell"],["shellcheck"],[".shellcheckrc"],[".sh",".bash",".zsh"],["shellcheck","-f","gcc","{file}"],"gcc","https://www.shellcheck.net/"),c("stylelint",["css"],["stylelint"],["stylelint.config.js",".stylelintrc.json"],[".css",".scss",".sass",".less"],["stylelint","--formatter","compact","{file}"],"regex","https://stylelint.io/","^(?<file>.+): line (?<line>\\d+), col (?<column>\\d+), (?<severity>error|warning) - (?<message>.+) \\((?<code>[^)]+)\\)$",["stylelint"],[0,2]),c("yamllint",["yaml"],["yamllint"],[".yamllint",".yamllint.yml"],[".yaml",".yml"],["yamllint","-f","parsable","{file}"],"regex","https://yamllint.readthedocs.io/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): \\[(?<severity>[^\\]]+)\\] (?<message>.*?) \\((?<code>[^)]+)\\)$"),c("markdownlint",["markdown"],["markdownlint"],[".markdownlint.json",".markdownlint.yaml"],[".md",".mdx"],["markdownlint","{file}"],"regex","https://github.com/DavidAnson/markdownlint","^(?<file>.+?):(?<line>\\d+)(?::(?<column>\\d+))? (?<severity>error|warning) (?<code>MD\\d+)(?:/\\S+)? (?<message>.*)$"),c("sqlfluff",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","lint","--format","sarif","{file}"],"sarif","https://docs.sqlfluff.com/"),c("hadolint",["dockerfile"],["hadolint"],[".hadolint.yaml"],[".dockerfile"],["hadolint","--format","checkstyle","{file}"],"checkstyle","https://github.com/hadolint/hadolint",void 0,void 0,[0,1],void 0,["Dockerfile","Containerfile"]),c("tflint",["terraform"],["tflint"],[".tflint.hcl"],[".tf"],["tflint","--format","checkstyle"],"checkstyle","https://github.com/terraform-linters/tflint",void 0,void 0,[0,2]),c("cmake-lint",["cmake"],["cmake-lint"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-lint","{file}"],"regex","https://cmake-format.readthedocs.io/","^(?<file>.+?):(?<line>\\d+),(?<column>\\d+): \\[(?<code>(?<severity>[A-Z])\\d+)\\] (?<message>.*)$",void 0,[0,1],0,["CMakeLists.txt"]),c("htmlhint",["html"],["htmlhint"],[".htmlhintrc"],[".html",".htm"],["htmlhint","--format","checkstyle","--nocolor","{file}"],"checkstyle","https://htmlhint.com/"),c("jsonlint",["json"],["jsonlint"],[".jsonlintrc",".jsonlintrc.json",".jsonlintrc.yaml",".jsonlintrc.yml",".jsonlintrc.js",".jsonlintrc.cjs","jsonlint.config.js","jsonlint.config.cjs"],[".json"],["jsonlint","-q","{file}"],"regex","https://github.com/prantlf/jsonlint","^(?:Error: )?(?<message>Parse (?<severity>error) on line (?<line>\\d+)(?:, column (?<column>\\d+))?:[^\\n]*)$",["@prantlf/jsonlint","jsonlint"]),c("taplo-check",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","check","--colors","never","{file}"],"regex","https://taplo.tamasfe.dev/","^(?<severity>error): (?<message>[^\\n]+)\\n\\s*\u250C\u2500 (?<file>.+):(?<line>\\d+):(?<column>\\d+)"),c("xmllint",["xml"],["xmllint"],[".xmllintrc"],[".xml",".xsd",".xsl"],["xmllint","--noout","{file}"],"regex","https://gnome.pages.gitlab.gnome.org/libxml2/xmllint.html","^(?<file>.+?):(?<line>\\d+): (?<severity>(?:parser |validity )?(?:error|warning)) : (?<message>.*)$",void 0,[0,1,2,3,4])];function c(t,e,n,i,o,f,s,l,r,d,b=[0,1],u,h){return{id:t,name:t,kind:"linter",languages:e,executables:n,configFiles:i,documentation:l,...d&&{dependencies:d},linter:{extensions:o,...h&&{fileNames:h},check:{command:f,successExitCodes:b},diagnostics:{format:s,...r&&{pattern:r},...u!==void 0&&{columnBase:u}}}}}a(c,"recipe");import w from"node:path";import ee from"node:os";import{fileURLToPath as te}from"node:url";function F(t,e){if(t.trim().length===0)return[];switch(e.format){case"pi-json":return B(t);case"eslint-json":return G(t);case"sarif":return H(t);case"checkstyle":return U(t);case"gcc":case"clang":return W(t);case"regex":return Z(t,g(e.pattern),e.columnBase??1)}}a(F,"parseDiagnostics");function B(t){let e=JSON.parse(t);return Array.isArray(e.diagnostics)?e.diagnostics.flatMap(y):[]}a(B,"parsePiJson");function G(t){return JSON.parse(t).flatMap(n=>Array.isArray(n.messages)?n.messages.flatMap(i=>y(i).map(o=>({...o,...n.filePath&&{file:n.filePath}}))):[])}a(G,"parseEslintJson");function H(t){return(JSON.parse(t).runs??[]).flatMap(n=>(n.results??[]).flatMap(i=>{let o=i.locations?.[0]?.physicalLocation,f=o?.region??{},s=i.message;return y({file:o?.artifactLocation?.uri,line:f.startLine,column:f.startColumn,message:s?.text,code:i.ruleId,severity:Q(i.level)})}))}a(H,"parseSarif");function U(t){let e=[];for(let n of t.matchAll(/<file\s+([^>]+)>([\s\S]*?)<\/file>/gu)){let i=z(g(n[1])).name;for(let o of g(n[2]).matchAll(/<error\s+([^>]+?)\/?>(?:<\/error>)?/gu)){let f=z(g(o[1]));e.push(...y({file:i,line:Number(f.line),column:Number(f.column??1),message:f.message,code:f.source,severity:f.severity}))}}return e}a(U,"parseCheckstyle");function z(t){return Object.fromEntries([...t.matchAll(/([\w-]+)="([^"]*)"/gu)].map(e=>[g(e[1]),Y(g(e[2]))]))}a(z,"xmlAttributes");function W(t){return X(t,/^(?<file>.+?):(?<line>\d+):(?<column>\d+):\s*(?<severity>fatal error|error|warning|note|info|hint):\s*(?<message>.*?)(?:\s+\[(?<code>[^\]]+)\])?$/u)}a(W,"parseCompilerLines");function Z(t,e,n){return[...t.replaceAll(`\r
1
+ import{a as _}from"./chunk-MGCHOGQD.js";import{a as T,b as N}from"./chunk-T6LX2RX5.js";import{a as O}from"./chunk-K5G4FDXD.js";import{a as P}from"./chunk-QDLTO5PH.js";import{a as j,b as L}from"./chunk-QIK2E64R.js";import{b as E,c as S,g as D,i as $,j as C,k as I,n as A}from"./chunk-M5MJP7Z2.js";import{a as R}from"./chunk-WZI4YC2O.js";import"./chunk-N34ATN52.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import le from"node:path";var p=[c("dart-analyze",["dart"],["dart"],["analysis_options.yaml","pubspec.yaml"],[".dart"],["dart","analyze","--format","machine","{file}"],"regex","https://dart.dev/tools/dart-analyze","^(?<severity>[^|]+)\\|[^|]+\\|(?<code>[^|]+)\\|(?<file>[^|]+)\\|(?<line>\\d+)\\|(?<column>\\d+)\\|\\d+\\|(?<message>.*)$",void 0,[0,1,2,3]),c("zig-ast-check",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","ast-check","{file}"],"gcc","https://ziglang.org/documentation/master/"),c("lintr",["r"],["Rscript"],[".lintr","DESCRIPTION"],[".r"],["Rscript","-e","print(lintr::lint(commandArgs(TRUE)[1]))","{file}"],"regex","https://lintr.r-lib.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[^:]+): \\[(?<code>[^\\]]+)\\] (?<message>.*)$"),c("clang-tidy",["c","cpp"],["clang-tidy"],[".clang-tidy","compile_commands.json"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-tidy","{file}"],"clang","https://clang.llvm.org/extra/clang-tidy/"),c("eslint",["javascript","typescript","vue","svelte"],["eslint"],["eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","eslint.config.mts","eslint.config.cts",".eslintrc",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".eslintrc.yaml",".eslintrc.yml"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".vue",".svelte"],["eslint","--format","json","{file}"],"eslint-json","https://eslint.org/docs/latest/",void 0,["eslint"]),c("oxlint",["javascript","typescript"],["oxlint"],[".oxlintrc.json",".oxlintrc.jsonc","oxlint.config.ts","oxlint.config.mts"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],["oxlint","--format","sarif","{file}"],"sarif","https://oxc.rs/docs/guide/usage/linter.html",void 0,["oxlint"]),c("ruff",["python"],["ruff"],["pyproject.toml","ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","check","--output-format","concise","{file}"],"regex","https://docs.astral.sh/ruff/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<code>\\S+) (?<message>.+)$",["ruff"]),c("golangci-lint",["go"],["golangci-lint"],[".golangci.yml",".golangci.yaml","go.mod"],[".go"],["golangci-lint","run","--output.text.path=","--output.checkstyle.path=stdout","--show-stats=false","./..."],"checkstyle","https://golangci-lint.run/"),c("clippy",["rust"],["cargo"],["Cargo.toml","clippy.toml"],[".rs"],["cargo","clippy","--message-format","short"],"gcc","https://doc.rust-lang.org/clippy/"),c("dotnet-format",["csharp"],["dotnet"],[".editorconfig","global.json"],[".cs"],["dotnet","format","--verify-no-changes","--include","{relativeFile}"],"regex","https://learn.microsoft.com/dotnet/core/tools/dotnet-format","^(?<file>.+)\\((?<line>\\d+),(?<column>\\d+)\\): (?<severity>error|warning) (?<code>[^:]+): (?<message>.*?)(?: \\[.*\\])?$",void 0,[0,2]),c("checkstyle",["java"],["checkstyle"],["checkstyle.xml","pom.xml"],[".java"],["checkstyle","-c","checkstyle.xml","-f","xml","{file}"],"checkstyle","https://checkstyle.org/"),c("detekt",["kotlin"],["detekt"],["detekt.yml","build.gradle.kts"],[".kt",".kts"],["detekt","--input","{file}","--config","detekt.yml"],"regex","https://detekt.dev/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<message>.*?) \\[(?<code>[^\\]]+)\\]$",void 0,[0,2]),c("rubocop",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--format","clang","{file}"],"regex","https://docs.rubocop.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?:\\[Correctable\\] )?(?<code>[^:]+): (?<message>.*)$"),c("phpcs",["php"],["phpcs"],["phpcs.xml","phpcs.xml.dist","composer.json"],[".php"],["phpcs","--report=checkstyle","{file}"],"checkstyle","https://github.com/PHPCSStandards/PHP_CodeSniffer",void 0,void 0,[0,1,2,3]),c("swiftlint",["swift"],["swiftlint"],[".swiftlint.yml","Package.swift"],[".swift"],["swiftlint","lint","--quiet","--reporter","checkstyle","{file}"],"checkstyle","https://github.com/realm/SwiftLint",void 0,void 0,[0,2]),c("scalafix",["scala"],["scalafix"],[".scalafix.conf"],[".scala",".sc"],["scalafix","--check","--files","{file}"],"gcc","https://scalacenter.github.io/scalafix/",void 0,void 0,[0,2,64,66]),c("credo",["elixir"],["mix"],["mix.exs",".credo.exs"],[".ex",".exs"],["mix","credo","--strict","--format","flycheck","--files-included","{file}"],"regex","https://hexdocs.pm/credo/","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?<message>.+)$",void 0,Array.from({length:32},(t,e)=>e)),c("psscriptanalyzer",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};Invoke-ScriptAnalyzer -Path $args[0] @options | ForEach-Object {"$($_.ScriptPath):$($_.Line):$($_.Column): $($_.Severity): $($_.Message) [$($_.RuleName)]"}',"{file}"],"regex","https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-scriptanalyzer","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>\\w+): (?<message>.+) \\[(?<code>[^\\]]+)\\]$",void 0,[0]),c("luacheck",["lua"],["luacheck"],[".luacheckrc"],[".lua"],["luacheck","--formatter","plain","--codes","--no-color","{file}"],"regex","https://github.com/lunarmodules/luacheck","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): \\((?<code>(?<severity>[WE])\\d+)\\) (?<message>.+)$",void 0,[0,1,2]),c("shellcheck",["shell"],["shellcheck"],[".shellcheckrc"],[".sh",".bash",".zsh"],["shellcheck","-f","gcc","{file}"],"gcc","https://www.shellcheck.net/"),c("stylelint",["css"],["stylelint"],["stylelint.config.js",".stylelintrc.json"],[".css",".scss",".sass",".less"],["stylelint","--formatter","compact","{file}"],"regex","https://stylelint.io/","^(?<file>.+): line (?<line>\\d+), col (?<column>\\d+), (?<severity>error|warning) - (?<message>.+) \\((?<code>[^)]+)\\)$",["stylelint"],[0,2]),c("yamllint",["yaml"],["yamllint"],[".yamllint",".yamllint.yml"],[".yaml",".yml"],["yamllint","-f","parsable","{file}"],"regex","https://yamllint.readthedocs.io/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): \\[(?<severity>[^\\]]+)\\] (?<message>.*?) \\((?<code>[^)]+)\\)$"),c("markdownlint",["markdown"],["markdownlint"],[".markdownlint.json",".markdownlint.yaml"],[".md",".mdx"],["markdownlint","{file}"],"regex","https://github.com/DavidAnson/markdownlint","^(?<file>.+?):(?<line>\\d+)(?::(?<column>\\d+))? (?<severity>error|warning) (?<code>MD\\d+)(?:/\\S+)? (?<message>.*)$"),c("sqlfluff",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","lint","--format","sarif","{file}"],"sarif","https://docs.sqlfluff.com/"),c("hadolint",["dockerfile"],["hadolint"],[".hadolint.yaml"],[".dockerfile"],["hadolint","--format","checkstyle","{file}"],"checkstyle","https://github.com/hadolint/hadolint",void 0,void 0,[0,1],void 0,["Dockerfile","Containerfile"]),c("tflint",["terraform"],["tflint"],[".tflint.hcl"],[".tf"],["tflint","--format","checkstyle"],"checkstyle","https://github.com/terraform-linters/tflint",void 0,void 0,[0,2]),c("cmake-lint",["cmake"],["cmake-lint"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-lint","{file}"],"regex","https://cmake-format.readthedocs.io/","^(?<file>.+?):(?<line>\\d+),(?<column>\\d+): \\[(?<code>(?<severity>[A-Z])\\d+)\\] (?<message>.*)$",void 0,[0,1],0,["CMakeLists.txt"]),c("htmlhint",["html"],["htmlhint"],[".htmlhintrc"],[".html",".htm"],["htmlhint","--format","checkstyle","--nocolor","{file}"],"checkstyle","https://htmlhint.com/"),c("jsonlint",["json"],["jsonlint"],[".jsonlintrc",".jsonlintrc.json",".jsonlintrc.yaml",".jsonlintrc.yml",".jsonlintrc.js",".jsonlintrc.cjs","jsonlint.config.js","jsonlint.config.cjs"],[".json"],["jsonlint","-q","{file}"],"regex","https://github.com/prantlf/jsonlint","^(?:Error: )?(?<message>Parse (?<severity>error) on line (?<line>\\d+)(?:, column (?<column>\\d+))?:[^\\n]*)$",["@prantlf/jsonlint","jsonlint"]),c("taplo-check",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","check","--colors","never","{file}"],"regex","https://taplo.tamasfe.dev/","^(?<severity>error): (?<message>[^\\n]+)\\n\\s*\u250C\u2500 (?<file>.+):(?<line>\\d+):(?<column>\\d+)"),c("xmllint",["xml"],["xmllint"],[".xmllintrc"],[".xml",".xsd",".xsl"],["xmllint","--noout","{file}"],"regex","https://gnome.pages.gitlab.gnome.org/libxml2/xmllint.html","^(?<file>.+?):(?<line>\\d+): (?<severity>(?:parser |validity )?(?:error|warning)) : (?<message>.*)$",void 0,[0,1,2,3,4])];function c(t,e,n,i,o,f,s,l,r,d,b=[0,1],u,h){return{id:t,name:t,kind:"linter",languages:e,executables:n,configFiles:i,documentation:l,...d&&{dependencies:d},linter:{extensions:o,...h&&{fileNames:h},check:{command:f,successExitCodes:b},diagnostics:{format:s,...r&&{pattern:r},...u!==void 0&&{columnBase:u}}}}}a(c,"recipe");import w from"node:path";import ee from"node:os";import{fileURLToPath as te}from"node:url";function F(t,e){if(t.trim().length===0)return[];switch(e.format){case"pi-json":return B(t);case"eslint-json":return G(t);case"sarif":return H(t);case"checkstyle":return U(t);case"gcc":case"clang":return W(t);case"regex":return Z(t,g(e.pattern),e.columnBase??1)}}a(F,"parseDiagnostics");function B(t){let e=JSON.parse(t);return Array.isArray(e.diagnostics)?e.diagnostics.flatMap(y):[]}a(B,"parsePiJson");function G(t){return JSON.parse(t).flatMap(n=>Array.isArray(n.messages)?n.messages.flatMap(i=>y(i).map(o=>({...o,...n.filePath&&{file:n.filePath}}))):[])}a(G,"parseEslintJson");function H(t){return(JSON.parse(t).runs??[]).flatMap(n=>(n.results??[]).flatMap(i=>{let o=i.locations?.[0]?.physicalLocation,f=o?.region??{},s=i.message;return y({file:o?.artifactLocation?.uri,line:f.startLine,column:f.startColumn,message:s?.text,code:i.ruleId,severity:Q(i.level)})}))}a(H,"parseSarif");function U(t){let e=[];for(let n of t.matchAll(/<file\s+([^>]+)>([\s\S]*?)<\/file>/gu)){let i=z(g(n[1])).name;for(let o of g(n[2]).matchAll(/<error\s+([^>]+?)\/?>(?:<\/error>)?/gu)){let f=z(g(o[1]));e.push(...y({file:i,line:Number(f.line),column:Number(f.column??1),message:f.message,code:f.source,severity:f.severity}))}}return e}a(U,"parseCheckstyle");function z(t){return Object.fromEntries([...t.matchAll(/([\w-]+)="([^"]*)"/gu)].map(e=>[g(e[1]),Y(g(e[2]))]))}a(z,"xmlAttributes");function W(t){return X(t,/^(?<file>.+?):(?<line>\d+):(?<column>\d+):\s*(?<severity>fatal error|error|warning|note|info|hint):\s*(?<message>.*?)(?:\s+\[(?<code>[^\]]+)\])?$/u)}a(W,"parseCompilerLines");function Z(t,e,n){return[...t.replaceAll(`\r
2
2
  `,`
3
3
  `).matchAll(new RegExp(e,"gmu"))].flatMap(i=>i.groups===void 0?[]:y({...i.groups,...i.groups.column!==void 0&&{column:Number(i.groups.column)+(1-n)}}))}a(Z,"parseRegexLines");function X(t,e){return t.split(/\r?\n/u).flatMap(n=>{let i=n.match(e)?.groups;return i===void 0?[]:y(i)})}a(X,"parseMatchingLines");function y(t){if(typeof t!="object"||t===null)return[];let e=t,n=M(e.line??e.startLine),i=M(e.column??e.startColumn,1),o=typeof e.message=="string"?e.message:void 0;return n===void 0||o===void 0?[]:[{...typeof e.file=="string"&&{file:e.file},code:q(e.code??e.ruleId,"lint"),message:o,line:n,column:i??1,severity:K(e.severity)}]}a(y,"normalizeDiagnostic");function M(t,e){let n=typeof t=="string"?Number.parseInt(t,10):t;return typeof n=="number"&&Number.isInteger(n)&&n>=1?n:e}a(M,"numberValue");function q(t,e){return typeof t=="string"||typeof t=="number"?String(t):e}a(q,"stringValue");function K(t){if(t===2)return"error";if(t===1)return"warning";let e=q(t,"warning").toLowerCase();return e.includes("error")||e==="e"||e==="f"||e==="fatal"?"error":e==="info"||e==="note"||e==="notice"?"info":e==="hint"?"hint":"warning"}a(K,"severityValue");function Q(t){return t==="error"||t==="warning"||t==="note"?t:"warning"}a(Q,"sarifSeverity");function Y(t){return t.replace(/&#(x[0-9a-f]+|\d+);/giu,(e,n)=>{let i=n.toLowerCase().startsWith("x")?Number.parseInt(n.slice(1),16):Number(n);return i<=1114111?String.fromCodePoint(i):e}).replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}a(Y,"decodeXml");var m=class t{constructor(e,n,i=new Map){this.linters=e;this.availableBuiltIns=n;this.evidence=i}static{a(this,"LintCommandRegistry")}static async fromDirectory(e,n={}){let i=await D(e,"linters",r=>A(r).linters,n),o=n.environment??process.env,f=await Promise.all(i.entries.filter(r=>r.layer==="built-in").map(async r=>({id:r.id,available:await C(r.config.check,e,o)}))),s=await R(e,p),l=[...i.entries].sort((r,d)=>r.layer==="built-in"&&d.layer==="built-in"?(s.get(d.id)?.score??0)-(s.get(r.id)?.score??0):0);return new t(l,new Set(f.filter(r=>r.available&&(!n.requireBuiltInEvidence||(s.get(r.id)?.score??0)>0)).map(r=>r.id)),s)}static fromConfig(e){return new t(Object.entries(e.linters).map(([n,i])=>({id:n,config:i,layer:"project",sourcePath:"<memory>"})),new Set)}resolve(e,n){return this.resolveEntry(e,n)?.config}resolveEntry(e,n){return $(this.linters,this.availableBuiltIns,this.evidence,e,n)}get entries(){return this.linters}};async function k(t,e){let n;try{let l=w.basename(t.check.command[0]??"").toLocaleLowerCase(),r=l==="ruff"||l==="ruff.exe",d=e.env??process.env;n=await I(t.check,{...e,...r?{env:{...d,RUFF_CACHE_DIR:d.RUFF_CACHE_DIR??w.join(ee.tmpdir(),"pi-agent-ide","ruff-cache")}}:{}})}catch(l){return{ok:!1,diagnostics:[],failure:`command could not start: ${l instanceof Error?l.message:String(l)}`}}let i=t.diagnostics.format==="regex"||t.diagnostics.format==="clang"?[n.stdout,n.stderr].filter(l=>l.trim().length>0).join(`
4
4
  `):n.stdout.trim().length>0?n.stdout:n.stderr,o;try{o=F(i,t.diagnostics)}catch{return{ok:!1,diagnostics:[],failure:`invalid ${t.diagnostics.format} diagnostics: ${i.trim().slice(0,200)||"empty command output"}`}}let f=n.ok&&(n.exitCode===0||o.length>0),s=t.check.cwd==="file"?w.dirname(e.filePath):e.projectRoot;return o=o.filter(l=>{if(l.file===void 0)return!0;let r=l.file.startsWith("file:")?te(l.file):l.file;return O(w.resolve(s,r),e.filePath)}).map(({file:l,...r})=>r),{ok:f,diagnostics:o,...!f&&{failure:n.stderr.trim().slice(0,200)||`command exited with code ${String(n.exitCode)}`}}}a(k,"runConfiguredLinter");function J(t){return{kind:"linter",name:"command-lint",priority:100,extensions:["*"],detect:a(()=>Promise.resolve(!0),"detect"),async lint({filePath:e,fix:n},i){let o=t.resolve(e,i.cwd);if(o===void 0)return{ok:!0,diagnostics:[]};let f=n===!0&&o.fix!==void 0?o.fix:o.check,s=await k({...o,check:f},{projectRoot:i.cwd,filePath:e});return{ok:s.ok,diagnostics:s.diagnostics}}}}a(J,"createCommandLinter");import{copyFile as ne,mkdtemp as ie,rm as re}from"node:fs/promises";import x from"node:path";var V={protocol:T,apiVersion:1,id:"lint",setup(t){for(let e of p)t.addToolRecipe(e);t.addSetupCheck({id:"effective-config",inspect:oe}),t.addCheck({id:"config",title:"Linter",async run(e){try{let n=await m.fromDirectory(e.cwd,{environment:e.env}),i=se(n,e.files,e.cwd);return i.length===0?[{status:"skip",message:"No linter matches the inspected project files"}]:await Promise.all(i.map(async({entry:o,source:f})=>{let s=`${o.id} [${o.layer}] command ${JSON.stringify(o.config.check.command)}`,l=await ie(x.join(x.dirname(f),".pi-agent-ide-doctor-")),r=x.join(l,x.basename(f));try{await ne(f,r);let d=await k(o.config,{projectRoot:e.cwd,filePath:r,env:e.env});return d.ok?{status:"pass",message:`${s}: probe passed`,detail:o.sourcePath}:{status:"fail",message:`${s}: probe failed`,detail:d.failure??o.sourcePath}}catch(d){return{status:"fail",message:`${s}: ${d instanceof Error?d.message:String(d)}`,detail:o.sourcePath}}finally{await re(l,{recursive:!0,force:!0})}}))}catch(n){return[{status:"fail",message:n instanceof Error?n.message:String(n)}]}}})}};async function oe(t){try{let e=await m.fromDirectory(t.cwd,{environment:t.env}),n=[],i=new Map;for(let[o,f]of t.detectedLanguages){let s=f.map(l=>e.resolveEntry(l,t.cwd)).find(l=>l!==void 0);s!==void 0&&(n.push({kind:"linter",languageId:o,toolId:s.id}),await C(s.config.check,t.cwd,t.env)||i.set(s.id,{id:`linter-${s.id}-unavailable`,message:`Configured linter ${s.id} cannot run ${JSON.stringify(s.config.check.command)}`}))}return{selections:n,actions:[...i.values()]}}catch(e){return{actions:[{id:"linter-config-invalid",message:`Linter configuration cannot load: ${e instanceof Error?e.message:String(e)}`}]}}}a(oe,"inspectLinterSetup");function se(t,e,n){let i=new Map;for(let o of e){let f=t.resolveEntry(o,n);f!==void 0&&!i.has(f.id)&&i.set(f.id,{entry:f,source:o})}return[...i.values()]}a(se,"applicableLinters");async function ae(t){let e=new Map,n=a((s,l=!1)=>{let r=JSON.stringify([s,l]),d=e.get(r);return d===void 0&&(d=ce(s,l),e.set(r,d)),d},"registryFor"),i=a(async(s,l)=>{let r=await S(l,s,"linters",p);return r===void 0?void 0:{projectRoot:r,external:r!==le.resolve(l)}},"resolveProject"),o={kind:"linter",name:"pi-agent-ide-lint",priority:200,extensions:["*"],detect:a(async s=>(await n(s.cwd),!0),"detect"),async lint(s,l){let r=await i(s.filePath,l.cwd);if(r===void 0)return{ok:!0,diagnostics:[]};let d=await n(r.projectRoot,r.external);return J(d).lint(s,{cwd:r.projectRoot})}},f={protocol:j,apiVersion:4,id:"lint",setup(s){s.addTool(o),s.addDiagnosticSource({id:"lint",async diagnose(l,r){let d=await i(l,r.cwd);if(d===void 0)return{status:"unavailable",diagnostics:[],reason:"No local linter project found for this file"};let b=await n(d.projectRoot,d.external);r.signal.throwIfAborted();let u=b.resolve(l,d.projectRoot);if(!u)return{status:"unavailable",diagnostics:[],reason:"No linter configured for this file"};let h=E(u.check.command),v=await k(u,{projectRoot:d.projectRoot,filePath:l,signal:r.signal});return!v.ok&&v.diagnostics.length===0?{status:"unavailable",diagnostics:[],reason:v.failure??"Lint check failed",source:h}:{status:"ready",diagnostics:v.diagnostics,source:h}}})}};await Promise.all([P(t,f),_(t,V)])}a(ae,"registerLint");async function ce(t,e){let n=e?t:process.env.PI_AGENT_IDE_CONFIG_DIR??t;return m.fromDirectory(n,{includeGlobal:!e,requireBuiltInEvidence:!0})}a(ce,"loadRegistry");export{ae as default};