pi-agent-ide 0.8.0 → 0.8.2

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 (508) hide show
  1. package/CHANGELOG.md +70 -40
  2. package/README.md +15 -8
  3. package/dist/{chunk-ICDI27GZ.js → chunk-235QMMVA.js} +1 -1
  4. package/dist/{chunk-N7LMRL64.js → chunk-47SPPIXK.js} +1 -1
  5. package/dist/chunk-4DIUPEDF.js +2 -0
  6. package/dist/{chunk-JMVDFOTQ.js → chunk-57F5GTHO.js} +1 -1
  7. package/dist/{chunk-NULNW6GK.js → chunk-6FGLAVPJ.js} +1 -1
  8. package/dist/{chunk-KL776TGR.js → chunk-6H32W35W.js} +1 -1
  9. package/dist/{chunk-QP2QSQ4U.js → chunk-6OJ565FL.js} +1 -1
  10. package/dist/{chunk-TWWND6NI.js → chunk-6R3Y4AD3.js} +1 -1
  11. package/dist/{chunk-CPZJPGLG.js → chunk-6T7PSDQW.js} +1 -1
  12. package/dist/{chunk-4OYVLXWD.js → chunk-6TJPMBUQ.js} +1 -1
  13. package/dist/{chunk-SBLKPTL3.js → chunk-6XFUICD7.js} +1 -1
  14. package/dist/chunk-7VSVJRRF.js +28 -0
  15. package/dist/{chunk-7JV4VN73.js → chunk-AAC77UD4.js} +1 -1
  16. package/dist/chunk-ANM3Y5FO.js +11 -0
  17. package/dist/chunk-BB4A5UI3.js +5 -0
  18. package/dist/{chunk-7TJ6DWW3.js → chunk-CPELC6JE.js} +1 -1
  19. package/dist/chunk-FTPC44FP.js +33 -0
  20. package/dist/{chunk-SBNR4WZF.js → chunk-GSOYVIQS.js} +1 -1
  21. package/dist/{chunk-Z3PGADVA.js → chunk-HSRH76JN.js} +1 -1
  22. package/dist/{chunk-CSXHCSTH.js → chunk-HSZ4AQ6L.js} +1 -1
  23. package/dist/chunk-I6NPILT5.js +1 -0
  24. package/dist/chunk-K7SRNBIV.js +1 -0
  25. package/dist/{chunk-R5XJSEOE.js → chunk-LCWBVOII.js} +3 -3
  26. package/dist/{chunk-MZXX353D.js → chunk-LEJKDYCK.js} +1 -1
  27. package/dist/{chunk-3G54ZL2L.js → chunk-NJ7C4KMA.js} +1 -1
  28. package/dist/{chunk-CTJV77FR.js → chunk-NUM3YQGK.js} +1 -1
  29. package/dist/chunk-OJEIX7OZ.js +1 -0
  30. package/dist/{chunk-EY65TFHJ.js → chunk-PJL3UVMJ.js} +1 -1
  31. package/dist/{chunk-E4HPRLRB.js → chunk-QT3EAHOG.js} +1 -1
  32. package/dist/{chunk-HCN5W76B.js → chunk-RIJMXO43.js} +1 -1
  33. package/dist/chunk-RMI3NMQY.js +23 -0
  34. package/dist/chunk-RQ7JJ7GV.js +4 -0
  35. package/dist/{chunk-4XPUN4QN.js → chunk-RVU73VKN.js} +1 -1
  36. package/dist/{chunk-OJX3RJ5A.js → chunk-RW2GTYQI.js} +1 -1
  37. package/dist/{chunk-PNP2KNGP.js → chunk-SDAH3ECM.js} +1 -1
  38. package/dist/chunk-SGQWRIRJ.js +10 -0
  39. package/dist/{chunk-IUSLSROY.js → chunk-SMIFCAAX.js} +1 -1
  40. package/dist/chunk-SWBJS3U4.js +1 -0
  41. package/dist/chunk-T7MWQQIF.js +3 -0
  42. package/dist/{chunk-RAZP42IQ.js → chunk-VAXLSPPU.js} +1 -1
  43. package/dist/{chunk-XZDOVPRC.js → chunk-VMTOFEXF.js} +1 -1
  44. package/dist/{chunk-7HDK3NRQ.js → chunk-VXP5BMW7.js} +1 -1
  45. package/dist/{chunk-WE42GBGU.js → chunk-XAHU42FP.js} +3 -3
  46. package/dist/{chunk-UBH6X3D3.js → chunk-XBQR74IK.js} +1 -1
  47. package/dist/{chunk-7NS3QUIE.js → chunk-XG7QNAKW.js} +1 -1
  48. package/dist/{chunk-GW6NZQTQ.js → chunk-XLWCSJMR.js} +1 -1
  49. package/dist/{chunk-2K65BSXS.js → chunk-XXLLY66B.js} +1 -1
  50. package/dist/chunk-YFP4P2FV.js +1 -0
  51. package/dist/{chunk-75SWXD2Z.js → chunk-YIXP2ALP.js} +1 -1
  52. package/dist/{chunk-MOJ5RR35.js → chunk-ZJQRLVVV.js} +1 -1
  53. package/dist/entry-0.js +1 -1
  54. package/dist/entry-1.js +1 -1
  55. package/dist/entry-10.js +1 -1
  56. package/dist/entry-11.js +1 -1
  57. package/dist/entry-12.js +1 -1
  58. package/dist/entry-13.js +1 -1
  59. package/dist/entry-14.js +1 -1
  60. package/dist/entry-15.js +1 -1
  61. package/dist/entry-16.js +1 -1
  62. package/dist/entry-17.js +1 -1
  63. package/dist/entry-18.js +1 -0
  64. package/dist/entry-19.js +1 -1
  65. package/dist/entry-2.js +1 -1
  66. package/dist/entry-20.js +1 -1
  67. package/dist/entry-22.js +1 -1
  68. package/dist/entry-23.js +1 -1
  69. package/dist/entry-24.js +1 -1
  70. package/dist/entry-25.js +1 -1
  71. package/dist/entry-26.js +1 -2
  72. package/dist/entry-27.js +1 -1
  73. package/dist/entry-28.js +1 -4
  74. package/dist/entry-29.js +2 -1
  75. package/dist/entry-3.js +1 -1
  76. package/dist/entry-30.js +1 -1
  77. package/dist/entry-31.js +4 -1
  78. package/dist/entry-32.js +1 -18
  79. package/dist/entry-33.js +1 -1
  80. package/dist/entry-34.js +1 -1
  81. package/dist/entry-35.js +18 -1
  82. package/dist/entry-36.js +1 -1
  83. package/dist/entry-37.js +1 -1
  84. package/dist/entry-38.js +1 -1
  85. package/dist/entry-39.js +1 -1
  86. package/dist/entry-4.js +1 -1
  87. package/dist/entry-40.js +1 -1
  88. package/dist/entry-41.js +1 -1
  89. package/dist/entry-42.js +1 -1
  90. package/dist/entry-43.js +1 -1
  91. package/dist/entry-44.js +1 -1
  92. package/dist/entry-45.js +1 -1
  93. package/dist/entry-46.js +1 -25
  94. package/dist/entry-47.js +1 -1
  95. package/dist/entry-48.js +1 -1
  96. package/dist/entry-49.js +25 -1
  97. package/dist/entry-5.js +1 -1
  98. package/dist/entry-50.js +1 -1
  99. package/dist/entry-51.js +1 -3
  100. package/dist/entry-52.js +1 -13
  101. package/dist/entry-53.js +1 -1
  102. package/dist/entry-54.js +3 -1
  103. package/dist/entry-55.js +13 -1
  104. package/dist/entry-56.js +1 -1
  105. package/dist/entry-57.js +1 -1
  106. package/dist/entry-58.js +1 -1
  107. package/dist/entry-59.js +1 -1
  108. package/dist/entry-6.js +1 -1
  109. package/dist/entry-60.js +1 -1
  110. package/dist/entry-61.js +1 -1
  111. package/dist/entry-62.js +1 -0
  112. package/dist/entry-63.js +1 -1
  113. package/dist/entry-64.js +1 -0
  114. package/dist/entry-65.js +0 -1
  115. package/dist/entry-66.js +1 -1
  116. package/dist/entry-67.js +0 -1
  117. package/dist/entry-68.js +1 -1
  118. package/dist/entry-69.js +1 -1
  119. package/dist/entry-7.js +1 -1
  120. package/dist/entry-70.js +1 -1
  121. package/dist/entry-71.js +1 -1
  122. package/dist/entry-72.js +1 -0
  123. package/dist/entry-73.js +1 -1
  124. package/dist/entry-74.js +1 -0
  125. package/dist/entry-75.js +0 -1
  126. package/dist/entry-76.js +1 -1
  127. package/dist/entry-77.js +0 -1
  128. package/dist/entry-78.js +1 -80
  129. package/dist/entry-79.js +1 -21
  130. package/dist/entry-8.js +1 -1
  131. package/dist/entry-80.js +1 -2
  132. package/dist/entry-81.js +80 -1
  133. package/dist/entry-82.js +22 -1
  134. package/dist/entry-83.js +2 -1
  135. package/dist/entry-84.js +1 -3
  136. package/dist/entry-85.js +1 -1
  137. package/dist/entry-86.js +1 -1
  138. package/dist/entry-87.js +1 -1
  139. package/dist/entry-88.js +3 -0
  140. package/dist/entry-89.js +1 -0
  141. package/dist/entry-9.js +1 -1
  142. package/dist/entry-90.js +1 -0
  143. package/dist/entry-91.js +1 -0
  144. package/dist/pi-agent-ide.js +53 -31
  145. package/docs/agent-guides/debugger.md +2 -0
  146. package/docs/agent-guides/editing.md +3 -3
  147. package/docs/agent-guides/search-code.md +5 -3
  148. package/docs/agent-guides/select-code.md +9 -6
  149. package/docs/agent-guides/ssh.md +1 -1
  150. package/docs/code-review.md +5 -0
  151. package/docs/configuration.md +52 -8
  152. package/docs/development.md +9 -13
  153. package/docs/directory-operations.md +1 -1
  154. package/docs/extensions.md +99 -2
  155. package/docs/releases.md +1 -1
  156. package/docs/settings-help.md +39 -0
  157. package/docs/structured-results.md +11 -6
  158. package/docs/tools.md +1 -0
  159. package/docs/user-hooks.md +4 -2
  160. package/node_modules/pi-agent-doctor/package.json +7 -10
  161. package/node_modules/pi-agent-doctor/runtime/entry-26.js +1 -0
  162. package/node_modules/pi-agent-doctor/runtime/entry-27.js +1 -0
  163. package/node_modules/pi-agent-documentation/package.json +2 -2
  164. package/node_modules/pi-agent-documentation/runtime/entry-28.js +1 -0
  165. package/node_modules/pi-agent-filesystem/package.json +8 -8
  166. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  167. package/node_modules/pi-agent-filesystem-jq/package.json +6 -7
  168. package/node_modules/pi-agent-filesystem-jq/runtime/entry-31.js +2 -0
  169. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  170. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  171. package/node_modules/pi-agent-filesystem-text/runtime/entry-33.js +2 -0
  172. package/node_modules/pi-agent-ide-ast/package.json +15 -41
  173. package/node_modules/pi-agent-ide-ast/runtime/entry-34.js +1 -0
  174. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +6 -5
  175. package/node_modules/pi-agent-ide-changes/package.json +10 -11
  176. package/node_modules/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  177. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  178. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  179. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  180. package/node_modules/pi-agent-ide-languages/runtime/entry-39.js +2 -0
  181. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  182. package/node_modules/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  183. package/node_modules/pi-agent-ide-lsp/package.json +10 -13
  184. package/node_modules/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  185. package/node_modules/pi-agent-image/package.json +3 -3
  186. package/node_modules/pi-agent-invariant/package.json +2 -2
  187. package/node_modules/pi-agent-pdf/package.json +3 -4
  188. package/node_modules/pi-agent-read/package.json +12 -12
  189. package/node_modules/pi-agent-read/runtime/entry-46.js +0 -1
  190. package/node_modules/pi-agent-read/runtime/entry-49.js +2 -0
  191. package/node_modules/pi-agent-resource/package.json +2 -2
  192. package/node_modules/pi-agent-resource/src/resource-error.ts +11 -0
  193. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -0
  194. package/node_modules/pi-agent-search/package.json +9 -9
  195. package/node_modules/pi-agent-search/runtime/entry-51.js +0 -1
  196. package/node_modules/pi-agent-search/runtime/entry-52.js +1 -0
  197. package/node_modules/pi-agent-search/runtime/entry-54.js +2 -0
  198. package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  199. package/node_modules/pi-agent-search/src/api/presentation.ts +10 -2
  200. package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -5
  201. package/node_modules/pi-agent-search/src/api/search.ts +7 -0
  202. package/node_modules/pi-agent-search/src/core/search-core.ts +23 -3
  203. package/node_modules/pi-agent-search-text/index.ts +2 -0
  204. package/node_modules/pi-agent-search-text/package.json +14 -14
  205. package/node_modules/pi-agent-search-text/runtime/entry-55.js +1 -0
  206. package/node_modules/pi-agent-search-text/runtime/entry-57.js +1 -0
  207. package/node_modules/pi-agent-search-text/src/search-backend.ts +18 -10
  208. package/node_modules/pi-agent-search-text/src/search-session.ts +68 -9
  209. package/node_modules/pi-agent-text/package.json +3 -3
  210. package/node_modules/pi-agent-text/runtime/entry-59.js +1 -0
  211. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  212. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-60.js +2 -0
  213. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -6
  214. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-61.js +1 -0
  215. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-62.js +2 -0
  216. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  217. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  218. package/node_modules/pi-agent-text-editor/index.ts +2 -0
  219. package/node_modules/pi-agent-text-editor/package.json +26 -34
  220. package/node_modules/pi-agent-text-editor/runtime/entry-78.js +0 -1
  221. package/node_modules/pi-agent-text-editor/runtime/entry-79.js +1 -0
  222. package/node_modules/pi-agent-text-editor/runtime/entry-80.js +1 -0
  223. package/node_modules/pi-agent-text-editor/runtime/entry-81.js +2 -0
  224. package/node_modules/pi-agent-text-editor/src/api/delete-guard.ts +1 -1
  225. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  226. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  227. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  228. package/node_modules/pi-agent-text-editor/src/core/delete-policy.ts +6 -12
  229. package/node_modules/pi-agent-text-editor/src/core/extension.ts +4 -1
  230. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +40 -11
  231. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  232. package/node_modules/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  233. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +29 -20
  234. package/node_modules/pi-agent-text-editor/src/core/temporary-directories.ts +13 -9
  235. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  236. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +118 -36
  237. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  238. package/node_modules/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  239. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  240. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +35 -14
  241. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  242. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  243. package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  244. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  245. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  246. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -8
  247. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  248. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +35 -2
  249. package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  250. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -5
  251. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  252. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +1 -0
  253. package/node_modules/pi-agent-tool-ui/package.json +6 -2
  254. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +1 -0
  255. package/node_modules/pi-agent-tool-ui/runtime/entry-86.js +1 -0
  256. package/node_modules/pi-agent-tool-ui/src/operation-approval.ts +271 -0
  257. package/node_modules/pi-agent-web/package.json +8 -11
  258. package/node_modules/pi-agent-web-html/package.json +3 -5
  259. package/node_modules/pi-agent-web-html/runtime/entry-88.js +2 -0
  260. package/node_modules/pi-agent-web-image/package.json +4 -4
  261. package/node_modules/pi-agent-web-image/runtime/entry-89.js +2 -0
  262. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  263. package/node_modules/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  264. package/node_modules/pi-agent-web-text/package.json +4 -4
  265. package/node_modules/pi-agent-web-text/runtime/entry-91.js +2 -0
  266. package/package.json +65 -53
  267. package/skills/configure-agent-ide/SKILL.md +38 -0
  268. package/src/api/approval.ts +5 -0
  269. package/src/api/content.ts +6 -0
  270. package/src/api/settings.ts +198 -0
  271. package/src/api/tips.ts +3 -0
  272. package/src/backend/debugger-registration.ts +5 -1
  273. package/src/code-review/extension.ts +10 -4
  274. package/src/code-review/reviewer.ts +8 -0
  275. package/src/composite/host-version.ts +29 -5
  276. package/src/composite/ide-alias-rendering.ts +97 -0
  277. package/src/composite/nested-tool-rendering.ts +90 -9
  278. package/src/composite/preferences.ts +13 -0
  279. package/src/composite/search-facts.ts +45 -0
  280. package/src/composite/settings-documentation.ts +68 -0
  281. package/src/composite/settings-help.ts +106 -0
  282. package/src/composite/settings-registry.ts +94 -0
  283. package/src/composite/text-results.ts +170 -30
  284. package/src/composite/tool-availability.ts +11 -2
  285. package/src/core/diagnostic-entry.ts +31 -8
  286. package/src/core/diagnostic-store.ts +19 -3
  287. package/src/core/extension.ts +7 -2
  288. package/src/documentation/extension.ts +12 -0
  289. package/src/documentation/registry.ts +10 -2
  290. package/src/documentation/search.ts +166 -0
  291. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  292. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  293. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -7
  294. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-31.js +2 -0
  295. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  296. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-32.js +2 -0
  297. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  298. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-33.js +2 -0
  299. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +2 -0
  300. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -11
  301. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -5
  302. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-88.js +2 -0
  303. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  304. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +2 -0
  305. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  306. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  307. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  308. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-91.js +2 -0
  309. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +2 -0
  310. package/src/extensions/pi-agent-read/package.json +12 -12
  311. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  312. package/src/extensions/pi-agent-read/runtime/entry-47.js +1 -0
  313. package/src/extensions/pi-agent-read/runtime/entry-49.js +2 -0
  314. package/src/extensions/pi-agent-search/package.json +9 -9
  315. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +2 -0
  316. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -14
  317. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +1 -0
  318. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +1 -0
  319. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +1 -0
  320. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +18 -10
  321. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +68 -9
  322. package/src/extensions/pi-agent-search/runtime/entry-51.js +0 -1
  323. package/src/extensions/pi-agent-search/runtime/entry-52.js +1 -0
  324. package/src/extensions/pi-agent-search/runtime/entry-53.js +1 -0
  325. package/src/extensions/pi-agent-search/runtime/entry-54.js +2 -0
  326. package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  327. package/src/extensions/pi-agent-search/src/api/presentation.ts +10 -2
  328. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -5
  329. package/src/extensions/pi-agent-search/src/api/search.ts +7 -0
  330. package/src/extensions/pi-agent-search/src/core/search-core.ts +23 -3
  331. package/src/extensions/pi-agent-text-editor/index.ts +2 -0
  332. package/src/extensions/pi-agent-text-editor/package.json +26 -34
  333. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  334. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-60.js +2 -0
  335. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -6
  336. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-61.js +1 -0
  337. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-62.js +2 -0
  338. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  339. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-63.js +1 -0
  340. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  341. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -8
  342. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  343. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +35 -2
  344. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  345. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -5
  346. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +0 -1
  347. package/src/extensions/pi-agent-text-editor/runtime/entry-79.js +1 -0
  348. package/src/extensions/pi-agent-text-editor/runtime/entry-80.js +1 -0
  349. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +2 -0
  350. package/src/extensions/pi-agent-text-editor/src/api/delete-guard.ts +1 -1
  351. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  352. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  353. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  354. package/src/extensions/pi-agent-text-editor/src/core/delete-policy.ts +6 -12
  355. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +4 -1
  356. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +40 -11
  357. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  358. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  359. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +29 -20
  360. package/src/extensions/pi-agent-text-editor/src/core/temporary-directories.ts +13 -9
  361. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  362. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +118 -36
  363. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  364. package/src/extensions/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  365. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  366. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +35 -14
  367. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  368. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  369. package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  370. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  371. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  372. package/src/pi-agent-ide.ts +74 -15
  373. package/src/plugins/pi-agent-ide-ast/package.json +15 -41
  374. package/src/plugins/pi-agent-ide-ast/runtime/entry-34.js +1 -0
  375. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +6 -5
  376. package/src/plugins/pi-agent-ide-changes/package.json +10 -11
  377. package/src/plugins/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  378. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  379. package/src/plugins/pi-agent-ide-debugger/index.ts +158 -55
  380. package/src/plugins/pi-agent-ide-debugger/src/debugmcp-client.ts +118 -0
  381. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +47 -0
  382. package/src/plugins/pi-agent-ide-debugger/src/renderer.ts +2 -0
  383. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +146 -1
  384. package/src/plugins/pi-agent-ide-debugger/src/ui.ts +12 -0
  385. package/src/plugins/pi-agent-ide-debugger/src/vscode-backend.ts +497 -0
  386. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  387. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  388. package/src/plugins/pi-agent-ide-languages/runtime/entry-39.js +2 -0
  389. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  390. package/src/plugins/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  391. package/src/plugins/pi-agent-ide-lsp/package.json +10 -13
  392. package/src/plugins/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  393. package/src/plugins/pi-agent-ide-terminal/index.ts +2 -0
  394. package/src/plugins/pi-agent-ide-terminal/src/origin.ts +30 -0
  395. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +34 -0
  396. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +11 -2
  397. package/src/plugins/pi-agent-ide-terminal/src/types.ts +9 -0
  398. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +72 -26
  399. package/src/tips/core.ts +5 -2
  400. package/src/tips/extension.ts +30 -2
  401. package/src/tips/persistence.ts +29 -27
  402. package/src/tips/setup-hint.ts +19 -0
  403. package/dist/chunk-3ZGDMTMD.js +0 -25
  404. package/dist/chunk-5KFVDYCI.js +0 -1
  405. package/dist/chunk-ABFCAOU5.js +0 -1
  406. package/dist/chunk-BIG45IPN.js +0 -2
  407. package/dist/chunk-BMOJTJJJ.js +0 -3
  408. package/dist/chunk-BQ67M4NC.js +0 -3
  409. package/dist/chunk-IH5NW5JX.js +0 -11
  410. package/dist/chunk-NRZO5KJT.js +0 -9
  411. package/dist/chunk-O36UC74T.js +0 -1
  412. package/dist/chunk-OLI3JPHJ.js +0 -28
  413. package/dist/chunk-SSWUUBIR.js +0 -1
  414. package/dist/chunk-UUJJRXHG.js +0 -29
  415. package/dist/entry-21.js +0 -1
  416. package/docs/research/apply-native-capability-matrix.md +0 -174
  417. package/docs/research/apply-read-latency.md +0 -221
  418. package/docs/research/codemode-write-context.md +0 -56
  419. package/docs/research/lpt-393-fuzzy-results/file.json +0 -152
  420. package/docs/research/lpt-393-fuzzy-results/repo.json +0 -122
  421. package/docs/research/lpt-393-search-fuzzy-fallback.md +0 -97
  422. package/docs/research/native-codemode-batch-decision.md +0 -31
  423. package/docs/research/native-codemode-batching.md +0 -65
  424. package/node_modules/pi-agent-doctor/runtime/entry-19.js +0 -1
  425. package/node_modules/pi-agent-doctor/runtime/entry-20.js +0 -1
  426. package/node_modules/pi-agent-doctor/runtime/entry-21.js +0 -1
  427. package/node_modules/pi-agent-filesystem/runtime/entry-26.js +0 -2
  428. package/node_modules/pi-agent-filesystem-image/runtime/entry-27.js +0 -2
  429. package/node_modules/pi-agent-filesystem-jq/runtime/entry-28.js +0 -2
  430. package/node_modules/pi-agent-ide-ast/runtime/entry-31.js +0 -1
  431. package/node_modules/pi-agent-ide-changes/runtime/entry-33.js +0 -1
  432. package/node_modules/pi-agent-ide-changes/runtime/entry-34.js +0 -2
  433. package/node_modules/pi-agent-ide-languages/runtime/entry-36.js +0 -2
  434. package/node_modules/pi-agent-image/runtime/entry-39.js +0 -1
  435. package/node_modules/pi-agent-invariant/runtime/entry-40.js +0 -1
  436. package/node_modules/pi-agent-pdf/runtime/entry-41.js +0 -1
  437. package/node_modules/pi-agent-search/runtime/entry-49.js +0 -1
  438. package/node_modules/pi-agent-search-text/runtime/entry-52.js +0 -2
  439. package/node_modules/pi-agent-search-text/runtime/entry-54.js +0 -1
  440. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-57.js +0 -2
  441. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -2
  442. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
  443. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-61.js +0 -2
  444. package/node_modules/pi-agent-text-editor/runtime/entry-62.js +0 -1
  445. package/node_modules/pi-agent-text-editor/runtime/entry-64.js +0 -1
  446. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-79.js +0 -2
  447. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  448. package/node_modules/pi-agent-tool-call-interception/runtime/entry-81.js +0 -1
  449. package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +0 -1
  450. package/node_modules/pi-agent-web-html/runtime/entry-84.js +0 -2
  451. package/node_modules/pi-agent-web-image/runtime/entry-85.js +0 -2
  452. package/node_modules/pi-agent-web-pdf/runtime/entry-86.js +0 -2
  453. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-27.js +0 -2
  454. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-28.js +0 -2
  455. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-29.js +0 -2
  456. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-26.js +0 -2
  457. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-84.js +0 -2
  458. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-85.js +0 -2
  459. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-86.js +0 -2
  460. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +0 -2
  461. package/src/extensions/pi-agent-read/runtime/entry-42.js +0 -1
  462. package/src/extensions/pi-agent-read/runtime/entry-43.js +0 -1
  463. package/src/extensions/pi-agent-read/runtime/entry-44.js +0 -1
  464. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-52.js +0 -2
  465. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +0 -1
  466. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-54.js +0 -1
  467. package/src/extensions/pi-agent-search/runtime/entry-49.js +0 -1
  468. package/src/extensions/pi-agent-search/runtime/entry-50.js +0 -1
  469. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-57.js +0 -2
  470. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -2
  471. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
  472. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-61.js +0 -2
  473. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-79.js +0 -2
  474. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  475. package/src/extensions/pi-agent-text-editor/runtime/entry-62.js +0 -1
  476. package/src/extensions/pi-agent-text-editor/runtime/entry-63.js +0 -1
  477. package/src/extensions/pi-agent-text-editor/runtime/entry-64.js +0 -1
  478. package/src/plugins/pi-agent-ide-ast/runtime/entry-31.js +0 -1
  479. package/src/plugins/pi-agent-ide-ast/runtime/entry-32.js +0 -2
  480. package/src/plugins/pi-agent-ide-changes/runtime/entry-33.js +0 -1
  481. package/src/plugins/pi-agent-ide-changes/runtime/entry-34.js +0 -2
  482. package/src/plugins/pi-agent-ide-languages/runtime/entry-36.js +0 -2
  483. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-25.js +0 -0
  484. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem}/runtime/entry-29.js +0 -0
  485. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  486. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-pdf}/runtime/entry-32.js +0 -0
  487. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  488. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  489. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
  490. /package/node_modules/{pi-agent-read → pi-agent-image}/runtime/entry-42.js +0 -0
  491. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-43.js +0 -0
  492. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-44.js +0 -0
  493. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-47.js +0 -0
  494. /package/node_modules/{pi-agent-search → pi-agent-read}/runtime/entry-48.js +0 -0
  495. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-50.js +0 -0
  496. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-53.js +0 -0
  497. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-56.js +0 -0
  498. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-search-text}/runtime/entry-58.js +0 -0
  499. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-63.js +0 -0
  500. /package/node_modules/{pi-agent-web → pi-agent-text-editor-stale-anchor}/runtime/entry-83.js +0 -0
  501. /package/node_modules/{pi-agent-web-text → pi-agent-web}/runtime/entry-87.js +0 -0
  502. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  503. /package/src/extensions/{pi-agent-search → pi-agent-read}/runtime/entry-48.js +0 -0
  504. /package/src/extensions/{pi-agent-text-editor/plugins/pi-agent-text-anchor-exact → pi-agent-search/plugins/pi-agent-search-text}/runtime/entry-58.js +0 -0
  505. /package/src/extensions/{pi-agent-read/extensions/pi-agent-web → pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor}/runtime/entry-83.js +0 -0
  506. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  507. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  508. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
@@ -0,0 +1,33 @@
1
+ import{a as We,b as ze,c as Ke}from"./chunk-ESPNEJHK.js";import{a as Ge}from"./chunk-L2B4DTVS.js";import{a as Ve}from"./chunk-6H32W35W.js";import"./chunk-NUM3YQGK.js";import{a as Me}from"./chunk-RW2GTYQI.js";import{a as He,b as qe,c as Je}from"./chunk-RIJMXO43.js";import{a as K,g as D}from"./chunk-PJL3UVMJ.js";import{a as ce,b as S,c as T}from"./chunk-R2U5WXYR.js";import{c as Fe}from"./chunk-W7CASEO3.js";import{e as Re,f as Ie}from"./chunk-T7I2VX3J.js";import{a as Te}from"./chunk-YJ6T3PEP.js";import{b as _e,c as Ae}from"./chunk-S72FVLUX.js";import{a as Ue}from"./chunk-XXLLY66B.js";import{c as Oe,d as Ne}from"./chunk-235QMMVA.js";import{a as U}from"./chunk-K5G4FDXD.js";import{e as $e}from"./chunk-PS2B6THP.js";import{a as je}from"./chunk-BU7IZLKB.js";import{a as xe,b as Ce}from"./chunk-S5PL5DFQ.js";import{f as Le,i as Be,j as ue}from"./chunk-LCWBVOII.js";import"./chunk-ZPT5D4VP.js";import{d as Ee}from"./chunk-756K3LJY.js";import{a as d}from"./chunk-EI7MMDWY.js";import O from"node:path";import{access as Vr}from"node:fs/promises";import{StringEnum as _t}from"@earendil-works/pi-ai";import{defineTool as Jr}from"@earendil-works/pi-coding-agent";import{Type as y}from"typebox";async function X(n,e=process.env,t=process.platform,r=o=>Ee(o,n,e)){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let o=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let a of o)if(await r(a.command))return a;return o[0]}d(X,"resolvePythonDebuggerCommand");import Mt from"cross-spawn";import{cp as Vt,mkdtemp as Jt,readdir as Gt,rm as Wt,stat as Y}from"node:fs/promises";import{tmpdir as zt}from"node:os";import Kt from"node:net";import A from"node:path";import{pathToFileURL as Xt}from"node:url";import{createMessageConnection as Yt,StreamMessageReader as Zt,StreamMessageWriter as Qt}from"vscode-jsonrpc/node";import Ut from"cross-spawn";import Ft from"node:net";var Ht=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),qt=128,k=class n{static{d(this,"DapClient")}#o;#a;#r;#t;#i;#e=new Map;#u=[];#d=new Set;#m=new Set;#l=Buffer.alloc(0);#f=1;#p;#h;#b;constructor(e,t,r,o){this.#o=e,this.#a=t,this.#r=r,this.#t=o,o&&o.completion.then(()=>this.#s(new Error("Debug adapter transport completed")),a=>this.#s(a instanceof Error?a:new Error("Debug adapter transport failed"))),e.on("data",a=>this.#v(a)),e.once("error",a=>this.#s(a)),t.once("error",a=>this.#s(a)),e.once("close",()=>this.#s(new Error("Debug adapter connection closed"))),r!==void 0&&(r.stderr.on("data",a=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(a)}),r.once("error",a=>this.#s(a)),r.once("exit",(a,i)=>{this.#s(new Error(`Debug adapter exited${a===null?"":` with code ${a}`}${i===null?"":` (${i})`}`))}))}static start(e,t,r){let a=Ut(e,[...t],{cwd:r,env:process.env,stdio:["pipe","pipe","pipe"]});return new n(a.stdout,a.stdin,a)}static fromTransport(e){return new n(e.readable,e.writable,void 0,e)}static fromSocket(e,t=1){let r=new n(e,e);return r.#f=t,r}static connect(e,t="127.0.0.1"){return new Promise((r,o)=>{let a=Ft.createConnection({port:e,host:t}),i=d(s=>o(s),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),r(new n(a,a))})})}onReverseRequest(e){this.#h=e}onEvent(e){return this.#m.add(e),()=>this.#m.delete(e)}request(e,t,r={}){if(this.#p!==void 0)return Promise.reject(this.#p);if(r.signal?.aborted===!0)return Promise.reject(r.signal.reason instanceof Error?r.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#b=void 0);let o=this.#f++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((s,u)=>{let c,p=d(()=>{c!==void 0&&clearTimeout(c),r.signal?.removeEventListener("abort",b)},"cleanup"),b=d(()=>{this.#e.delete(o),p(),u(r.signal?.reason instanceof Error?r.signal.reason:new Error("Debug operation aborted"))},"abort");r.timeoutMs!==void 0&&(c=setTimeout(()=>{this.#e.delete(o),p(),u(new Error(`Timed out waiting for debug response ${e}`))},r.timeoutMs)),this.#e.set(o,{resolve:d(l=>s(l),"resolve"),reject:u,cleanup:p}),r.signal?.addEventListener("abort",b,{once:!0})});return this.#w(a),i}takeEvent(e){let t=this.#u.findIndex(r=>e.includes(r.event));return t<0?void 0:this.#u.splice(t,1)[0]}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,r){let o=new Set(e),a=this.#u.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#u.splice(a,1)[0]):this.#p!==void 0?Promise.reject(this.#p):new Promise((i,s)=>{let u={events:o,resolve:d(p=>{clearTimeout(u.timer),this.#d.delete(u),i(p)},"resolve"),reject:d(p=>{clearTimeout(u.timer),this.#d.delete(u),s(p)},"reject"),timer:setTimeout(()=>{this.#d.delete(u),s(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#d.add(u);let c=d(()=>u.reject(r?.reason instanceof Error?r.reason:new Error("Debug operation aborted")),"abort");r?.aborted===!0?c():r?.addEventListener("abort",c,{once:!0})})}close(){this.#o.destroy(),this.#a.destroy(),this.#r!==void 0&&!this.#r.killed&&this.#r.kill(),this.#s(new Error("Debug adapter closed")),this.#t&&!this.#i&&(this.#i=Promise.resolve().then(()=>this.#t?.stop()),this.#i.catch(()=>{}))}async dispose(){this.close(),await this.#i}#w(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#a.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
2
+ \r
3
+ `),t]))}#v(e){for(this.#l=Buffer.concat([this.#l,e]);;){let t=this.#l.indexOf(`\r
4
+ \r
5
+ `);if(t<0)return;let r=this.#l.subarray(0,t).toString("ascii"),o=/^Content-Length:\s*(\d+)$/imu.exec(r);if(o===null){this.#s(new Error("Debug adapter sent a frame without Content-Length"));return}let a=Number(o[1]),i=t+4;if(this.#l.length<i+a)return;let s=this.#l.subarray(i,i+a).toString("utf8");this.#l=this.#l.subarray(i+a);try{this.#y(JSON.parse(s))}catch(u){this.#s(u instanceof Error?u:new Error(String(u)));return}}}#y(e){if(e.type==="event")if(e.event==="stopped"){let t=JSON.stringify(e.body??null);if(t===this.#b)return;this.#b=t}else e.event==="continued"&&(this.#b=void 0);if(e.type==="response"){let t=this.#e.get(e.request_seq);if(t===void 0)return;this.#e.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 r of this.#m)r(e);let t=[...this.#d].find(r=>r.events.has(e.event));t!==void 0?t.resolve(e):Ht.has(e.event)&&(this.#u.length===qt&&this.#u.shift(),this.#u.push(e));return}this.#g(e)}async#g(e){try{if(this.#h===void 0)throw new Error(`Client does not support reverse request ${e.command}`);let t=await this.#h(e);this.#w({seq:this.#f++,type:"response",request_seq:e.seq,success:!0,command:e.command,...t===void 0?{}:{body:t}})}catch(t){this.#w({seq:this.#f++,type:"response",request_seq:e.seq,success:!1,command:e.command,message:t instanceof Error?t.message:String(t)})}}#s(e){if(this.#p===void 0){this.#p=e;for(let t of this.#e.values())t.cleanup(),t.reject(e);this.#e.clear();for(let t of this.#d)t.reject(e);this.#d.clear()}}};function Q(n=process.env){return n.PI_JAVA_PATH??(n.JAVA_HOME===void 0?"java":A.join(n.JAVA_HOME,"bin",process.platform==="win32"?"java.exe":"java"))}d(Q,"javaExecutable");async function ee(n=process.env,e=process.platform){let t=n.PI_JDTLS_HOME??"/opt/pi-debug-adapters/jdtls",r=n.PI_JAVA_DEBUG_PLUGIN_PATH??"/opt/pi-debug-adapters/java-debug/com.microsoft.java.debug.plugin-0.53.2.jar",o=A.join(t,e==="win32"?"config_win":"config_linux");try{let a=(await Gt(A.join(t,"plugins"))).filter(s=>/^org\.eclipse\.equinox\.launcher_[^/]+\.jar$/u.test(s));if(a.length!==1)throw new Error("Expected one Equinox launcher jar");let i=A.join(t,"plugins",a[0]);if(!(await Y(i)).isFile()||!(await Y(r)).isFile()||!(await Y(o)).isDirectory())throw new Error("Expected JDT LS configuration and Java debug plugin files");return{launcher:i,configuration:o,plugin:r}}catch(a){throw new Error(`Java debugger requires JDT LS (PI_JDTLS_HOME) and java-debug plugin (PI_JAVA_DEBUG_PLUGIN_PATH): ${a instanceof Error?a.message:String(a)}`,{cause:a})}}d(ee,"javaDebuggerFiles");var H=class{static{d(this,"JavaDebugRuntime")}#o;#a;#r;#t;#i;#e;get processIds(){return[this.#o?.pid,this.#a?.pid].filter(e=>e!==void 0)}async start(e,t){if(t.throwIfAborted(),e.mainClass===void 0)throw new Error("Java debug sessions require mainClass");let r=await tr(e),o=await this.connect(e.cwd,t);t.throwIfAborted(),this.#a=this.#d(["-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0","-cp",r.join(A.delimiter),e.mainClass,...e.args],e.cwd,process.env);let a=await rr(this.#a,t),i=A.dirname(e.sourceFile);for(let s of e.mainClass.split(".").slice(1))i=A.dirname(i);return{client:o,attach:{hostName:"127.0.0.1",port:a,timeout:1e4,sourcePaths:[i]}}}async connect(e,t,r=process.env){t.throwIfAborted();let o=await ee(r);this.#i=await Jt(A.join(zt(),"pi-java-debug-"));let a=A.join(this.#i,"configuration");await Vt(o.configuration,a,{recursive:!0});let i={...r};delete i.CLIENT_PORT,delete i.CLIENT_HOST,t.throwIfAborted(),this.#o=this.#d(["-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Xmx512m","--add-modules=ALL-SYSTEM","--add-opens","java.base/java.util=ALL-UNNAMED","--add-opens","java.base/java.lang=ALL-UNNAMED","-jar",o.launcher,"-configuration",a,"-data",A.join(this.#i,"workspace")],e,i);let s=this.#o;await Z(new Promise((f,g)=>{s.once("spawn",f),s.once("error",g)}),t);let u=new AbortController,c=new class extends Qt{async write(f){try{await super.write(f)}catch(g){u.abort(g)}}}(s.stdin),p=Yt(new Zt(s.stdout),c);this.#r=p;let b="";s.stderr.on("data",f=>{b=(b+f.toString()).slice(-4e3)}),s.once("error",f=>u.abort(f)),s.once("exit",f=>u.abort(new Error(`Java debugger language server exited (${String(f)}): ${b}`)));let l=AbortSignal.any([t,u.signal]);p.onRequest("workspace/configuration",f=>f.items.map(()=>null)),p.onRequest("client/registerCapability",()=>null),p.onRequest("window/workDoneProgress/create",()=>null),p.listen(),await Z(p.sendRequest("initialize",{processId:process.pid,rootUri:Xt(e).href,capabilities:{},initializationOptions:{bundles:[o.plugin],settings:{java:{import:{gradle:{enabled:!1},maven:{enabled:!1}}}}}}),l),await p.sendNotification("initialized",{});let h=await Z(p.sendRequest("workspace/executeCommand",{command:"vscode.java.startDebugSession",arguments:[]}),l);if(typeof h!="number"||!Number.isInteger(h)||h<1||h>65535)throw new Error("JDT LS did not return a Java DAP port; check PI_JAVA_DEBUG_PLUGIN_PATH");return this.#t=await er(h,l),this.#t}close(){return this.#e??=this.#u(),this.#e}async#u(){this.#t?.close(),this.#r?.dispose(),await Promise.all([Xe(this.#a),Xe(this.#o)]),this.#i!==void 0&&await Wt(this.#i,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}#d(e,t,r){let o=Mt(Q(r),[...e],{cwd:t,env:r,stdio:"pipe",windowsHide:!0});return o.stdin.on("error",()=>{}),o}};function er(n,e){return e.throwIfAborted(),new Promise((t,r)=>{let o=Kt.createConnection({port:n,host:"127.0.0.1"}),a=d(()=>{o.destroy(),r(e.reason)},"abort"),i=d(()=>{e.removeEventListener("abort",a)},"cleanup");e.addEventListener("abort",a,{once:!0}),o.once("error",s=>{i(),r(s)}),o.once("connect",()=>{i(),t(k.fromSocket(o))})})}d(er,"connectDap");async function tr(n){let e=`${n.mainClass.replaceAll(".",A.sep)}.class`,t=["build/classes/java/main","target/classes","out/production","bin","."],r=[];for(let o of t){let a=A.resolve(n.cwd,o);try{(await Y(A.join(a,e))).isFile()&&r.push(a)}catch{}}if(r.length===0)throw new Error(`Java main class ${n.mainClass} is not compiled. Compile with javac -g into build/classes/java/main, target/classes, out/production, bin, or the project directory.`);return r}d(tr,"javaClassPaths");async function Z(n,e){let t=d(()=>{},"abort"),r=new Promise((o,a)=>{t=d(()=>a(e.reason),"abort"),e.addEventListener("abort",t,{once:!0}),e.aborted&&t()});try{return await Promise.race([n,r])}finally{e.removeEventListener("abort",t)}}d(Z,"bounded");function rr(n,e){return Z(new Promise((t,r)=>{let o="",a=d(i=>{o=(o+i.toString()).slice(-4e3);let s=/Listening for transport dt_socket at address: (\d+)/u.exec(o);s!==null&&t(Number(s[1]))},"consume");n.stdout.on("data",a),n.stderr.on("data",a),n.once("error",r),n.once("exit",i=>r(new Error(`Java target exited before JDWP was ready (${String(i)}): ${o}`)))}),e)}d(rr,"targetReady");async function Xe(n){n===void 0||n.pid===void 0||n.exitCode!==null||n.signalCode!==null||await new Promise((e,t)=>{let r=d(()=>{clearTimeout(i),clearTimeout(s),n.removeListener("exit",o),n.removeListener("error",a)},"cleanup"),o=d(()=>{r(),e()},"exited"),a=d(u=>{r(),t(u)},"failed"),i=setTimeout(()=>{n.kill("SIGKILL")},500),s=setTimeout(()=>{r(),t(new Error(`Could not stop owned Java process ${String(n.pid)} within 2 seconds`))},2e3);n.once("exit",o),n.once("error",a),n.kill()})}d(Xe,"stopProcess");var Ye=[{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:"java-debug / JDT LS",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"}],le=[{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:"java-debug",name:"Microsoft Java Debug Server",kind:"debugger",languages:["java"],executables:["java"],dependencies:["JDK 21+","Eclipse JDT LS 1.61.0","Microsoft java-debug 0.53.2"],documentation:"https://github.com/microsoft/java-debug",debugger:{runtimeExecutables:["java"],adapterExecutables:["java"],platforms:["linux","win32"],install:"Install JDK 21+, Eclipse JDT LS 1.61.0 and the java-debug 0.53.2 plugin jar (from vscode-java-debug 0.59.0). Set PI_JAVA_PATH (or JAVA_HOME), PI_JDTLS_HOME and PI_JAVA_DEBUG_PLUGIN_PATH. Compile with javac -g before debugging. Pi owns a suspended target JVM and attaches through JDT LS; Kotlin still uses its own adapter."}},{id:"kotlin-debug-adapter",name:"Kotlin Debug Adapter",kind:"debugger",languages:["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 te(n){return le.find(e=>e.languages.includes(n))}d(te,"debuggerRecipeForLanguage");import{readdir as et,readFile as ar}from"node:fs/promises";import{homedir as ge}from"node:os";import R from"node:path";var Ze="2025-06-18",V=class n{static{d(this,"DebugMcpClient")}#o;#a;#r=1;constructor(e){this.#o=e}static async connect(e,t){let r=new n(`http://127.0.0.1:${e}/mcp`);return await r.#t("initialize",{protocolVersion:Ze,capabilities:{},clientInfo:{name:"pi-agent-ide",version:"1"}},t),await r.#i({jsonrpc:"2.0",method:"notifications/initialized"},t),r}async call(e,t,r){let o=await this.#t("tools/call",{name:e,arguments:t},r),a=(o.content??[]).flatMap(i=>i.type==="text"&&i.text!==void 0?[i.text]:[]).join(`
6
+ `);if(o.isError===!0)throw new Error(a||`DebugMCP ${e} failed`);return a}async close(){this.#a!==void 0&&(await fetch(this.#o,{method:"DELETE",headers:this.#e(),signal:AbortSignal.timeout(1e3)}).catch(()=>{}),this.#a=void 0)}async#t(e,t,r){let o=this.#r++,a=await this.#i({jsonrpc:"2.0",id:o,method:e,params:t},r),i=await nr(a,o);if(i.error!==void 0)throw new Error(`DebugMCP ${e} failed: ${i.error.message??"unknown error"}`);return i.result}async#i(e,t){let r=await fetch(this.#o,{method:"POST",headers:{...this.#e(),"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify(e),...t===void 0?{}:{signal:t}});if(!r.ok)throw new Error(`DebugMCP returned HTTP ${r.status}: ${await r.text()}`);return this.#a=r.headers.get("mcp-session-id")??this.#a,r}#e(){return this.#a===void 0?{}:{"mcp-session-id":this.#a,"mcp-protocol-version":Ze}}};async function nr(n,e){let t=await n.text(),r=(n.headers.get("content-type")??"").includes("text/event-stream")?t.split(/\r?\n/u).filter(o=>o.startsWith("data:")).map(o=>o.slice(5).trim()):[t];for(let o of r){if(o.length===0)continue;let a=JSON.parse(o);if(a.id===e)return a}throw new Error("DebugMCP returned no response")}d(nr,"responseMessage");var ne="ozzafar.debugmcpextension";function ae(n=process.env){return Number(n.PI_DEBUGMCP_PORT??3001)}d(ae,"debugMcpPort");var or=6e4,ir=30,Qe=6e4,sr=new Set([".exe",".out",".bin",".elf",".so",".dll",".dylib"]);function pe(n,e=process.platform){return e==="win32"?n.replace(/^[A-Z](?=:)/u,t=>t.toLowerCase()):n}d(pe,"vscodePath");function dr(n){return sr.has(R.extname(n).toLowerCase())}d(dr,"isExecutable");var ur={continue:"continue_execution",next:"step_over",stepIn:"step_into",stepOut:"step_out"};async function fe(n){for(let e of cr()){let t=await et(e).catch(()=>[]);for(let r of t){if(!/^window-\d+\.json$/u.test(r))continue;let o=await lr(R.join(e,r));if(o!==void 0&&n.every(a=>o.workspaceFolders.some(i=>gr(a,i))))return o}}}d(fe,"findVscodeWindow");async function tt(){for(let n of[R.join(ge(),".vscode-server","extensions"),R.join(ge(),".vscode","extensions")])if((await et(n).catch(()=>[])).some(t=>t.startsWith(`${ne}-`)))return!0;return!1}d(tt,"debugMcpInstalled");async function rt(n){try{return await(await V.connect(ae(),n)).close(),!0}catch{return!1}}d(rt,"debugMcpResponds");var re=class n{static{d(this,"VscodeDebugSession")}window;#o;#a;#r=new Map;#t;constructor(e,t,r){this.window=e,this.#o=t,this.#a=r}static async open(e,t){let r=await fe([e.cwd,e.program,e.sourceFile]);if(r===void 0)throw new Error(`No running VS Code window with DebugMCP has ${e.cwd} open`);let o=ae(),a;try{a=await V.connect(o,t)}catch(s){throw t?.throwIfAborted(),new Error(`DebugMCP did not respond on port ${o}: ${yr(s)}`,{cause:s})}let i=new n(r,a,e.program);try{if(await i.#i(t),(await i.status(0,t)).status!=="no-session")throw new Error(`VS Code window "${r.name}" already has an active debug session`)}catch(s){throw await a.close(),s}return i}async addBreakpoint(e,t,r){let o=`${e}:${t}`,a=this.#r.get(o);if(a!==void 0){this.#r.set(o,a+1);return}let i=await this.#e("list_breakpoints",{},r);br(i).has(`${R.basename(e)}:${t}`)||(await this.#e("add_breakpoint",{fileFullPath:pe(e),line:t},r),this.#r.set(o,1))}async removeBreakpoint(e,t,r){let o=`${e}:${t}`,a=this.#r.get(o);if(a!==void 0){if(a>1){this.#r.set(o,a-1);return}this.#r.delete(o),await this.#e("remove_breakpoint",{fileFullPath:pe(e),line:t},r)}}async start(e,t){if(e.configuration===void 0&&e.test===void 0&&dr(e.program))throw new Error(`VS Code cannot choose a debugger for the executable ${R.basename(e.program)}. Add a .vscode/launch.json configuration for it (for example "cppvsdbg" or "cppdbg") and pass its name as configuration.`);let r=AbortSignal.timeout(Qe);try{await this.#e("start_debugging",{fileFullPath:e.program,workingDirectory:e.cwd,...e.configuration===void 0?{}:{configurationName:e.configuration},...e.test===void 0?{}:{testName:e.test}},t===void 0?r:AbortSignal.any([t,r]))}catch(a){throw!r.aborted||t?.aborted===!0?a:(await this.#e("stop_debugging",{}).catch(()=>{}),new Error(`VS Code did not start the debug session within ${Qe/1e3} s. Check that the VS Code window has the debugger extension for this configuration and that no prompt is waiting in VS Code.`,{cause:a}))}let o=await this.status(0,t);return this.#t=o.configurationName,o}async command(e,t){return await this.#e(ur[e],{},t),this.status(ir,t)}async status(e,t){let r=d(async a=>fr(JSON.parse(await this.#e("get_debug_status",a===0?{}:{waitForPauseSeconds:a},t))),"read"),o=await r(e);for(let a=0;o.status==="paused"&&o.frame===void 0&&a<20;a++)await new Promise(i=>setTimeout(i,100)),o=await r(0);return o}async locals(e){let t=mr(await this.#e("list_variable_names",{scope:"local"},e)).slice(0,50);if(t.length===0)return[];let r=await this.#e("get_variables_values",{variableNames:t.map(({name:o})=>o),scope:"local"},e);return hr(r,t)}async evaluate(e,t){return wr(await this.#e("evaluate_expression",{expression:e},t))}async#i(e){await this.#o.call("remove_breakpoint",{fileFullPath:this.#a,line:0},e)}async#e(e,t,r){try{return await this.#o.call(e,t,r)}catch(o){throw await this.#i().catch(()=>{}),o}}async close(e){try{for(let r of this.#r.keys()){let o=r.lastIndexOf(":");await this.#e("remove_breakpoint",{fileFullPath:pe(r.slice(0,o)),line:Number(r.slice(o+1))},e)}this.#r.clear();let t=await this.status(0,e);t.status!=="no-session"&&t.configurationName===this.#t&&await this.#e("stop_debugging",{},e)}finally{await this.#o.close()}}};function cr(){let n=ge();return[R.join(n,".vscode-server","data","User"),R.join(n,".config","Code","User"),R.join(n,"Library","Application Support","Code","User"),...process.env.APPDATA===void 0?[]:[R.join(process.env.APPDATA,"Code","User")]].map(e=>R.join(e,"globalStorage",ne,"window-registry"))}d(cr,"registryDirectories");async function lr(n){try{let e=JSON.parse(await ar(n,"utf8"));return typeof e.pid!="number"||typeof e.updatedAt!="number"||!Array.isArray(e.workspaceFolders)||Date.now()-e.updatedAt>or||!pr(e.pid)?void 0:{pid:e.pid,name:typeof e.name=="string"?e.name:"",workspaceFolders:e.workspaceFolders.filter(t=>typeof t=="string")}}catch{return}}d(lr,"readRegistration");function pr(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}d(pr,"processAlive");function gr(n,e,t=process.platform){let r=t==="win32"?R.win32:R.posix,o=d(s=>t==="win32"?r.resolve(s).toLowerCase():r.resolve(s),"fold"),a=o(e),i=o(n);return i===a||i.startsWith(a.endsWith(r.sep)?a:a+r.sep)}d(gr,"isInside");function fr(n){let e=n.status==="paused"||n.status==="running"?n.status:"no-session",t=typeof n.configurationName=="string"?n.configurationName:void 0,r=typeof n.state=="object"&&n.state!==null?n.state:{},o=Array.isArray(r.stackTrace)&&typeof r.stackTrace[0]=="string"?/^(.*):(\d+)$/u.exec(r.stackTrace[0]):null,a=typeof r.currentLine=="number"?r.currentLine:o===null?void 0:Number(o[2]),i=a===void 0?void 0:{id:typeof r.frameId=="number"?r.frameId:0,threadId:typeof r.threadId=="number"?r.threadId:0,name:typeof r.frameName=="string"?r.frameName:o?.[1]??"",...typeof r.fileFullPath=="string"?{file:r.fileFullPath}:{},line:a};return{status:e,...t===void 0?{}:{configurationName:t},...e==="paused"&&i!==void 0?{frame:i}:{}}}d(fr,"debugState");function br(n){return new Set(n.split(/\r?\n/u).flatMap(e=>{let t=/^\d+\. (?:Breakpoint|Logpoint) (.+?):(\d+)(?: \(|$)/u.exec(e);return t===null?[]:[`${t[1]}:${t[2]}`]}))}d(br,"listedBreakpoints");function mr(n){return n.split(/\r?\n/u).flatMap(e=>{let t=/^ {2}(\S.*?)(?: \(([^()]*)\))?$/u.exec(e);if(t===null||/^(?:No variables in this scope|Error retrieving variables:)/u.test(e.trim()))return[];let r=t[1],o=t[2];return r===void 0?[]:[{name:r,...o===void 0?{}:{type:o}}]})}d(mr,"variableNames");function hr(n,e){let t=n.split(/\r?\n/u);return e.flatMap(({name:r,type:o})=>{let a=` ${r}`,i=t.find(p=>p===a||p.startsWith(`${a}: `)||p.startsWith(`${a} (`));if(i===void 0)return[];let s=i.slice(a.length),u=o===void 0?void 0:` (${o})`,c=s.startsWith(": ")?s.slice(2):"<complex value>";return u!==void 0&&c.endsWith(u)&&(c=c.slice(0,-u.length)),[{name:r,value:c,...o===void 0?{}:{type:o}}]})}d(hr,"variableValues");function wr(n){let e=n.split(/\r?\n/u),t=e.findIndex(a=>a.startsWith("Result: ")),r=/^Result: (.*?)(?: \(([^()]*)\))?$/u.exec(e[t]??"");if(r===null)throw new Error(`DebugMCP returned no evaluation result: ${n}`);let o=e.slice(t+1).filter(a=>/^ {2}\S/u.test(a));return{result:[r[1],...o].join(`
7
+ `),...r[2]===void 0?{}:{type:r[2]}}}d(wr,"evaluation");function yr(n){return n instanceof Error?n.message:String(n)}d(yr,"message");var nt="/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js",at="/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh",ot={protocol:_e,apiVersion:Ae,id:"debugger",setup(n){for(let e of le)n.addToolRecipe(e);n.addSetupCheck({id:"effective-config",inspect:vr}),n.addCheck({id:"adapters",title:"Debug adapters",run:Dr}),n.addCheck({id:"vscode",title:"VS Code debugger backend",run:Pr})}};async function vr(n,e=n.workspace?.platform??process.platform){let t=new Map([...n.detectedLanguageIds].map(te).filter(a=>a!==void 0).map(a=>[a.id,a])),r=[...n.detectedLanguageIds].flatMap(a=>{let i=te(a);return i===void 0?[]:[{kind:"debugger",languageId:a,toolId:i.id}]}),o=[];for(let a of Ye)a.status==="planned"&&n.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 i=a.debugger;if(i===void 0)continue;let s=e==="linux"||e==="darwin"||e==="win32"?e:void 0;if(s===void 0||!i.platforms.includes(s)){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 be(n,e):void 0,c=await Sr(a.id==="java-debug"?[Q(n.env)]:u===void 0?i.runtimeExecutables:[u.command],n);if(c!==void 0){o.push({id:`debugger-${a.id}-runtime`,category:"missing-runtime",message:`Runtime ${c} is unavailable. ${i.install}`});continue}if(!await kr(a.id,n,e)){o.push({id:`debugger-${a.id}-adapter`,category:"missing-adapter",message:`${a.name} is not installed. ${i.install}`});continue}await Er(a.id,n,e)||o.push({id:`debugger-${a.id}-startup`,category:"adapter-startup",message:`${a.name} is installed but cannot start. ${i.install}`})}return{selections:r,actions:o}}d(vr,"inspectDebuggerSetup");async function Dr(n){let e=[...new Map([...n.detectedLanguageIds].map(te).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 r=await st(t.id,n);if(t.id==="java-debug"&&r.ok&&n.workspace===void 0){let o=new H;try{await o.connect(n.cwd,AbortSignal.timeout(2e4),n.env),r={ok:!0,detail:`${r.detail}
8
+ Java DAP bridge ready`}}catch(a){r={ok:!1,detail:a instanceof Error?a.message:String(a)}}finally{await o.close()}}return{status:r.ok?"pass":"fail",message:`${t.name}: ${r.ok?"available":"unavailable"}`,detail:r.detail}}))}d(Dr,"checkDebuggerAdapters");async function Pr(n){if(n.workspace!==void 0)return[{status:"skip",message:"The VS Code backend debugs only local workspaces"}];let e=await fe([n.cwd]);return e!==void 0?await rt(n.signal)?[{status:"pass",message:`VS Code backend: available in "${e.name}"`}]:[{status:"fail",message:"VS Code backend: DebugMCP does not respond",detail:`"${e.name}" has this workspace open, but DebugMCP does not accept connections on port ${ae(n.env)}. Set PI_DEBUGMCP_PORT when debugmcp.serverPort differs.`}]:await tt()?[{status:"skip",message:"VS Code backend: no VS Code window with DebugMCP has this workspace open",detail:"Open the workspace in VS Code to debug through it; debug uses native adapters meanwhile."}]:await T(n,"code")?[{status:"warn",message:"VS Code backend: DebugMCP is not installed",detail:`Install it with: code --install-extension ${ne}`}]:[{status:"skip",message:"VS Code backend: VS Code is not installed"}]}d(Pr,"checkVscodeBackend");async function it(n,e){if(n.workspace!==void 0)return S(n,"python3",["-c","import glob,os,sys; home,plugin=sys.argv[1:]; launchers=glob.glob(os.path.join(home,'plugins','org.eclipse.equinox.launcher_*.jar')); ok=len(launchers)==1 and os.path.isfile(plugin) and os.path.isdir(os.path.join(home,'config_linux')); print('Java debugger files ready' if ok else 'Missing JDT LS or java-debug plugin'); sys.exit(0 if ok else 1)",n.env.PI_JDTLS_HOME??"/opt/pi-debug-adapters/jdtls",n.env.PI_JAVA_DEBUG_PLUGIN_PATH??"/opt/pi-debug-adapters/java-debug/com.microsoft.java.debug.plugin-0.53.2.jar"]);try{return await ee(n.env,e),{ok:!0,detail:"Java debugger files ready"}}catch(t){return n.signal?.throwIfAborted(),{ok:!1,detail:t instanceof Error?t.message:String(t)}}}d(it,"probeJavaFiles");async function Sr(n,e){for(let t of n)if(!await T(e,t))return t}d(Sr,"firstMissingExecutable");async function kr(n,e,t=e.workspace?.platform??process.platform){let{env:r}=e;if(n==="elixir-ls-debug-adapter")return q(e,r.PI_ELIXIR_LS_DEBUG_PATH??at);if(n==="vsc-debugger")return(await S(e,r.PI_R_PATH??"R",["--vanilla","--quiet","-e","quit(status=if (requireNamespace('vscDebugger', quietly=TRUE)) 0 else 1)"])).ok;if(n==="vscode-js-debug")return q(e,r.PI_JS_DEBUG_PATH??nt);if(n.startsWith("lldb-dap"))return await T(e,r.PI_LLDB_DAP_PATH??(t==="win32"?"lldb-dap":"lldb-dap-18"))||await T(e,"lldb-dap");if(n==="delve")return T(e,r.PI_DELVE_PATH??"dlv");if(n==="java-debug")try{return e.workspace!==void 0?(await it(e,t)).ok:(await ee(r,t),!0)}catch{return!1}if(n==="kotlin-debug-adapter")return T(e,r.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter");if(n==="julia-debug-adapter")return q(e,`${r.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia"}/Project.toml`);if(n==="dart-debug-adapter")return T(e,r.PI_DART_PATH??"dart");if(n==="netcoredbg")return T(e,r.PI_NETCOREDBG_PATH??"netcoredbg");if(n==="rdbg")return T(e,r.PI_RUBY_DEBUG_PATH??"rdbg");let a={"vscode-php-debug":r.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js","local-lua-debugger":r.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js","vscode-bash-debug":r.PI_BASH_DEBUG_PATH??"/opt/pi-debug-adapters/bash-debug/extension/out/bashDebug.js","powershell-editor-services-debug":`${r.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services"}/PowerShellEditorServices/Start-EditorServices.ps1`}[n];if(a!==void 0)return q(e,a);if(n!=="debugpy")return!1;let i=await be(e,t);return(await S(e,i.command,[...i.args,"-c","import importlib.util; raise SystemExit(importlib.util.find_spec('debugpy') is None)"])).ok}d(kr,"adapterInstalled");async function Er(n,e,t=e.workspace?.platform??process.platform){return(await st(n,e,t)).ok}d(Er,"adapterAvailable");async function st(n,e,t=e.workspace?.platform??process.platform){let{env:r}=e;if(n==="elixir-ls-debug-adapter")return J(r.PI_ELIXIR_LS_DEBUG_PATH??at,e);if(n==="vsc-debugger")return S(e,r.PI_R_PATH??"R",["--vanilla","--quiet","-e","library(vscDebugger); cat(as.character(packageVersion('vscDebugger')))"]);if(n==="dart-debug-adapter")return S(e,r.PI_DART_PATH??"dart",["--version"]);if(n==="debugpy"){let a=await be(e,t);return S(e,a.command,[...a.args,"-c","import debugpy; print(debugpy.__version__)"])}if(n==="delve")return S(e,r.PI_DELVE_PATH??"dlv",["version"]);if(n==="julia-debug-adapter"){let a=r.PI_JULIA_DEBUG_PROJECT??"/opt/pi-debug-adapters/julia";return S(e,r.PI_JULIA_PATH??"julia",[`--project=${a}`,"--startup-file=no","-e","using DebugAdapter"])}if(n==="java-debug"){let a=await it(e,t);if(!a.ok)return a;let i=await S(e,Q(r),["-version"]);if(!i.ok)return i;let s=/version "(\d+)/u.exec(i.detail)?.[1];return Number(s)>=21?i:{ok:!1,detail:"Java debugger requires JDK 21 or newer. Set PI_JAVA_PATH or JAVA_HOME."}}if(n==="kotlin-debug-adapter"){let a=await S(e,r.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",["--help"]);return a.ok?S(e,"java",["-version"]):a}if(n==="netcoredbg"){let a=await S(e,r.PI_NETCOREDBG_PATH??"netcoredbg",["--version"]);return a.ok?S(e,"dotnet",["--version"]):a}if(n.startsWith("lldb-dap")){let a=r.PI_LLDB_DAP_PATH??(t==="win32"?"lldb-dap":await T(e,"lldb-dap-18")?"lldb-dap-18":"lldb-dap");return S(e,a,["--version"])}if(n==="rdbg")return S(e,r.PI_RUBY_DEBUG_PATH??"rdbg",["--version"]);if(n==="vscode-php-debug"){let a=await S(e,r.PI_PHP_PATH??"php",["-r","exit(extension_loaded('xdebug') ? 0 : 1);"]);return a.ok?J(r.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js",e):a}if(n==="local-lua-debugger"){let a=await S(e,r.PI_LUA_PATH??"lua",["-v"]);return a.ok?J(r.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js",e):a}if(n==="vscode-bash-debug"){let a=await S(e,r.PI_BASH_PATH??"bash",["--version"]);return a.ok?J(r.PI_BASH_DEBUG_PATH??"/opt/pi-debug-adapters/bash-debug/extension/out/bashDebug.js",e):a}if(n==="powershell-editor-services-debug"){let a=await S(e,r.PI_PWSH_PATH??"pwsh",["--version"]),i=r.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";return a.ok?J(`${i}/PowerShellEditorServices/Start-EditorServices.ps1`,e):a}if(n!=="vscode-js-debug")return{ok:!1,detail:`Unknown debugger adapter: ${n}`};let o=r.PI_JS_DEBUG_PATH??nt;return await q(e,o)?S(e,e.workspace?"node":process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1]); console.log(process.version)",o]):{ok:!1,detail:`${o} does not exist`}}d(st,"probeAdapter");async function J(n,e){return await q(e,n)?S(e,e.workspace?"node":process.execPath,["-e","const fs=require('node:fs'); fs.accessSync(process.argv[1])",n]):{ok:!1,detail:`${n} does not exist`}}d(J,"probeAdapterFile");async function be(n,e){return X(n.cwd,n.env,e,t=>T(n,t))}d(be,"pythonCommand");async function q(n,e){if(!n.workspace)return ce(n,e);let t=n.workspace.toNativeUri(n.cwd).replace(/\/?$/u,"/"),r=e.split("/").map(encodeURIComponent).join("/"),o=n.workspace.fromNativeUri(new URL(r,t).href);return ce(n,o)}d(q,"adapterFileExists");import _r from"node:path";import{fileURLToPath as Ar}from"node:url";function ut(n){return{id:"debug-breakpoints",present(e,t){let r=n.get(t.source),o=n.sourceFile(t.source)??dt(t.source,t.cwd)??dt(e.source,t.cwd);if(o===void 0)return e;let a=n.breakpointsForFile(o,r?.source);if(a.length===0)return e;let i=Rr(a);return{...e,lines:e.lines.map(s=>{let u=i.get(s.lineNumber);return u===void 0?s:{...s,presentation:{...s.presentation,suffix:`${s.presentation?.suffix??""}${Ir(u)}`,compactSuffix:`${s.presentation?.compactSuffix??""}${Tr(u)}`}}})}}}}d(ut,"createBreakpointPresenter");function Rr(n){let e=new Map;for(let t of n){let r=e.get(t.line)??[];r.push(t),e.set(t.line,r)}return e}d(Rr,"groupByLine");function dt(n,e){if(n.startsWith("file://"))return Ar(n);if(!/^[a-z][a-z\d+.-]*:/iu.test(n))return _r.resolve(e,n)}d(dt,"filesystemSource");function Ir(n){return n.map(e=>` ${e.verified?"\u25CF":"\u25CB"} breakpoint ${e.source} (${e.verified?"verified":"pending"})`).join("")}d(Ir,"renderAgentBreakpoints");function Tr(n){let t=n.filter(o=>o.verified).length===n.length?"\u25CF":"\u25CB",r=n.length===1?"breakpoint":`${n.length} breakpoints`;return` ${t} ${r}`}d(Tr,"renderUserBreakpoints");import oe from"node:path";import{Text as me}from"@earendil-works/pi-tui";function he(n,e,t,r){return new me(`${r.fg("toolTitle",n)} ${r.fg("muted",`\xB7 ${bt(e,t)}`)}
9
+ ${r.fg("accent","\u25C6 configure debugger")}`,0,0)}d(he,"renderDebugCall");function ct(n,e,t){return new me(`${pt(n,t)}
10
+ ${t.fg("accent",Cr(e))}`,0,0)}d(ct,"renderDebugActionCall");function G(n,e,t,r,o){let a=xr(n,e,t);return o!==void 0&&a.unshift(t.fg("error",`\u2717 ${o}`)),r!==void 0&&a.unshift(`${t.fg("accent",r.expression)} ${t.fg("muted","=")} ${t.fg("toolOutput",r.result)}${r.type===void 0?"":t.fg("dim",` ${r.type}`)}`),new me(a.join(`
11
+ `),0,0)}d(G,"renderDebugResult");function lt(n,e){let t=[pt(n,e),gt(n.status,e)];return n.stop?.frame!==void 0&&t.push(` ${e.fg("warning","\u25CF")} ${n.stop.frame.name} ${e.fg("muted",`\xB7 ${ft(n.stop)}`)}`),t}d(lt,"renderActiveDebugger");function xr(n,e,t){let r=[];if(n.status==="stopped"&&n.stop!==void 0){r.push(t.fg("warning",`\u25CF stopped \xB7 ${n.stop.reason}`),t.fg("text",`${n.stop.frame?.name??"unknown frame"} ${t.fg("muted",`\xB7 ${ft(n.stop)}`)}`));for(let a of n.stop.sourceLines){let i=a.current?t.fg("warning",">"):t.fg("dim","\u2502"),s=a.current?"text":"dim";r.push(`${i} ${String(a.lineNumber).padStart(4)} ${t.fg(s,a.content)}`)}let o=e?n.stop.variables:n.stop.variables.slice(0,6);if(o.length>0){r.push(t.fg("muted","Locals"));for(let a of o)r.push(` ${t.fg("accent",a.name.padEnd(16))} ${t.fg("toolOutput",a.value)}${a.type===void 0?"":t.fg("dim",` ${a.type}`)}`);o.length<n.stop.variables.length&&r.push(t.fg("muted",` \u2026 ${n.stop.variables.length-o.length} more`))}return r}if(r.push(gt(n.status,t)),n.breakpoints.length>0){let o=n.breakpoints.filter(a=>a.verified).length;r.push(t.fg("muted",`${n.breakpoints.length} breakpoint${n.breakpoints.length===1?"":"s"} \xB7 ${o} verified`))}return r}d(xr,"debugResultLines");function pt(n,e){return`${e.fg("toolTitle",n.options.adapter)} ${e.fg("muted",`\xB7 ${bt(n.options.program,n.options.cwd)}`)}`}d(pt,"debugIdentity");function Cr(n){let e=n.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 ${n.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}d(Cr,"actionLabel");function gt(n,e){return n==="configured"?e.fg("muted","\u25C7 ready"):n==="running"?e.fg("accent","\u25CF running"):n==="stopped"?e.fg("warning","\u25CF stopped"):e.fg("success","\u25A0 stopped debugging")}d(gt,"statusLine");function ft(n){let e=n.frame?.source?.path??n.frame?.source?.name??"unknown";return`${oe.basename(e)}:${n.frame?.line??"?"}`}d(ft,"shortFrame");function bt(n,e){let t=oe.relative(e,n),r=".".repeat(2),o=t===r||t.startsWith(`${r}${oe.sep}`);return t.length>0&&!o?t:oe.basename(n)}d(bt,"shortPath");function we(n){let e=ye(n);if(e===void 0)return;let t=e.snapshot;return typeof t=="object"&&t!==null?t:void 0}d(we,"debuggerSnapshotFromResult");function mt(n){let e=ye(n);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}:{}}}d(mt,"debuggerEvaluationFromResult");function ht(n){let e=ye(n),t=e?.ok===!1?e.error:void 0;return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"?t.message:void 0}d(ht,"debuggerFailureFromResult");function ye(n){if(typeof n!="object"||n===null)return;let e=n.metadata;if(typeof e!="object"||e===null)return;let t=e.semanticAction;return typeof t=="object"&&t!==null?t:void 0}d(ye,"semanticActionFromResult");function wt(n){return{id:"debugger",onDidChange:d(e=>n.onDidChange(e),"onDidChange"),list:d(()=>n.list().map(e=>n.snapshot(e)).filter(e=>e.status==="configured"||e.status==="running"||e.status==="stopped").map(e=>({source:e.source,...e.remote===void 0?{}:{remote:e.remote},owned:!0,kind:"debugger",title:e.options.adapter,description:e.options.program,status:e.status==="configured"?"configured":e.status==="stopped"?"paused":"running",renderSummary:d(t=>lt(e,t),"renderSummary"),renderDetail:d(t=>G(e,!0,t),"renderDetail"),stop:d(()=>n.delete(e.source),"stop")})),"list")}}d(wt,"debuggerProcessProvider");import M from"cross-spawn";import{randomBytes as yt}from"node:crypto";import{mkdtemp as jr,readFile as kt,rm as $r}from"node:fs/promises";import Et from"node:net";import{tmpdir as Lr}from"node:os";import E from"node:path";var se=class{static{d(this,"DebugSessionManager")}#o=new Map;#a=new Set;#r;constructor(e){this.#r=e}setOwnerResolver(e){this.#r=e}#t(e){let t=this.#r?.(e.options.cwd);if(t?.key!==e.ownerKey)throw new Error("Debugger resource owner changed");return t}create(e,t){let r=this.#r?.(e.cwd);if(!r&&[e.cwd,e.program,e.sourceFile].some(i=>i?.includes("://")))throw new Error("No debugger workspace owner");if(r)for(let i of[e.cwd,e.program,e.sourceFile??e.program])r.serverPath(i);let o=yt(6).toString("hex"),a={id:o,source:`debug:${o}`,options:{...e,sourceFile:e.sourceFile??e.program},...r===void 0?{}:{ownerKey:r.key},...t===void 0?{}:{vscode:t},breakpoints:new Map,status:"configured",stopGeneration:0};return this.#o.set(o,a),this.#n(a),a}get(e){let t=/^debug:([a-f\d]{12})(?:\/|$)/u.exec(e);return t===null?void 0:this.#o.get(t[1])}list(){return[...this.#o.values()]}snapshot(e){return{id:e.id,source:e.source,options:e.options,status:e.status,...e.remote===void 0?{}:{remote:e.remote},breakpoints:[...e.breakpoints.values()].map(t=>({...t})),...e.stop===void 0?{}:{stop:e.stop}}}onDidChange(e){return this.#a.add(e),()=>this.#a.delete(e)}breakpointsForFile(e,t){return this.list().filter(r=>t===void 0||r.source===t).flatMap(r=>[...r.breakpoints.values()]).filter(r=>U(r.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`}async readSource(e){let t=this.get(e),r=this.sourceFile(e);if(t===void 0||r===void 0)throw new Error(`Unknown debug source ${e}`);let o=this.#t(t);return o===void 0?kt(r,"utf8"):o.readText(r)}async addBreakpoint(e,t,r){let o=this.get(e),a=this.sourceFile(e);if(o===void 0||a===void 0)throw new Error(`Unknown debug source ${e}`);if(this.#t(o),o.status==="terminated")throw new Error("Cannot add a breakpoint to a terminated session");let i=yt(5).toString("hex"),s={id:i,source:`${o.source}/breakpoint/${i}`,file:a,requestedLine:t,line:t,verified:!1};return o.vscode!==void 0&&await o.vscode.addBreakpoint(a,t,r),o.breakpoints.set(i,s),o.client!==void 0&&await this.#s(o,o.client,a,r),this.#n(o),s}breakpoint(e){let t=this.get(e);return t===void 0?void 0:[...t.breakpoints.values()].find(r=>r.source===e)}async start(e,t){return e.vscode!==void 0?this.#i(e,e.vscode,t):e.options.adapter==="java"&&this.#t(e)===void 0?this.#u(e,t):this.#d(e,t,2)}async#i(e,t,r){if(e.status!=="configured")throw new Error(`Session is already ${e.status}`);e.status="running",this.#n(e);try{let{program:o,cwd:a,configuration:i,test:s}=e.options,u=await t.start({program:o,cwd:a,...i===void 0?{}:{configuration:i},...s===void 0?{}:{test:s}},r);await this.#e(e,t,u)}catch(o){throw e.status="configured",this.#n(e),o}return e}async#e(e,t,r,o){if(r.status!=="paused"){e.status=r.status==="running"?"running":"terminated",e.stop=void 0,this.#n(e);return}let a=r.frame===void 0?void 0:{id:r.frame.id,name:r.frame.name,line:r.frame.line,...Or(r.frame.file??Br(e,r.frame,o))},i=!1;for(let s of e.breakpoints.values())a?.source?.path!==void 0&&U(s.file,a.source.path)&&s.line===a.line&&(s.verified=!0,i=!0);e.stopGeneration++,e.stop={generation:e.stopGeneration,reason:i?"breakpoint":"step",threadId:r.frame?.threadId??0,...a===void 0?{}:{frame:a},variables:a===void 0?[]:await vt(t),sourceLines:a===void 0?[]:await Dt(a)},e.status="stopped",this.#n(e)}async#u(e,t){if(e.status!=="configured")throw new Error(`Session is already ${e.status}`);let r=new H;e.javaRuntime=r;let o=AbortSignal.any([...t===void 0?[]:[t],AbortSignal.timeout(3e4)]),a=d(()=>{r.close()},"abortStartup");e.status="running",this.#n(e);try{let{client:i,attach:s}=await r.start(e.options,o);return e.client=i,e.controlClient=i,o.addEventListener("abort",a,{once:!0}),e.clients=[i],await ve(i,"java",o),await Promise.all([i.waitForAnyEvent(["initialized"],3e4,o),i.request("attach",s,{signal:o})]),await this.#g(e,i,o),await i.request("configurationDone",void 0,{signal:o}),await this.#c(e,o),this.snapshot(e).status==="terminated"&&await r.close(),e}catch(i){throw await r.close(),e.javaRuntime=void 0,e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.status="configured",this.#n(e),i}finally{o.removeEventListener("abort",a)}}async#d(e,t,r){if(e.status!=="configured")throw new Error(`Session is already ${e.status}`);t?.throwIfAborted();let o=this.#t(e);o===void 0&&e.options.adapter==="powershell"&&(e.adapterTemporaryDirectory=await jr(E.join(Lr(),"pi-powershell-debug-")));let a=o===void 0?await this.#m(e):await o.prepare(e.options,t);a.remote&&(e.remote=a.remote);let i=a.client;e.client=i,e.controlClient=i,e.clients=[i],e.options.adapter==="node"&&(e.targetReady=new Promise(s=>{e.resolveTargetReady=s})),e.status="running",this.#n(e);try{if(o!==void 0&&e.options.adapter==="node"){if(!a.connectChild)throw new Error("Owned Node adapter has no child connection");i.onReverseRequest(this.#y(e,a.connectChild))}(o!==void 0||e.options.adapter!=="r")&&await ve(i,a.adapterID,t);let s=i.waitForAnyEvent(["initialized"],3e4,t),u=i.request(a.request,a.launch,{signal:t});await Promise.race([s,u.then(()=>s)]),await this.#g(e,i,t);let c=i.request("configurationDone",void 0,{signal:t});if(e.options.adapter==="kotlin"?c.catch(()=>{}):await c,await u,e.options.adapter==="r"&&(e.rStarted=!0),e.targetReady!==void 0&&await e.targetReady,await this.#c(e,t),this.snapshot(e).status==="terminated"&&r>0&&(e.options.adapter==="dart"||e.options.adapter==="kotlin")&&e.breakpoints.size>0){await Promise.all((e.clients??[i]).map(p=>p.dispose())),e.adapterProcess?.kill(),await Pe(e),e.client=void 0,e.controlClient=void 0,e.clients=void 0,e.adapterProcess=void 0,e.status="configured";for(let p of e.breakpoints.values())p.verified=!1;return this.#n(e),await this.#d(e,t,r-1)}return e}catch(s){throw await Promise.all((e.clients??[i]).map(u=>u.dispose())),e.adapterProcess?.kill(),await Pe(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.#n(e),s}}async refresh(e){if(e.vscode!==void 0){e.status==="running"&&await this.#e(e,e.vscode,await e.vscode.status(0));return}if(e.client!==void 0){for(let t=e.client.takeEvent(["breakpoint"]);t!==void 0;t=e.client.takeEvent(["breakpoint"]))this.#D(e,t);if(e.status!=="terminated")for(;;){let t=e.client.takeEvent([...e.status==="running"?["stopped"]:[],"terminated","exited"]);if(t===void 0)return;if(t.event==="stopped")await this.#P(e,t);else{e.status="terminated",e.stop=void 0,this.#n(e),await e.javaRuntime?.close();return}}}}async command(e,t,r){if(this.#t(e),await this.refresh(e),e.status!=="stopped"||e.stop===void 0)throw new Error(`Cannot ${t} while session is ${e.status}`);if(e.vscode!==void 0){let i=e.vscode,s=e.stop.frame;return e.stop=void 0,e.status="running",this.#n(e),await this.#e(e,i,await i.command(t,r),s),e}let o=j(e),a=e.stop.threadId;return await o.request(t,{threadId:a},{signal:r}),e.stop=void 0,e.status="running",this.#n(e),await this.#c(e,r),this.snapshot(e).status==="terminated"&&await e.javaRuntime?.close(),e}async evaluate(e,t,r){if(this.#t(e),await this.refresh(e),e.status!=="stopped"||e.stop?.frame===void 0)throw new Error(`Cannot evaluate while session is ${e.status}`);let o=t.trim(),a=e.stop,i=e.stop.frame.id;if(o.length===0)throw new Error("Debug evaluation requires an expression");if(e.vscode!==void 0){let u=await e.vscode.evaluate(o,r);return e.stop={...a,variables:await vt(e.vscode,r)},this.#n(e),{expression:o,...u,variablesReference:0}}let s=await j(e).request("evaluate",{expression:o,frameId:e.stop.frame.id,context:e.options.adapter==="powershell"?"watch":"repl"},{signal:r});if(typeof s.result!="string")throw new Error("Debug adapter returned no evaluation result");return e.stop={...a,variables:await this.#S(e,i)},this.#n(e),{expression:o,result:s.result,variablesReference:s.variablesReference??0,...s.type===void 0?{}:{type:s.type}}}async delete(e,t){let r=this.get(e);if(r===void 0)throw new Error(`Unknown debug session ${e}`);let o=/\/breakpoint\/([a-f\d]{10})$/u.exec(e);if(o!==null){let a=r.breakpoints.get(o[1]);if(a===void 0)throw new Error(`Unknown debug breakpoint ${e}`);r.breakpoints.delete(a.id),await r.vscode?.removeBreakpoint(a.file,a.requestedLine,t),r.client!==void 0&&r.status!=="terminated"&&await this.#s(r,r.client,a.file,t),this.#n(r);return}if(e!==r.source)throw new Error(`Cannot delete debug resource ${e}`);await r.vscode?.close(t).catch(()=>{}),r.client!==void 0&&(await(r.controlClient??r.client).request("disconnect",{terminateDebuggee:!0},{signal:t,timeoutMs:500}).catch(()=>{}),await Promise.all((r.clients??[r.client]).map(a=>a.dispose()))),await r.javaRuntime?.close(),await qr(r.adapterProcess),await Pe(r),r.status="terminated",this.#n(r),this.#o.delete(r.id)}async dispose(){await Promise.all(this.list().map(e=>this.delete(e.source)))}async#m(e){let t=await Mr(e.options,e.adapterTemporaryDirectory),r=e.options.adapter==="node"?await this.#v(e):e.options.adapter==="delve"?await this.#f(e):e.options.adapter==="ruby"?await this.#l(e):e.options.adapter==="julia"?await this.#p(e):e.options.adapter==="r"?await this.#h(e):k.start(t.command,t.args,e.options.cwd);return{...t,client:r}}async#l(e){let t=await ie(),r=process.env.PI_RUBY_DEBUG_PATH??"rdbg";return e.adapterProcess=M(r,["--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"]}),De(e.adapterProcess,`rdbg:${String(t)}`),await Pt(e.adapterProcess,"Debugger can attach via TCP/IP","rdbg"),k.connect(t)}async#f(e){let t=await ie(),r=process.env.PI_DELVE_PATH??"dlv";return e.adapterProcess=M(r,["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 Pt(e.adapterProcess,"DAP server listening","Delve"),k.connect(t)}async#p(e){let t=await ie(),r=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=M(r,["--startup-file=no","--history-file=no",`--project=${o}`,"-e",a,String(t)],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),De(e.adapterProcess,`DebugAdapter.jl:${String(t)}`),await new Promise(i=>setTimeout(i,25)),St(t,"DebugAdapter.jl")}async#h(e){let t=Et.createServer();await new Promise((s,u)=>{t.once("error",u),t.listen(0,"127.0.0.1",()=>s())});let r=t.address();if(r===null||typeof r=="string")throw t.close(),new Error("Could not start the vscDebugger DAP listener");let o=new Promise((s,u)=>{t.once("connection",c=>{t.close();let p=k.fromSocket(c,2);p.onEvent(b=>this.#b(e,b)),s(p)}),t.once("error",u)}),a=process.env.PI_R_PATH??"R";e.rPromptInputs=[],e.rAtBrowserPrompt=!1,e.rStarted=!1,e.adapterProcess=M(a,["--vanilla","--quiet"],{cwd:e.options.cwd,env:process.env,stdio:["pipe","pipe","pipe"]}),De(e.adapterProcess,`vscDebugger:${String(r.port)}`),this.#w(e);let i=Ur({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:r.port}});return e.adapterProcess.stdin?.write(`library(vscDebugger); vscDebugger:::.vsc.handleDap(${JSON.stringify(i)})
12
+ `),Fr(o,e.adapterProcess,t)}#b(e,t){if(process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(`[vscDebugger:event] ${JSON.stringify(t)}
13
+ `),t.event!=="custom")return;let r=B(t.body),o=typeof r.reason=="string"?r.reason:"",a=typeof r.text=="string"?r.text:"";if(!(o!=="writeToStdin"||a.length===0)){if(r.when==="browserPrompt"&&e.rAtBrowserPrompt===!0){e.rAtBrowserPrompt=!1,e.adapterProcess?.stdin?.write(`${a}
14
+ `);return}e.rPromptInputs?.push(a)}}#w(e){let t="";e.adapterProcess?.stdout?.on("data",r=>{for(t+=r.toString("utf8");;){let o=/Browse\[\d+\]> /u.exec(t),a=/(?:^|\r?\n)__PI_R_PROMPT__(?:\r?\n|$)/u.exec(t),i=o?.index??Number.POSITIVE_INFINITY,s=a?.index??Number.POSITIVE_INFINITY;if(!Number.isFinite(i)&&!Number.isFinite(s)){t=t.slice(-128);return}if(i<s){t=t.slice(i+(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)
15
+ `))},100)):e.adapterProcess?.stdin?.write(`${u}
16
+ `)}else t=t.slice(s+(a?.[0].length??0)),e.adapterProcess?.stdin?.write(`vscDebugger::.vsc.listenForDAP(timeout=-1)
17
+ `),e.rStarted===!0&&e.client?.request("custom",{reason:"showingPrompt",which:"topLevel"}).catch(()=>{})}})}async#v(e){let t=await ie(),r=process.env.PI_JS_DEBUG_PATH??"/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js";e.adapterProcess=M(process.execPath,[r,String(t),"127.0.0.1"],{cwd:e.options.cwd,env:process.env,stdio:["ignore","pipe","pipe"]}),e.adapterProcess.stderr?.on("data",()=>{}),await Hr(e.adapterProcess);let o=await St(t);return o.onReverseRequest(this.#y(e,()=>k.connect(t))),o}#y(e,t){return async r=>{if(r.command!=="startDebugging")throw new Error(`Client does not support reverse request ${r.command}`);let o=B(r.arguments),a=B(o.configuration),i=this.#t(e),s=await t();e.clients?.push(s),s.onReverseRequest(this.#y(e,t)),await ve(s,"pwa-node");let u=s.waitForEvent("initialized"),c=s.request(typeof o.request=="string"?o.request:"launch",{...a,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[E.join(E.dirname(i?.serverPath(e.options.program)??e.options.program),"**","*.js")]});return await Promise.race([u,c.then(()=>u)]),e.client=s,await this.#g(e,s),await s.request("configurationDone"),await c,e.resolveTargetReady?.(),{}}}async#g(e,t,r){let o=new Set([...e.breakpoints.values()].map(a=>a.file));for(let a of o)await this.#s(e,t,a,r)}async#s(e,t,r,o){let a=[...e.breakpoints.values()].filter(s=>s.file===r),i=await t.request("setBreakpoints",{source:{path:this.#t(e)?.serverPath(r)??r,name:E.basename(r)},breakpoints:a.map(({requestedLine:s})=>({line:s})),sourceModified:!1},{signal:o});for(let[s,u]of a.entries()){let c=i.breakpoints?.[s];u.verified=c?.verified===!0,u.line=c?.line??u.requestedLine,u.adapterId=c?.id}}async#c(e,t){let r=await j(e).waitForAnyEvent(["stopped","terminated","exited","loadedSource","breakpoint","custom"],3e4,t),o=B(r.body);if(r.event==="custom"&&e.options.adapter==="r"){await this.#c(e,t);return}if(r.event==="loadedSource"){let a=B(o.source),i=this.#t(e);if(i!==void 0&&e.options.adapter==="node"&&typeof a.path=="string"&&!E.posix.isAbsolute(a.path)){await this.#c(e,t);return}let s=typeof a.path=="string"?i?.resourcePath(a.path)??E.resolve(a.path):void 0,u=s===void 0?void 0:[...e.breakpoints.values()].find(c=>U(c.file,s))?.file;u!==void 0&&await this.#s(e,j(e),u,t),await this.#c(e,t);return}if(r.event==="breakpoint"){this.#D(e,r),await this.#c(e,t);return}if(o.reason==="exit"){e.status="terminated",e.stop=void 0,this.#n(e);return}if(e.options.adapter==="node"&&o.reason==="entry"){await this.#g(e,j(e),t);let a=typeof o.threadId=="number"?o.threadId:1;await j(e).request("continue",{threadId:a},{signal:t}),await this.#c(e,t);return}if((e.options.adapter==="dart"||e.options.adapter==="kotlin")&&o.reason==="entry"){let a=j(e);if(await this.#g(e,a,t),e.options.adapter==="kotlin"){let s=Date.now()+5e3;for(;[...e.breakpoints.values()].some(u=>!u.verified)&&Date.now()<s;)await new Promise(u=>setTimeout(u,50)),await this.#g(e,a,t)}let i=typeof o.threadId=="number"?o.threadId:1;await a.request("continue",{threadId:i},{signal:t}),await this.#c(e,t);return}if(r.event!=="stopped"){e.status="terminated",e.stop=void 0,this.#n(e);return}if(await this.#P(e,r,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.#c(e,t);return}if(e.options.adapter==="shell"&&e.stopGeneration===1&&e.stop?.frame!==void 0&&![...e.breakpoints.values()].some(a=>U(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 j(e).request("continue",{threadId:a},{signal:t}),await this.#c(e,t);return}e.options.adapter==="shell"&&this.#n(e)}#D(e,t){let r=B(B(t.body).breakpoint),o=B(r.source);for(let a of e.breakpoints.values())(typeof r.id=="number"&&a.adapterId!==void 0?r.id===a.adapterId:typeof o.path=="string"&&U(this.#t(e)?.resourcePath(o.path)??o.path,a.file)&&r.line===a.requestedLine)&&(typeof r.line=="number"&&(a.line=r.line),a.verified=r.verified===!0);this.#n(e)}async#P(e,t,r=!0){let o=j(e),a=B(t.body),i=(await o.request("threads")).threads?.[0]?.id,s=typeof a.threadId=="number"?a.threadId:i;if(s===void 0)throw new Error("Debugger stopped without a thread");let u=this.#t(e),c=(await Nr(o,s,e.options.adapter==="dart")).stackFrames?.[0],p=c?.source?.path===void 0||u===void 0?c:{...c,source:{...c.source,path:u.resourcePath(c.source.path)}};if(p?.source?.path!==void 0)for(let l of e.breakpoints.values())U(l.file,p.source.path)&&l.line===p.line&&(l.verified=!0);let b=p===void 0?[]:await this.#S(e,p.id);e.stopGeneration++,e.stop={generation:e.stopGeneration,reason:typeof a.reason=="string"?a.reason:"stopped",threadId:s,...p===void 0?{}:{frame:p},variables:b,sourceLines:p===void 0?[]:await Dt(p,u?.readText.bind(u))},e.status="stopped",r&&this.#n(e)}async#S(e,t){let r=j(e),o=(await r.request("scopes",{frameId:t})).scopes??[],a=e.options.adapter==="r"?o:o.filter(s=>[s.name.toLowerCase(),s.presentationHint?.toLowerCase()].some(u=>u?.includes("local")===!0||u==="variables")),i=[];for(let s of a){let u=await r.request("variables",{variablesReference:s.variablesReference,start:0,count:100});i.push(...u.variables??[])}return i}#n(e){let t=this.snapshot(e);for(let r of this.#a)r(t)}};function Br(n,e,t){let r=new Set([...n.breakpoints.values()].filter(o=>o.line===e.line).map(o=>o.file));return r.size===1?[...r][0]:t?.name===e.name?t.source?.path:void 0}d(Br,"inferVscodeFrameFile");function Or(n){return n===void 0?{}:{source:{path:n}}}d(Or,"withSourcePath");async function vt(n,e){return(await n.locals(e)).map(t=>({...t,variablesReference:0}))}d(vt,"vscodeVariables");async function Dt(n,e){let t=n.source?.path;if(t===void 0)return[];try{let r=(await(e===void 0?kt(t,"utf8"):e(t))).split(/\r?\n/u),o=Math.max(1,n.line-2),a=Math.min(r.length,n.line+2);return r.slice(o-1,a).map((i,s)=>({lineNumber:o+s,content:i,current:o+s===n.line}))}catch(r){if(e!==void 0)throw r;return[]}}d(Dt,"sourceWindow");async function Nr(n,e,t){let r=Date.now()+1e3,o;do{try{let a=await n.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()<r);throw o instanceof Error?o:new Error("Could not read debugger stack")}d(Nr,"requestStackTrace");function W(n){let e=[`Session: ${n.source}`,`Adapter: ${n.options.adapter}`,`Program: ${E.relative(n.options.cwd,n.options.program)||n.options.program}`,`Status: ${n.status}`];if(n.breakpoints.size>0){e.push("","Breakpoints:");for(let t of n.breakpoints.values())e.push(`- ${t.source} ${E.relative(n.options.cwd,t.file)}:${t.line} (${t.verified?"verified":"pending"})`)}if(n.stop!==void 0){let{stop:t}=n;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 r of t.variables)e.push(`- ${r.name}: ${r.value}${r.type===void 0?"":` (${r.type})`}`)}}return e.join(`
18
+ `)}d(W,"renderDebugSession");function j(n){if(n.client===void 0)throw new Error("Debug adapter is not running");return n.client}d(j,"requiredClient");function B(n){return typeof n=="object"&&n!==null?n:{}}d(B,"asRecord");function Ur(n){let e=JSON.stringify(n);return`Content-Length: ${Buffer.byteLength(e,"utf8")}\r
19
+ \r
20
+ ${e}`}d(Ur,"dapFrame");function ve(n,e,t){return n.request("initialize",{clientID:"pi-agent-ide",adapterID:e,pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsRunInTerminalRequest:!1,supportsStartDebuggingRequest:!0},{signal:t})}d(ve,"initializeClient");function ie(){return new Promise((n,e)=>{let t=Et.createServer();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let r=t.address();if(r===null||typeof r=="string"){t.close(),e(new Error("Could not allocate a debug adapter port"));return}t.close(o=>o===void 0?n(r.port):e(o))})})}d(ie,"availablePort");function De(n,e){if(process.env.PI_DEBUG_DAP_TRACE==="1"){process.stderr.write(`[${e}] pid=${String(n.pid)}
21
+ `),n.once("exit",(t,r)=>process.stderr.write(`[${e}] exit code=${String(t)} signal=${String(r)}
22
+ `));for(let t of[n.stdout,n.stderr])t?.on("data",r=>process.stderr.write(`[${e}] ${r.toString("utf8")}`))}}d(De,"traceAdapterProcess");function Fr(n,e,t){return new Promise((r,o)=>{let a=setTimeout(()=>s(new Error("Timed out starting vscDebugger")),5e3),i=d(()=>{clearTimeout(a),e.off("error",s),e.off("exit",u)},"cleanup"),s=d(c=>{i(),t.close(),e.killed||e.kill(),o(c)},"fail"),u=d(c=>s(new Error(`vscDebugger exited with code ${String(c)} before connecting`)),"onExit");e.once("error",s),e.once("exit",u),n.then(c=>{i(),r(c)},s)})}d(Fr,"waitForRAdapterConnection");function Pt(n,e,t){return new Promise((r,o)=>{let a=[n.stdout,n.stderr].filter(c=>c!==null),i=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),s=d(()=>{clearTimeout(i);for(let c of a)c.off("data",u)},"cleanup"),u=d(c=>{c.toString("utf8").includes(e)&&(s(),r())},"onData");for(let c of a)c.on("data",u);n.once("error",c=>{s(),o(c)}),n.once("exit",c=>{s(),o(new Error(`${t} server exited with code ${String(c)}`))})})}d(Pt,"waitForAdapterReady");function Hr(n){return new Promise((e,t)=>{let r=n.stdout;if(r===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=d(i=>{i.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),r.off("data",a),e())},"onData");r.on("data",a),n.once("error",t),n.once("exit",i=>t(new Error(`js-debug server exited with code ${i}`)))})}d(Hr,"waitForJsDebugReady");async function St(n,e="js-debug"){let t;for(let r=0;r<100;r++)try{return await k.connect(n)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}d(St,"connectWithRetry");async function Pe(n){n.adapterTemporaryDirectory!==void 0&&(await $r(n.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),n.adapterTemporaryDirectory=void 0)}d(Pe,"removeAdapterTemporaryDirectory");async function qr(n){if(!(n===void 0||n.exitCode!==null||n.signalCode!==null)){if(process.platform!=="win32"||n.pid===void 0){n.kill();return}await new Promise(e=>{let t=M("taskkill.exe",["/pid",String(n.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{n.kill(),e()}),t.once("exit",()=>e())})}}d(qr,"terminateOwnedAdapterProcess");async function Mr(n,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:n.program,cwd:n.cwd,args:[...n.args]};if(n.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(n.adapter==="debugpy"){let r=await X(n.cwd);return{command:r.command,args:[...r.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(n.adapter==="kotlin"){if(n.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:n.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:n.mainClass,projectRoot:n.cwd,stopOnEntry:!0}}}if(n.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(n.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:[n.program,...n.args],projectDir:n.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(n.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(n.adapter==="lldb-dap")return{command:E.extname(n.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(n.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(n.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:n.program,workingDirectory:n.cwd,commandLineArgs:[...n.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(n.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(n.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(n.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:n.program},extensionPath:E.dirname(E.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:n.cwd}};if(n.adapter==="shell"){let r=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??E.join(r,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:E.join(r,"bashdb_dir/bashdb"),pathBashdbLib:E.join(r,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(n.adapter==="powershell"){let r=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",`& '${E.join(r,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${E.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${E.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${r.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:n.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:[E.join(E.dirname(n.program),"**","*.js")]}}}d(Mr,"adapterRecipe");var Se=y.Object({source:y.String(),sourceResource:y.String(),breakpointsResource:y.String(),adapter:y.String(),program:y.String(),cwd:y.String(),status:y.String(),breakpoints:y.Array(y.Object({source:y.String(),file:y.String(),line:y.Integer(),verified:y.Boolean()},{additionalProperties:!1}))},{additionalProperties:!1}),Gr=Le(Se),Wr=y.Object({backend:y.Optional(_t(["auto","vscode","native"],{description:"Select the debugger backend. auto (default) debugs through VS Code when the local program is inside a workspace open in VS Code with the DebugMCP extension, that window has no active debug session, and args and mainClass are omitted; otherwise it uses the native adapter. vscode fails with the unmet condition instead of falling back. native always launches the selected adapter."})),adapter:y.Optional(_t(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed native 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. Required for the native backend; VS Code chooses its debugger from launch.json or the file type."})),program:y.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:y.Optional(y.String({description:"Source file used for anchored breakpoints. Defaults to program. Relative paths resolve from cwd."})),args:y.Optional(y.Array(y.String(),{description:"Arguments passed to the debugged program by the native backend. For VS Code, put them in a launch.json configuration."})),mainClass:y.Optional(y.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),configuration:y.Optional(y.String({minLength:1,description:"Name of a .vscode/launch.json configuration to launch in VS Code. Use it for program arguments or environment. VS Code backend only."})),test:y.Optional(y.String({minLength:1,description:"Name of one test to debug through the VS Code Testing API; set program to its test file. VS Code backend only."})),cwd:y.Optional(y.String({description:"Select a local working directory or ssh://target/absolute/path. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function Tt(n,e){Ie(n,[await Re({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(b=>({tool:b,resourcePrefixes:["debug:"]}))]})]);let t=ze("debugger"),r=t!==void 0&&typeof t.evaluate=="function"?t:new se;r.setOwnerResolver(e?.workspace);let o=new Map,a=At(r,"debugger-source"),i=At(r,"debugger-input"),s=Ge(n).add(wt(r)),u=ut(r),c={protocol:xe,apiVersion:Ce,id:"debugger",setup(b){b.addResolver({resolver:a,matchesCall:d(l=>r.sourceFile(l)!==void 0,"matchesCall"),renderCall(l,h,f){let g=F(l)?l:{},m=typeof g.path=="string"?g.path:"",v=r.get(m),w=r.sourceFile(m);if(v===void 0||w===void 0)throw new Error("Debugger source header lost its session");let P=O.relative(v.options.cwd,w),_=Array.isArray(g.views)?g.views.filter(z=>typeof z=="string"):[],x=typeof g.offset=="number"?g.offset:1,I=typeof g.limit=="number"?g.limit:void 0,L=I===void 0?String(x):`${x}-${x+I-1}`;return $e(f.lastComponent,{tool:"debug file",primary:{text:`${P}:${L}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:m},{label:"file",value:w},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:f.expanded},h)}}),b.addView({view:"breakpoints",presenter:u}),b.describe({path:"debug:<session> \u2014 debugger state.",views:"breakpoints \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped."})}},p={protocol:Oe,apiVersion:Ne,id:"debugger",setup(b){b.addResolver({resolver:i}),b.tool("insert").describe('For debug:<session>, omit anchor and put start, continue, step over, step into, step out, or evaluate <expression> in text. Evaluate requires a stopped frame. For debug:<session>/source, use a fresh Read/Search line anchor and text "breakpoint"; the result reports pending or verified readiness. These actions do not edit source text.'),b.tool("insert").addSemanticHandler({matches:d(l=>Kr(l,r),"matches"),execute:d(async(l,h)=>{let f=h,g=It(r,f.path);if(r.sourceFile(f.path)!==void 0){if(f.text!=="breakpoint"||f.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let v=await l.resolveAnchor("anchor"),w=await r.addBreakpoint(f.path,v.lineNumber,l.signal);return{source:w.source,summary:`Breakpoint ${w.source} registered at ${O.relative(g.options.cwd,w.file)}:${w.line} (${w.verified?"verified":"pending"}).`,data:{kind:"debug-breakpoint",session:g.source,file:w.file,line:w.line,verified:w.verified,snapshot:r.snapshot(g)}}}if(f.path!==g.source||f.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let m;try{m=await Yr(r,g,f.text,l.signal)}catch(v){if(l.signal?.aborted===!0)throw v;let w=v instanceof Error?v.message:String(v);return{source:g.source,summary:`${f.text.trim()} failed: ${w}
23
+
24
+ ${W(g)}`,data:{...Rt(r,g,f.text),ok:!1,effect:"not-applied",error:{code:"DEBUG_ACTION_FAILED",message:w}}}}return{source:g.source,summary:m===void 0?W(g):`${m.expression} = ${m.result}${m.type===void 0?"":` (${m.type})`}`,data:Rt(r,g,f.text,m)}},"execute")}),b.tool("delete").addSemanticHandler({matches:d(l=>Xr(l,r),"matches"),execute:d(async(l,h)=>{let f=h.path,g=It(r,f),m=r.snapshot(g);o.set(f,m);let v=f.includes("/breakpoint/");await r.delete(f,l.signal);let w=v?r.snapshot(g):{...m,status:"terminated"};return{source:f,summary:`Deleted ${f}.`,data:{kind:v?"debug-breakpoint":"debug-session",deleted:!0,snapshot:w}}},"execute")}),b.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 l of["insert","delete"])b.addToolRenderer({tool:l,matches(h,f){return f==="call"?F(h)&&typeof h.path=="string"&&(r.get(h.path)!==void 0||o.has(h.path)):we(F(h)&&"details"in h?h.details:h)!==void 0},renderCall(h,f,g){let m=h,v=m.path===void 0?void 0:r.get(m.path),w=m.path===void 0?void 0:o.get(m.path),P=g.state;v!==void 0?P.snapshot=r.snapshot(v):w!==void 0&&(P.snapshot=w);let _=P.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let x=m.path===void 0?void 0:r.breakpoint(m.path)??(w??_).breakpoints.find(z=>z.source===m.path),I=m.path===void 0?void 0:r.sourceFile(m.path),L=l==="delete"?x===void 0?"delete-session":`delete-breakpoint ${O.basename(x.file)}:${x.line}`:m.text==="breakpoint"&&I!==void 0?`breakpoint ${O.basename(I)}:${en(m)}`:m.text??"debug action";return ct(_,L,f)},renderResult(h,f,g){let m=we(h.details);if(m===void 0)throw new Error("Debugger result is missing its session");let v=mt(h.details);return G(m,f.expanded,g,v,ht(h.details))}})}};await Promise.all([Te(n,ot),je(n,c)]),await Ue(n,p),n.registerTool(Jr({name:"debug",exposure:"deferred",namespace:{name:"ide_debug",description:"Create debugger sessions and inspect debug resources."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},label:"Debug session",promptSnippet:"Configure a local debugger session",description:"Use debug to create a configured debugger session on a local or supported SSH workspace, through VS Code or a native adapter. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:Wr,outputSchema:Gr,async execute(b,l,h,f,g){let m=l.backend??"auto",v=l.cwd??g.cwd,w=l.program;try{if(h?.throwIfAborted(),m==="vscode"&&[l.cwd,l.program,l.source].some(de=>de?.includes("://")))throw new Error("The VS Code backend debugs only local workspaces");let P=await e?.resolveOptions(l,g.cwd,h);if(P===void 0&&[v,w,l.source].some(de=>de?.includes("://")))throw new Error(`No debugger workspace owner: ${w}`);v=P?.cwd??O.resolve(g.cwd,l.cwd??"."),w=P?.program??O.resolve(v,l.program),P===void 0&&await Vr(w),h?.throwIfAborted();let _=O.resolve(v,l.source??l.program),x=P===void 0&&m!=="native"?await zr(m,l,{cwd:v,program:w,sourceFile:_},h):{unavailable:"native backend requested"},I;if("vscode"in x)I=r.create({adapter:"vscode",program:w,sourceFile:_,args:[],cwd:v,...l.configuration===void 0?{}:{configuration:l.configuration},...l.test===void 0?{}:{test:l.test}},x.vscode);else{if(l.configuration!==void 0||l.test!==void 0)throw new Error("configuration and test need the VS Code backend");if(P!==void 0)I=r.create(P);else{if(l.adapter===void 0)throw new Error(`Select an adapter for the native debugger backend. VS Code is not used: ${x.unavailable}`);I=r.create({adapter:l.adapter,program:w,sourceFile:_,args:l.args??[],cwd:v,...l.mainClass===void 0?{}:{mainClass:l.mainClass}})}}let L=Zr(r,I),{snapshot:z,stop:mn,...Nt}=L;return ue({content:[{type:"text",text:`${W(I)}
25
+ Source: ${L.sourceResource}
26
+ Breakpoints: ${L.breakpointsResource}
27
+
28
+ Next: read ${I.source} to inspect the configured session. To set a breakpoint, read ${L.sourceResource} with views ["anchors"], then insert "breakpoint" at an anchor.`}],details:L},Se,{status:"success",data:Nt,errors:[]})}catch(P){return ue({content:[{type:"text",text:P instanceof Error?P.message:String(P)}],details:{adapter:l.adapter??m,program:w,cwd:v,status:"failed"},isError:!0},Se,{status:"error",errors:[Be(P,"DEBUG_SESSION_FAILED",w)]})}},renderCall(b,l){let h=typeof b.cwd=="string"?b.cwd:".",f=typeof b.program=="string"?b.program:"program",g=h.startsWith("ssh://")?h:O.resolve(process.cwd(),h),m=f.startsWith("ssh://")||g.startsWith("ssh://")?f:O.resolve(g,f);return he(typeof b.adapter=="string"?b.adapter:b.backend==="vscode"?"vscode":"debugger",m,g,l)},renderResult(b,l,h){let f=F(b.details)?b.details.snapshot:void 0;if(typeof f=="object"&&f!==null)return G(f,l.expanded,h);let g=b.details;return he(g.adapter,g.program,g.cwd,h)}})),n.on("session_shutdown",async b=>{if(s(),b.reason!=="quit"){We("debugger",r);return}Ke("debugger",r),await r.dispose()})}d(Tt,"registerDebuggerWithOwner");async function zr(n,e,t,r){try{let o=(e.args?.length??0)>0?"args":e.mainClass===void 0?void 0:"mainClass";if(o!==void 0)throw new Error(`it does not accept ${o}; use a launch.json configuration`);return{vscode:await re.open(t,r)}}catch(o){r?.throwIfAborted();let a=o instanceof Error?o.message:String(o);if(n==="vscode"||e.configuration!==void 0||e.test!==void 0)throw new Error(`VS Code backend unavailable: ${a}`,{cause:o});return{unavailable:a}}}d(zr,"openVscodeBackend");function At(n,e){return{id:e,tryResolve(t){let r=n.get(t);return r===void 0?Promise.resolve({kind:"not-handled"}):Promise.resolve({kind:"resolved",resource:{source:t,async read(){await n.refresh(r);let o=n.sourceFile(t);if(o!==void 0)return[tn(o,await n.readSource(t))];if(t===`${r.source}/breakpoints`)return[{type:"text",text:Qr(r)}];let a=n.breakpoint(t);if(t!==r.source&&a===void 0)throw new Error(`Unknown debug resource ${t}`);return[{type:"text",text:a===void 0?W(r):`Breakpoint: ${a.source}
29
+ File: ${a.file}
30
+ Line: ${a.line}
31
+ Status: ${a.verified?"verified":"pending"}`}]}}})}}}d(At,"createDebugResourceResolver");function Kr(n,e){if(!F(n)||typeof n.path!="string"||typeof n.text!="string")return!1;let t=e.get(n.path);return t!==void 0&&(n.path===t.source||e.sourceFile(n.path)!==void 0)}d(Kr,"matchesDebugInsert");function Xr(n,e){if(!F(n)||typeof n.path!="string")return!1;let t=e.get(n.path);return t!==void 0&&(n.path===t.source||n.path.startsWith(`${t.source}/breakpoint/`))}d(Xr,"matchesDebugDelete");async function Yr(n,e,t,r){let o=t.trim(),a=/^evaluate\s+(.+)$/isu.exec(o);if(a!==null)return await n.evaluate(e,a[1],r);switch(o.toLowerCase()){case"start":{await n.start(e,r);return}case"continue":{await n.command(e,"continue",r);return}case"step over":{await n.command(e,"next",r);return}case"step into":{await n.command(e,"stepIn",r);return}case"step out":{await n.command(e,"stepOut",r);return}default:throw new Error(`Unknown debug command ${JSON.stringify(t)}`)}}d(Yr,"executeSessionCommand");function Zr(n,e){return{source:e.source,sourceResource:n.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:r,line:o,verified:a})=>({source:t,file:r,line:o,verified:a})),...e.stop===void 0?{}:{stop:e.stop},snapshot:n.snapshot(e)}}d(Zr,"debugDetails");function Rt(n,e,t,r){return{kind:"debug-command",command:t,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:o,file:a,line:i,verified:s})=>({source:o,file:a,line:i,verified:s})),...e.stop===void 0?{}:{stop:e.stop},...r===void 0?{}:{evaluation:r},snapshot:n.snapshot(e)}}d(Rt,"debugActionData");function Qr(n){return n.breakpoints.size===0?`No breakpoints in ${n.source}.`:[...n.breakpoints.values()].map(e=>`${e.verified?"\u25CF":"\u25CB"} ${e.file}:${e.line} \xB7 ${e.source} (${e.verified?"verified":"pending"})`).join(`
32
+ `)}d(Qr,"renderBreakpointList");function It(n,e){let t=n.get(e);if(t===void 0)throw new Error(`Unknown debug session ${e}`);return t}d(It,"requiredSession");function en(n){let e=F(n)&&typeof n.anchor=="string"?n.anchor:void 0;return/^(\d+)#/u.exec(e??"")?.[1]??e??"selected line"}d(en,"breakpointLine");function F(n){return typeof n=="object"&&n!==null}d(F,"isRecord");function tn(n,e){return{type:"text",text:e,sourceLines:Object.fromEntries(e.split(/\r?\n/u).map((t,r)=>[String(r+1),{source:n,lineNumber:r+1,content:t}]))}}d(tn,"debugSourceContent");import N from"node:path";import{readFile as Bt}from"node:fs/promises";import{Type as $}from"typebox";import{Value as cn}from"typebox/value";import{Writable as rn}from"node:stream";import{callbackify as xt}from"node:util";async function C(n,e,t){t.signal?.throwIfAborted();let r=n.resolve(e);if(!r)throw new D("UNSUPPORTED_SOURCE",e,"not-applied");let o=Object.entries(await Me(r.backend,r.location.path,t.env,t.signal)).map(([c,p])=>`${c}=${p}`),a=await r.backend.startProcess("env",[...o,t.command,...t.args],r.location.path,{signal:t.signal});a.stderr.resume();let i=new rn({write:xt(async(c,p)=>{await a.write(c)}),final:xt(async()=>{await a.end()})}),s,u=a.completion.then(c=>{if(c.exitCode!==0)throw new D("ADAPTER_EXITED",e,"unknown")});return u.catch(()=>{}),{readable:a.stdout,writable:i,completion:u,remote:{target:r.location.target,pid:a.pid,...a.identity===void 0?{}:{identity:a.identity}},stop(){return s??=Ve(a,n,e).finally(()=>{i.destroy()}),s}}}d(C,"startSshDapTransport");import{readFile as nn}from"node:fs/promises";var Ct;async function jt(n,e,t){t.signal?.throwIfAborted();let r=Buffer.from(JSON.stringify({kind:t.kind,program:t.program,args:t.args})+`
33
+ `);if(r.byteLength>65536)throw new D("BYTE_LIMIT",e,"not-applied");Ct??=nn(new URL("./dap-tcp-worker.py",new URL("../src/backend/dap-tcp-transport.ts",import.meta.url).href),"utf8");let o=await C(n,e,{command:"python3",args:["-c",await Ct],signal:t.signal});try{return await new Promise((a,i)=>{o.writable.once("error",i),o.writable.write(r,s=>s?i(s):a())}),t.signal?.throwIfAborted(),o}catch(a){throw await o.stop(),a}}d(jt,"startSshTcpDapTransport");import{readFile as an}from"node:fs/promises";async function $t(n,e,t,r){r?.throwIfAborted();let o=n.resolve(e);if(!o)throw new D("UNSUPPORTED_SOURCE",e,"not-applied");let a=await o.backend.execute("python3",["-c","import tempfile; print(tempfile.mkdtemp(prefix='pi-agent-ide-node-',dir='/tmp'))"],o.location.path,{signal:r}),i=a.stdout.toString("utf8").trim();if(a.exitCode!==0||!/^\/tmp\/pi-agent-ide-node-[A-Za-z0-9_-]+$/u.test(i))throw new D("INVALID_RESPONSE",e,"unknown");let s,u=new Set,c=new Set,p,b=d(()=>p!==void 0,"isStopping"),l=d(async()=>{if((await o.backend.execute("python3",["-c","import shutil,sys; shutil.rmtree(sys.argv[1])",i],o.location.path)).exitCode!==0)throw new D("CLEANUP_FAILED",e,"unknown")},"cleanup"),h=d(()=>(p??=(async()=>{try{await Promise.allSettled([...c]);let g=(await Promise.allSettled([...u].map(m=>m.stop()))).find(m=>m.status==="rejected");if(g)throw g.reason}finally{try{await s?.stop()}finally{await l()}}})(),p),"stop");try{let f=await an(new URL("./dap-unix-worker.py",new URL("../src/backend/dap-node-transport.ts",import.meta.url).href),"utf8");s=await C(n,e,{command:"python3",args:["-c","import os,sys; script=os.environ.get('PI_JS_DEBUG_PATH','/opt/pi-debug-adapters/js-debug/src/dapDebugServer.js'); os.execvpe('node',['node',script,sys.argv[1]],os.environ)",`${i}/dap.sock`],env:{TMPDIR:i},signal:r}),s.readable.resume();let g=s,m=g.remote.identity;if(!m)throw new D("CAPABILITY_UNAVAILABLE",e,"not-applied");let v=d(async()=>{if(b())throw new D("SESSION_CLOSED",e,"not-applied");let P=C(n,e,{command:"python3",args:["-c",f,`${i}/dap.sock`,String(g.remote.pid),m],signal:r});c.add(P);try{let _=await P;if(u.add(_),b())throw new D("SESSION_CLOSED",e,"not-applied");return _}finally{c.delete(P)}},"connect"),w=await v();return{client:k.fromTransport({readable:w.readable,writable:w.writable,completion:Promise.race([w.completion,g.completion]),stop:h}),connectChild:d(async()=>k.fromTransport(await v()),"connectChild"),adapterID:"pwa-node",request:"launch",remote:g.remote,launch:t}}catch(f){throw await h(),f}}d($t,"prepareSshNodeDebugger");import{readFile as on}from"node:fs/promises";import{Type as ke}from"typebox";import{Value as sn}from"typebox/value";var dn=ke.Object({port:ke.Integer({minimum:1,maximum:65535}),sourceRoot:ke.String()},{additionalProperties:!1});async function Lt(n,e,t,r){if(t.mainClass===void 0)throw new D("INVALID_REQUEST",e,"not-applied");let o=await on(new URL("./dap-java-worker.py",new URL("../src/backend/dap-java-transport.ts",import.meta.url).href),"utf8"),a=AbortSignal.any([...r===void 0?[]:[r],AbortSignal.timeout(4e4)]),i=await C(n,e,{command:"python3",args:["-c",o,JSON.stringify({mainClass:t.mainClass,args:t.args,sourceFile:t.sourceFile})],signal:r});try{let s=await un(i,e,a);a.throwIfAborted();let u=k.fromTransport(i);return i.readable.resume(),{client:u,adapterID:"java",request:"attach",launch:{hostName:"127.0.0.1",port:s.port,timeout:1e4,sourcePaths:[s.sourceRoot]},remote:i.remote}}catch(s){throw await i.stop(),s}}d(Lt,"prepareSshJavaDebugger");function un(n,e,t){return new Promise((r,o)=>{let a=Buffer.alloc(0),i=d(()=>{t.removeEventListener("abort",c),n.readable.removeListener("data",p),n.readable.removeListener("end",u),n.readable.removeListener("error",s)},"cleanup"),s=d(b=>{i(),o(b)},"failed"),u=d(()=>s(new D("ADAPTER_EXITED",e,"not-applied")),"closed"),c=d(()=>s(t.reason),"aborted"),p=d(b=>{a=Buffer.concat([a,b]);let l=a.indexOf(10);if(l<0){a.length>4096&&s(new D("INVALID_RESPONSE",e,"not-applied"));return}n.readable.pause(),i();try{if(l>4096)throw new Error("Java startup header limit");let h=JSON.parse(a.subarray(0,l).toString("utf8"));if(!sn.Check(dn,h))throw new Error("Invalid Java startup header");a.length>l+1&&n.readable.unshift(a.subarray(l+1)),r(h)}catch{o(new D("INVALID_RESPONSE",e,"not-applied"))}},"received");n.readable.on("data",p),n.readable.once("end",u),n.readable.once("error",s),t.addEventListener("abort",c,{once:!0}),n.completion.then(u,s),t.aborted&&c()})}d(un,"readReady");var ln=$.Object({phpDebug:$.String(),php:$.String(),luaDebug:$.String(),lua:$.String(),bashRoot:$.String(),bashDebug:$.Union([$.String(),$.Null()]),bash:$.String()},{additionalProperties:!1});async function pn(n,e,t,r,o){let a={phpDebug:["PI_PHP_DEBUG_PATH","/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],php:["PI_PHP_PATH","php"],luaDebug:["PI_LUA_DEBUG_PATH","/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],lua:["PI_LUA_PATH","lua"],bashRoot:["PI_BASH_DEBUG_ROOT","/opt/pi-debug-adapters/bash-debug/extension"],bashDebug:["PI_BASH_DEBUG_PATH",null],bash:["PI_BASH_PATH","/usr/bin/bash"]},i=await n.execute("python3",["-c","import json,os,sys; fields=json.loads(sys.argv[1]); print(json.dumps({k:os.environ.get(v[0],v[1]) for k,v in fields.items()}))",JSON.stringify(a)],r,{signal:o});if(i.exitCode!==0)throw new D("DEPENDENCY_UNAVAILABLE",e.program,"not-applied");let s;try{s=JSON.parse(i.stdout.toString("utf8"))}catch{throw new D("INVALID_RESPONSE",e.program,"not-applied")}if(!cn.Check(ln,s))throw new D("INVALID_RESPONSE",e.program,"not-applied");let u={name:"Pi Agent IDE debug session",request:"launch",program:t,cwd:r,args:[...e.args]};if(e.adapter==="php")return{command:"node",overrides:[],args:[s.phpDebug],adapterID:"php",launch:{...u,type:"php",runtimeExecutable:s.php,runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",hostname:"127.0.0.1",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(e.adapter==="lua")return{command:"node",overrides:[],args:[s.luaDebug],adapterID:"lua-local",launch:{...u,type:"lua-local",program:{lua:s.lua,file:t},extensionPath:N.posix.dirname(N.posix.dirname(s.luaDebug)),workspacePath:r}};if(e.adapter==="shell")return{command:"node",overrides:[],args:[s.bashDebug??N.posix.join(s.bashRoot,"out/bashDebug.js")],adapterID:"bashdb",launch:{...u,type:"bashdb",pathBash:s.bash,pathBashdb:N.posix.join(s.bashRoot,"bashdb_dir/bashdb"),pathBashdbLib:N.posix.join(s.bashRoot,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}};throw new D("CAPABILITY_UNAVAILABLE",e.program,"not-applied")}d(pn,"nodeStdioRecipe");function gn(n,e,t,r){let o={name:"Pi Agent IDE debug session",request:"launch",program:e,cwd:t,args:[...n.args]};switch(n.adapter){case"debugpy":return{command:"python3",overrides:["PI_PYTHON_PATH"],args:["-m","debugpy.adapter"],adapterID:"debugpy",launch:{...o,type:"python",console:"internalConsole",justMyCode:!1}};case"dart":return{command:"dart",overrides:["PI_DART_PATH"],args:["debug_adapter"],adapterID:"dart",launch:{...o,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};case"kotlin":{if(n.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:"kotlin-debug-adapter",overrides:["PI_KOTLIN_DEBUG_ADAPTER_PATH"],args:[],adapterID:n.adapter,launch:{...o,type:"kotlin",mainClass:n.mainClass,projectRoot:t,stopOnEntry:!0}}}case"netcoredbg":return{command:"netcoredbg",overrides:["PI_NETCOREDBG_PATH"],args:["--interpreter=vscode"],adapterID:"coreclr",launch:{...o,type:"coreclr",console:"internalConsole"}};case"elixir":return{command:"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh",overrides:["PI_ELIXIR_LS_DEBUG_PATH"],args:[],adapterID:"mix_task",launch:{name:o.name,request:"launch",type:"mix_task",task:"run",taskArgs:[e,...n.args],projectDir:t,startApps:!0,exitAfterTaskReturns:!0}};case"lldb-dap":{let a=N.posix.extname(r).toLowerCase()===".swift";return{command:a?"lldb-dap":"lldb-dap-18",overrides:a?["PI_SWIFT_LLDB_DAP_PATH","PI_LLDB_DAP_PATH"]:["PI_LLDB_DAP_PATH"],args:[],adapterID:"lldb-dap",launch:{...o,type:"lldb-dap"}}}default:throw new D("CAPABILITY_UNAVAILABLE",n.program,"not-applied")}}d(gn,"stdioRecipe");function Ot(n){return e=>{let t=n.resolve(e);if(!t){if(e.includes("://"))throw new D("UNSUPPORTED_SOURCE",e,"not-applied");return}let r=d(u=>{let c=n.resolve(u,t.location.source);if(!c||c.location.target!==t.location.target)throw new D("UNSUPPORTED_SOURCE",u,"not-applied");return c},"resolve"),{id:o,host:a,workspace:i,configFile:s}=t.backend.target;return{key:JSON.stringify([o,a,i,s??null]),serverPath:d(u=>r(u).location.path,"serverPath"),resourcePath(u){if(!N.posix.isAbsolute(u)||u.includes("\0"))throw new D("INVALID_RESPONSE",t.location.source,"not-applied");return K(t.location.target,u).source},async readText(u){let c=r(u);return new TextDecoder("utf-8",{fatal:!0}).decode((await c.backend.read(c.location.path)).bytes)},async prepare(u,c){c?.throwIfAborted();let p=r(u.program).location.path,b=r(u.cwd).location.path,l=r(u.sourceFile).location.path;if(u.adapter==="java")return await Lt(n,t.location.source,{...u,cwd:b,program:p,sourceFile:l},c);if(u.adapter==="delve"||u.adapter==="ruby"||u.adapter==="julia"){let g=await jt(n,t.location.source,{kind:u.adapter,program:p,args:u.args,signal:c}),m=u.adapter==="delve"?"go":u.adapter==="ruby"?"rdbg":"julia";return{client:k.fromTransport(g),adapterID:m,request:"launch",remote:g.remote,launch:{name:"Pi Agent IDE debug session",request:"launch",type:m,program:p,cwd:b,args:[...u.args],...u.adapter==="delve"?{mode:"debug"}:{},...u.adapter==="julia"?{stopOnEntry:!1}:{}}}}if(u.adapter==="node")return $t(n,t.location.source,{name:"Pi Agent IDE debug session",request:"launch",type:"pwa-node",program:p,cwd:b,args:[...u.args],console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[N.posix.join(N.posix.dirname(p),"**","*.js")]},c);if(u.adapter==="r"){let g=await Bt(new URL("./dap-r-worker.py",new URL("../src/backend/debugger-workspace-owner.ts",import.meta.url).href),"utf8"),m=await C(n,t.location.source,{command:"python3",args:["-c",g],signal:c});return{client:k.fromTransport(m),adapterID:"R-Debugger",request:"launch",remote:m.remote,launch:{name:"Pi Agent IDE debug session",request:"launch",type:"R-Debugger",debugMode:"file",file:p,workingDirectory:b,commandLineArgs:[...u.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}}}if(u.adapter==="powershell"){let g=await Bt(new URL("./dap-powershell-worker.py",new URL("../src/backend/debugger-workspace-owner.ts",import.meta.url).href),"utf8"),m=await C(n,t.location.source,{command:"python3",args:["-c",g],signal:c});return{client:k.fromTransport(m),adapterID:"PowerShell",request:"launch",remote:m.remote,launch:{name:"Pi Agent IDE debug session",request:"launch",program:p,script:p,cwd:b,args:[...u.args],createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}let h=u.adapter==="php"||u.adapter==="lua"||u.adapter==="shell"?await pn(t.backend,u,p,b,c):gn(u,p,b,l),f=await C(n,t.location.source,{command:"python3",args:["-c","import json,os,sys; names=json.loads(sys.argv[1]); p=next((os.environ[n] for n in names if os.environ.get(n)),sys.argv[2]); args=json.loads(sys.argv[3]); os.execvpe(p,[p,*args],os.environ)",JSON.stringify(h.overrides),h.command,JSON.stringify(h.args)],signal:c});return{client:k.fromTransport(f),adapterID:h.adapterID,request:"launch",remote:f.remote,launch:h.launch}}}}}d(Ot,"createSshDebuggerWorkspaceOwner");function fn(n){return{workspace:Ot(n),async resolveOptions(e,t,r){r?.throwIfAborted();let o=n.resolve(e.program),a=e.cwd??(o?K(o.location.target,o.backend.target.workspace).source:t),i=n.resolve(a,t);if(!i){if([a,e.program,e.source].some(p=>p?.includes("://")))throw new D("UNSUPPORTED_SOURCE",e.program,"not-applied");return}let s=e.adapter;if(s===void 0)throw new Error("Select an adapter: SSH workspaces use the native debugger backend");let u=n.resolve(e.program,i.location.source),c=n.resolve(e.source??e.program,i.location.source);if(!u||!c||u.location.target!==i.location.target||c.location.target!==i.location.target)throw new D("UNSUPPORTED_SOURCE",e.program,"not-applied");return await u.backend.stat(u.location.path,{signal:r}),c.location.source!==u.location.source&&await c.backend.stat(c.location.path,{signal:r}),{adapter:s,program:u.location.source,sourceFile:c.location.source,cwd:i.location.source,args:e.args??[],...e.mainClass===void 0?{}:{mainClass:e.mainClass}}}}}d(fn,"createSshDebuggerAccess");async function bn(n){let e=new Je(await qe(He(Fe())));await Tt(n,fn(e))}d(bn,"registerOwnedDebugger");export{fn as createSshDebuggerAccess,bn as default};
@@ -1 +1 @@
1
- import{a as b}from"./chunk-E4HPRLRB.js";import{a as y}from"./chunk-3G54ZL2L.js";import{a as k,b as E}from"./chunk-7HDK3NRQ.js";import"./chunk-KL776TGR.js";import{b as S}from"./chunk-OJX3RJ5A.js";import"./chunk-CTJV77FR.js";import{a as u,b as w,c as v}from"./chunk-HCN5W76B.js";import{g as c}from"./chunk-EY65TFHJ.js";import{a as p,b as h,d as P}from"./chunk-7NS3QUIE.js";import{c as f}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-2K65BSXS.js";import"./chunk-ICDI27GZ.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-N7LMRL64.js";import"./chunk-RAZP42IQ.js";import"./chunk-BIG45IPN.js";import"./chunk-SSWUUBIR.js";import"./chunk-PS2B6THP.js";import"./chunk-R5XJSEOE.js";import"./chunk-DUUOCBS3.js";import"./chunk-T4FTT3U4.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import"./chunk-KINKBPPX.js";import{c as m}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import R from"node:path";function g(d){let n=i(o=>{let e=d.resolve(o);if(!e)throw new c("UNSUPPORTED_SOURCE",o,"not-applied");return e},"resolve");return{transport:i(o=>y(d,o),"transport"),async readText(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes.toString("utf8")},async readSnapshot(o,e){let r=n(o),t=await r.backend.read(r.location.path,{signal:e});return{content:t.bytes.toString("utf8"),version:t.version}},async readBytes(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes},async exists(o,e){let r=n(o);try{return await r.backend.stat(r.location.path,{signal:e}),!0}catch(t){if(t instanceof c&&t.code==="ENOENT")return!1;throw t}},async isFile(o,e){let r=n(o);return(await r.backend.stat(r.location.path,{signal:e})).kind==="file"},async entries(o,e){let r=n(o);return(await r.backend.list(r.location.path,{signal:e})).map(t=>({name:t.name,kind:t.kind==="symlink"?"other":t.kind}))}}}i(g,"createSshLspWorkspaceOwner");async function O(d){let n=new v(await w(u(f()))),o=g(n);await P(d,{workspace:i(e=>e.startsWith("ssh://")?o:void 0,"workspace"),async loadRegistry(e,r,t){t?.throwIfAborted();let s=n.resolve(e);if(s)return h.fromPackageDir(e,{signal:t,layerAccess:k(n,t),includeGlobal:!r,requireBuiltInEvidence:r,recipes:p,recipeEvidence:i(a=>E(s.backend,s.location.path,a,t),"recipeEvidence"),executableAvailability:i(a=>S(s.backend,s.location.path,a,t),"executableAvailability")});if(e.includes("://"))throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return h.fromPackageDir(r?e:process.env.PI_AGENT_IDE_CONFIG_DIR??e,{signal:t,includeGlobal:!r,requireBuiltInEvidence:r,recipes:p})},async resolveProject(e,r,t){if(t?.throwIfAborted(),e.startsWith("ssh://")||r.startsWith("ssh://")){let a=n.resolve(e,r);if(!a)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");let l=n.resolve(r);if(l&&l.location.target!==a.location.target)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return b(a.backend,a.location.path,l?.location.path,"lsp-servers",p,t)}let s=await m(r,e,"lsp-servers",p,t);return s===void 0?void 0:{cwd:s,external:s!==R.resolve(r)}}})}i(O,"registerOwnedLsp");export{O as default};
1
+ import{a as y}from"./chunk-NJ7C4KMA.js";import"./chunk-6H32W35W.js";import"./chunk-NUM3YQGK.js";import{a as b}from"./chunk-QT3EAHOG.js";import{a as k,b as E}from"./chunk-VXP5BMW7.js";import{b as S}from"./chunk-RW2GTYQI.js";import{a as u,b as w,c as v}from"./chunk-RIJMXO43.js";import{g as c}from"./chunk-PJL3UVMJ.js";import{a as p,b as h,d as P}from"./chunk-XG7QNAKW.js";import"./chunk-47SPPIXK.js";import"./chunk-4DIUPEDF.js";import"./chunk-VAXLSPPU.js";import"./chunk-I6NPILT5.js";import{c as f}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-XXLLY66B.js";import"./chunk-235QMMVA.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-LCWBVOII.js";import"./chunk-DUUOCBS3.js";import"./chunk-T4FTT3U4.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import"./chunk-KINKBPPX.js";import{c as m}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import R from"node:path";function g(d){let n=i(o=>{let e=d.resolve(o);if(!e)throw new c("UNSUPPORTED_SOURCE",o,"not-applied");return e},"resolve");return{transport:i(o=>y(d,o),"transport"),async readText(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes.toString("utf8")},async readSnapshot(o,e){let r=n(o),t=await r.backend.read(r.location.path,{signal:e});return{content:t.bytes.toString("utf8"),version:t.version}},async readBytes(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes},async exists(o,e){let r=n(o);try{return await r.backend.stat(r.location.path,{signal:e}),!0}catch(t){if(t instanceof c&&t.code==="ENOENT")return!1;throw t}},async isFile(o,e){let r=n(o);return(await r.backend.stat(r.location.path,{signal:e})).kind==="file"},async entries(o,e){let r=n(o);return(await r.backend.list(r.location.path,{signal:e})).map(t=>({name:t.name,kind:t.kind==="symlink"?"other":t.kind}))}}}i(g,"createSshLspWorkspaceOwner");async function O(d){let n=new v(await w(u(f()))),o=g(n);await P(d,{workspace:i(e=>e.startsWith("ssh://")?o:void 0,"workspace"),async loadRegistry(e,r,t){t?.throwIfAborted();let s=n.resolve(e);if(s)return h.fromPackageDir(e,{signal:t,layerAccess:k(n,t),includeGlobal:!r,requireBuiltInEvidence:r,recipes:p,recipeEvidence:i(a=>E(s.backend,s.location.path,a,t),"recipeEvidence"),executableAvailability:i(a=>S(s.backend,s.location.path,a,t),"executableAvailability")});if(e.includes("://"))throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return h.fromPackageDir(r?e:process.env.PI_AGENT_IDE_CONFIG_DIR??e,{signal:t,includeGlobal:!r,requireBuiltInEvidence:r,recipes:p})},async resolveProject(e,r,t){if(t?.throwIfAborted(),e.startsWith("ssh://")||r.startsWith("ssh://")){let a=n.resolve(e,r);if(!a)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");let l=n.resolve(r);if(l&&l.location.target!==a.location.target)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return b(a.backend,a.location.path,l?.location.path,"lsp-servers",p,t)}let s=await m(r,e,"lsp-servers",p,t);return s===void 0?void 0:{cwd:s,external:s!==R.resolve(r)}}})}i(O,"registerOwnedLsp");export{O as default};
@@ -1,3 +1,3 @@
1
- import{a as N,b as B}from"./chunk-VDP5CQHM.js";import{a as z}from"./chunk-YJ6T3PEP.js";import{b as S,c as v}from"./chunk-S72FVLUX.js";import{d as T}from"./chunk-IICJXZBU.js";import{a as C}from"./chunk-BU7IZLKB.js";import{a as P,b as x}from"./chunk-S5PL5DFQ.js";import{a as O}from"./chunk-N7LMRL64.js";import{a as A,b as k}from"./chunk-RAZP42IQ.js";import{a as $,c as b,e as D,f as _,g as L,h as y,i as H}from"./chunk-BIG45IPN.js";import{e as I}from"./chunk-SSWUUBIR.js";import{F as E,l as W}from"./chunk-R5XJSEOE.js";import{e as R}from"./chunk-756K3LJY.js";import{a as i}from"./chunk-EI7MMDWY.js";var M={protocol:S,apiVersion:v,id:"web-browser",setup(r){r.addCheck({id:"system-browser",title:"Browser web reads",async run(e){try{e.signal?.throwIfAborted();let t=e.workspace?await V(e.workspace,e.signal):await R(await N(e.env.PI_AGENT_IDE_BROWSER_PATH,e.env),["--version"],e.cwd,e.env,e.signal);return e.signal?.throwIfAborted(),[t.ok?{status:"pass",message:"Chrome/Chromium is available",detail:t.detail}:{status:"warn",message:"Chrome/Chromium cannot start",detail:t.detail}]}catch(t){return e.signal?.throwIfAborted(),[{status:"warn",message:"Browser reads are unavailable",detail:t instanceof Error?t.message:String(t)}]}}})}};async function V(r,e){if(!r.probeBrowser)throw new Error("Project owner does not provide a browser probe");return r.probeBrowser(e)}i(V,"probeOwnerBrowser");function F(r){return{id:"web",readResources:i(e=>e.path!==void 0&&/^https?:/iu.test(e.path)?[e.path]:[],"readResources"),async tryResolve(e,t){let o=e.path;if(o===void 0||!/^(?:https?:|web:)/iu.test(o))return{kind:"not-handled"};if(e.include!==void 0||e.exclude!==void 0)return{kind:"failed",error:new Error("File include/exclude globs do not apply to a web page.")};let s=q(e),a=await r.tryResolve(o,t);if(a.kind!=="resolved")return a;if(a.resource.read===void 0)return{kind:"failed",error:new Error(`Cannot read ${o}`)};let n=await a.resource.read({signal:t.signal});if(n.some(l=>l.type!=="text"))return{kind:"failed",error:new Error(`Web search requires text content: ${o}`)};let u=n.map(l=>l.type==="text"?l.text:"").join(`
1
+ import{a as N,b as B}from"./chunk-VDP5CQHM.js";import{a as O}from"./chunk-47SPPIXK.js";import{a as $,c as b,e as D,f as _,g as L,h as y,i as H}from"./chunk-4DIUPEDF.js";import{a as A,b as k}from"./chunk-VAXLSPPU.js";import{e as I}from"./chunk-I6NPILT5.js";import{a as z}from"./chunk-YJ6T3PEP.js";import{b as S,c as v}from"./chunk-S72FVLUX.js";import{d as T}from"./chunk-IICJXZBU.js";import{a as C}from"./chunk-BU7IZLKB.js";import{a as P,b as x}from"./chunk-S5PL5DFQ.js";import{F as E,l as W}from"./chunk-LCWBVOII.js";import{e as R}from"./chunk-756K3LJY.js";import{a as i}from"./chunk-EI7MMDWY.js";var M={protocol:S,apiVersion:v,id:"web-browser",setup(r){r.addCheck({id:"system-browser",title:"Browser web reads",async run(e){try{e.signal?.throwIfAborted();let t=e.workspace?await V(e.workspace,e.signal):await R(await N(e.env.PI_AGENT_IDE_BROWSER_PATH,e.env),["--version"],e.cwd,e.env,e.signal);return e.signal?.throwIfAborted(),[t.ok?{status:"pass",message:"Chrome/Chromium is available",detail:t.detail}:{status:"warn",message:"Chrome/Chromium cannot start",detail:t.detail}]}catch(t){return e.signal?.throwIfAborted(),[{status:"warn",message:"Browser reads are unavailable",detail:t instanceof Error?t.message:String(t)}]}}})}};async function V(r,e){if(!r.probeBrowser)throw new Error("Project owner does not provide a browser probe");return r.probeBrowser(e)}i(V,"probeOwnerBrowser");function F(r){return{id:"web",readResources:i(e=>e.path!==void 0&&/^https?:/iu.test(e.path)?[e.path]:[],"readResources"),async tryResolve(e,t){let o=e.path;if(o===void 0||!/^(?:https?:|web:)/iu.test(o))return{kind:"not-handled"};if(e.include!==void 0||e.exclude!==void 0)return{kind:"failed",error:new Error("File include/exclude globs do not apply to a web page.")};let s=q(e),a=await r.tryResolve(o,t);if(a.kind!=="resolved")return a;if(a.resource.read===void 0)return{kind:"failed",error:new Error(`Cannot read ${o}`)};let n=await a.resource.read({signal:t.signal});if(n.some(l=>l.type!=="text"))return{kind:"failed",error:new Error(`Web search requires text content: ${o}`)};let u=n.map(l=>l.type==="text"?l.text:"").join(`
2
2
  `),d=[],h=e.limit??50;for(let[l,m]of u.split(/\r\n|\n|\r/u).entries()){t.signal?.throwIfAborted();for(let c of m.matchAll(s)){if(c[0].length===0)continue;let p=c.index,f=p+c[0].length;if(!(e.wholeWord===!0&&(new RegExp("\\p{L}|\\p{N}|_","u").test(m[p-1]??"")||new RegExp("\\p{L}|\\p{N}|_","u").test(m[f]??"")))){if(d.length===h)return{kind:"resolved",payload:{source:o,matches:d,complete:!1}};d.push({source:o,lineNumber:l+1,startColumn:p,endColumn:f,matchedText:c[0],lineText:m})}}}let g=d.length===0&&D(e.query)?U(u,o,e.query,t.signal):void 0;return{kind:"resolved",payload:{source:o,matches:d,complete:!0,...g===void 0?{}:{fuzzy:g}}}},toScriptData(e){let t=e;return{...I(t.matches,t.complete),...t.fuzzy===void 0?{}:{fuzzy:{...t.fuzzy,candidates:t.fuzzy.candidates.map(o=>y(o))}}}},renderResult(e,t,o){let s=e.details;return $(s.matches,s.complete,o,t.expanded,void 0,["Web page \xB7 read-only",...s.complete?[]:["Limit reached \xB7 incomplete results"]])},format(e){let t=e,o=t.matches.length===0?`No matches in ${t.source}`:`${t.matches.length}${t.complete?"":"+"} matches in ${t.source}${t.complete?"":" (limit reached)"}`,s=[o];t.fuzzy?.status==="skipped"&&s.push(`Possible-name fallback skipped: ${t.fuzzy.message}`),t.fuzzy?.candidates.length&&s.push("Possible names \u2014 spelling suggestions, not equivalent behavior.",...t.fuzzy.candidates.map(n=>H(y(n))));let a=Buffer.byteLength(o);for(let n of t.matches){let u=`${t.source}:${n.lineNumber}:${n.startColumn+1} ${j(n)}`;if(a+=Buffer.byteLength(u)+1,a>48*1024){s.push("Output shortened. Narrow the query or lower the limit.");break}s.push(u)}return{content:[{type:"text",text:s.join(`
3
3
  `)}],details:t}}}}i(F,"createWebSearchResolver");function U(r,e,t,o){o?.throwIfAborted();let s=performance.now(),a=new _;if(a.addText(r),a.limited)return{status:"skipped",message:"name collection reached its byte or unique-name budget",candidates:[]};let n=[];for(let u of L(t,a.names)){if(o?.throwIfAborted(),performance.now()-s>b.timeoutMs)return{status:"skipped",message:"extra search reached its time budget",candidates:[]};let d=new RegExp(u.identifier.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),"gu"),h=[],g=!0,l=0;e:for(let[m,c]of r.split(/\r\n|\n|\r/u).entries()){if(performance.now()-s>b.timeoutMs)return{status:"skipped",message:"extra search reached its time budget",candidates:[]};o?.throwIfAborted();for(let p of c.matchAll(d)){let f=p.index,w=f+p[0].length;if(!(/[\p{L}\p{N}_$]/u.test(c[f-1]??"")||/[\p{L}\p{N}_$]/u.test(c[w]??""))){if(l+=Buffer.byteLength(c),h.length===b.matchesPerCandidate||l>b.verificationBytes){g=!1;break e}h.push({source:e,lineNumber:m+1,startColumn:f,endColumn:w,matchedText:p[0],lineText:c})}}}h.length>0&&n.push({...u,matches:h,complete:g})}return n.length===0?void 0:{status:"ready",candidates:n}}i(U,"searchFuzzyText");function j(r){let e=Math.max(0,r.startColumn-64),t=Math.min(r.lineText.length,r.startColumn+192);return`${e>0?"\u2026":""}${r.lineText.slice(e,t)}${t<r.lineText.length?"\u2026":""}`}i(j,"previewMatch");function q(r){let e=r.query,t=e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e,o=e.startsWith("regex:")?e.slice(6):t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(o,r.caseSensitive===!0?"gu":"giu")}i(q,"searchPattern");var G={provider:"web",capability:"read"},J=T({kind:"markdown",label:"WEB"});async function Q(r){await K(r)}i(Q,"registerWeb");async function K(r,e){let t=E(r,G),o=B(t,{owner:e?.(t)}),s={protocol:P,apiVersion:x,id:"web",setup(n){n.addResolver({resolver:o,renderResult:J,preserveTruncatedOutput:!0}),n.describe({path:i(()=>W(e?"HTTP(S) URLs use local HTTP/browser execution; web:ssh://target/https://\u2026 explicitly uses the configured target. Web content is read-only. Target browser fallback requires target-installed Node, playwright-core and Chrome/Chromium. Browser reads enable page JavaScript and disable the Chromium sandbox, using a fresh temporary profile.":"HTTP(S) URL \u2014 remote content.",t.listDescriptions()),"path")})}},a={protocol:A,apiVersion:k,id:"web",setup(n){n.addResolver({resolver:F(o),priority:-100}),n.describe("HTTP(S) Search reuses converted page text for zero-result identifier spelling suggestions. Candidate groups carry the URL and line ranges, never editable SEARCH references."),n.addPromptGuideline(e?"Use search with an HTTP(S) path for local web execution or web:ssh://target/https://\u2026 for explicit target execution; no prior read is required.":"Use search with an HTTP(S) path to find text on a web page; no prior read is required.")}};await Promise.all([C(r,s),O(r,a),Promise.resolve(z(r,M))])}i(K,"registerWebWithOwner");export{Q as a,K as b};
@@ -1,4 +1,4 @@
1
- import{a as Ae}from"./chunk-IUSLSROY.js";import{a as Ee}from"./chunk-3G54ZL2L.js";import{a as Ie,b as Re}from"./chunk-7HDK3NRQ.js";import{a as xe}from"./chunk-NULNW6GK.js";import"./chunk-KL776TGR.js";import{b as Ce}from"./chunk-OJX3RJ5A.js";import"./chunk-CTJV77FR.js";import{a as X,d as ke}from"./chunk-SBLKPTL3.js";import"./chunk-XZDOVPRC.js";import{a as Pe,b as Se,c as Oe}from"./chunk-HCN5W76B.js";import{a as De}from"./chunk-7TJ6DWW3.js";import{a as K,g as D}from"./chunk-EY65TFHJ.js";import{c as ve}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-R5XJSEOE.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as ue,b as fe,c as ge}from"./chunk-JMVDFOTQ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await Ke(le(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:p}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,p,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:p}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
1
+ import{a as Ee}from"./chunk-NJ7C4KMA.js";import{a as xe}from"./chunk-6FGLAVPJ.js";import"./chunk-6H32W35W.js";import"./chunk-NUM3YQGK.js";import{a as X,d as ke}from"./chunk-6XFUICD7.js";import{a as Ae}from"./chunk-SMIFCAAX.js";import{a as Ie,b as Re}from"./chunk-VXP5BMW7.js";import{b as Ce}from"./chunk-RW2GTYQI.js";import{a as Pe,b as Se,c as Oe}from"./chunk-RIJMXO43.js";import"./chunk-VMTOFEXF.js";import{a as De}from"./chunk-CPELC6JE.js";import{a as K,g as D}from"./chunk-PJL3UVMJ.js";import{c as ve}from"./chunk-W7CASEO3.js";import{a as ue,b as fe,c as ge}from"./chunk-57F5GTHO.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-LCWBVOII.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await Ke(le(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:p}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,p,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:p}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
2
2
  `;return t===i?!1:(o?await o.writeText(n,i,t,e):await Qe(n,i,{encoding:"utf8",signal:e}),!0)}s(q,"writeJson");function je(n,r){let t=new Set,o;for(let e of n.trim().split(/\s+/u).filter(Boolean))if(["--apply","--no-apply","--agent"].includes(e))t.add(e);else if(e.startsWith("ssh://")&&o===void 0)o=e;else throw new TypeError("Use /pi-agent-ide-doctor [ssh://target/path] [--apply | --no-apply] [--agent]");if(t.has("--apply")&&t.has("--no-apply"))throw new TypeError("Choose --apply or --no-apply, not both");return{cwd:o??r,flags:t}}s(je,"parseDoctorArguments");var z=class{static{s(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(r){let t=this.plugins.get(r.id);if(t!==void 0)return t;let o=this.queue.then(async()=>{let e=!0,i=[],a=[],u=[],f=[],h={addLanguage:s(p=>{V(p,i,r.id,"language",()=>e)},"addLanguage"),addToolRecipe:s(p=>{V(p,a,r.id,"tool recipe",()=>e)},"addToolRecipe"),addSetupCheck:s(p=>{V(p,u,r.id,"setup check",()=>e)},"addSetupCheck"),addCheck:s(p=>{V(p,f,r.id,"check",()=>e)},"addCheck")};try{await r.setup(h)}finally{e=!1}$e(this.languages,i,"language"),$e(this.recipes,a,"tool recipe"),this.languages.push(...i),this.recipes.push(...a),this.setupChecks.push(...u),this.checks.push(...f)});return this.plugins.set(r.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(r.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function Ne(n,r){let t=[],o=[];for(let e of n.setupChecks)try{let i=await e.value.inspect(r);t.push(...(i.selections??[]).map(a=>({...a,pluginId:e.pluginId}))),o.push(...(i.actions??[]).map(a=>({...a,pluginId:e.pluginId})))}catch{}return{selections:t,actions:o}}s(Ne,"runContributedSetupChecks");async function Le(n,r){let t=[];for(let o of n.checks)try{t.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(r)})}catch(e){t.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:e instanceof Error?e.message:String(e)}]})}return t}s(Le,"runContributedChecks");function $e(n,r,t){for(let o of r){let e=n.find(i=>i.value.id===o.value.id)?.pluginId;if(e!==void 0)throw new Error(`${t} ${o.value.id} is already owned by doctor plugin ${e}`)}}s($e,"assertAvailable");function V(n,r,t,o,e){if(!e())throw new Error(`Doctor plugin ${t} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(r.some(i=>i.value.id===n.id))throw new Error(`Doctor plugin ${t} registered ${o} ${n.id} twice`);r.push({pluginId:t,value:n})}s(V,"add");import st from"node:path";import{readFile as Ze}from"node:fs/promises";async function _e(n,r,t,o=process.env,e,i){e?.throwIfAborted();let a=t.filter(({value:g})=>g.languages.some(y=>r.has(y))),u=a.map(g=>g.value),f=i?await i.evidence(u,e):await de(n,u,void 0,e),h=await et(n,e,i),p=[...new Set(u.flatMap(g=>g.executables))],m=i?await i.executableAvailability(p.map(g=>({command:[g]})),e):void 0;if(e?.throwIfAborted(),m&&(m.length!==p.length||m.some(g=>typeof g!="boolean")))throw new TypeError("Invalid Doctor executable availability report");let w=[];for(let g of a){e?.throwIfAborted();let y=g.value,C=[],I=1,b=f.get(y.id),O=b?.config;O!==void 0&&(I+=6,C.push(`project config: ${O}`)),h.has(`${y.kind}:${y.id}`)&&(I+=6,C.push("Pi Agent IDE config"));let c=b?.dependency;c!==void 0&&(I+=4,C.push(`project dependency: ${c}`));let d=m?y.executables.find(l=>m[p.indexOf(l)]===!0):await qe(n,y.executables,o,e);d!==void 0&&(I+=3,C.push(`executable: ${d}`)),w.push({pluginId:g.pluginId,recipe:y,score:I,evidence:C,...d&&{executable:d}})}return w.sort((g,y)=>y.score-g.score||g.recipe.id.localeCompare(y.recipe.id))}s(_e,"discoverRecipeCandidates");function Ue(n,r,t=[]){let o=new Map,e=new Map(t.map(i=>[`${i.kind}:${i.languageId}`,i.toolId]));for(let i of r)for(let a of["formatter","linter","lsp"]){let u=e.get(`${a}:${i}`),f=u===void 0?4:7,h=n.filter(m=>m.recipe.kind===a&&m.recipe.languages.includes(i)&&m.executable!==void 0&&m.recipe.id!==u&&m.score>=f),p=h[0];p!==void 0&&(h.filter(m=>m.score===p.score).length>1||o.set(`${p.recipe.kind}:${p.recipe.id}`,p))}return[...o.values()]}s(Ue,"selectSuggestedRecipes");async function qe(n,r,t,o){for(let e of r)if(await pe(e,n,t,o))return e}s(qe,"firstExecutable");async function et(n,r,t){let o=new Set;for(let[e,i,a]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{r?.throwIfAborted();let u=t?(await t.configPaths(e,r)).project:L(n,e),f=t?await t.readText(u,r):await Ze(u,{encoding:"utf8",signal:r});if(r?.throwIfAborted(),f===void 0)continue;let h=JSON.parse(f);if(typeof h!="object"||h===null||Array.isArray(h))continue;let m=h[i];if(typeof m=="object"&&m!==null&&!Array.isArray(m))for(let w of Object.keys(m))o.add(`${a}:${w}`)}catch(u){if(r?.throwIfAborted(),!(u instanceof SyntaxError)&&!(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT"))throw u}return o}s(et,"managedRecipeIds");import{execFile as tt}from"node:child_process";import{readdir as ot}from"node:fs/promises";import _ from"node:path";import{promisify as nt}from"node:util";var rt=nt(tt),it=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Be(n,r){r?.throwIfAborted();try{let o=(await rt("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:r})).stdout.split("\0").filter(Boolean).map(e=>_.resolve(n,e)).filter(e=>!Me(e));return r?.throwIfAborted(),o.length>0?o:await ee(n,r)}catch{return r?.throwIfAborted(),ee(n,r)}}s(Be,"collectProjectFiles");function Fe(n,r,t=process.platform){let o=new Map,e=t==="win32"?_.win32:_;for(let i of r){let a=new Set(i.extensions.map(p=>p.toLowerCase())),u=s(p=>t==="win32"?p.toLowerCase():p,"normalizeName"),f=new Set(i.fileNames?.map(u)),h=n.filter(p=>!p.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")&&(a.has(e.extname(p).toLowerCase())||f.has(u(e.basename(p)))));h.length>0&&o.set(i.id,h)}return o}s(Fe,"detectProjectLanguages");async function ee(n,r){r?.throwIfAborted();let t=[];for(let o of await ot(n,{withFileTypes:!0})){if(o.isDirectory()&&it.has(o.name))continue;let e=_.join(n,o.name);Me(e)||(o.isDirectory()?t.push(...await ee(e,r)):o.isFile()&&t.push(e))}return t}s(ee,"walk");function Me(n){return n.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")}s(Me,"isManagedIdeConfig");function at(n,r){if(n.includes("://")&&!r||r&&r.source!==n)throw Object.assign(new Error(`Doctor requires the owner of ${n}`),{code:"UNSUPPORTED_SOURCE"})}s(at,"assertWorkspace");async function te(n,r,t=process.env,o,e){o?.throwIfAborted(),at(r,e);let i=e?await e.files(o):await Be(r,o);o?.throwIfAborted();let a=Fe(i,n.languages.map(w=>w.value),e?.platform),u=new Set(a.keys()),f={cwd:r,files:i,detectedLanguageIds:u,detectedLanguages:a,env:e?{...e.toolPaths}:t,signal:o,workspace:e},[h,p]=await Promise.all([_e(r,u,n.recipes,e?{...e.toolPaths}:t,o,e),Ne(n,f)]);o?.throwIfAborted();let m=new Map;for(let w of u)for(let g of["formatter","linter","lsp"]){if(p.selections.some(b=>b.languageId===w&&b.kind===g))continue;let y=h.filter(b=>b.recipe.kind===g&&b.recipe.languages.includes(w)),C=s(b=>b.score-(b.executable===void 0?0:3),"nativeScore"),I=Math.max(1,...y.map(C));for(let b of y){if(b.executable!==void 0||C(b)!==I||I<=1)continue;let O=`${g}-${b.recipe.id}-unavailable`;m.set(O,{id:O,pluginId:b.pluginId,message:`Native project setup selects ${b.recipe.id}, but its executable is unavailable. Install ${b.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:r,files:i,detectedLanguages:a,candidates:h,selections:p.selections,actions:[...p.actions,...m.values()],suggestions:Ue(h,u,p.selections)}}s(te,"inspectDoctorSetup");async function Y(n,r,t=process.env,o,e){let i=await te(n,r,t,o,e),a=new Set(i.detectedLanguages.keys()),u={cwd:r,files:i.files,detectedLanguageIds:a,detectedLanguages:i.detectedLanguages,env:e?{...e.toolPaths}:t,signal:o,workspace:e},f=await Le(n,u);o?.throwIfAborted();let h=[{status:"pass",message:`Project: ${r}`},i.files.length>0?{status:"pass",message:`${i.files.length} project files inspected`}:{status:"warn",message:"No project files found"},a.size>0?{status:"pass",message:`Detected: ${[...a].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...i,sections:[{title:"Project",pluginId:"doctor",findings:h},...f]}}s(Y,"runDoctor");function M(n){let r=["Pi Agent IDE doctor",""];for(let t of n.sections){r.push(`${t.title} (${t.pluginId})`);for(let o of t.findings)r.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&r.push(` \`${o.detail}\``);r.push("")}if(n.actions.length>0){r.push("Setup needs attention");for(let t of n.actions)r.push(` ${t.message} [${t.pluginId}]`);r.push("")}if(n.suggestions.length>0){r.push("Suggested configuration");for(let t of n.suggestions){let o=t.evidence.length>0?` \u2014 ${t.evidence.join(", ")}`:"";r.push(` ${t.recipe.kind.padEnd(9)} ${t.recipe.id} [${t.pluginId}]${o}`)}r.push("")}return r.join(`
3
3
  `).trimEnd()}s(M,"formatDoctorReport");function oe(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(r=>r.findings.some(t=>t.status==="fail"))}s(oe,"doctorNeedsWork");function We(n){let r=n.candidates.map(t=>({owner:t.pluginId,id:t.recipe.id,kind:t.recipe.kind,languages:t.recipe.languages,evidence:t.evidence,documentation:t.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",M(n),"","Relevant registered recipes:",JSON.stringify(r,null,2),"",`Project root: ${n.cwd.includes("://")?n.cwd:st.resolve(n.cwd)}`].join(`
4
4
  `)}s(We,"buildDoctorAgentPrompt");import{createHash as ct}from"node:crypto";var dt="doctor",ne=3;function Je(n,r){let t=ue(n,pt(r));t!==void 0&&t.catch(()=>{})}s(Je,"registerDoctorTipProvider");function pt(n){return{protocol:fe,apiVersion:ge,id:dt,async getTip(r){let t=await n(r),o=lt(t);if(o.length===0)return;let e=o.slice(0,ne).map(i=>`\u2022 ${i.message}`);return o.length>ne&&e.push(`\u2022 ${o.length-ne} more`),{id:`doctor-setup-${ut(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...e,"Run /pi-agent-ide-doctor"].join(`
@@ -0,0 +1 @@
1
+ import{H as d,f as c}from"./chunk-LCWBVOII.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var b=t.Object({query:t.String({minLength:1,description:"Text to find or a Boolean expression. Quote text to keep it literal. Use regex:<pattern> for regular expressions, files:<pattern> for file paths, ast:<pattern> for syntax patterns, symbols:<query> for language symbols, or process:<query> for running processes."}),path:t.Optional(t.Union(d.anyOf,{description:"File, directory, URL, docs:all for all packaged guide bodies, docs:<id> for one guide, unchanged Read/Search/Select/edit result, its UUID, or an array of such results. Use literal text or regex: for docs: sources. Results select only their registered ranges unless symbols: navigation follows external references."})),navigation:t.Optional(t.Literal("references",{description:"Only for symbols: queries. Explicitly follow symbols represented inside path to their references outside that scope. Without navigation, all returned ranges stay inside path."})),include:t.Optional(t.String({description:"Optional include glob for local or SSH files"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local or SSH files"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum displayed items, including compact file summaries (default 50)."}))},{additionalProperties:!1});import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},O=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),h=e.Union([e.Object({...g,fuzzy:e.Optional(O)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),P=c(h);function T(o,l,n,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((r,a)=>({source:r.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:r.lineNumber,startColumn:r.startColumn,endLine:r.endLineNumber??r.lineNumber,endColumn:r.endColumn},...Buffer.byteLength(r.matchedText)<=4096?{matchedText:r.matchedText}:{textTruncated:!0},...n===void 0?{}:{references:{line:`SEARCH#${n}:${a+1}:line`,match:`SEARCH#${n}:${a+1}:match`}}})),...l&&n!==void 0?{all:{line:`SEARCH#${n}:all:line`,match:`SEARCH#${n}:all:match`}}:{}}}s(T,"selectionData");export{b as a,O as b,h as c,P as d,T as e};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-VMTOFEXF.js";import"./chunk-CPELC6JE.js";import"./chunk-PJL3UVMJ.js";import"./chunk-LCWBVOII.js";import"./chunk-EI7MMDWY.js";export{a as runOwnedSshCommand};
@@ -1,3 +1,3 @@
1
- import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Se}from"node:async_hooks";function ie(){return{pending:new Set,active:new Se}}i(ie,"createSchedulerState");function be(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(be,"conflicts");function Ee(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Ee,"coveredAccess");async function xe(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(xe,"waitForDependencies");var U=class r{constructor(e=ie()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(S=>{if(n?.throwIfAborted(),!Ee(a.accesses,S,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return S});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(m=>{p=m}),h={accesses:c,done:l};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await xe(s.then(async S=>(await Promise.all(d.map(F=>Promise.race([F.done,F.accesses.then(Te=>be(S,Te)?F.done:void 0)]))),S)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Ae=Symbol.for("pi-agent-resource.resource-scheduler-state"),Oe=globalThis,ke=Oe[Ae]??=ie(),Ne=new U(ke);import{realpath as Pe,stat as je}from"node:fs/promises";import P from"node:path";import{fileURLToPath as Ie}from"node:url";async function ae(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=P.resolve(e,r.startsWith("file:")?Ie(r):r),[o,s]=await Promise.allSettled([Pe(n),je(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let h=P.dirname(n);if(h===n)a=n;else{let y=(await ae(h,e,t)).find(S=>S.resource.startsWith("file:"));a=P.join(y?.resource.slice(5)??h,P.basename(n))}}let d=a.split(P.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(ae,"resourceAccesses");import{randomUUID as _e}from"node:crypto";import{mkdir as Ue,mkdtemp as $e,readFile as Le,rm as De,writeFile as He}from"node:fs/promises";import{tmpdir as We}from"node:os";import ce from"node:path";var K=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#o=new Set;#n;#t;#r;constructor(e={}){this.#n=e.parentDirectory??We(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#r!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#o.add(n);try{return await n}finally{this.#o.delete(n)}}dispose(){return this.#r??=this.#a(),this.#r}async#i(e,t){let n=await this.#d(),o=_e(),s=`temp:${o}`,a=ce.join(n,`${o}.txt`);return await He(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#o),this.#e.clear(),this.#t!==void 0&&await De(await this.#t,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#r!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#r!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await Le(t,"utf8")}]}async#d(){return this.#t??=(async()=>(await Ue(this.#n,{recursive:!0}),$e(ce.join(this.#n,"pi-agent-read-"))))(),this.#t}};import{Type as g}from"typebox";import{Value as Ve}from"typebox/value";var $=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ue(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array($,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array($,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array($)},required:["status","errors"],additionalProperties:!1}}i(ue,"structuredResultSchema");var de=1024*1024;function q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>de)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function le(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(le,"resultError");function Me(r,e,t){try{if(q(t),!Ve.Check(ue(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=le(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Me,"withStructuredResult");var J=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError"}static{i(this,"ResourceError")}};function ze(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
- `)}i(ze,"renderContentDescription");import{Type as f}from"typebox";import{Value as Qe}from"typebox/value";import{Type as u}from"typebox";import{Value as Be}from"typebox/value";var C={additionalProperties:!0},j=u.Function([],u.Unknown()),v=u.String({minLength:1}),Fe=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},C),Ke=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},C),qe=u.Object({type:u.Literal("custom"),kind:v,data:u.Unknown()},C),Je=u.Array(u.Union([Fe,Ke,qe]),{minItems:1}),fe=u.Union([u.Object({source:v,link:u.Optional(v),read:j,write:u.Optional(u.Never())},C),u.Object({source:v,link:u.Optional(v),read:u.Optional(u.Never()),write:j},C),u.Object({source:v,link:u.Optional(v),read:j,write:j},C)]),Ye=u.Object({id:v,tryResolve:j},C),Ge=u.Union([u.Object({kind:u.Literal("not-handled")},C),u.Object({kind:u.Literal("resolved"),resource:fe},C),u.Object({kind:u.Literal("failed"),error:u.Unknown()},C)]);function Y(r){return L(Je,r)?D(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(Y,"isAgentContent");function pe(r){return L(fe,r)?D(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(pe,"isResource");function Xe(r){return L(Ye,r)}i(Xe,"isResourceResolver");function Ze(r){return L(Ge,r)?D(()=>{let e=r;return e.kind!=="resolved"||pe(e.resource)}):!1}i(Ze,"isResourceResolutionAttempt");function L(r,e){return D(()=>Be.Check(r,e))}i(L,"safeCheck");function D(r){try{return r()}catch{return!1}}i(D,"safeEvaluate");var R={additionalProperties:!0},et=f.Function([],f.Unknown()),H=f.String({minLength:1}),tt=f.Object({provider:H,capability:f.Union([f.Literal("read"),f.Literal("write")])},R),rt=f.Object({source:H,bytes:f.Unknown(),mediaType:f.Optional(f.String())},R),nt=f.Object({signal:f.Optional(f.Unknown())},R),ot=f.Object({id:H,description:H,tryConvert:et},R),st=f.Union([f.Object({kind:f.Literal("not-handled")},R),f.Object({kind:f.Literal("converted"),content:f.Unknown()},R),f.Object({kind:f.Literal("failed"),error:f.Unknown()},R)]),it=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},R);function O(r){return k(tt,r)&&E(()=>r.provider.trim().length>0)}i(O,"isContentTarget");function G(r){return k(rt,r)?E(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(G,"isContentInput");function X(r){return k(nt,r)?E(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(X,"isContentConversionContext");function ge(r){return k(ot,r)?E(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(ge,"isContentConverter");function Z(r){return k(st,r)?E(()=>{let e=r;return e.kind!=="converted"||Y(e.content)}):!1}i(Z,"isContentConversionAttempt");function b(r){return k(it,r)?E(()=>{let e=r;return O(e.target)&&ge(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(b,"isContentConverterRegistration");function k(r,e){return E(()=>Qe.Check(r,e))}i(k,"safeCheck");function E(r){try{return r()}catch{return!1}}i(E,"safeEvaluate");var W=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function ee(r){if(!O(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!b(o))throw new TypeError("Invalid content converter registration");if(!x(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!G(o))throw new TypeError("Invalid content input");if(!X(s))throw new TypeError("Invalid content conversion context");Q(s.signal);let a=n();for(let{converter:d}of a){Q(s.signal);let c=await d.tryConvert(o,s);if(Q(s.signal),!Z(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new W(o.source,e)}}}i(ee,"createContentRunner");function x(r,e){return r.provider===e.provider&&r.capability===e.capability}i(x,"targetsEqual");function Q(r){r?.throwIfAborted()}i(Q,"throwIfAborted");import{Type as w}from"typebox";import{Value as at}from"typebox/value";var N="pi-agent-resource/content-conversion",V=2,I=`${N}/host/ready`,_=`${N}/converter/register`,he={additionalProperties:!0},ct=w.Function([],w.Unknown()),ut=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(V),target:w.Unknown()},he),dt=w.Object({registration:w.Unknown(),accept:ct},he);function te(r){return me(ut,r)&&ne(()=>O(r.target))}i(te,"isContentHostReady");function re(r){return me(dt,r)&&ne(()=>b(r.registration))}i(re,"isContentConverterRegistrationRequest");function me(r,e){return ne(()=>at.Check(r,e))}i(me,"safeCheck");function ne(r){try{return r()}catch{return!1}}i(ne,"safeEvaluate");var ye="pi-agent-resource:content-host-lookup";function lt(r,e){let t;if(r.events.emit(ye,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return Ce(r,t),t.host;let n=ee(e),o=r.events.on(_,c=>{if(!re(c))throw new Error("Invalid content converter registration request");if(!x(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(ye,c=>{if(!ft(c))throw new Error("Invalid content host lookup request");x(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return Ce(r,d),r.events.emit(I,{protocol:N,apiVersion:V,target:n.target}),s}i(lt,"createContentHost");function ft(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(ft,"isHostLookup");function Ce(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(Ce,"retainOwner");function pt(r,e){if(!b(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!te(s))throw new Error("Invalid content conversion host readiness event");if(!x(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(pt,"connectContentConverter");import{createHash as ve,randomUUID as oe}from"node:crypto";import{statSync as gt}from"node:fs";import{readFile as ht}from"node:fs/promises";import T from"node:path";import{fileURLToPath as mt}from"node:url";import{Type as M}from"typebox";var yt=M.Union([M.String(),M.Array(M.String())]),A="RESULT#",Re="pi-agent-resource:result-targets",B=class{static{i(this,"ResultTargetStore")}#e=new Map;#o=new Map;#n=new Map;#t=new Map;clear(){this.#e.clear(),this.#o.clear(),this.#n.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${A}${oe()}`;return this.#e.set(o,{state:"ready",targets:se(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${A}${oe()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:se(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:se(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await we(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}publish(e,t,n,o=[]){let s=oe();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
- ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let h of l){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#o.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ve("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#o.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(A)?e.slice(A.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#t.get(a);if(!c&&!s&&e.startsWith(A)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ve("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#t.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#t.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>z(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>z(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=z(e,t),o=JSON.stringify([T.resolve(t),n]),s=Ct(e,t),a=this.#n.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#n.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#n.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(A))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(A))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function z(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return mt(t)}catch{}return T.resolve(e,t)}i(z,"sourcePath");function Ct(r,e){try{let t=gt(z(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(Ct,"fileStamp");async function we(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await ht(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(we,"verifyResultTargets");function se(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(se,"combineTargets");function vt(r){let e;if(r.events.emit(Re,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new B,n=r.events.on(Re,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(vt,"connectResultTargets");export{U as a,Ne as b,ae as c,K as d,$ as e,ue as f,de as g,q as h,le as i,Me as j,J as k,ze as l,Y as m,pe as n,Xe as o,Ze as p,O as q,G as r,X as s,ge as t,Z as u,b as v,W as w,ee as x,x as y,N as z,V as A,I as B,_ as C,te as D,re as E,lt as F,pt as G,yt as H,B as I,we as J,vt as K};
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as be}from"node:async_hooks";function ie(){return{pending:new Set,active:new be}}i(ie,"createSchedulerState");function Ee(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(Ee,"conflicts");function xe(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(xe,"coveredAccess");async function Ae(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(Ae,"waitForDependencies");var $=class r{constructor(e=ie()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(S=>{if(n?.throwIfAborted(),!xe(a.accesses,S,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return S});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(m=>{p=m}),h={accesses:c,done:l};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await Ae(s.then(async S=>(await Promise.all(d.map(z=>Promise.race([z.done,z.accesses.then(Se=>Ee(S,Se)?z.done:void 0)]))),S)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Oe=Symbol.for("pi-agent-resource.resource-scheduler-state"),ke=globalThis,Ne=ke[Oe]??=ie(),Pe=new $(Ne);import{realpath as je,stat as Ie}from"node:fs/promises";import P from"node:path";import{fileURLToPath as _e}from"node:url";async function ae(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=P.resolve(e,r.startsWith("file:")?_e(r):r),[o,s]=await Promise.allSettled([je(n),Ie(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let h=P.dirname(n);if(h===n)a=n;else{let y=(await ae(h,e,t)).find(S=>S.resource.startsWith("file:"));a=P.join(y?.resource.slice(5)??h,P.basename(n))}}let d=a.split(P.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(ae,"resourceAccesses");import{randomUUID as $e}from"node:crypto";import{mkdir as Ue,mkdtemp as Le,readFile as De,rm as He,writeFile as We}from"node:fs/promises";import{tmpdir as Ve}from"node:os";import ce from"node:path";var K=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#n=new Set;#o;#t;#r;constructor(e={}){this.#o=e.parentDirectory??Ve(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#r!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#n.add(n);try{return await n}finally{this.#n.delete(n)}}dispose(){return this.#r??=this.#a(),this.#r}async#i(e,t){let n=await this.#d(),o=$e(),s=`temp:${o}`,a=ce.join(n,`${o}.txt`);return await We(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#n),this.#e.clear(),this.#t!==void 0&&await He(await this.#t,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#r!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#r!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await De(t,"utf8")}]}async#d(){return this.#t??=(async()=>(await Ue(this.#o,{recursive:!0}),Le(ce.join(this.#o,"pi-agent-read-"))))(),this.#t}};import{Type as g}from"typebox";import{Value as Me}from"typebox/value";var U=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ue(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(U,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U)},required:["status","errors"],additionalProperties:!1}}i(ue,"structuredResultSchema");var de=1024*1024;function q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>de)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function le(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(le,"resultError");function Be(r,e,t){try{if(q(t),!Me.Check(ue(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=le(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Be,"withStructuredResult");var fe=Symbol.for("pi-agent-resource.ResourceError"),J=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError"}static{i(this,"ResourceError")}[fe]=!0;static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&t[fe]===!0}};function Fe(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(Fe,"renderContentDescription");import{Type as f}from"typebox";import{Value as et}from"typebox/value";import{Type as u}from"typebox";import{Value as ze}from"typebox/value";var C={additionalProperties:!0},j=u.Function([],u.Unknown()),v=u.String({minLength:1}),Ke=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},C),qe=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},C),Je=u.Object({type:u.Literal("custom"),kind:v,data:u.Unknown()},C),Ye=u.Array(u.Union([Ke,qe,Je]),{minItems:1}),pe=u.Union([u.Object({source:v,link:u.Optional(v),read:j,write:u.Optional(u.Never())},C),u.Object({source:v,link:u.Optional(v),read:u.Optional(u.Never()),write:j},C),u.Object({source:v,link:u.Optional(v),read:j,write:j},C)]),Ge=u.Object({id:v,tryResolve:j},C),Xe=u.Union([u.Object({kind:u.Literal("not-handled")},C),u.Object({kind:u.Literal("resolved"),resource:pe},C),u.Object({kind:u.Literal("failed"),error:u.Unknown()},C)]);function Y(r){return L(Ye,r)?D(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(Y,"isAgentContent");function ge(r){return L(pe,r)?D(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(ge,"isResource");function Ze(r){return L(Ge,r)}i(Ze,"isResourceResolver");function Qe(r){return L(Xe,r)?D(()=>{let e=r;return e.kind!=="resolved"||ge(e.resource)}):!1}i(Qe,"isResourceResolutionAttempt");function L(r,e){return D(()=>ze.Check(r,e))}i(L,"safeCheck");function D(r){try{return r()}catch{return!1}}i(D,"safeEvaluate");var R={additionalProperties:!0},tt=f.Function([],f.Unknown()),H=f.String({minLength:1}),rt=f.Object({provider:H,capability:f.Union([f.Literal("read"),f.Literal("write")])},R),nt=f.Object({source:H,bytes:f.Unknown(),mediaType:f.Optional(f.String())},R),ot=f.Object({signal:f.Optional(f.Unknown())},R),st=f.Object({id:H,description:H,tryConvert:tt},R),it=f.Union([f.Object({kind:f.Literal("not-handled")},R),f.Object({kind:f.Literal("converted"),content:f.Unknown()},R),f.Object({kind:f.Literal("failed"),error:f.Unknown()},R)]),at=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},R);function O(r){return k(rt,r)&&E(()=>r.provider.trim().length>0)}i(O,"isContentTarget");function G(r){return k(nt,r)?E(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(G,"isContentInput");function X(r){return k(ot,r)?E(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(X,"isContentConversionContext");function he(r){return k(st,r)?E(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(he,"isContentConverter");function Z(r){return k(it,r)?E(()=>{let e=r;return e.kind!=="converted"||Y(e.content)}):!1}i(Z,"isContentConversionAttempt");function b(r){return k(at,r)?E(()=>{let e=r;return O(e.target)&&he(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(b,"isContentConverterRegistration");function k(r,e){return E(()=>et.Check(r,e))}i(k,"safeCheck");function E(r){try{return r()}catch{return!1}}i(E,"safeEvaluate");var W=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function ee(r){if(!O(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!b(o))throw new TypeError("Invalid content converter registration");if(!x(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!G(o))throw new TypeError("Invalid content input");if(!X(s))throw new TypeError("Invalid content conversion context");Q(s.signal);let a=n();for(let{converter:d}of a){Q(s.signal);let c=await d.tryConvert(o,s);if(Q(s.signal),!Z(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new W(o.source,e)}}}i(ee,"createContentRunner");function x(r,e){return r.provider===e.provider&&r.capability===e.capability}i(x,"targetsEqual");function Q(r){r?.throwIfAborted()}i(Q,"throwIfAborted");import{Type as w}from"typebox";import{Value as ct}from"typebox/value";var N="pi-agent-resource/content-conversion",V=2,I=`${N}/host/ready`,_=`${N}/converter/register`,me={additionalProperties:!0},ut=w.Function([],w.Unknown()),dt=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(V),target:w.Unknown()},me),lt=w.Object({registration:w.Unknown(),accept:ut},me);function te(r){return ye(dt,r)&&ne(()=>O(r.target))}i(te,"isContentHostReady");function re(r){return ye(lt,r)&&ne(()=>b(r.registration))}i(re,"isContentConverterRegistrationRequest");function ye(r,e){return ne(()=>ct.Check(r,e))}i(ye,"safeCheck");function ne(r){try{return r()}catch{return!1}}i(ne,"safeEvaluate");var Ce="pi-agent-resource:content-host-lookup";function ft(r,e){let t;if(r.events.emit(Ce,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return ve(r,t),t.host;let n=ee(e),o=r.events.on(_,c=>{if(!re(c))throw new Error("Invalid content converter registration request");if(!x(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(Ce,c=>{if(!pt(c))throw new Error("Invalid content host lookup request");x(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return ve(r,d),r.events.emit(I,{protocol:N,apiVersion:V,target:n.target}),s}i(ft,"createContentHost");function pt(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(pt,"isHostLookup");function ve(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(ve,"retainOwner");function gt(r,e){if(!b(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!te(s))throw new Error("Invalid content conversion host readiness event");if(!x(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(gt,"connectContentConverter");import{createHash as Re,randomUUID as oe}from"node:crypto";import{statSync as ht}from"node:fs";import{readFile as mt}from"node:fs/promises";import T from"node:path";import{fileURLToPath as yt}from"node:url";import{Type as M}from"typebox";var Ct=M.Union([M.String(),M.Array(M.String())]),A="RESULT#",we="pi-agent-resource:result-targets",F=class{static{i(this,"ResultTargetStore")}#e=new Map;#n=new Map;#o=new Map;#t=new Map;clear(){this.#e.clear(),this.#n.clear(),this.#o.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${A}${oe()}`;return this.#e.set(o,{state:"ready",targets:se(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${A}${oe()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:se(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:se(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await Te(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}registerSearchReference(e,t,n){if(!/^SEARCH#[A-F\d]{4,64}:[1-9]\d*:(line|match)$/u.test(e))throw new Error("Only numbered Search references can alias a snapshot.");if(!this.#e.has(t))throw new Error("A Search reference needs a registered result target.");this.resolve(t,n),this.#n.set(e,t)}publish(e,t,n,o=[]){let s=oe();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let h of l){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#n.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:Re("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#n.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(A)?e.slice(A.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#t.get(a);if(!c&&!s&&e.startsWith(A)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&Re("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#t.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#t.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>B(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>B(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=B(e,t),o=JSON.stringify([T.resolve(t),n]),s=vt(e,t),a=this.#o.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#o.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#o.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(A))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(A))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function B(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return yt(t)}catch{}return T.resolve(e,t)}i(B,"sourcePath");function vt(r,e){try{let t=ht(B(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(vt,"fileStamp");async function Te(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await mt(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(Te,"verifyResultTargets");function se(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(se,"combineTargets");function Rt(r){let e;if(r.events.emit(we,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new F,n=r.events.on(we,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(Rt,"connectResultTargets");export{$ as a,Pe as b,ae as c,K as d,U as e,ue as f,de as g,q as h,le as i,Be as j,J as k,Fe as l,Y as m,ge as n,Ze as o,Qe as p,O as q,G as r,X as s,he as t,Z as u,b as v,W as w,ee as x,x as y,N as z,V as A,I as B,_ as C,te as D,re as E,ft as F,gt as G,Ct as H,F as I,Te as J,Rt as K};