pi-agent-ide 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +5 -3
  3. package/dist/{chunk-TGC2ZACO.js → chunk-235QMMVA.js} +1 -1
  4. package/dist/{chunk-OI3HBIPK.js → chunk-4DIUPEDF.js} +1 -1
  5. package/dist/{chunk-2ITKAXHO.js → chunk-6FGLAVPJ.js} +1 -1
  6. package/dist/{chunk-7LOVUWNI.js → chunk-6H32W35W.js} +1 -1
  7. package/dist/{chunk-YHREORHH.js → chunk-6OJ565FL.js} +1 -1
  8. package/dist/{chunk-E2PHA4SQ.js → chunk-6R3Y4AD3.js} +1 -1
  9. package/dist/{chunk-VNTY7BKC.js → chunk-6T7PSDQW.js} +1 -1
  10. package/dist/{chunk-D4IA2MTA.js → chunk-6TJPMBUQ.js} +1 -1
  11. package/dist/{chunk-JKMXND6V.js → chunk-6XFUICD7.js} +1 -1
  12. package/dist/{chunk-A64JRDZK.js → chunk-AAC77UD4.js} +1 -1
  13. package/dist/{chunk-HFJGCYFO.js → chunk-ANM3Y5FO.js} +5 -5
  14. package/dist/{chunk-Q5X6OXNS.js → chunk-CPELC6JE.js} +1 -1
  15. package/dist/chunk-GBUJOR6V.js +28 -0
  16. package/dist/{chunk-3WO2NOEQ.js → chunk-GSOYVIQS.js} +1 -1
  17. package/dist/{chunk-AIT3YWR5.js → chunk-HSRH76JN.js} +1 -1
  18. package/dist/{chunk-ID4RJIVZ.js → chunk-HSZ4AQ6L.js} +1 -1
  19. package/dist/chunk-I6NPILT5.js +1 -0
  20. package/dist/chunk-K7SRNBIV.js +1 -0
  21. package/dist/{chunk-DXONCYWF.js → chunk-LCWBVOII.js} +3 -3
  22. package/dist/{chunk-EMRJP6EM.js → chunk-LEJKDYCK.js} +1 -1
  23. package/dist/{chunk-HCK7OIQ3.js → chunk-NJ7C4KMA.js} +1 -1
  24. package/dist/{chunk-BQAKA3FU.js → chunk-NUM3YQGK.js} +1 -1
  25. package/dist/chunk-OJEIX7OZ.js +1 -0
  26. package/dist/chunk-PBQDHYNX.js +1 -0
  27. package/dist/{chunk-4HWKBCBH.js → chunk-PJL3UVMJ.js} +1 -1
  28. package/dist/chunk-PT35ZFLH.js +33 -0
  29. package/dist/{chunk-AKNHSDGV.js → chunk-QT3EAHOG.js} +1 -1
  30. package/dist/{chunk-LLRUJD62.js → chunk-RIJMXO43.js} +1 -1
  31. package/dist/chunk-RMI3NMQY.js +23 -0
  32. package/dist/chunk-RQ7JJ7GV.js +4 -0
  33. package/dist/{chunk-AUL5FGGK.js → chunk-RVU73VKN.js} +1 -1
  34. package/dist/{chunk-WPBQ45ZL.js → chunk-RW2GTYQI.js} +1 -1
  35. package/dist/{chunk-BR7GRH4A.js → chunk-SDAH3ECM.js} +1 -1
  36. package/dist/chunk-SGQWRIRJ.js +10 -0
  37. package/dist/{chunk-N56WAVYA.js → chunk-SMIFCAAX.js} +1 -1
  38. package/dist/chunk-SWBJS3U4.js +1 -0
  39. package/dist/{chunk-WXGTU2M6.js → chunk-VMTOFEXF.js} +1 -1
  40. package/dist/{chunk-GEMDU6XW.js → chunk-VXP5BMW7.js} +1 -1
  41. package/dist/{chunk-LAJQSHEI.js → chunk-XAHU42FP.js} +3 -3
  42. package/dist/{chunk-ZV5ETNLQ.js → chunk-XBQR74IK.js} +1 -1
  43. package/dist/{chunk-TXG2H7YQ.js → chunk-XG7QNAKW.js} +1 -1
  44. package/dist/{chunk-PRLIHLCS.js → chunk-XLWCSJMR.js} +1 -1
  45. package/dist/{chunk-M4TVRCMZ.js → chunk-XXLLY66B.js} +1 -1
  46. package/dist/chunk-YFP4P2FV.js +1 -0
  47. package/dist/{chunk-SWA5B5B2.js → chunk-YIXP2ALP.js} +1 -1
  48. package/dist/{chunk-246NTPOS.js → chunk-ZJQRLVVV.js} +1 -1
  49. package/dist/entry-0.js +1 -1
  50. package/dist/entry-1.js +1 -1
  51. package/dist/entry-10.js +1 -1
  52. package/dist/entry-11.js +1 -1
  53. package/dist/entry-12.js +1 -1
  54. package/dist/entry-13.js +1 -1
  55. package/dist/entry-14.js +1 -1
  56. package/dist/entry-15.js +1 -1
  57. package/dist/entry-16.js +1 -1
  58. package/dist/entry-17.js +1 -1
  59. package/dist/entry-18.js +1 -1
  60. package/dist/entry-19.js +1 -0
  61. package/dist/entry-2.js +1 -1
  62. package/dist/entry-20.js +1 -1
  63. package/dist/entry-22.js +1 -1
  64. package/dist/entry-23.js +1 -1
  65. package/dist/entry-24.js +1 -1
  66. package/dist/entry-25.js +1 -1
  67. package/dist/entry-26.js +1 -1
  68. package/dist/entry-27.js +1 -2
  69. package/dist/entry-28.js +1 -1
  70. package/dist/entry-29.js +2 -4
  71. package/dist/entry-3.js +1 -1
  72. package/dist/entry-30.js +1 -1
  73. package/dist/entry-31.js +4 -1
  74. package/dist/entry-32.js +1 -1
  75. package/dist/entry-33.js +1 -18
  76. package/dist/entry-34.js +1 -1
  77. package/dist/entry-35.js +18 -1
  78. package/dist/entry-36.js +1 -1
  79. package/dist/entry-37.js +1 -1
  80. package/dist/entry-38.js +1 -1
  81. package/dist/entry-39.js +1 -1
  82. package/dist/entry-4.js +1 -1
  83. package/dist/entry-40.js +1 -1
  84. package/dist/entry-41.js +1 -1
  85. package/dist/entry-42.js +1 -1
  86. package/dist/entry-43.js +1 -1
  87. package/dist/entry-44.js +1 -1
  88. package/dist/entry-45.js +1 -1
  89. package/dist/entry-46.js +1 -1
  90. package/dist/entry-47.js +1 -25
  91. package/dist/entry-48.js +1 -1
  92. package/dist/entry-49.js +25 -1
  93. package/dist/entry-5.js +1 -1
  94. package/dist/entry-50.js +1 -1
  95. package/dist/entry-51.js +1 -1
  96. package/dist/entry-52.js +1 -3
  97. package/dist/entry-53.js +1 -13
  98. package/dist/entry-54.js +3 -1
  99. package/dist/entry-55.js +13 -1
  100. package/dist/entry-56.js +1 -1
  101. package/dist/entry-57.js +1 -1
  102. package/dist/entry-58.js +1 -1
  103. package/dist/entry-59.js +1 -1
  104. package/dist/entry-6.js +1 -1
  105. package/dist/entry-60.js +1 -1
  106. package/dist/entry-61.js +1 -1
  107. package/dist/entry-62.js +1 -1
  108. package/dist/entry-63.js +1 -0
  109. package/dist/entry-64.js +1 -1
  110. package/dist/entry-66.js +1 -1
  111. package/dist/entry-67.js +0 -1
  112. package/dist/entry-68.js +1 -1
  113. package/dist/entry-69.js +1 -1
  114. package/dist/entry-7.js +1 -1
  115. package/dist/entry-70.js +1 -1
  116. package/dist/entry-71.js +1 -1
  117. package/dist/entry-72.js +1 -1
  118. package/dist/entry-73.js +1 -0
  119. package/dist/entry-74.js +1 -1
  120. package/dist/entry-76.js +1 -1
  121. package/dist/entry-77.js +0 -1
  122. package/dist/entry-78.js +1 -1
  123. package/dist/entry-79.js +1 -80
  124. package/dist/entry-8.js +1 -1
  125. package/dist/entry-80.js +1 -22
  126. package/dist/entry-81.js +80 -2
  127. package/dist/entry-82.js +22 -1
  128. package/dist/entry-83.js +2 -1
  129. package/dist/entry-84.js +1 -1
  130. package/dist/entry-85.js +1 -3
  131. package/dist/entry-86.js +1 -1
  132. package/dist/entry-87.js +1 -1
  133. package/dist/entry-88.js +3 -1
  134. package/dist/entry-89.js +1 -0
  135. package/dist/entry-9.js +1 -1
  136. package/dist/entry-90.js +1 -0
  137. package/dist/entry-91.js +1 -0
  138. package/dist/pi-agent-ide.js +29 -36
  139. package/docs/agent-guides/debugger.md +2 -0
  140. package/docs/agent-guides/editing.md +3 -3
  141. package/docs/agent-guides/search-code.md +2 -2
  142. package/docs/agent-guides/select-code.md +9 -6
  143. package/docs/code-review.md +5 -0
  144. package/docs/configuration.md +36 -4
  145. package/docs/development.md +8 -0
  146. package/docs/directory-operations.md +1 -1
  147. package/docs/extensions.md +98 -1
  148. package/docs/structured-results.md +11 -6
  149. package/docs/user-hooks.md +2 -2
  150. package/node_modules/pi-agent-doctor/package.json +7 -7
  151. package/node_modules/pi-agent-doctor/runtime/entry-27.js +1 -0
  152. package/node_modules/pi-agent-documentation/package.json +2 -2
  153. package/node_modules/pi-agent-documentation/runtime/entry-28.js +1 -0
  154. package/node_modules/pi-agent-filesystem/package.json +8 -8
  155. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  156. package/node_modules/pi-agent-filesystem-jq/package.json +6 -6
  157. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  158. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-32.js +2 -0
  159. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  160. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  161. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +6 -5
  162. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  163. package/node_modules/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  164. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  165. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  166. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  167. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  168. package/node_modules/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  169. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  170. package/node_modules/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  171. package/node_modules/pi-agent-image/package.json +3 -3
  172. package/node_modules/pi-agent-invariant/package.json +2 -2
  173. package/node_modules/pi-agent-pdf/package.json +3 -3
  174. package/node_modules/pi-agent-read/package.json +12 -12
  175. package/node_modules/pi-agent-read/runtime/entry-47.js +0 -1
  176. package/node_modules/pi-agent-read/runtime/entry-49.js +2 -0
  177. package/node_modules/pi-agent-resource/package.json +2 -2
  178. package/node_modules/pi-agent-resource/src/resource-error.ts +11 -0
  179. package/node_modules/pi-agent-search/package.json +9 -9
  180. package/node_modules/pi-agent-search/runtime/entry-52.js +0 -1
  181. package/node_modules/pi-agent-search/runtime/entry-53.js +1 -0
  182. package/node_modules/pi-agent-search/runtime/entry-54.js +2 -0
  183. package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -5
  184. package/node_modules/pi-agent-search-text/package.json +14 -14
  185. package/node_modules/pi-agent-search-text/runtime/entry-55.js +1 -0
  186. package/node_modules/pi-agent-search-text/runtime/entry-58.js +1 -0
  187. package/node_modules/pi-agent-text/package.json +3 -3
  188. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  189. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  190. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  191. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  192. package/node_modules/pi-agent-text-editor/index.ts +2 -0
  193. package/node_modules/pi-agent-text-editor/package.json +26 -26
  194. package/node_modules/pi-agent-text-editor/runtime/entry-79.js +0 -1
  195. package/node_modules/pi-agent-text-editor/runtime/entry-80.js +1 -0
  196. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  197. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  198. package/node_modules/pi-agent-text-editor/src/core/extension.ts +3 -1
  199. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +45 -44
  200. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  201. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +27 -18
  202. package/node_modules/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  203. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  204. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +29 -6
  205. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  206. package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  207. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  208. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  209. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  210. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  211. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +14 -3
  212. package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  213. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -5
  214. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +2 -0
  215. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  216. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +1 -0
  217. package/node_modules/pi-agent-tool-ui/package.json +6 -2
  218. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +1 -0
  219. package/node_modules/pi-agent-tool-ui/runtime/entry-86.js +1 -0
  220. package/node_modules/pi-agent-tool-ui/src/operation-approval.ts +271 -0
  221. package/node_modules/pi-agent-web/package.json +8 -8
  222. package/node_modules/pi-agent-web-html/package.json +3 -3
  223. package/node_modules/pi-agent-web-image/package.json +4 -4
  224. package/node_modules/pi-agent-web-image/runtime/entry-89.js +2 -0
  225. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  226. package/node_modules/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  227. package/node_modules/pi-agent-web-text/package.json +4 -4
  228. package/node_modules/pi-agent-web-text/runtime/entry-91.js +2 -0
  229. package/package.json +62 -54
  230. package/src/api/approval.ts +5 -0
  231. package/src/api/settings.ts +198 -0
  232. package/src/backend/debugger-registration.ts +5 -1
  233. package/src/code-review/extension.ts +10 -4
  234. package/src/code-review/reviewer.ts +8 -0
  235. package/src/composite/host-version.ts +29 -5
  236. package/src/composite/ide-alias-rendering.ts +97 -0
  237. package/src/composite/nested-tool-rendering.ts +74 -4
  238. package/src/composite/search-facts.ts +45 -0
  239. package/src/composite/settings-documentation.ts +32 -23
  240. package/src/composite/settings-registry.ts +94 -0
  241. package/src/composite/text-results.ts +120 -8
  242. package/src/composite/tool-availability.ts +11 -2
  243. package/src/core/diagnostic-entry.ts +31 -8
  244. package/src/core/diagnostic-store.ts +19 -3
  245. package/src/core/extension.ts +7 -2
  246. package/src/core/reload-resource-store.ts +23 -3
  247. package/src/documentation/registry.ts +10 -2
  248. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  249. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  250. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -6
  251. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  252. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-32.js +2 -0
  253. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  254. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-33.js +2 -0
  255. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +2 -0
  256. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  257. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  258. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  259. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +2 -0
  260. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  261. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  262. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  263. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-91.js +2 -0
  264. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +2 -0
  265. package/src/extensions/pi-agent-read/package.json +12 -12
  266. package/src/extensions/pi-agent-read/runtime/entry-47.js +0 -1
  267. package/src/extensions/pi-agent-read/runtime/entry-48.js +1 -0
  268. package/src/extensions/pi-agent-read/runtime/entry-49.js +2 -0
  269. package/src/extensions/pi-agent-search/package.json +9 -9
  270. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -14
  271. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +1 -0
  272. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +1 -0
  273. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-58.js +1 -0
  274. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  275. package/src/extensions/pi-agent-search/runtime/entry-53.js +1 -0
  276. package/src/extensions/pi-agent-search/runtime/entry-54.js +2 -0
  277. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -5
  278. package/src/extensions/pi-agent-text-editor/index.ts +2 -0
  279. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  280. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  281. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  282. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  283. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-63.js +1 -0
  284. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  285. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +14 -3
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  289. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -5
  290. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +2 -0
  291. package/src/extensions/pi-agent-text-editor/runtime/entry-79.js +0 -1
  292. package/src/extensions/pi-agent-text-editor/runtime/entry-80.js +1 -0
  293. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +2 -0
  294. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  295. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  296. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +3 -1
  297. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +45 -44
  298. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  299. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +27 -18
  300. package/src/extensions/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  301. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  302. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +29 -6
  303. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  304. package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  305. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  306. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  307. package/src/pi-agent-ide.ts +61 -14
  308. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  309. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +6 -5
  310. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  311. package/src/plugins/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  312. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  313. package/src/plugins/pi-agent-ide-debugger/index.ts +159 -60
  314. package/src/plugins/pi-agent-ide-debugger/src/debugmcp-client.ts +118 -0
  315. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +47 -0
  316. package/src/plugins/pi-agent-ide-debugger/src/renderer.ts +2 -0
  317. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +146 -1
  318. package/src/plugins/pi-agent-ide-debugger/src/ui.ts +12 -0
  319. package/src/plugins/pi-agent-ide-debugger/src/vscode-backend.ts +497 -0
  320. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  321. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  322. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  323. package/src/plugins/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  324. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  325. package/src/plugins/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  326. package/src/plugins/pi-agent-ide-terminal/index.ts +3 -2
  327. package/src/plugins/pi-agent-ide-terminal/src/origin.ts +30 -0
  328. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +34 -0
  329. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +11 -2
  330. package/src/plugins/pi-agent-ide-terminal/src/types.ts +9 -0
  331. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +72 -26
  332. package/dist/chunk-ESPNEJHK.js +0 -1
  333. package/dist/chunk-GNACBJM3.js +0 -1
  334. package/dist/chunk-VMGZMXEM.js +0 -10
  335. package/dist/chunk-W3YFF6OO.js +0 -1
  336. package/dist/chunk-W7M3V7FR.js +0 -28
  337. package/dist/chunk-WMHSVEIT.js +0 -29
  338. package/dist/chunk-XSIKDVAR.js +0 -25
  339. package/dist/chunk-YTYLS2UM.js +0 -1
  340. package/dist/chunk-Z2QGNTGQ.js +0 -1
  341. package/dist/entry-21.js +0 -1
  342. package/node_modules/pi-agent-doctor/runtime/entry-20.js +0 -1
  343. package/node_modules/pi-agent-doctor/runtime/entry-21.js +0 -1
  344. package/node_modules/pi-agent-filesystem/runtime/entry-27.js +0 -2
  345. package/node_modules/pi-agent-filesystem-image/runtime/entry-28.js +0 -2
  346. package/node_modules/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  347. package/node_modules/pi-agent-ide-formatter/runtime/entry-36.js +0 -2
  348. package/node_modules/pi-agent-image/runtime/entry-40.js +0 -1
  349. package/node_modules/pi-agent-invariant/runtime/entry-41.js +0 -1
  350. package/node_modules/pi-agent-search/runtime/entry-49.js +0 -1
  351. package/node_modules/pi-agent-search-text/runtime/entry-53.js +0 -2
  352. package/node_modules/pi-agent-search-text/runtime/entry-54.js +0 -1
  353. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-58.js +0 -2
  354. package/node_modules/pi-agent-text-editor/runtime/entry-64.js +0 -1
  355. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-80.js +0 -2
  356. package/node_modules/pi-agent-tool-call-interception/runtime/entry-82.js +0 -1
  357. package/node_modules/pi-agent-tool-ui/runtime/entry-83.js +0 -1
  358. package/node_modules/pi-agent-web/runtime/entry-84.js +0 -2
  359. package/node_modules/pi-agent-web-html/runtime/entry-85.js +0 -2
  360. package/node_modules/pi-agent-web-image/runtime/entry-86.js +0 -2
  361. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-28.js +0 -2
  362. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-29.js +0 -2
  363. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-27.js +0 -2
  364. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-85.js +0 -2
  365. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-86.js +0 -2
  366. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-87.js +0 -2
  367. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-84.js +0 -2
  368. package/src/extensions/pi-agent-read/runtime/entry-43.js +0 -1
  369. package/src/extensions/pi-agent-read/runtime/entry-44.js +0 -1
  370. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +0 -2
  371. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-54.js +0 -1
  372. package/src/extensions/pi-agent-search/runtime/entry-49.js +0 -1
  373. package/src/extensions/pi-agent-search/runtime/entry-50.js +0 -1
  374. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-58.js +0 -2
  375. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -1
  376. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-80.js +0 -2
  377. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +0 -2
  378. package/src/extensions/pi-agent-text-editor/runtime/entry-63.js +0 -1
  379. package/src/extensions/pi-agent-text-editor/runtime/entry-64.js +0 -1
  380. package/src/plugins/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  381. package/src/plugins/pi-agent-ide-ast/runtime/entry-33.js +0 -2
  382. package/src/plugins/pi-agent-ide-formatter/runtime/entry-36.js +0 -2
  383. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-26.js +0 -0
  384. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem}/runtime/entry-29.js +0 -0
  385. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  386. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-31.js +0 -0
  387. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-text}/runtime/entry-33.js +0 -0
  388. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-34.js +0 -0
  389. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  390. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  391. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
  392. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-39.js +0 -0
  393. /package/node_modules/{pi-agent-pdf → pi-agent-image}/runtime/entry-42.js +0 -0
  394. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-43.js +0 -0
  395. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-44.js +0 -0
  396. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-48.js +0 -0
  397. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-50.js +0 -0
  398. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-57.js +0 -0
  399. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-59.js +0 -0
  400. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-60.js +0 -0
  401. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-61.js +0 -0
  402. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-62.js +0 -0
  403. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-63.js +0 -0
  404. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-81.js +0 -0
  405. /package/node_modules/{pi-agent-web-pdf → pi-agent-web}/runtime/entry-87.js +0 -0
  406. /package/node_modules/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-88.js +0 -0
  407. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  408. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-31.js +0 -0
  409. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-88.js +0 -0
  410. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-60.js +0 -0
  411. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-61.js +0 -0
  412. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-62.js +0 -0
  413. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-34.js +0 -0
  414. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  415. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  416. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
  417. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-39.js +0 -0
@@ -1 +1 @@
1
- import{a as w}from"./chunk-Q5X6OXNS.js";import{g as f}from"./chunk-4HWKBCBH.js";import{a as s}from"./chunk-EI7MMDWY.js";async function I(l,g,h,i,e){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<=0)throw new TypeError("Owned command deadlines and byte limits must be positive");e.signal?.throwIfAborted();let o=new AbortController,y=e.signal?AbortSignal.any([e.signal,o.signal]):o.signal,B=setTimeout(()=>o.abort(new f("TIMEOUT",i,e.effect)),e.timeoutMs),a,u,d;try{a=await w(l,g,h,l.workspace,{signal:y,timeoutMs:e.timeoutMs});let r=[],n=[],c=0,m=s((t,T)=>{c+=t.length,c>e.maxBytes?o.abort(new f(e.limitCode??"BYTE_LIMIT",i,e.effect)):T.push(t)},"consume");if(a.stdout.on("data",t=>m(t,r)),a.stderr.on("data",t=>m(t,n)),e.input!==void 0)for(let t=0;t<e.input.length;t+=65536)await a.write(e.input.subarray(t,t+65536));if(e.closeInput||e.input!==void 0)try{await a.end()}catch(t){if(!(t instanceof f)||t.code!=="INPUT_CLOSED")throw t}let{exitCode:b}=await a.completion;d={stdout:Buffer.concat(r),stderr:Buffer.concat(n),exitCode:b}}catch(r){let n=o.signal.aborted?o.signal.reason:r;u=n instanceof f&&(n.source!==i||n.effect==="unknown"&&e.effect==="not-applied")?new f(n.code,i,n.effect==="not-applied"?"not-applied":e.effect,{cause:n}):n}finally{clearTimeout(B)}try{await a?.stop()}catch(r){throw d===void 0?new AggregateError([u,r],"Target command and cleanup failed",{cause:r}):r}if(d===void 0)throw u;return d}s(I,"runOwnedSshCommand");export{I as a};
1
+ import{a as w}from"./chunk-CPELC6JE.js";import{g as f}from"./chunk-PJL3UVMJ.js";import{a as s}from"./chunk-EI7MMDWY.js";async function I(l,g,h,i,e){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<=0)throw new TypeError("Owned command deadlines and byte limits must be positive");e.signal?.throwIfAborted();let o=new AbortController,y=e.signal?AbortSignal.any([e.signal,o.signal]):o.signal,B=setTimeout(()=>o.abort(new f("TIMEOUT",i,e.effect)),e.timeoutMs),a,u,d;try{a=await w(l,g,h,l.workspace,{signal:y,timeoutMs:e.timeoutMs});let r=[],n=[],c=0,m=s((t,T)=>{c+=t.length,c>e.maxBytes?o.abort(new f(e.limitCode??"BYTE_LIMIT",i,e.effect)):T.push(t)},"consume");if(a.stdout.on("data",t=>m(t,r)),a.stderr.on("data",t=>m(t,n)),e.input!==void 0)for(let t=0;t<e.input.length;t+=65536)await a.write(e.input.subarray(t,t+65536));if(e.closeInput||e.input!==void 0)try{await a.end()}catch(t){if(!(t instanceof f)||t.code!=="INPUT_CLOSED")throw t}let{exitCode:b}=await a.completion;d={stdout:Buffer.concat(r),stderr:Buffer.concat(n),exitCode:b}}catch(r){let n=o.signal.aborted?o.signal.reason:r;u=n instanceof f&&(n.source!==i||n.effect==="unknown"&&e.effect==="not-applied")?new f(n.code,i,n.effect==="not-applied"?"not-applied":e.effect,{cause:n}):n}finally{clearTimeout(B)}try{await a?.stop()}catch(r){throw d===void 0?new AggregateError([u,r],"Target command and cleanup failed",{cause:r}):r}if(d===void 0)throw u;return d}s(I,"runOwnedSshCommand");export{I as a};
@@ -1 +1 @@
1
- import{a as u,g as p}from"./chunk-4HWKBCBH.js";import{a as S}from"./chunk-BXGMMZT3.js";import{a as l}from"./chunk-EI7MMDWY.js";import d from"node:path";function k(m,n){return{async paths(i,s,a=n){a?.throwIfAborted();let r=m.resolve(i);if(!r)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");let f=await r.backend.execute("python3",["-c","import json,os;print(json.dumps({'home':os.environ.get('HOME',''),'agent':os.environ.get('PI_CODING_AGENT_DIR','')}))"],r.location.path,{signal:a});if(f.exitCode!==0)throw new p("CONFIG_ENVIRONMENT_FAILED",i,"not-applied");let o=JSON.parse(f.stdout.toString("utf8"));if(typeof o!="object"||o===null||!("home"in o)||!("agent"in o)||typeof o.home!="string"||typeof o.agent!="string"||!o.home.startsWith("/"))throw new TypeError("Invalid remote configuration environment");let c=o.agent.trim()?d.posix.resolve(r.location.path,o.agent.trim()):d.posix.join(o.home,".pi","agent");return{project:u(r.location.target,d.posix.join(r.location.path,".pi","pi-agent-ide",`${s}.json`)).source,global:u(r.location.target,d.posix.join(c,"extensions","pi-agent-ide",`${s}.json`)).source}},async readText(i,s=n){s?.throwIfAborted();let a=m.resolve(i);if(!a)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");return(await a.backend.read(a.location.path,{signal:s})).bytes.toString("utf8")}}}l(k,"createSshToolConfigAccess");import{readFile as E}from"node:fs/promises";import g from"node:path";import{Type as t}from"typebox";import{Value as y}from"typebox/value";var w=t.Object({content:t.Record(t.String(),t.Union([t.String(),t.Null()])),markers:t.Record(t.String(),t.Boolean()),names:t.Array(t.String())});async function U(m,n,i,s){s?.throwIfAborted();let a=[...new Set(["package.json",...i.flatMap(e=>Object.keys(e.configSections??{}))])],r=[...new Set(i.flatMap(e=>e.configFiles??[]))];for(let e of[...a,...r]){let h=g.posix.relative(n,g.posix.resolve(n,e));if(h===".."||h.startsWith("../")||g.posix.isAbsolute(e))throw new p("UNSUPPORTED_SOURCE",n,"not-applied")}let f=await E(new URL("./recipe-evidence-worker.py",new URL("../src/backend/recipe-evidence.ts",import.meta.url).href),{encoding:"utf8",signal:s}),o=await m.execute("python3",["-c",f,n,JSON.stringify({files:a,markers:r.filter(e=>!e.includes("*")),listNames:r.some(e=>e.includes("*"))})],n,{signal:s});if(o.exitCode!==0)throw new p("EVIDENCE_FAILED",n,"not-applied");let c=JSON.parse(o.stdout.toString("utf8"));if(y.Check(t.Object({error:t.Literal("CONTENT_LIMIT")}),c))throw new p("CONTENT_LIMIT",n,"not-applied");if(!y.Check(w,c))throw new p("INVALID_RESPONSE",n,"not-applied");return S(n,i,{readText:l(e=>Promise.resolve(c.content[e]??void 0),"readText"),hasMarker:l(e=>Promise.resolve(e.includes("*")?c.names.some(h=>g.matchesGlob(h,e)):c.markers[e]===!0),"hasMarker")},s)}l(U,"inspectSshRecipeEvidence");export{k as a,U as b};
1
+ import{a as u,g as p}from"./chunk-PJL3UVMJ.js";import{a as S}from"./chunk-BXGMMZT3.js";import{a as l}from"./chunk-EI7MMDWY.js";import d from"node:path";function k(m,n){return{async paths(i,s,a=n){a?.throwIfAborted();let r=m.resolve(i);if(!r)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");let f=await r.backend.execute("python3",["-c","import json,os;print(json.dumps({'home':os.environ.get('HOME',''),'agent':os.environ.get('PI_CODING_AGENT_DIR','')}))"],r.location.path,{signal:a});if(f.exitCode!==0)throw new p("CONFIG_ENVIRONMENT_FAILED",i,"not-applied");let o=JSON.parse(f.stdout.toString("utf8"));if(typeof o!="object"||o===null||!("home"in o)||!("agent"in o)||typeof o.home!="string"||typeof o.agent!="string"||!o.home.startsWith("/"))throw new TypeError("Invalid remote configuration environment");let c=o.agent.trim()?d.posix.resolve(r.location.path,o.agent.trim()):d.posix.join(o.home,".pi","agent");return{project:u(r.location.target,d.posix.join(r.location.path,".pi","pi-agent-ide",`${s}.json`)).source,global:u(r.location.target,d.posix.join(c,"extensions","pi-agent-ide",`${s}.json`)).source}},async readText(i,s=n){s?.throwIfAborted();let a=m.resolve(i);if(!a)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");return(await a.backend.read(a.location.path,{signal:s})).bytes.toString("utf8")}}}l(k,"createSshToolConfigAccess");import{readFile as E}from"node:fs/promises";import g from"node:path";import{Type as t}from"typebox";import{Value as y}from"typebox/value";var w=t.Object({content:t.Record(t.String(),t.Union([t.String(),t.Null()])),markers:t.Record(t.String(),t.Boolean()),names:t.Array(t.String())});async function U(m,n,i,s){s?.throwIfAborted();let a=[...new Set(["package.json",...i.flatMap(e=>Object.keys(e.configSections??{}))])],r=[...new Set(i.flatMap(e=>e.configFiles??[]))];for(let e of[...a,...r]){let h=g.posix.relative(n,g.posix.resolve(n,e));if(h===".."||h.startsWith("../")||g.posix.isAbsolute(e))throw new p("UNSUPPORTED_SOURCE",n,"not-applied")}let f=await E(new URL("./recipe-evidence-worker.py",new URL("../src/backend/recipe-evidence.ts",import.meta.url).href),{encoding:"utf8",signal:s}),o=await m.execute("python3",["-c",f,n,JSON.stringify({files:a,markers:r.filter(e=>!e.includes("*")),listNames:r.some(e=>e.includes("*"))})],n,{signal:s});if(o.exitCode!==0)throw new p("EVIDENCE_FAILED",n,"not-applied");let c=JSON.parse(o.stdout.toString("utf8"));if(y.Check(t.Object({error:t.Literal("CONTENT_LIMIT")}),c))throw new p("CONTENT_LIMIT",n,"not-applied");if(!y.Check(w,c))throw new p("INVALID_RESPONSE",n,"not-applied");return S(n,i,{readText:l(e=>Promise.resolve(c.content[e]??void 0),"readText"),hasMarker:l(e=>Promise.resolve(e.includes("*")?c.names.some(h=>g.matchesGlob(h,e)):c.markers[e]===!0),"hasMarker")},s)}l(U,"inspectSshRecipeEvidence");export{k as a,U as b};
@@ -1,4 +1,4 @@
1
- import{a as re,b as ie,c as oe}from"./chunk-DEP55R35.js";import{a as ee,b as te,c as ne}from"./chunk-R2U5WXYR.js";import{e as B,f as W}from"./chunk-T7I2VX3J.js";import{a as V}from"./chunk-YJ6T3PEP.js";import{b as M,c as _}from"./chunk-S72FVLUX.js";import{a as J}from"./chunk-M4TVRCMZ.js";import{c as Z,d as Y}from"./chunk-TGC2ZACO.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as R,j as S}from"./chunk-DXONCYWF.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return H(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return H(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return H(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function H(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(H,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,D=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new D(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=U(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=U(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?$(t,d,`<!-- change: ${a} -->`):($(t,d,`<!-- change-begin: ${a} -->`),$(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function $(n,e,t){if(e.kind==="current"){U(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s($,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function U(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(U,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var L=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(L),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
2
- `)),0,0)}},async execute(d,c,a,l,f){try{let u=await r(c,a,f);return S(u,L,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=R(u,"INDEX_CHANGE_FAILED",c.file);return S({content:[{type:"text",text:p.message}],details:{action:n,change:c.change,file:N(c.file,f.cwd)}},L,{status:"error",data:{action:n,change:c.change,file:N(c.file,f.cwd),effect:xe(u)},errors:[p]})}}})}s(he,"createIndexChangeTool");function ze(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return async(i,d,c)=>{let a=N(i.file,c.cwd);return _e(a,()=>t.run(async()=>{let l=e.readText?await e.readText(a,d):await Fe(a,"utf8"),f=await h.create(e,m(a,c.cwd),d);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${i.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:c.cwd,...d!==void 0&&{signal:d}},i.change,n);if(u.status==="unavailable"){if("failure"in u&&u.failure!==void 0){if(n==="stage"&&u.reason==="index-write-failed"){let y=R(u.failure,"INDEX_CHANGE_FAILED",i.file);throw Object.assign(new Error(`${y.message}
1
+ import{a as re,b as ie,c as oe}from"./chunk-DEP55R35.js";import{a as ee,b as te,c as ne}from"./chunk-R2U5WXYR.js";import{e as B,f as W}from"./chunk-T7I2VX3J.js";import{a as V}from"./chunk-YJ6T3PEP.js";import{b as M,c as _}from"./chunk-S72FVLUX.js";import{a as J}from"./chunk-XXLLY66B.js";import{c as Z,d as Y}from"./chunk-235QMMVA.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as S,j as H}from"./chunk-LCWBVOII.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return D(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return D(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return D(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function D(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(D,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,$=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new $(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=L(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=L(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?U(t,d,`<!-- change: ${a} -->`):(U(t,d,`<!-- change-begin: ${a} -->`),U(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function U(n,e,t){if(e.kind==="current"){L(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s(U,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function L(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(L,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var N=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(N),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
2
+ `)),0,0)}},async execute(d,c,a,l,f){try{let u=await r(c,a,f);return H(u,N,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=S(u,"INDEX_CHANGE_FAILED",c.file);return H({content:[{type:"text",text:p.message}],details:{action:n,change:c.change,file:O(c.file,f.cwd)}},N,{status:"error",data:{action:n,change:c.change,file:O(c.file,f.cwd),effect:xe(u)},errors:[p]})}}})}s(he,"createIndexChangeTool");function ze(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return async(i,d,c)=>{let a=O(i.file,c.cwd);return _e(a,()=>t.run(async()=>{let l=e.readText?await e.readText(a,d):await Fe(a,"utf8"),f=await h.create(e,m(a,c.cwd),d);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${i.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:c.cwd,...d!==void 0&&{signal:d}},i.change,n);if(u.status==="unavailable"){if("failure"in u&&u.failure!==void 0){if(n==="stage"&&u.reason==="index-write-failed"){let y=S(u.failure,"INDEX_CHANGE_FAILED",i.file);throw Object.assign(new Error(`${y.message}
3
3
  The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`,{cause:u.failure}),{effect:xe(u.failure)})}throw u.failure}throw n==="stage"&&u.reason==="stale-selector"?Object.assign(new Error(`${u.message}. Read ${i.file} with views: ["changes"] and use a current CHANGE# anchor.`),{effect:"not-applied"}):n==="stage"&&u.reason==="index-write-failed"&&!d?.aborted?new Error(`${u.message}
4
- The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function N(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(N,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as O}from"typebox";var Ke=O.Object({file:O.Optional({...q,description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."}),change:O.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Ke,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[I],nonAnchorValues:["last"]}],async mutate(r,o){let i=r.sourceFor("file"),d,c;if(o.change==="last")d=e.restore(i,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,m(i,r.cwd),r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:i,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},o.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(d=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;c=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:Xe(r.sourceDocument.content,d),action:"edited"}]]),...c!==void 0&&{afterWrite:c}}}}}s(ye,"createUndoMutationTool");function Xe(n,e){let t=[],r=0,o,i=0,d="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+i,insert:d}),o=void 0,i=0,d="")},"flush");for(let a of Qe(n,e)){if(!a.added&&!a.removed){c(),r+=a.value.length;continue}o??=r,a.removed?(r+=a.value.length,i+=a.value.length):d+=a.value}return c(),t}s(Xe,"createTextChanges");function qe(n){return Ze(n,de(n))}s(qe,"registerGitChanges");async function Ze(n,e){W(n,[await B({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new A,r=new G,o=le(e),i=ue(e),d={protocol:z,apiVersion:Q,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},c={protocol:Z,apiVersion:Y,id:"current-git-changes",setup(a){a.addAnchorResolver({...i,kind:I,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ye(e,t,r)),a.addTextPresenter({presenter:o})}};await Promise.all([V(n,ae),K(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
4
+ The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function O(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(O,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as R}from"typebox";var Ke=R.Object({file:R.Optional(R.Union(q.anyOf,{description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."})),change:R.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Ke,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[I],nonAnchorValues:["last"]}],async mutate(r,o){let i=r.sourceFor("file"),d,c;if(o.change==="last")d=e.restore(i,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,m(i,r.cwd),r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:i,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},o.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(d=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;c=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:Xe(r.sourceDocument.content,d),action:"edited"}]]),...c!==void 0&&{afterWrite:c}}}}}s(ye,"createUndoMutationTool");function Xe(n,e){let t=[],r=0,o,i=0,d="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+i,insert:d}),o=void 0,i=0,d="")},"flush");for(let a of Qe(n,e)){if(!a.added&&!a.removed){c(),r+=a.value.length;continue}o??=r,a.removed?(r+=a.value.length,i+=a.value.length):d+=a.value}return c(),t}s(Xe,"createTextChanges");function qe(n){return Ze(n,de(n))}s(qe,"registerGitChanges");async function Ze(n,e){W(n,[await B({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new A,r=new G,o=le(e),i=ue(e),d={protocol:z,apiVersion:Q,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},c={protocol:Z,apiVersion:Y,id:"current-git-changes",setup(a){a.addAnchorResolver({...i,kind:I,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ye(e,t,r)),a.addTextPresenter({presenter:o})}};await Promise.all([V(n,ae),K(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
@@ -1 +1 @@
1
- import{a as d,b as u,c as w}from"./chunk-LLRUJD62.js";import"./chunk-4HWKBCBH.js";import{b as f}from"./chunk-LAJQSHEI.js";import"./chunk-DEP55R35.js";import"./chunk-R2U5WXYR.js";import{c}from"./chunk-W7CASEO3.js";import"./chunk-T7I2VX3J.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-M4TVRCMZ.js";import"./chunk-TGC2ZACO.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import{readFile as x}from"node:fs/promises";async function g(o){let n=new w(await u(d(c())));await f(o,m(o,n))}i(g,"registerOwnedGit");function m(o,n){return{exec:i(async(t,r,e)=>{let a=n.resolve(e.cwd);if(!a){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e.cwd))throw new Error(`Unsupported Git resource: ${e.cwd}`);return o.exec(t,r,e)}let s=await a.backend.execute(t,r,a.location.path,e);return{code:s.exitCode,stdout:s.stdout.toString("utf8"),stderr:s.stderr.toString("utf8")}},"exec"),async writeIndex(t,r){let e=n.resolve(r.cwd);return e?(await e.backend.writeGitIndex(e.location.path,t,r),!0):!1},async readText(t,r){let e=n.resolve(t);if(e)return(await e.backend.read(e.location.path,{signal:r})).bytes.toString("utf8");if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t))throw new Error(`Unsupported Git resource: ${t}`);return x(t,{encoding:"utf8",signal:r})}}}i(m,"createOwnedGitExecutor");export{m as createOwnedGitExecutor,g as default};
1
+ import{a as d,b as u,c as w}from"./chunk-RIJMXO43.js";import"./chunk-PJL3UVMJ.js";import{b as f}from"./chunk-XAHU42FP.js";import"./chunk-DEP55R35.js";import"./chunk-R2U5WXYR.js";import{c}from"./chunk-W7CASEO3.js";import"./chunk-T7I2VX3J.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-XXLLY66B.js";import"./chunk-235QMMVA.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-LCWBVOII.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import{readFile as x}from"node:fs/promises";async function g(o){let n=new w(await u(d(c())));await f(o,m(o,n))}i(g,"registerOwnedGit");function m(o,n){return{exec:i(async(t,r,e)=>{let a=n.resolve(e.cwd);if(!a){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e.cwd))throw new Error(`Unsupported Git resource: ${e.cwd}`);return o.exec(t,r,e)}let s=await a.backend.execute(t,r,a.location.path,e);return{code:s.exitCode,stdout:s.stdout.toString("utf8"),stderr:s.stderr.toString("utf8")}},"exec"),async writeIndex(t,r){let e=n.resolve(r.cwd);return e?(await e.backend.writeGitIndex(e.location.path,t,r),!0):!1},async readText(t,r){let e=n.resolve(t);if(e)return(await e.backend.read(e.location.path,{signal:r})).bytes.toString("utf8");if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t))throw new Error(`Unsupported Git resource: ${t}`);return x(t,{encoding:"utf8",signal:r})}}}i(m,"createOwnedGitExecutor");export{m as createOwnedGitExecutor,g as default};
@@ -1,4 +1,4 @@
1
- import{a as nt}from"./chunk-47SPPIXK.js";import{a as tt,b as rt}from"./chunk-VAXLSPPU.js";import{a as ot,b as st}from"./chunk-OI3HBIPK.js";import{e as it}from"./chunk-YTYLS2UM.js";import{a as ze,c as He}from"./chunk-TOYN4W4F.js";import{a as Ge}from"./chunk-YJ6T3PEP.js";import{b as Fe,c as Ve}from"./chunk-S72FVLUX.js";import{a as et}from"./chunk-M4TVRCMZ.js";import{c as Qe,d as Ye,f as Ze}from"./chunk-TGC2ZACO.js";import{d as Xe}from"./chunk-IICJXZBU.js";import{a as Ke}from"./chunk-BU7IZLKB.js";import{a as Be,b as Je}from"./chunk-S5PL5DFQ.js";import{J as F}from"./chunk-DXONCYWF.js";import{f as Ie,g as De,h as Ae}from"./chunk-DUUOCBS3.js";import{a as q,b as E,c as J,d as M}from"./chunk-T4FTT3U4.js";import{m as Ee}from"./chunk-ZPT5D4VP.js";import{a as Oe}from"./chunk-ZAWRSA7N.js";import{a as je,b as Te}from"./chunk-OFILFO6D.js";import{b as $e,c as We,g as Ue,j as Ne,p as qe}from"./chunk-IMGIDBCC.js";import{a as Me}from"./chunk-BXGMMZT3.js";import{a as _}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Dr from"node:path";var V=[{id:"vue-typescript-language-server",name:"vue-typescript-language-server",kind:"lsp",languages:["vue"],executables:["typescript-language-server"],dependencies:["typescript-language-server","@vue/typescript-plugin"],configFiles:["tsconfig.json"],documentation:"https://github.com/vuejs/language-tools/tree/master/packages/typescript-plugin",lsp:{command:["typescript-language-server","--stdio"],rootMarkers:["tsconfig.json","package.json"],languageIds:{vue:[".vue"]},initializationOptions:{plugins:[{name:"@vue/typescript-plugin",location:"{project}/node_modules/@vue/typescript-plugin",languages:["vue"]}]}}},b("elixir-ls",["elixir"],["elixir-ls"],["mix.exs"],{elixir:[".ex",".exs"]},["elixir-ls"],"https://github.com/elixir-lsp/elixir-ls",void 0,void 0,{elixirLS:{mcpEnabled:!1}}),b("metals",["scala"],["metals"],["build.sbt","project.scala",".bsp"],{scala:[".scala",".sc"]},["metals"],"https://scalameta.org/metals/"),{id:"angular-language-server",name:"angular-language-server",kind:"lsp",languages:["typescript","html"],executables:["ngserver"],dependencies:["@angular/language-server"],configFiles:["angular.json"],documentation:"https://github.com/angular/vscode-ng-language-service",lsp:{command:["ngserver","--stdio","--tsProbeLocations",".","--ngProbeLocations","."],rootMarkers:["angular.json"],requireRootMarker:!0,languageIds:{typescript:[".ts"],html:[".html"]}}},b("svelte-language-server",["svelte"],["svelteserver"],["svelte.config.js","package.json"],{svelte:[".svelte"]},["svelteserver","--stdio"],"https://github.com/sveltejs/language-tools/tree/master/packages/language-server",["svelte-language-server"]),b("dart-language-server",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],{dart:[".dart"]},["dart","language-server","--protocol=lsp"],"https://dart.dev/tools/dart-language-server"),b("r-language-server",["r"],["Rscript"],["DESCRIPTION",".lintr",".Rprofile"],{r:[".r"]},["Rscript","-e","languageserver::run()"],"https://github.com/REditorSupport/languageserver"),b("zls",["zig"],["zls"],["build.zig","build.zig.zon","zls.json"],{zig:[".zig",".zon"]},["zls"],"https://zigtools.org/zls/"),b("clangd",["c","cpp"],["clangd"],[".clangd","compile_commands.json","CMakeLists.txt"],{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"]},["clangd"],"https://clangd.llvm.org/"),b("typescript-language-server",["javascript","typescript"],["typescript-language-server"],["tsconfig.json","jsconfig.json","package.json"],{javascript:[".js",".mjs",".cjs"],javascriptreact:[".jsx"],typescript:[".ts",".mts",".cts"],typescriptreact:[".tsx"]},["typescript-language-server","--stdio"],"https://github.com/typescript-language-server/typescript-language-server",["typescript-language-server"]),b("basedpyright",["python"],["basedpyright-langserver","pyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["basedpyright-langserver","--stdio"],"https://docs.basedpyright.com/",["basedpyright"]),b("gopls",["go"],["gopls"],["go.mod","go.work"],{go:[".go"]},["gopls"],"https://go.dev/gopls/"),b("rust-analyzer",["rust"],["rust-analyzer"],["Cargo.toml","rust-project.json"],{rust:[".rs"]},["rust-analyzer"],"https://rust-analyzer.github.io/"),b("csharp-ls",["csharp"],["csharp-ls"],[".sln",".csproj"],{csharp:[".cs"]},["csharp-ls"],"https://github.com/razzmatazz/csharp-language-server"),b("jdtls",["java"],["jdtls"],["pom.xml","build.gradle",".project"],{java:[".java"]},["jdtls"],"https://projects.eclipse.org/projects/eclipse.jdt.ls"),b("kotlin-language-server",["kotlin"],["kotlin-language-server"],["build.gradle.kts","pom.xml"],{kotlin:[".kt",".kts"]},["kotlin-language-server"],"https://github.com/fwcd/kotlin-language-server"),b("solargraph",["ruby"],["solargraph"],["Gemfile",".solargraph.yml"],{ruby:[".rb",".rake"]},["solargraph","stdio"],"https://solargraph.org/"),b("intelephense",["php"],["intelephense"],["composer.json"],{php:[".php"]},["intelephense","--stdio"],"https://intelephense.com/"),b("sourcekit-lsp",["swift"],["sourcekit-lsp"],["Package.swift"],{swift:[".swift"]},["sourcekit-lsp"],"https://github.com/swiftlang/sourcekit-lsp"),b("lua-language-server",["lua"],["lua-language-server"],[".luarc.json",".luarc.jsonc"],{lua:[".lua"]},["lua-language-server"],"https://luals.github.io/"),b("bash-language-server",["shell"],["bash-language-server"],[".shellcheckrc"],{shell:[".sh",".bash"]},["bash-language-server","start"],"https://github.com/bash-lsp/bash-language-server"),b("vscode-css-language-server",["css"],["vscode-css-language-server"],["package.json"],{css:[".css",".scss",".less"]},["vscode-css-language-server","--stdio"],"https://github.com/microsoft/vscode-css-languageservice",void 0,void 0,{css:{},scss:{},less:{}}),b("vscode-html-language-server",["html"],["vscode-html-language-server"],["package.json"],{html:[".html",".htm"]},["vscode-html-language-server","--stdio"],"https://github.com/microsoft/vscode-html-languageservice"),b("yaml-language-server",["yaml"],["yaml-language-server"],[".yamllint","package.json"],{yaml:[".yaml",".yml"]},["yaml-language-server","--stdio"],"https://github.com/redhat-developer/yaml-language-server"),b("taplo-lsp",["toml"],["taplo"],["taplo.toml"],{toml:[".toml"]},["taplo","lsp","stdio"],"https://taplo.tamasfe.dev/"),b("marksman",["markdown"],["marksman"],[".marksman.toml"],{markdown:[".md",".mdx"]},["marksman","server"],"https://github.com/artempyanykh/marksman"),b("terraform-ls",["terraform"],["terraform-ls"],[".terraform.lock.hcl"],{terraform:[".tf",".tfvars"]},["terraform-ls","serve"],"https://github.com/hashicorp/terraform-ls"),b("kotlin-lsp",["kotlin"],["intellij-server"],["build.gradle.kts","build.gradle","pom.xml","settings.gradle.kts"],{kotlin:[".kt",".kts"]},["intellij-server","--stdio"],"https://github.com/Kotlin/kotlin-lsp"),b("julia-language-server",["julia"],["julia"],["Project.toml","JuliaProject.toml"],{julia:[".jl"]},["julia","--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],"https://github.com/julia-vscode/LanguageServer.jl"),b("powershell-editor-services",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],{powershell:[".ps1",".psm1",".psd1"]},["pwsh","-NoProfile","-NonInteractive","-Command",'$ErrorActionPreference="Stop";Import-Module PowerShellEditorServices;$d=Join-Path (Get-Location) ".agents/tmp/powershell-lsp-$PID";[IO.Directory]::CreateDirectory($d)|Out-Null;Start-EditorServices -HostName Pi -HostProfileId Pi -HostVersion 1.0.0 -Stdio -LanguageServiceOnly -LogPath (Join-Path $d "server.log") -SessionDetailsPath (Join-Path $d "session.json")'],"https://github.com/PowerShell/PowerShellEditorServices"),b("neocmakelsp",["cmake"],["neocmakelsp"],["CMakeLists.txt",".neocmake.toml",".neocmakelint.toml"],{cmake:[".cmake"]},["neocmakelsp","stdio"],"https://github.com/neocmakelsp/neocmakelsp",void 0,{cmake:["CMakeLists.txt"]}),b("vscode-json-language-server",["json"],["vscode-json-language-server"],["package.json"],{json:[".json",".jsonc"]},["vscode-json-language-server","--stdio"],"https://github.com/microsoft/vscode-json-languageservice"),b("lemminx",["xml"],["lemminx"],[".lemminx.json"],{xml:[".xml",".xsd",".xsl"]},["lemminx"],"https://github.com/eclipse-lemminx/lemminx"),b("sqls",["sql"],["sqls"],[".sqls.yml"],{sql:[".sql"]},["sqls"],"https://github.com/sqls-server/sqls"),b("docker-langserver",["dockerfile"],["docker-langserver"],["Dockerfile"],{dockerfile:[".dockerfile"]},["docker-langserver","--stdio"],"https://github.com/rcjsuen/dockerfile-language-server-nodejs",void 0,{dockerfile:["Dockerfile","Containerfile"]})];function b(n,e,t,r,o,s,i,l,c,p){return{id:n,name:n,kind:"lsp",languages:e,executables:t,configFiles:r,documentation:i,...l&&{dependencies:l},lsp:{command:s,rootMarkers:r,languageIds:o,...c&&{fileNames:c},...p&&{settings:p}}}}a(b,"recipe");import Jt from"node:path";import Kt from"cross-spawn";import{createMessageConnection as Xt,CancellationTokenSource as Qt,StreamMessageReader as Yt}from"vscode-jsonrpc/node";import{URI as ct}from"vscode-uri";import{watch as Nt}from"node:fs";import{readdir as qt,stat as Ft}from"node:fs/promises";import z from"node:path";import{URI as le}from"vscode-uri";var ne=class{constructor(e,t,r){this.root=e;this.changed=t;this.failed=r}static{a(this,"LspFileWatchers")}registrations=new Map;disposed=!1;async register(e,t){let r=[];try{for(let o of t){let s=o.globPattern,i=typeof s=="string"?this.root:le.parse(typeof s.baseUri=="string"?s.baseUri:s.baseUri.uri).fsPath,l=typeof s=="string"?s:s.pattern,c=a(g=>z.matchesGlob(z.isAbsolute(l)?z.join(i,g):g,l),"matches"),p=new Set((await qt(i,{recursive:!0})).filter(c));if(this.disposed)throw new Error("Language server file watchers are disposed");let d=Nt(i,{recursive:!0},(g,u)=>{!u||!c(u)||Ft(z.join(i,u)).then(()=>{if(!this.registrations.get(e)?.includes(d))return;let m=p.has(u)?2:1;p.add(u),(o.kind??7)&(m===1?1:2)&&this.changed({uri:le.file(z.join(i,u)).toString(),type:m})},m=>{if(this.registrations.get(e)?.includes(d)){if(m.code!=="ENOENT"){this.failed(m);return}p.delete(u)&&(o.kind??7)&4&&this.changed({uri:le.file(z.join(i,u)).toString(),type:3})}})});d.on("error",this.failed),r.push(d)}}catch(o){for(let s of r)s.close();throw o}this.unregister(e),this.registrations.set(e,r)}unregister(e){for(let t of this.registrations.get(e)??[])t.close();this.registrations.delete(e)}dispose(){this.disposed=!0;for(let e of this.registrations.keys())this.unregister(e)}};import{StreamMessageWriter as Vt}from"vscode-jsonrpc/node";var oe=class extends Vt{constructor(t,r){super(t);this.fail=r}static{a(this,"TransportWriter")}async write(t){try{await super.write(t)}catch(r){this.fail(r)}}};import zt from"node:path";import{URI as Ht}from"vscode-uri";function k(n,e){if(e.startsWith("ssh://")){let t=at(e);if(n.includes("://")){let o=at(n);if(o.host!==t.host)throw new Error("Document belongs to another language server owner");return o.href}let r=zt.posix.resolve(decodeURIComponent(t.pathname),n);return t.pathname=r.split("/").map(encodeURIComponent).join("/"),t.href}if(n.startsWith("ssh://")||n.includes("://")&&!n.startsWith("file://"))throw new Error("Document belongs to another language server owner");return n.startsWith("file://")?n:Ht.file(n).toString()}a(k,"documentUri");function at(n){let e=new URL(n);if(e.protocol!=="ssh:"||!e.hostname||e.username||e.password||e.port||e.search||e.hash)throw new Error("Invalid language server resource owner");return decodeURIComponent(e.pathname),e}a(at,"checkedRemote");async function A(n,e){if(e?.aborted)throw n.catch(()=>{}),e.reason;if(!e)return n;let t;try{return await Promise.race([n,new Promise((r,o)=>{t=a(()=>o(e.reason),"onAbort"),e.addEventListener("abort",t,{once:!0})})])}finally{t&&e.removeEventListener("abort",t)}}a(A,"waitWithSignal");var H=class{static{a(this,"SharedStartup")}controller=new AbortController;promise;settled=!1;waiters=0;constructor(e){this.promise=e(this.controller.signal);let t=a(()=>{this.settled=!0},"settled");this.promise.then(t,t)}async wait(e){this.waiters+=1;let t=await A(this.promise,e).then(r=>({value:r}),r=>({error:r}));if(this.waiters-=1,!this.settled&&this.waiters===0){this.controller.abort(e?.reason);try{await this.promise}catch(r){if(r!==this.controller.signal.reason)throw new AggregateError([this.controller.signal.reason,r],"Startup cancellation and cleanup failed",{cause:r})}}if("error"in t)throw t.error;return t.value}};var Gt=new Set(["uri","targetUri","target","oldUri","newUri","rootUri","documentUri","scopeUri","baseUri"]),Bt=new Set(["changes","relatedDocuments"]);function j(n,e){return Array.isArray(n)?n.map(t=>j(t,e)):typeof n!="object"||n===null?n:Object.fromEntries(Object.entries(n).map(([t,r])=>Gt.has(t)&&typeof r=="string"?[t,e(r)]:Bt.has(t)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?[t,Object.fromEntries(Object.entries(r).map(([o,s])=>[e(o),j(s,e)]))]:[t,j(r,e)]))}a(j,"mapLspUris");var $=class{static{a(this,"LspClient")}_process=null;_ownedProcess=null;_ownedStartup;_ownerTransport;_connection=null;_initialized=!1;_serverCapabilities=null;_disposed=!1;_shutdownPromise;_crashed=!1;_stderr="";_fileWatchers;_fileWatcherCleanup=Promise.resolve();_handlers=new Map;_documentVersions=new Map;_documentContents=new Map;_diagnosticPublications=new Map;_diagnosticMode="unknown";_activeDiagnosticRequests=new Set;serverId;rootUri;_command;_args;_env;_initOptions;_settings;_timeoutMs;constructor(e){this.serverId=e.serverId,this.rootUri=e.rootUri,this._command=e.command,this._args=e.command.slice(1),this._env=e.env??{},this._initOptions=e.initOptions,this._settings=e.settings,this._timeoutMs=e.timeoutMs??3e4,this._ownerTransport=e.ownerTransport}get ready(){return this._initialized&&!this._disposed}get crashed(){return this._crashed}get pid(){return this._process?.pid??null}get remote(){return this._ownedProcess?.remote}get commandName(){return $e(this._command)}get diagnosticMode(){return this._diagnosticMode}setDiagnosticMode(e){this._diagnosticMode=e}get timeoutMs(){return this._timeoutMs}supportsCommand(e){let t=this._serverCapabilities?.executeCommandProvider;return Array.isArray(t?.commands)&&t.commands.includes(e)}get hasWorkspaceSymbolCapability(){let e=this._serverCapabilities?.workspaceSymbolProvider;return e===!0||typeof e=="object"&&e!==null}get hasFoldingRangeCapability(){let e=this._serverCapabilities?.foldingRangeProvider;return e===!0||typeof e=="object"&&e!==null}documentContent(e){return this._documentContents.get(e)}documentVersion(e){return this._documentVersions.get(e)}diagnosticPublication(e){return this._diagnosticPublications.get(e)}beginDiagnosticRequest(e){this._activeDiagnosticRequests.add(e)}endDiagnosticRequest(e){this._activeDiagnosticRequests.delete(e)}hasActiveDiagnosticRequest(e){return this._activeDiagnosticRequests.has(e)}async start(e){e?.throwIfAborted();try{await this._start(e)}catch(t){try{await this.shutdown()}catch(r){throw new AggregateError([e?.aborted?e.reason:t,r],`[lsp] ${this.serverId}: startup and cleanup failed`,{cause:r})}throw e?.throwIfAborted(),t}}async _start(e){if(this._initialized)return;if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(!this.rootUri.startsWith("file://")&&!this._ownerTransport)throw Object.assign(new Error("No language server process transport for this resource owner"),{code:"UNSUPPORTED_SOURCE"});if(await this._closeFileWatchers(),e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let t=_(this._command[0]),r=this._ownerTransport?decodeURIComponent(new URL(this.rootUri).pathname):ct.parse(this.rootUri).fsPath,o=[{uri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,name:Jt.basename(r)||r}];this._ownedStartup=this._ownerTransport?.start({rootUri:this.rootUri,command:this._command,env:this._env,signal:e});let s=await this._ownedStartup;if(this._ownedProcess=s??null,e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let i=s?void 0:Kt(t,this._args,{stdio:["pipe","pipe","pipe"],...e&&{signal:e},cwd:r,env:qe({command:this._command,env:this._env},r,process.env)});this._process=i??null;let l=i?Zt(i):Promise.resolve(),c=_(s?.stdin??i?.stdin),p=_(s?.stdout??i?.stdout),d=_(s?.stderr??i?.stderr);c.on("error",()=>{}),p.on("error",()=>{}),d.on("error",()=>{}),this._stderr="",d.setEncoding("utf8"),d.on("data",h=>{this._stderr=(this._stderr+h).slice(-4096)}),i?.on("error",h=>{("code"in h?h.code:void 0)!=="ENOENT"&&console.error(`[lsp] ${this.serverId}: spawn failed:`,h),this._crashed=!0,this._connection?.dispose(),this._connection=null,this._process=null});let g=a(h=>{(s?this._ownedProcess!==s:this._process!==i)||(this._closeFileWatchers(),!this._disposed&&h!==0&&h!==null&&(this._crashed=!0),this._connection?.dispose(),this._connection=null,this._diagnosticPublications.clear(),this._activeDiagnosticRequests.clear(),this._diagnosticMode="unknown",this._process=null,this._initialized=!1)},"onExit");i?.on("exit",g),s?.completion.then(({exitCode:h})=>g(h),()=>{this._ownedProcess===s&&(this._crashed=!0,g(null))}),await A(l,e);let u=Xt(new Yt(p),new oe(c,h=>{this._connection!==u||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),u.dispose(),console.error(`[lsp] ${this.serverId}: transport write failed:`,h))}));this._connection=u,this._connection.onError(h=>{console.error(`[lsp] ${this.serverId}: connection error:`,h)});let m=a(h=>{this._sendNotification("workspace/didChangeWatchedFiles",{changes:[h]})},"changed"),y=a(h=>console.error(`[lsp] ${this.serverId}: file watcher failed:`,h),"failed");this._fileWatchers=this._ownerTransport?this._ownerTransport.fileWatchers?.(this.rootUri,m,y):new ne(r,m,y),this._connection.onRequest("client/registerCapability",async h=>{for(let w of h.registrations)if(w.method!=="workspace/didChangeConfiguration"){if(w.method!=="workspace/didChangeWatchedFiles")throw new Error(`Unsupported dynamic capability: ${w.method}`);if(!this._fileWatchers)throw new Error("File watching is unavailable for this server owner");await this._fileWatchers.register(w.id,w.registerOptions?.watchers??[])}return null}),this._connection.onRequest("client/unregisterCapability",async h=>{for(let w of h.unregisterations)await this._fileWatchers?.unregister(w.id);return null}),this._connection.onRequest("window/workDoneProgress/create",()=>null),this._connection.onRequest("workspace/configuration",h=>h.items.map(w=>{let S=this._settings??null;for(let R of w.section?.split(".").filter(Boolean)??[])S=typeof S=="object"&&S!==null?S[R]??null:null;return S})),this._connection.listen(),this._connection.onNotification((h,...w)=>{let S=this._ownerTransport,R=S?j(w[0],v=>S.fromServerUri(v)):w[0];if(h==="textDocument/publishDiagnostics"){let v=R;v&&typeof v.uri=="string"&&Array.isArray(v.diagnostics)&&this._documentVersions.has(v.uri)&&(v.version===void 0||v.version===this.documentVersion(v.uri))&&this._diagnosticPublications.set(v.uri,{diagnostics:v.diagnostics,...typeof v.version=="number"&&{version:v.version}})}for(let v of this._handlers.get(h)??[])v(R)}),this._connection.onRequest("workspace/workspaceFolders",()=>o);let f=await A(lt(this._connection.sendRequest("initialize",{processId:this._ownerTransport?null:process.pid,rootUri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,workspaceFolders:o,capabilities:{workspace:{applyEdit:!1,configuration:!0,workspaceFolders:!0,didChangeWatchedFiles:{dynamicRegistration:this._fileWatchers!==void 0,relativePatternSupport:this._fileWatchers!==void 0},symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0},publishDiagnostics:{relatedInformation:!0},diagnostic:{dynamicRegistration:!1,relatedDocumentSupport:!1},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},foldingRange:{lineFoldingOnly:!0}}},initializationOptions:this._initOptions}),this._timeoutMs,`[lsp] ${this.serverId}: initialize timed out`),e).catch(h=>{let w=this._stderr.trim();throw w?new Error(`[lsp] ${this.serverId}: ${w}`,{cause:h}):h});if(await this._connection.sendNotification("initialized",{capabilities:f.capabilities}),this._settings!==void 0&&await this._connection.sendNotification("workspace/didChangeConfiguration",{settings:this._settings}),this._crashed)throw new Error(`[lsp] ${this.serverId}: transport failed during initialization`);e?.throwIfAborted(),this._initialized=!0,this._serverCapabilities=f.capabilities,this._diagnosticMode=f.capabilities.diagnosticProvider?"pull":"push"}touch(){}async restart(e){await this.shutdown(),this._closeFileWatchers(),this._connection?.dispose(),this._connection=null,this._process=null,this._initialized=!1,this._crashed=!1,this._disposed=!1,this._shutdownPromise=void 0,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null,await this.start(e)}async sendRequest(e,t,r){this._assertReady(),r?.throwIfAborted();let o=this._ownerTransport,s=o?j(t,p=>o.toServerUri(p)):t,i=a(p=>o?j(p,d=>o.fromServerUri(d)):p,"mapResult");if(!r)return i(await _(this._connection).sendRequest(e,s));let l=new Qt,c;try{let p=_(this._connection).sendRequest(e,s,l.token);return i(await Promise.race([p,new Promise((d,g)=>{c=a(()=>{l.cancel(),g(r.reason)},"onAbort"),r.addEventListener("abort",c,{once:!0})})]))}finally{c&&r.removeEventListener("abort",c),l.dispose()}}sendNotification(e,t){this._assertReady(),this._sendNotification(e,t)}_sendNotification(e,t){let r=this._connection;if(!r)return;let o=this._ownerTransport,s=o?j(t,i=>o.toServerUri(i)):t;r.sendNotification(e,s).catch(i=>{this._connection!==r||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),r.dispose(),console.error(`[lsp] ${this.serverId}: notification ${e} failed:`,i))})}onNotification(e,t){let r=this._handlers.get(e)??[];return r.push(t),this._handlers.set(e,r),()=>{let o=r.indexOf(t);o!==-1&&r.splice(o,1)}}toUri(e){return k(e,this.rootUri)}serverDocumentPath(e){let t=this.toUri(e),r=this._ownerTransport?.toServerUri(t)??t;return this._ownerTransport?decodeURIComponent(new URL(r).pathname):ct.parse(r).fsPath}openDocument(e,t,r,o=1){let s=this._documentVersions.get(e);if(s!==void 0){this.changeDocument(e,t,Math.max(o,s+1));return}this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didOpen",{textDocument:{uri:e,languageId:r,version:o,text:t}}),this._documentVersions.set(e,o),this._documentContents.set(e,t)}syncDocument(e,t,r,o=!1){if(this._documentContents.get(e)===t)return;let s=this._documentVersions.get(e);s===void 0?this.openDocument(e,t,r):this.changeDocument(e,t,s+1);let i=this._serverCapabilities?.textDocumentSync,l=typeof i=="object"&&i!==null?i.save:void 0;o&&l&&this.sendNotification("textDocument/didSave",{textDocument:{uri:e},...typeof l=="object"&&l.includeText&&{text:t}})}changeDocument(e,t,r){let o=this._documentVersions.get(e),s=Math.max(r,(o??0)+1);this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didChange",{textDocument:{uri:e,version:s},contentChanges:[{text:t}]}),this._documentVersions.set(e,s),this._documentContents.set(e,t)}closeDocument(e){this.sendNotification("textDocument/didClose",{textDocument:{uri:e}}),this._documentVersions.delete(e),this._documentContents.delete(e),this._diagnosticPublications.delete(e)}shutdown(){return this._shutdownPromise??=this._shutdown()}async _shutdown(){this._disposed=!0;let e=this._closeFileWatchers();if(this._connection&&this._initialized)try{await lt(this._connection.sendRequest("shutdown"),Math.min(this._timeoutMs,1e3),`[lsp] ${this.serverId}: shutdown timed out`),await this._connection.sendNotification("exit").catch(()=>{})}catch{}this._connection?.dispose(),this._connection=null;let t=this._ownedProcess??await this._ownedStartup?.catch(()=>{});this._ownedProcess=null,this._ownedStartup=void 0;let r=Promise.resolve().then(()=>t?.stop()),o=this._process;this._process=null,o&&!o.killed&&(o.kill("SIGTERM"),setTimeout(()=>{o.exitCode===null&&o.signalCode===null&&o.kill("SIGKILL")},2e3).unref()),this._initialized=!1,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null;let s=await Promise.allSettled([r,e]),i=[];for(let l of s)l.status==="rejected"&&i.push(l.reason);if(i.length>0)throw new AggregateError(i,`[lsp] ${this.serverId}: owned cleanup failed`)}dispose(){return this.shutdown()}_closeFileWatchers(){let e=this._fileWatchers;return this._fileWatchers=void 0,e&&(this._fileWatcherCleanup=this._fileWatcherCleanup.catch(()=>{}).then(()=>e.dispose()),this._fileWatcherCleanup.catch(t=>{console.error(`[lsp] ${this.serverId}: file watcher cleanup failed:`,t)})),this._fileWatcherCleanup}_assertReady(){if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(this._crashed)throw new Error(`[lsp] ${this.serverId}: crashed \u2014 call restart()`);if(!this._initialized)throw new Error(`[lsp] ${this.serverId}: not started \u2014 call start()`);if(!this._connection)throw new Error(`[lsp] ${this.serverId}: connection lost`)}};function Zt(n){return new Promise((e,t)=>{let r=a(()=>{n.off("spawn",o),n.off("error",s)},"cleanup"),o=a(()=>{r(),e()},"onSpawn"),s=a(i=>{r(),t(i)},"onError");n.once("spawn",o),n.once("error",s)})}a(Zt,"waitForSpawn");function lt(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t))},e);n.then(i=>{clearTimeout(s),r(i)}).catch(i=>{clearTimeout(s),o(i instanceof Error?i:new Error(String(i)))})})}a(lt,"withTimeout");import{readFile as pt}from"node:fs/promises";import{URI as ut}from"vscode-uri";var K={Error:1,Warning:2,Information:3,Hint:4};var dt={command:"typescript.tsserverRequest",async request(n,e,t){return(await Promise.all(["syntacticDiagnosticsSync","semanticDiagnosticsSync","suggestionDiagnosticsSync"].map(async o=>{let s=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:[o,{file:n.serverDocumentPath(e),includeLinePosition:!0},{isAsync:!1,expectsResult:!0}]},t);if(!de(s)||s.success!==!0||!Array.isArray(s.body))throw new Error(`Invalid completed TypeScript diagnostic report: ${o}`);return s.body.map(er)}))).flat()}};function se(n){return n.supportsCommand(dt.command)?dt:void 0}a(se,"completedDiagnosticAdapter");function er(n){if(!de(n)||typeof n.message!="string"||typeof n.code!="number"&&typeof n.code!="string"||!de(n.startLocation)||!Number.isInteger(n.startLocation.line)||!Number.isInteger(n.startLocation.offset)||Number(n.startLocation.line)<1||Number(n.startLocation.offset)<1||!["error","warning","suggestion","message"].includes(String(n.category)))throw new Error("Invalid TypeScript diagnostic entry");return{code:String(n.code),message:n.message,line:Number(n.startLocation.line),column:Number(n.startLocation.offset),severity:n.category==="error"?"error":n.category==="warning"?"warning":n.category==="suggestion"?"hint":"info"}}a(er,"convertTypeScriptDiagnostic");function de(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}a(de,"isRecord");async function X(n,e,t,r={}){let o=new AbortController,s=AbortSignal.any([o.signal,...r.signal?[r.signal]:[]]),i=setTimeout(()=>o.abort(new Error(`[lsp] ${n.serverId}: diagnostics timed out for ${e}`)),n.timeoutMs);try{return await tr(n,e,t,r.content,s)}finally{clearTimeout(i)}}a(X,"requestDiagnostics");async function tr(n,e,t,r,o){if(o.throwIfAborted(),n.diagnosticMode!=="push"){let c=n.documentVersion(e);try{let p=await n.sendRequest("textDocument/diagnostic",{textDocument:{uri:e}},o);if(p.kind!=="full"||!Array.isArray(p.items))throw new Error("Invalid full diagnostic report");if(n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return n.setDiagnosticMode("pull"),gt(p.items,!1,!0)}catch(p){if(!rr(p))throw p;n.setDiagnosticMode("push")}}let s=se(n);if(s){n.documentVersion(e)===void 0&&n.syncDocument(e,r??await pt(ut.parse(e).fsPath,"utf8"),t??"plaintext");let c=n.documentVersion(e),p=await s.request(n,e,o);if(o.throwIfAborted(),n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return{diagnostics:p,syntaxErrors:[],otherDiagnostics:p,unversioned:!1,complete:!0}}o.throwIfAborted();let i=n.documentVersion(e)!==void 0,l=i?void 0:r??await pt(ut.parse(e).fsPath,"utf8");o.throwIfAborted(),n.beginDiagnosticRequest(e);try{return await new Promise((c,p)=>{let d=n.documentVersion(e)??1,g=a(f=>{let h=f;h.uri!==e||!Array.isArray(h.diagnostics)||h.version!==void 0&&h.version!==d||n.documentVersion(e)===d&&(y(),c(gt(h.diagnostics,h.version===void 0)))},"receive"),u=n.onNotification("textDocument/publishDiagnostics",g),m=a(()=>{y(),p(o.reason)},"onAbort");function y(){u(),o.removeEventListener("abort",m)}a(y,"cleanup"),o.addEventListener("abort",m,{once:!0});try{i||n.syncDocument(e,l??"",t??"plaintext");let f=n.diagnosticPublication(e);f&&g({uri:e,...f})}catch(f){y(),p(f)}})}finally{n.endDiagnosticRequest(e)}}a(tr,"requestCurrentDiagnostics");function pe(n){return{code:String(n.code??"LSP"),message:n.message,line:n.range.start.line+1,column:n.range.start.character+1,severity:n.severity===K.Warning?"warning":n.severity===K.Information?"info":n.severity===K.Hint?"hint":"error"}}a(pe,"toDiagnostic");function gt(n,e,t=!1){let r=n.map(pe);return{diagnostics:r,syntaxErrors:[],otherDiagnostics:r,unversioned:e,complete:t}}a(gt,"classify");function rr(n){return n!==null&&typeof n=="object"&&"code"in n&&n.code===-32601}a(rr,"isMethodNotFound");var nr={1:"File",2:"Module",3:"Namespace",4:"Package",5:"Class",6:"Method",7:"Property",8:"Field",9:"Constructor",10:"Enum",11:"Interface",12:"Function",13:"Variable",14:"Constant",15:"String",16:"Number",17:"Boolean",18:"Array",19:"Object",20:"Key",21:"Null",22:"EnumMember",23:"Struct",24:"Event",25:"Operator",26:"TypeParameter"};function T(n){return nr[n]??`SymbolKind(${n})`}a(T,"symbolKindName");async function Q(n,e,t){return await n.sendRequest("textDocument/documentSymbol",{textDocument:{uri:e}},t)??[]}a(Q,"requestDocumentSymbols");async function ue(n,e,t=100,r){return(await n.sendRequest("workspace/symbol",{query:e},r)??[]).slice(0,t)}a(ue,"requestWorkspaceSymbols");async function ie(n,e,t,r){return await n.sendRequest("textDocument/rename",{textDocument:{uri:e},position:t,newName:r})}a(ie,"requestRename");import Z from"node:path";import{URI as ar}from"vscode-uri";import{createHash as or}from"node:crypto";import{readdir as sr,stat as ae}from"node:fs/promises";import O from"node:path";import{URI as me}from"vscode-uri";async function ge(n,e){if(!n.supportsCommand("typescript.tsserverRequest"))return;if((await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:e,needFileNameList:!0},{isAsync:!1,expectsResult:!0}]}))?.success!==!0)throw new Error("TypeScript could not load the project for a workspace query.")}a(ge,"prepareProjectQuery");function mt(n,e){let t=a(r=>typeof r=="string"?r.replaceAll("{project}",()=>e):Array.isArray(r)?r.map(t):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([o,s])=>[o,t(s)])):r,"expand");return Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)]))}a(mt,"resolveInitializationOptions");var W=class n{constructor(e,t){this._registry=e;this._owner=t}static{a(this,"LspManager")}_clients=new Map;_clientStarts=new Map;_openDocs=new Set;_pushUnsubscribers=new Map;_pushHandlers=new Set;_pushFingerprints=new Map;_disposed=!1;static _instance=null;static getInstance(){if(!n._instance)throw new Error("[lsp] LspManager not initialized");return n._instance}static getInstanceOrNull(){return n._instance}static init(e,t){let r=n._instance;return r?._disposed?(r._registry=e,r._owner=t,r._disposed=!1,r):(n._instance=new n(e,t),n._instance)}static async resetForTest(){n._instance&&(await n._instance.shutdownAll(),n._instance=null)}requireOwner(){if(!this._owner)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});return this._owner}get workspaceRoot(){return this._registry.projectRoot}get clientCount(){return this._clients.size}onPushDiagnostics(e){return this._pushHandlers.add(e),()=>this._pushHandlers.delete(e)}async getOrStart(e,t,r,o){if(o?.throwIfAborted(),this._disposed)return null;let s=t.startsWith("ssh://"),i=s?this.requireOwner():void 0,l=i?await this._registry.resolveOwned(e,f=>i.exists(f,o)):this._registry.resolve(e);if(o?.throwIfAborted(),this._disposed)return null;let c=r==="symbols"?l[0]:l.find(f=>f.config.capabilities.includes(r));if(!c)return null;let p=s?t:me.file(t).toString(),d=`${c.serverId}:${p}`,g=this._clientStarts.get(d);if(g)return g.controller.signal.aborted?(await A(g.promise.catch(()=>{}),o),this.getOrStart(e,t,r,o)):g.wait(o);let u=this._clients.get(d);if(u?.ready)return u;let m=new H(f=>this._startClient(d,p,c,u,f));this._clientStarts.set(d,m);let y=a(()=>{this._clientStarts.get(d)===m&&this._clientStarts.delete(d)},"settled");return m.promise.then(y,y),m.wait(o)}async _startClient(e,t,r,o,s){let i=o??new $({serverId:r.serverId,rootUri:t,command:r.config.command,...t.startsWith("ssh://")&&this._owner&&{ownerTransport:this._owner.transport(t)},...r.config.env&&{env:r.config.env},...r.config.initializationOptions&&{initOptions:mt(r.config.initializationOptions,t.startsWith("ssh://")?decodeURIComponent(new URL(t).pathname):me.parse(t).fsPath)},...r.config.settings&&{settings:r.config.settings},...r.config.timeoutMs&&{timeoutMs:r.config.timeoutMs}});try{o?await o.restart(s):await i.start(s),s.throwIfAborted()}catch(l){try{await i.shutdown()}catch(c){if(c!==l)throw new AggregateError([l,c],"Language server startup and cleanup failed",{cause:c})}throw l}if(this._disposed)throw await i.shutdown(),new Error(`[lsp] ${r.serverId}: manager disposed during startup`);return this._clients.set(e,i),this._subscribeToPushDiagnostics(e,i),i}async isSourceFile(e,t,r){if(r?.throwIfAborted(),t.startsWith("ssh://")){if(this._owner===void 0)throw new Error("No language server workspace owner");return this._owner.isFile(k(e,t),r)}let o=await ae(O.resolve(t,e));return r?.throwIfAborted(),o.isFile()}async getWorkspaceClients(e,t="symbols",r=e,o=()=>!0,s){if(s?.throwIfAborted(),e.startsWith("ssh://")){let g=this._owner;if(!g)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});let u=new Set,m=new Set(this._registry.knownExtensions),y=new Set([".git",".cache","node_modules","dist","build"]),f=a(async w=>{if(s?.throwIfAborted(),m.size!==0)for(let S of await g.entries(w,s)){s?.throwIfAborted();let R=k(S.name,`${w}/`);if(S.kind==="directory")y.has(S.name)||await f(R);else if(S.kind==="file"){let v=O.posix.extname(S.name).toLowerCase();if(!m.has(v)||!o(R))continue;let D=await this.openFile(R,e,t,s);D&&(u.add(D.client),m.delete(v))}}},"visit"),h=k(r,e);if(await g.isFile(h,s)){if(!o(h))return[];let w=await this.openFile(h,e,t,s);return w?[w.client]:[]}return await f(h),[...u]}let i=new Set,l=new Set(this._registry.knownExtensions),c=new Set([".git",".cache","node_modules","dist","build"]),p=a(async g=>{if(s?.throwIfAborted(),l.size===0)return;let u;try{u=await sr(g,{withFileTypes:!0})}catch{return}for(let m of u){if(s?.throwIfAborted(),l.size===0)return;if(m.isDirectory()){c.has(m.name)||await p(O.join(g,m.name));continue}if(!m.isFile())continue;let y=O.extname(m.name).toLowerCase();if(!l.has(y))continue;let f=O.join(g,m.name);if(!o(f))continue;let h=await this.openFile(f,e,t,s);h&&(l.delete(y),h.client.hasWorkspaceSymbolCapability&&(await ge(h.client,f),i.add(h.client)))}},"visit"),d=O.resolve(e,r);if((await ae(d)).isFile()){if(!o(d))return[];let g=await this.openFile(d,e,t,s);return g===null||!g.client.hasWorkspaceSymbolCapability?[]:(await ge(g.client,d),[g.client])}return await p(d),s?.throwIfAborted(),[...i]}async prepareWorkspaceSymbols(e,t=e,r,o){return this.getWorkspaceClients(e,"symbols",t,r,o)}hasServerFor(e){return this._registry.resolve(e).length>0}languageId(e){return this._registry.languageId(e)}isOpen(e){return this._openDocs.has(e)}syncEditedSource(e,t){for(let r of this._clients.values()){if(!r.ready)continue;let o=r.toUri(e);if(r.documentContent(o)===void 0)continue;let s=this.languageId(O.extname(decodeURIComponent(new URL(o).pathname)));r.syncDocument(o,t,s,!0)}}async readSourceSnapshot(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readSnapshot(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported rename source"),{code:"UNSUPPORTED_SOURCE"});let r=a(i=>`${i.dev}:${i.ino}:${i.mode}:${i.size}:${i.mtimeMs}:${i.ctimeMs}`,"identity"),o=r(await ae(e)),s=await this.readSourceText(e,t);if(o!==r(await ae(e)))throw new Error("A rename source changed while reading it. No edits applied.");return{content:s,version:or("sha256").update(o).update("\0").update(s).digest("hex")}}async readSourceBytes(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readBytes(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{signal:t})}async readSourceText(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readText(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{encoding:"utf8",signal:t})}async openFile(e,t,r="diagnostics",o){if(o?.throwIfAborted(),e.startsWith("ssh://")&&!t.startsWith("ssh://")){if(!this._registry.projectRoot.startsWith("ssh://"))throw Object.assign(new Error("Remote document has no workspace owner"),{code:"UNSUPPORTED_SOURCE"});t=this._registry.projectRoot}let s=t.startsWith("ssh://"),i=s?k(e,t):O.resolve(t,e),l=await this.getOrStart(i,t,r,o);if(!l)return null;let c=l.toUri(i),p=s?this.requireOwner():void 0,g=(p?await this._registry.resolveOwned(i,u=>p.exists(u,o)):this._registry.resolve(i))[0]?.languageId??"plaintext";if(p){let u=await p.readText(c,o);return o?.throwIfAborted(),l.syncDocument(c,u,g),this._openDocs.add(c),{client:l,uri:c,languageId:g}}try{let{readFile:u}=await import("node:fs/promises"),m=await u(i,{encoding:"utf8",signal:o});o?.throwIfAborted(),l.syncDocument(c,m,g),this._openDocs.add(c)}catch(u){if(o?.throwIfAborted(),!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}return{client:l,uri:c,languageId:g}}_subscribeToPushDiagnostics(e,t){if(this._pushUnsubscribers.has(e))return;let r=t.onNotification("textDocument/publishDiagnostics",o=>{let s=ir(o);if(!s||t.hasActiveDiagnosticRequest(s.uri))return;let i=t.documentVersion(s.uri);if(s.version!==void 0&&i!==void 0&&s.version<i)return;let l=`${e}:${s.uri}`,c=s.diagnostics.map(pe),p=JSON.stringify([s.version,i,c]);if(this._pushFingerprints.get(l)===p)return;this._pushFingerprints.set(l,p);let d={cwd:t.rootUri.startsWith("ssh://")?t.rootUri:me.parse(t.rootUri).fsPath,serverId:t.serverId,uri:s.uri,diagnostics:c,...s.version!==void 0&&{version:s.version}};for(let g of this._pushHandlers)g(d)});this._pushUnsubscribers.set(e,r)}async shutdownAll(){this._disposed=!0;let e=[...this._clientStarts.values()];for(let i of e)i.controller.abort(new Error("Language server manager stopped"));let t=await Promise.allSettled(e.map(i=>i.promise)),r=[];for(let[i,l]of t.entries())l.status==="rejected"&&l.reason!==e[i]?.controller.signal.reason&&r.push(l.reason);let o=[...this._clients.values()],s=await Promise.allSettled(o.map(i=>i.shutdown()));for(let i of this._pushUnsubscribers.values())i();this._pushUnsubscribers.clear(),this._clientStarts.clear(),this._pushFingerprints.clear(),this._pushHandlers.clear(),this._clients.clear();for(let i of s)i.status==="rejected"&&r.push(i.reason);if(r.length>0)throw new AggregateError(r,"Language server cleanup failed")}dispose(){return this.shutdownAll()}};function ir(n){if(n===null||typeof n!="object")return;let e=n;if(!(typeof e.uri!="string"||!Array.isArray(e.diagnostics)))return{uri:e.uri,diagnostics:e.diagnostics,...typeof e.version=="number"&&{version:e.version}}}a(ir,"parsePushNotification");async function fe(n,e,t){if(t?.throwIfAborted(),!n.supportsCommand("typescript.tsserverRequest"))return;let r=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:n.serverDocumentPath(e),needFileNameList:!0},{isAsync:!1,expectsResult:!0}]},t);if(t?.throwIfAborted(),r?.success!==!0)throw new Error("TypeScript could not load the project for the workspace query.")}a(fe,"loadQueryProject");async function Y(n,e,t,r){return await fe(n,e,r),await n.sendRequest("textDocument/references",{textDocument:{uri:e},position:t,context:{includeDeclaration:!0}},r)??[]}a(Y,"requestReferences");async function he(n,e,t,r){let o=await n.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:e},position:t},r),s=o?.[0];if(!s)return{items:[],incoming:[],outgoing:[]};let[i,l]=await Promise.all([n.sendRequest("callHierarchy/incomingCalls",{item:s},r),n.sendRequest("callHierarchy/outgoingCalls",{item:s},r)]);return{items:o,incoming:i??[],outgoing:l??[]}}a(he,"requestCallHierarchy");function G(n,e,t){let r=e.startsWith("ssh://"),o=r?Z.posix:Z,s=a(d=>r?decodeURIComponent(new URL(k(d,e)).pathname):d,"native"),i=r?s(t.path??e):Z.resolve(e,t.path??"."),l=o.relative(i,s(n));if(l===".."||l.startsWith(`..${o.sep}`)||o.isAbsolute(l))return!1;let c=o.relative(s(e),s(n)).split(o.sep).join("/"),p=a(d=>d.split(",").some(g=>{let u=g.trim();return u.length>0&&o.matchesGlob(u.includes("/")?c:o.basename(s(n)),u)}),"matches");return(t.include===void 0||p(t.include))&&(t.exclude===void 0||!p(t.exclude))}a(G,"withinScope");function ye(n,e){let t=k(n,e);if(t.startsWith("ssh://"))return t;let r=ar.parse(t);if(r.scheme!=="file")throw new Error("Unsupported LSP source location.");return Z.resolve(r.fsPath)}a(ye,"sourceOf");function cr(n,e){return n.start.line===e.start.line&&n.start.character===e.start.character&&n.end.line===e.end.line&&n.end.character===e.end.character}a(cr,"sameRange");function ft(n,e,t){return n.flatMap(r=>[...r.name===e&&r.range!==void 0&&cr(r.range,t)&&r.selectionRange!==void 0?[r.selectionRange]:[],...ft(r.children??[],e,t)])}a(ft,"declarationNames");async function we(n,e,t,r,o={},s=W.getInstance()){r?.throwIfAborted();let i=o.resultScope;if(i!==void 0&&(await F(i,r),i.targets.length===0))return{hits:[],complete:i.complete};if(i===void 0&&o.path!==void 0&&!G(e.startsWith("ssh://")?k(o.path,e):Z.resolve(e,o.path),e,o)&&await s.isSourceFile(o.path,e,r))return{hits:[],complete:!0};let l=i?.targets.map(y=>y.source)??[o.path??e],c=new Set((await Promise.all(l.map(y=>s.prepareWorkspaceSymbols(e,y,f=>G(f,e,o),r)))).flat());if(c.size===0)throw new Error("LSP symbol search is unavailable: no provider supports workspace/symbol in this scope.");let p=new Map,d=a(async y=>{r?.throwIfAborted();let f=ye(y.uri,e),h=p.get(f);if(h===void 0){let{content:L,version:N}=await s.readSourceSnapshot(f,r);h={document:Ee(f,L),version:N},p.set(f,h)}let{document:w}=h,{start:S,end:R}=y.range,v=[S,R];for(let L of v){let N=w.lines[L.line];if(!Number.isInteger(L.line)||!Number.isInteger(L.character)||N===void 0||L.character<0||L.character>N.content.length)throw new Error("LSP range does not match its source snapshot.")}let D=_(w.lines[S.line]),re=a(L=>w.lines.slice(0,L).reduce((N,xe)=>N+xe.content.length+xe.lineEnding.length,0),"offset"),U=re(S.line)+S.character,C=re(R.line)+R.character;if(C<U)throw new Error("LSP returned a reversed source range.");return{source:f,lineNumber:S.line+1,endLineNumber:R.line+1,startColumn:S.character,endColumn:R.character,matchedText:w.content.slice(U,C),lineText:D.content}},"toMatch"),g=a(y=>G(y.source,e,o)&&(i===void 0||st(i,y)),"included"),u=[],m=new Set;for(let y of c){r?.throwIfAborted();let f=await ue(y,n,Number.MAX_SAFE_INTEGER,r);for(let h of f){if(r?.throwIfAborted(),!G(ye(h.location.uri,e),e,{}))continue;let w=await d(h.location),S=await s.openFile(w.source,e,"symbols",r);if(S===null)throw new Error("LSP references are unavailable for a discovered declaration.");let R=h.location;if(w.matchedText!==h.name){let C=await Q(S.client,S.uri,r),L=ft(C,h.name,h.location.range);if(L.length!==1)throw new Error("LSP declaration has no unique provider selectionRange; cannot search its references.");R={uri:S.uri,range:_(L[0])}}let v=await d(R),D={id:JSON.stringify([y.serverId,v.source,h.location.range]),name:h.name,kind:String(h.kind),source:v.source,range:{startLine:v.lineNumber,startColumn:v.startColumn,endLine:v.endLineNumber??v.lineNumber,endColumn:v.endColumn}},re=await Y(S.client,S.uri,R.range.start,r);r?.throwIfAborted();let U=[{...v,role:"definition",symbol:D}];for(let C of re){if(!G(ye(C.uri,e),e,{}))continue;let L=await d(C);L.source===v.source&&L.lineNumber===v.lineNumber&&L.startColumn===v.startColumn&&L.endLineNumber===v.endLineNumber&&L.endColumn===v.endColumn||U.push({...L,role:"reference",symbol:D})}if(!(o.navigation==="references"&&!U.some(g)))for(let C of U){if(o.navigation!=="references"&&!g(C)||o.navigation==="references"&&!G(C.source,e,{}))continue;let L=JSON.stringify([D.id,C.source,C.lineNumber,C.startColumn,C.endLineNumber,C.endColumn]);m.has(L)||(m.add(L),u.push(C))}}}r?.throwIfAborted();for(let[y,f]of p){let h=await s.readSourceSnapshot(y,r);if(h.version!==f.version||h.content!==f.document.content)throw new Error("LSP source changed during search.")}return i!==void 0&&await F(i,r),u.sort((y,f)=>y.source.localeCompare(f.source)||y.lineNumber-f.lineNumber||y.startColumn-f.startColumn||y.endColumn-f.endColumn||y.symbol.id.localeCompare(f.symbol.id)),{hits:u.slice(0,t),complete:(i?.complete??!0)&&u.length<=t}}a(we,"searchSymbols");import{readFile as lr}from"node:fs/promises";import ve from"node:path";import{fileURLToPath as dr}from"node:url";var pr={failureLabel:"SYMBOL_READ_FAILED",emptyReason:"no symbol source was produced."},be=10,Se=5,B=10;async function yt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath),c=await n.readSourceText(i.filePath,o);if(x(o),s!==c)throw new Error("The symbol source changed during resolution. Read it again before editing.");return{source:i.filePath,range:l.range,content:c}}a(yt,"resolveLspDeclaration");async function wt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath);if(s!==await n.readSourceText(e,o))throw new Error("The rename source changed during resolution.");return x(o),{client:i.client,uri:i.uri,position:l.selectionRange.start,content:s}}a(wt,"resolveLspRenameTarget");async function Pe(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await yr(s.filePath,n,o);x(o);let c=i.range.start.line+1,p=Math.min(i.range.end.line+1,l.lines.length),d=l.lines.slice(Math.max(0,c-1),Math.max(0,p)).map((u,m)=>{let y=c+m;return Ie({content:u,sourceLine:{source:s.filePath,lineNumber:y,content:u}})}),g={path:s.displayPath,heading:`symbol: ${M(i.selector)}`,details:[`defined in: ${s.displayPath}:${c}-${p} (${T(i.kind)})`],startLine:c,endLine:p,totalLines:l.lines.length,renderedLines:d};return De([g],pr)}a(Pe,"readLspSymbolBody");async function _e(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await Lt(s,i,o),c=new ce(r);return await ur(s,i,l,c)}a(_e,"readLspSymbolGraph");async function Ce(n,e,t,r){x(r);let o=await te(n,e,t,r),s=new ce(t),i=[`## file graph: ${o.displayPath}`,`Top-level declarations: ${o.symbols.length}`];for(let l of o.symbols){x(r);let c=await Lt(o,l,r);i.push("",...await hr(o,l,c,s))}return i.join(`
1
+ import{a as nt}from"./chunk-47SPPIXK.js";import{a as ot,b as st}from"./chunk-4DIUPEDF.js";import{a as tt,b as rt}from"./chunk-VAXLSPPU.js";import{e as it}from"./chunk-I6NPILT5.js";import{a as ze,c as He}from"./chunk-TOYN4W4F.js";import{a as Ge}from"./chunk-YJ6T3PEP.js";import{b as Fe,c as Ve}from"./chunk-S72FVLUX.js";import{a as et}from"./chunk-XXLLY66B.js";import{c as Qe,d as Ye,f as Ze}from"./chunk-235QMMVA.js";import{d as Xe}from"./chunk-IICJXZBU.js";import{a as Ke}from"./chunk-BU7IZLKB.js";import{a as Be,b as Je}from"./chunk-S5PL5DFQ.js";import{J as F}from"./chunk-LCWBVOII.js";import{f as Ie,g as De,h as Ae}from"./chunk-DUUOCBS3.js";import{a as q,b as E,c as J,d as M}from"./chunk-T4FTT3U4.js";import{m as Ee}from"./chunk-ZPT5D4VP.js";import{a as Oe}from"./chunk-ZAWRSA7N.js";import{a as je,b as Te}from"./chunk-OFILFO6D.js";import{b as $e,c as We,g as Ue,j as Ne,p as qe}from"./chunk-IMGIDBCC.js";import{a as Me}from"./chunk-BXGMMZT3.js";import{a as _}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Dr from"node:path";var V=[{id:"vue-typescript-language-server",name:"vue-typescript-language-server",kind:"lsp",languages:["vue"],executables:["typescript-language-server"],dependencies:["typescript-language-server","@vue/typescript-plugin"],configFiles:["tsconfig.json"],documentation:"https://github.com/vuejs/language-tools/tree/master/packages/typescript-plugin",lsp:{command:["typescript-language-server","--stdio"],rootMarkers:["tsconfig.json","package.json"],languageIds:{vue:[".vue"]},initializationOptions:{plugins:[{name:"@vue/typescript-plugin",location:"{project}/node_modules/@vue/typescript-plugin",languages:["vue"]}]}}},b("elixir-ls",["elixir"],["elixir-ls"],["mix.exs"],{elixir:[".ex",".exs"]},["elixir-ls"],"https://github.com/elixir-lsp/elixir-ls",void 0,void 0,{elixirLS:{mcpEnabled:!1}}),b("metals",["scala"],["metals"],["build.sbt","project.scala",".bsp"],{scala:[".scala",".sc"]},["metals"],"https://scalameta.org/metals/"),{id:"angular-language-server",name:"angular-language-server",kind:"lsp",languages:["typescript","html"],executables:["ngserver"],dependencies:["@angular/language-server"],configFiles:["angular.json"],documentation:"https://github.com/angular/vscode-ng-language-service",lsp:{command:["ngserver","--stdio","--tsProbeLocations",".","--ngProbeLocations","."],rootMarkers:["angular.json"],requireRootMarker:!0,languageIds:{typescript:[".ts"],html:[".html"]}}},b("svelte-language-server",["svelte"],["svelteserver"],["svelte.config.js","package.json"],{svelte:[".svelte"]},["svelteserver","--stdio"],"https://github.com/sveltejs/language-tools/tree/master/packages/language-server",["svelte-language-server"]),b("dart-language-server",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],{dart:[".dart"]},["dart","language-server","--protocol=lsp"],"https://dart.dev/tools/dart-language-server"),b("r-language-server",["r"],["Rscript"],["DESCRIPTION",".lintr",".Rprofile"],{r:[".r"]},["Rscript","-e","languageserver::run()"],"https://github.com/REditorSupport/languageserver"),b("zls",["zig"],["zls"],["build.zig","build.zig.zon","zls.json"],{zig:[".zig",".zon"]},["zls"],"https://zigtools.org/zls/"),b("clangd",["c","cpp"],["clangd"],[".clangd","compile_commands.json","CMakeLists.txt"],{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"]},["clangd"],"https://clangd.llvm.org/"),b("typescript-language-server",["javascript","typescript"],["typescript-language-server"],["tsconfig.json","jsconfig.json","package.json"],{javascript:[".js",".mjs",".cjs"],javascriptreact:[".jsx"],typescript:[".ts",".mts",".cts"],typescriptreact:[".tsx"]},["typescript-language-server","--stdio"],"https://github.com/typescript-language-server/typescript-language-server",["typescript-language-server"]),b("basedpyright",["python"],["basedpyright-langserver","pyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["basedpyright-langserver","--stdio"],"https://docs.basedpyright.com/",["basedpyright"]),b("gopls",["go"],["gopls"],["go.mod","go.work"],{go:[".go"]},["gopls"],"https://go.dev/gopls/"),b("rust-analyzer",["rust"],["rust-analyzer"],["Cargo.toml","rust-project.json"],{rust:[".rs"]},["rust-analyzer"],"https://rust-analyzer.github.io/"),b("csharp-ls",["csharp"],["csharp-ls"],[".sln",".csproj"],{csharp:[".cs"]},["csharp-ls"],"https://github.com/razzmatazz/csharp-language-server"),b("jdtls",["java"],["jdtls"],["pom.xml","build.gradle",".project"],{java:[".java"]},["jdtls"],"https://projects.eclipse.org/projects/eclipse.jdt.ls"),b("kotlin-language-server",["kotlin"],["kotlin-language-server"],["build.gradle.kts","pom.xml"],{kotlin:[".kt",".kts"]},["kotlin-language-server"],"https://github.com/fwcd/kotlin-language-server"),b("solargraph",["ruby"],["solargraph"],["Gemfile",".solargraph.yml"],{ruby:[".rb",".rake"]},["solargraph","stdio"],"https://solargraph.org/"),b("intelephense",["php"],["intelephense"],["composer.json"],{php:[".php"]},["intelephense","--stdio"],"https://intelephense.com/"),b("sourcekit-lsp",["swift"],["sourcekit-lsp"],["Package.swift"],{swift:[".swift"]},["sourcekit-lsp"],"https://github.com/swiftlang/sourcekit-lsp"),b("lua-language-server",["lua"],["lua-language-server"],[".luarc.json",".luarc.jsonc"],{lua:[".lua"]},["lua-language-server"],"https://luals.github.io/"),b("bash-language-server",["shell"],["bash-language-server"],[".shellcheckrc"],{shell:[".sh",".bash"]},["bash-language-server","start"],"https://github.com/bash-lsp/bash-language-server"),b("vscode-css-language-server",["css"],["vscode-css-language-server"],["package.json"],{css:[".css",".scss",".less"]},["vscode-css-language-server","--stdio"],"https://github.com/microsoft/vscode-css-languageservice",void 0,void 0,{css:{},scss:{},less:{}}),b("vscode-html-language-server",["html"],["vscode-html-language-server"],["package.json"],{html:[".html",".htm"]},["vscode-html-language-server","--stdio"],"https://github.com/microsoft/vscode-html-languageservice"),b("yaml-language-server",["yaml"],["yaml-language-server"],[".yamllint","package.json"],{yaml:[".yaml",".yml"]},["yaml-language-server","--stdio"],"https://github.com/redhat-developer/yaml-language-server"),b("taplo-lsp",["toml"],["taplo"],["taplo.toml"],{toml:[".toml"]},["taplo","lsp","stdio"],"https://taplo.tamasfe.dev/"),b("marksman",["markdown"],["marksman"],[".marksman.toml"],{markdown:[".md",".mdx"]},["marksman","server"],"https://github.com/artempyanykh/marksman"),b("terraform-ls",["terraform"],["terraform-ls"],[".terraform.lock.hcl"],{terraform:[".tf",".tfvars"]},["terraform-ls","serve"],"https://github.com/hashicorp/terraform-ls"),b("kotlin-lsp",["kotlin"],["intellij-server"],["build.gradle.kts","build.gradle","pom.xml","settings.gradle.kts"],{kotlin:[".kt",".kts"]},["intellij-server","--stdio"],"https://github.com/Kotlin/kotlin-lsp"),b("julia-language-server",["julia"],["julia"],["Project.toml","JuliaProject.toml"],{julia:[".jl"]},["julia","--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],"https://github.com/julia-vscode/LanguageServer.jl"),b("powershell-editor-services",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],{powershell:[".ps1",".psm1",".psd1"]},["pwsh","-NoProfile","-NonInteractive","-Command",'$ErrorActionPreference="Stop";Import-Module PowerShellEditorServices;$d=Join-Path (Get-Location) ".agents/tmp/powershell-lsp-$PID";[IO.Directory]::CreateDirectory($d)|Out-Null;Start-EditorServices -HostName Pi -HostProfileId Pi -HostVersion 1.0.0 -Stdio -LanguageServiceOnly -LogPath (Join-Path $d "server.log") -SessionDetailsPath (Join-Path $d "session.json")'],"https://github.com/PowerShell/PowerShellEditorServices"),b("neocmakelsp",["cmake"],["neocmakelsp"],["CMakeLists.txt",".neocmake.toml",".neocmakelint.toml"],{cmake:[".cmake"]},["neocmakelsp","stdio"],"https://github.com/neocmakelsp/neocmakelsp",void 0,{cmake:["CMakeLists.txt"]}),b("vscode-json-language-server",["json"],["vscode-json-language-server"],["package.json"],{json:[".json",".jsonc"]},["vscode-json-language-server","--stdio"],"https://github.com/microsoft/vscode-json-languageservice"),b("lemminx",["xml"],["lemminx"],[".lemminx.json"],{xml:[".xml",".xsd",".xsl"]},["lemminx"],"https://github.com/eclipse-lemminx/lemminx"),b("sqls",["sql"],["sqls"],[".sqls.yml"],{sql:[".sql"]},["sqls"],"https://github.com/sqls-server/sqls"),b("docker-langserver",["dockerfile"],["docker-langserver"],["Dockerfile"],{dockerfile:[".dockerfile"]},["docker-langserver","--stdio"],"https://github.com/rcjsuen/dockerfile-language-server-nodejs",void 0,{dockerfile:["Dockerfile","Containerfile"]})];function b(n,e,t,r,o,s,i,l,c,p){return{id:n,name:n,kind:"lsp",languages:e,executables:t,configFiles:r,documentation:i,...l&&{dependencies:l},lsp:{command:s,rootMarkers:r,languageIds:o,...c&&{fileNames:c},...p&&{settings:p}}}}a(b,"recipe");import Jt from"node:path";import Kt from"cross-spawn";import{createMessageConnection as Xt,CancellationTokenSource as Qt,StreamMessageReader as Yt}from"vscode-jsonrpc/node";import{URI as ct}from"vscode-uri";import{watch as Nt}from"node:fs";import{readdir as qt,stat as Ft}from"node:fs/promises";import z from"node:path";import{URI as le}from"vscode-uri";var ne=class{constructor(e,t,r){this.root=e;this.changed=t;this.failed=r}static{a(this,"LspFileWatchers")}registrations=new Map;disposed=!1;async register(e,t){let r=[];try{for(let o of t){let s=o.globPattern,i=typeof s=="string"?this.root:le.parse(typeof s.baseUri=="string"?s.baseUri:s.baseUri.uri).fsPath,l=typeof s=="string"?s:s.pattern,c=a(g=>z.matchesGlob(z.isAbsolute(l)?z.join(i,g):g,l),"matches"),p=new Set((await qt(i,{recursive:!0})).filter(c));if(this.disposed)throw new Error("Language server file watchers are disposed");let d=Nt(i,{recursive:!0},(g,u)=>{!u||!c(u)||Ft(z.join(i,u)).then(()=>{if(!this.registrations.get(e)?.includes(d))return;let m=p.has(u)?2:1;p.add(u),(o.kind??7)&(m===1?1:2)&&this.changed({uri:le.file(z.join(i,u)).toString(),type:m})},m=>{if(this.registrations.get(e)?.includes(d)){if(m.code!=="ENOENT"){this.failed(m);return}p.delete(u)&&(o.kind??7)&4&&this.changed({uri:le.file(z.join(i,u)).toString(),type:3})}})});d.on("error",this.failed),r.push(d)}}catch(o){for(let s of r)s.close();throw o}this.unregister(e),this.registrations.set(e,r)}unregister(e){for(let t of this.registrations.get(e)??[])t.close();this.registrations.delete(e)}dispose(){this.disposed=!0;for(let e of this.registrations.keys())this.unregister(e)}};import{StreamMessageWriter as Vt}from"vscode-jsonrpc/node";var oe=class extends Vt{constructor(t,r){super(t);this.fail=r}static{a(this,"TransportWriter")}async write(t){try{await super.write(t)}catch(r){this.fail(r)}}};import zt from"node:path";import{URI as Ht}from"vscode-uri";function k(n,e){if(e.startsWith("ssh://")){let t=at(e);if(n.includes("://")){let o=at(n);if(o.host!==t.host)throw new Error("Document belongs to another language server owner");return o.href}let r=zt.posix.resolve(decodeURIComponent(t.pathname),n);return t.pathname=r.split("/").map(encodeURIComponent).join("/"),t.href}if(n.startsWith("ssh://")||n.includes("://")&&!n.startsWith("file://"))throw new Error("Document belongs to another language server owner");return n.startsWith("file://")?n:Ht.file(n).toString()}a(k,"documentUri");function at(n){let e=new URL(n);if(e.protocol!=="ssh:"||!e.hostname||e.username||e.password||e.port||e.search||e.hash)throw new Error("Invalid language server resource owner");return decodeURIComponent(e.pathname),e}a(at,"checkedRemote");async function A(n,e){if(e?.aborted)throw n.catch(()=>{}),e.reason;if(!e)return n;let t;try{return await Promise.race([n,new Promise((r,o)=>{t=a(()=>o(e.reason),"onAbort"),e.addEventListener("abort",t,{once:!0})})])}finally{t&&e.removeEventListener("abort",t)}}a(A,"waitWithSignal");var H=class{static{a(this,"SharedStartup")}controller=new AbortController;promise;settled=!1;waiters=0;constructor(e){this.promise=e(this.controller.signal);let t=a(()=>{this.settled=!0},"settled");this.promise.then(t,t)}async wait(e){this.waiters+=1;let t=await A(this.promise,e).then(r=>({value:r}),r=>({error:r}));if(this.waiters-=1,!this.settled&&this.waiters===0){this.controller.abort(e?.reason);try{await this.promise}catch(r){if(r!==this.controller.signal.reason)throw new AggregateError([this.controller.signal.reason,r],"Startup cancellation and cleanup failed",{cause:r})}}if("error"in t)throw t.error;return t.value}};var Gt=new Set(["uri","targetUri","target","oldUri","newUri","rootUri","documentUri","scopeUri","baseUri"]),Bt=new Set(["changes","relatedDocuments"]);function j(n,e){return Array.isArray(n)?n.map(t=>j(t,e)):typeof n!="object"||n===null?n:Object.fromEntries(Object.entries(n).map(([t,r])=>Gt.has(t)&&typeof r=="string"?[t,e(r)]:Bt.has(t)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?[t,Object.fromEntries(Object.entries(r).map(([o,s])=>[e(o),j(s,e)]))]:[t,j(r,e)]))}a(j,"mapLspUris");var $=class{static{a(this,"LspClient")}_process=null;_ownedProcess=null;_ownedStartup;_ownerTransport;_connection=null;_initialized=!1;_serverCapabilities=null;_disposed=!1;_shutdownPromise;_crashed=!1;_stderr="";_fileWatchers;_fileWatcherCleanup=Promise.resolve();_handlers=new Map;_documentVersions=new Map;_documentContents=new Map;_diagnosticPublications=new Map;_diagnosticMode="unknown";_activeDiagnosticRequests=new Set;serverId;rootUri;_command;_args;_env;_initOptions;_settings;_timeoutMs;constructor(e){this.serverId=e.serverId,this.rootUri=e.rootUri,this._command=e.command,this._args=e.command.slice(1),this._env=e.env??{},this._initOptions=e.initOptions,this._settings=e.settings,this._timeoutMs=e.timeoutMs??3e4,this._ownerTransport=e.ownerTransport}get ready(){return this._initialized&&!this._disposed}get crashed(){return this._crashed}get pid(){return this._process?.pid??null}get remote(){return this._ownedProcess?.remote}get commandName(){return $e(this._command)}get diagnosticMode(){return this._diagnosticMode}setDiagnosticMode(e){this._diagnosticMode=e}get timeoutMs(){return this._timeoutMs}supportsCommand(e){let t=this._serverCapabilities?.executeCommandProvider;return Array.isArray(t?.commands)&&t.commands.includes(e)}get hasWorkspaceSymbolCapability(){let e=this._serverCapabilities?.workspaceSymbolProvider;return e===!0||typeof e=="object"&&e!==null}get hasFoldingRangeCapability(){let e=this._serverCapabilities?.foldingRangeProvider;return e===!0||typeof e=="object"&&e!==null}documentContent(e){return this._documentContents.get(e)}documentVersion(e){return this._documentVersions.get(e)}diagnosticPublication(e){return this._diagnosticPublications.get(e)}beginDiagnosticRequest(e){this._activeDiagnosticRequests.add(e)}endDiagnosticRequest(e){this._activeDiagnosticRequests.delete(e)}hasActiveDiagnosticRequest(e){return this._activeDiagnosticRequests.has(e)}async start(e){e?.throwIfAborted();try{await this._start(e)}catch(t){try{await this.shutdown()}catch(r){throw new AggregateError([e?.aborted?e.reason:t,r],`[lsp] ${this.serverId}: startup and cleanup failed`,{cause:r})}throw e?.throwIfAborted(),t}}async _start(e){if(this._initialized)return;if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(!this.rootUri.startsWith("file://")&&!this._ownerTransport)throw Object.assign(new Error("No language server process transport for this resource owner"),{code:"UNSUPPORTED_SOURCE"});if(await this._closeFileWatchers(),e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let t=_(this._command[0]),r=this._ownerTransport?decodeURIComponent(new URL(this.rootUri).pathname):ct.parse(this.rootUri).fsPath,o=[{uri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,name:Jt.basename(r)||r}];this._ownedStartup=this._ownerTransport?.start({rootUri:this.rootUri,command:this._command,env:this._env,signal:e});let s=await this._ownedStartup;if(this._ownedProcess=s??null,e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let i=s?void 0:Kt(t,this._args,{stdio:["pipe","pipe","pipe"],...e&&{signal:e},cwd:r,env:qe({command:this._command,env:this._env},r,process.env)});this._process=i??null;let l=i?Zt(i):Promise.resolve(),c=_(s?.stdin??i?.stdin),p=_(s?.stdout??i?.stdout),d=_(s?.stderr??i?.stderr);c.on("error",()=>{}),p.on("error",()=>{}),d.on("error",()=>{}),this._stderr="",d.setEncoding("utf8"),d.on("data",h=>{this._stderr=(this._stderr+h).slice(-4096)}),i?.on("error",h=>{("code"in h?h.code:void 0)!=="ENOENT"&&console.error(`[lsp] ${this.serverId}: spawn failed:`,h),this._crashed=!0,this._connection?.dispose(),this._connection=null,this._process=null});let g=a(h=>{(s?this._ownedProcess!==s:this._process!==i)||(this._closeFileWatchers(),!this._disposed&&h!==0&&h!==null&&(this._crashed=!0),this._connection?.dispose(),this._connection=null,this._diagnosticPublications.clear(),this._activeDiagnosticRequests.clear(),this._diagnosticMode="unknown",this._process=null,this._initialized=!1)},"onExit");i?.on("exit",g),s?.completion.then(({exitCode:h})=>g(h),()=>{this._ownedProcess===s&&(this._crashed=!0,g(null))}),await A(l,e);let u=Xt(new Yt(p),new oe(c,h=>{this._connection!==u||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),u.dispose(),console.error(`[lsp] ${this.serverId}: transport write failed:`,h))}));this._connection=u,this._connection.onError(h=>{console.error(`[lsp] ${this.serverId}: connection error:`,h)});let m=a(h=>{this._sendNotification("workspace/didChangeWatchedFiles",{changes:[h]})},"changed"),y=a(h=>console.error(`[lsp] ${this.serverId}: file watcher failed:`,h),"failed");this._fileWatchers=this._ownerTransport?this._ownerTransport.fileWatchers?.(this.rootUri,m,y):new ne(r,m,y),this._connection.onRequest("client/registerCapability",async h=>{for(let w of h.registrations)if(w.method!=="workspace/didChangeConfiguration"){if(w.method!=="workspace/didChangeWatchedFiles")throw new Error(`Unsupported dynamic capability: ${w.method}`);if(!this._fileWatchers)throw new Error("File watching is unavailable for this server owner");await this._fileWatchers.register(w.id,w.registerOptions?.watchers??[])}return null}),this._connection.onRequest("client/unregisterCapability",async h=>{for(let w of h.unregisterations)await this._fileWatchers?.unregister(w.id);return null}),this._connection.onRequest("window/workDoneProgress/create",()=>null),this._connection.onRequest("workspace/configuration",h=>h.items.map(w=>{let S=this._settings??null;for(let R of w.section?.split(".").filter(Boolean)??[])S=typeof S=="object"&&S!==null?S[R]??null:null;return S})),this._connection.listen(),this._connection.onNotification((h,...w)=>{let S=this._ownerTransport,R=S?j(w[0],v=>S.fromServerUri(v)):w[0];if(h==="textDocument/publishDiagnostics"){let v=R;v&&typeof v.uri=="string"&&Array.isArray(v.diagnostics)&&this._documentVersions.has(v.uri)&&(v.version===void 0||v.version===this.documentVersion(v.uri))&&this._diagnosticPublications.set(v.uri,{diagnostics:v.diagnostics,...typeof v.version=="number"&&{version:v.version}})}for(let v of this._handlers.get(h)??[])v(R)}),this._connection.onRequest("workspace/workspaceFolders",()=>o);let f=await A(lt(this._connection.sendRequest("initialize",{processId:this._ownerTransport?null:process.pid,rootUri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,workspaceFolders:o,capabilities:{workspace:{applyEdit:!1,configuration:!0,workspaceFolders:!0,didChangeWatchedFiles:{dynamicRegistration:this._fileWatchers!==void 0,relativePatternSupport:this._fileWatchers!==void 0},symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0},publishDiagnostics:{relatedInformation:!0},diagnostic:{dynamicRegistration:!1,relatedDocumentSupport:!1},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},foldingRange:{lineFoldingOnly:!0}}},initializationOptions:this._initOptions}),this._timeoutMs,`[lsp] ${this.serverId}: initialize timed out`),e).catch(h=>{let w=this._stderr.trim();throw w?new Error(`[lsp] ${this.serverId}: ${w}`,{cause:h}):h});if(await this._connection.sendNotification("initialized",{capabilities:f.capabilities}),this._settings!==void 0&&await this._connection.sendNotification("workspace/didChangeConfiguration",{settings:this._settings}),this._crashed)throw new Error(`[lsp] ${this.serverId}: transport failed during initialization`);e?.throwIfAborted(),this._initialized=!0,this._serverCapabilities=f.capabilities,this._diagnosticMode=f.capabilities.diagnosticProvider?"pull":"push"}touch(){}async restart(e){await this.shutdown(),this._closeFileWatchers(),this._connection?.dispose(),this._connection=null,this._process=null,this._initialized=!1,this._crashed=!1,this._disposed=!1,this._shutdownPromise=void 0,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null,await this.start(e)}async sendRequest(e,t,r){this._assertReady(),r?.throwIfAborted();let o=this._ownerTransport,s=o?j(t,p=>o.toServerUri(p)):t,i=a(p=>o?j(p,d=>o.fromServerUri(d)):p,"mapResult");if(!r)return i(await _(this._connection).sendRequest(e,s));let l=new Qt,c;try{let p=_(this._connection).sendRequest(e,s,l.token);return i(await Promise.race([p,new Promise((d,g)=>{c=a(()=>{l.cancel(),g(r.reason)},"onAbort"),r.addEventListener("abort",c,{once:!0})})]))}finally{c&&r.removeEventListener("abort",c),l.dispose()}}sendNotification(e,t){this._assertReady(),this._sendNotification(e,t)}_sendNotification(e,t){let r=this._connection;if(!r)return;let o=this._ownerTransport,s=o?j(t,i=>o.toServerUri(i)):t;r.sendNotification(e,s).catch(i=>{this._connection!==r||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),r.dispose(),console.error(`[lsp] ${this.serverId}: notification ${e} failed:`,i))})}onNotification(e,t){let r=this._handlers.get(e)??[];return r.push(t),this._handlers.set(e,r),()=>{let o=r.indexOf(t);o!==-1&&r.splice(o,1)}}toUri(e){return k(e,this.rootUri)}serverDocumentPath(e){let t=this.toUri(e),r=this._ownerTransport?.toServerUri(t)??t;return this._ownerTransport?decodeURIComponent(new URL(r).pathname):ct.parse(r).fsPath}openDocument(e,t,r,o=1){let s=this._documentVersions.get(e);if(s!==void 0){this.changeDocument(e,t,Math.max(o,s+1));return}this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didOpen",{textDocument:{uri:e,languageId:r,version:o,text:t}}),this._documentVersions.set(e,o),this._documentContents.set(e,t)}syncDocument(e,t,r,o=!1){if(this._documentContents.get(e)===t)return;let s=this._documentVersions.get(e);s===void 0?this.openDocument(e,t,r):this.changeDocument(e,t,s+1);let i=this._serverCapabilities?.textDocumentSync,l=typeof i=="object"&&i!==null?i.save:void 0;o&&l&&this.sendNotification("textDocument/didSave",{textDocument:{uri:e},...typeof l=="object"&&l.includeText&&{text:t}})}changeDocument(e,t,r){let o=this._documentVersions.get(e),s=Math.max(r,(o??0)+1);this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didChange",{textDocument:{uri:e,version:s},contentChanges:[{text:t}]}),this._documentVersions.set(e,s),this._documentContents.set(e,t)}closeDocument(e){this.sendNotification("textDocument/didClose",{textDocument:{uri:e}}),this._documentVersions.delete(e),this._documentContents.delete(e),this._diagnosticPublications.delete(e)}shutdown(){return this._shutdownPromise??=this._shutdown()}async _shutdown(){this._disposed=!0;let e=this._closeFileWatchers();if(this._connection&&this._initialized)try{await lt(this._connection.sendRequest("shutdown"),Math.min(this._timeoutMs,1e3),`[lsp] ${this.serverId}: shutdown timed out`),await this._connection.sendNotification("exit").catch(()=>{})}catch{}this._connection?.dispose(),this._connection=null;let t=this._ownedProcess??await this._ownedStartup?.catch(()=>{});this._ownedProcess=null,this._ownedStartup=void 0;let r=Promise.resolve().then(()=>t?.stop()),o=this._process;this._process=null,o&&!o.killed&&(o.kill("SIGTERM"),setTimeout(()=>{o.exitCode===null&&o.signalCode===null&&o.kill("SIGKILL")},2e3).unref()),this._initialized=!1,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null;let s=await Promise.allSettled([r,e]),i=[];for(let l of s)l.status==="rejected"&&i.push(l.reason);if(i.length>0)throw new AggregateError(i,`[lsp] ${this.serverId}: owned cleanup failed`)}dispose(){return this.shutdown()}_closeFileWatchers(){let e=this._fileWatchers;return this._fileWatchers=void 0,e&&(this._fileWatcherCleanup=this._fileWatcherCleanup.catch(()=>{}).then(()=>e.dispose()),this._fileWatcherCleanup.catch(t=>{console.error(`[lsp] ${this.serverId}: file watcher cleanup failed:`,t)})),this._fileWatcherCleanup}_assertReady(){if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(this._crashed)throw new Error(`[lsp] ${this.serverId}: crashed \u2014 call restart()`);if(!this._initialized)throw new Error(`[lsp] ${this.serverId}: not started \u2014 call start()`);if(!this._connection)throw new Error(`[lsp] ${this.serverId}: connection lost`)}};function Zt(n){return new Promise((e,t)=>{let r=a(()=>{n.off("spawn",o),n.off("error",s)},"cleanup"),o=a(()=>{r(),e()},"onSpawn"),s=a(i=>{r(),t(i)},"onError");n.once("spawn",o),n.once("error",s)})}a(Zt,"waitForSpawn");function lt(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t))},e);n.then(i=>{clearTimeout(s),r(i)}).catch(i=>{clearTimeout(s),o(i instanceof Error?i:new Error(String(i)))})})}a(lt,"withTimeout");import{readFile as pt}from"node:fs/promises";import{URI as ut}from"vscode-uri";var K={Error:1,Warning:2,Information:3,Hint:4};var dt={command:"typescript.tsserverRequest",async request(n,e,t){return(await Promise.all(["syntacticDiagnosticsSync","semanticDiagnosticsSync","suggestionDiagnosticsSync"].map(async o=>{let s=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:[o,{file:n.serverDocumentPath(e),includeLinePosition:!0},{isAsync:!1,expectsResult:!0}]},t);if(!de(s)||s.success!==!0||!Array.isArray(s.body))throw new Error(`Invalid completed TypeScript diagnostic report: ${o}`);return s.body.map(er)}))).flat()}};function se(n){return n.supportsCommand(dt.command)?dt:void 0}a(se,"completedDiagnosticAdapter");function er(n){if(!de(n)||typeof n.message!="string"||typeof n.code!="number"&&typeof n.code!="string"||!de(n.startLocation)||!Number.isInteger(n.startLocation.line)||!Number.isInteger(n.startLocation.offset)||Number(n.startLocation.line)<1||Number(n.startLocation.offset)<1||!["error","warning","suggestion","message"].includes(String(n.category)))throw new Error("Invalid TypeScript diagnostic entry");return{code:String(n.code),message:n.message,line:Number(n.startLocation.line),column:Number(n.startLocation.offset),severity:n.category==="error"?"error":n.category==="warning"?"warning":n.category==="suggestion"?"hint":"info"}}a(er,"convertTypeScriptDiagnostic");function de(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}a(de,"isRecord");async function X(n,e,t,r={}){let o=new AbortController,s=AbortSignal.any([o.signal,...r.signal?[r.signal]:[]]),i=setTimeout(()=>o.abort(new Error(`[lsp] ${n.serverId}: diagnostics timed out for ${e}`)),n.timeoutMs);try{return await tr(n,e,t,r.content,s)}finally{clearTimeout(i)}}a(X,"requestDiagnostics");async function tr(n,e,t,r,o){if(o.throwIfAborted(),n.diagnosticMode!=="push"){let c=n.documentVersion(e);try{let p=await n.sendRequest("textDocument/diagnostic",{textDocument:{uri:e}},o);if(p.kind!=="full"||!Array.isArray(p.items))throw new Error("Invalid full diagnostic report");if(n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return n.setDiagnosticMode("pull"),gt(p.items,!1,!0)}catch(p){if(!rr(p))throw p;n.setDiagnosticMode("push")}}let s=se(n);if(s){n.documentVersion(e)===void 0&&n.syncDocument(e,r??await pt(ut.parse(e).fsPath,"utf8"),t??"plaintext");let c=n.documentVersion(e),p=await s.request(n,e,o);if(o.throwIfAborted(),n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return{diagnostics:p,syntaxErrors:[],otherDiagnostics:p,unversioned:!1,complete:!0}}o.throwIfAborted();let i=n.documentVersion(e)!==void 0,l=i?void 0:r??await pt(ut.parse(e).fsPath,"utf8");o.throwIfAborted(),n.beginDiagnosticRequest(e);try{return await new Promise((c,p)=>{let d=n.documentVersion(e)??1,g=a(f=>{let h=f;h.uri!==e||!Array.isArray(h.diagnostics)||h.version!==void 0&&h.version!==d||n.documentVersion(e)===d&&(y(),c(gt(h.diagnostics,h.version===void 0)))},"receive"),u=n.onNotification("textDocument/publishDiagnostics",g),m=a(()=>{y(),p(o.reason)},"onAbort");function y(){u(),o.removeEventListener("abort",m)}a(y,"cleanup"),o.addEventListener("abort",m,{once:!0});try{i||n.syncDocument(e,l??"",t??"plaintext");let f=n.diagnosticPublication(e);f&&g({uri:e,...f})}catch(f){y(),p(f)}})}finally{n.endDiagnosticRequest(e)}}a(tr,"requestCurrentDiagnostics");function pe(n){return{code:String(n.code??"LSP"),message:n.message,line:n.range.start.line+1,column:n.range.start.character+1,severity:n.severity===K.Warning?"warning":n.severity===K.Information?"info":n.severity===K.Hint?"hint":"error"}}a(pe,"toDiagnostic");function gt(n,e,t=!1){let r=n.map(pe);return{diagnostics:r,syntaxErrors:[],otherDiagnostics:r,unversioned:e,complete:t}}a(gt,"classify");function rr(n){return n!==null&&typeof n=="object"&&"code"in n&&n.code===-32601}a(rr,"isMethodNotFound");var nr={1:"File",2:"Module",3:"Namespace",4:"Package",5:"Class",6:"Method",7:"Property",8:"Field",9:"Constructor",10:"Enum",11:"Interface",12:"Function",13:"Variable",14:"Constant",15:"String",16:"Number",17:"Boolean",18:"Array",19:"Object",20:"Key",21:"Null",22:"EnumMember",23:"Struct",24:"Event",25:"Operator",26:"TypeParameter"};function T(n){return nr[n]??`SymbolKind(${n})`}a(T,"symbolKindName");async function Q(n,e,t){return await n.sendRequest("textDocument/documentSymbol",{textDocument:{uri:e}},t)??[]}a(Q,"requestDocumentSymbols");async function ue(n,e,t=100,r){return(await n.sendRequest("workspace/symbol",{query:e},r)??[]).slice(0,t)}a(ue,"requestWorkspaceSymbols");async function ie(n,e,t,r){return await n.sendRequest("textDocument/rename",{textDocument:{uri:e},position:t,newName:r})}a(ie,"requestRename");import Z from"node:path";import{URI as ar}from"vscode-uri";import{createHash as or}from"node:crypto";import{readdir as sr,stat as ae}from"node:fs/promises";import O from"node:path";import{URI as me}from"vscode-uri";async function ge(n,e){if(!n.supportsCommand("typescript.tsserverRequest"))return;if((await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:e,needFileNameList:!0},{isAsync:!1,expectsResult:!0}]}))?.success!==!0)throw new Error("TypeScript could not load the project for a workspace query.")}a(ge,"prepareProjectQuery");function mt(n,e){let t=a(r=>typeof r=="string"?r.replaceAll("{project}",()=>e):Array.isArray(r)?r.map(t):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([o,s])=>[o,t(s)])):r,"expand");return Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)]))}a(mt,"resolveInitializationOptions");var W=class n{constructor(e,t){this._registry=e;this._owner=t}static{a(this,"LspManager")}_clients=new Map;_clientStarts=new Map;_openDocs=new Set;_pushUnsubscribers=new Map;_pushHandlers=new Set;_pushFingerprints=new Map;_disposed=!1;static _instance=null;static getInstance(){if(!n._instance)throw new Error("[lsp] LspManager not initialized");return n._instance}static getInstanceOrNull(){return n._instance}static init(e,t){let r=n._instance;return r?._disposed?(r._registry=e,r._owner=t,r._disposed=!1,r):(n._instance=new n(e,t),n._instance)}static async resetForTest(){n._instance&&(await n._instance.shutdownAll(),n._instance=null)}requireOwner(){if(!this._owner)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});return this._owner}get workspaceRoot(){return this._registry.projectRoot}get clientCount(){return this._clients.size}onPushDiagnostics(e){return this._pushHandlers.add(e),()=>this._pushHandlers.delete(e)}async getOrStart(e,t,r,o){if(o?.throwIfAborted(),this._disposed)return null;let s=t.startsWith("ssh://"),i=s?this.requireOwner():void 0,l=i?await this._registry.resolveOwned(e,f=>i.exists(f,o)):this._registry.resolve(e);if(o?.throwIfAborted(),this._disposed)return null;let c=r==="symbols"?l[0]:l.find(f=>f.config.capabilities.includes(r));if(!c)return null;let p=s?t:me.file(t).toString(),d=`${c.serverId}:${p}`,g=this._clientStarts.get(d);if(g)return g.controller.signal.aborted?(await A(g.promise.catch(()=>{}),o),this.getOrStart(e,t,r,o)):g.wait(o);let u=this._clients.get(d);if(u?.ready)return u;let m=new H(f=>this._startClient(d,p,c,u,f));this._clientStarts.set(d,m);let y=a(()=>{this._clientStarts.get(d)===m&&this._clientStarts.delete(d)},"settled");return m.promise.then(y,y),m.wait(o)}async _startClient(e,t,r,o,s){let i=o??new $({serverId:r.serverId,rootUri:t,command:r.config.command,...t.startsWith("ssh://")&&this._owner&&{ownerTransport:this._owner.transport(t)},...r.config.env&&{env:r.config.env},...r.config.initializationOptions&&{initOptions:mt(r.config.initializationOptions,t.startsWith("ssh://")?decodeURIComponent(new URL(t).pathname):me.parse(t).fsPath)},...r.config.settings&&{settings:r.config.settings},...r.config.timeoutMs&&{timeoutMs:r.config.timeoutMs}});try{o?await o.restart(s):await i.start(s),s.throwIfAborted()}catch(l){try{await i.shutdown()}catch(c){if(c!==l)throw new AggregateError([l,c],"Language server startup and cleanup failed",{cause:c})}throw l}if(this._disposed)throw await i.shutdown(),new Error(`[lsp] ${r.serverId}: manager disposed during startup`);return this._clients.set(e,i),this._subscribeToPushDiagnostics(e,i),i}async isSourceFile(e,t,r){if(r?.throwIfAborted(),t.startsWith("ssh://")){if(this._owner===void 0)throw new Error("No language server workspace owner");return this._owner.isFile(k(e,t),r)}let o=await ae(O.resolve(t,e));return r?.throwIfAborted(),o.isFile()}async getWorkspaceClients(e,t="symbols",r=e,o=()=>!0,s){if(s?.throwIfAborted(),e.startsWith("ssh://")){let g=this._owner;if(!g)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});let u=new Set,m=new Set(this._registry.knownExtensions),y=new Set([".git",".cache","node_modules","dist","build"]),f=a(async w=>{if(s?.throwIfAborted(),m.size!==0)for(let S of await g.entries(w,s)){s?.throwIfAborted();let R=k(S.name,`${w}/`);if(S.kind==="directory")y.has(S.name)||await f(R);else if(S.kind==="file"){let v=O.posix.extname(S.name).toLowerCase();if(!m.has(v)||!o(R))continue;let D=await this.openFile(R,e,t,s);D&&(u.add(D.client),m.delete(v))}}},"visit"),h=k(r,e);if(await g.isFile(h,s)){if(!o(h))return[];let w=await this.openFile(h,e,t,s);return w?[w.client]:[]}return await f(h),[...u]}let i=new Set,l=new Set(this._registry.knownExtensions),c=new Set([".git",".cache","node_modules","dist","build"]),p=a(async g=>{if(s?.throwIfAborted(),l.size===0)return;let u;try{u=await sr(g,{withFileTypes:!0})}catch{return}for(let m of u){if(s?.throwIfAborted(),l.size===0)return;if(m.isDirectory()){c.has(m.name)||await p(O.join(g,m.name));continue}if(!m.isFile())continue;let y=O.extname(m.name).toLowerCase();if(!l.has(y))continue;let f=O.join(g,m.name);if(!o(f))continue;let h=await this.openFile(f,e,t,s);h&&(l.delete(y),h.client.hasWorkspaceSymbolCapability&&(await ge(h.client,f),i.add(h.client)))}},"visit"),d=O.resolve(e,r);if((await ae(d)).isFile()){if(!o(d))return[];let g=await this.openFile(d,e,t,s);return g===null||!g.client.hasWorkspaceSymbolCapability?[]:(await ge(g.client,d),[g.client])}return await p(d),s?.throwIfAborted(),[...i]}async prepareWorkspaceSymbols(e,t=e,r,o){return this.getWorkspaceClients(e,"symbols",t,r,o)}hasServerFor(e){return this._registry.resolve(e).length>0}languageId(e){return this._registry.languageId(e)}isOpen(e){return this._openDocs.has(e)}syncEditedSource(e,t){for(let r of this._clients.values()){if(!r.ready)continue;let o=r.toUri(e);if(r.documentContent(o)===void 0)continue;let s=this.languageId(O.extname(decodeURIComponent(new URL(o).pathname)));r.syncDocument(o,t,s,!0)}}async readSourceSnapshot(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readSnapshot(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported rename source"),{code:"UNSUPPORTED_SOURCE"});let r=a(i=>`${i.dev}:${i.ino}:${i.mode}:${i.size}:${i.mtimeMs}:${i.ctimeMs}`,"identity"),o=r(await ae(e)),s=await this.readSourceText(e,t);if(o!==r(await ae(e)))throw new Error("A rename source changed while reading it. No edits applied.");return{content:s,version:or("sha256").update(o).update("\0").update(s).digest("hex")}}async readSourceBytes(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readBytes(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{signal:t})}async readSourceText(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readText(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{encoding:"utf8",signal:t})}async openFile(e,t,r="diagnostics",o){if(o?.throwIfAborted(),e.startsWith("ssh://")&&!t.startsWith("ssh://")){if(!this._registry.projectRoot.startsWith("ssh://"))throw Object.assign(new Error("Remote document has no workspace owner"),{code:"UNSUPPORTED_SOURCE"});t=this._registry.projectRoot}let s=t.startsWith("ssh://"),i=s?k(e,t):O.resolve(t,e),l=await this.getOrStart(i,t,r,o);if(!l)return null;let c=l.toUri(i),p=s?this.requireOwner():void 0,g=(p?await this._registry.resolveOwned(i,u=>p.exists(u,o)):this._registry.resolve(i))[0]?.languageId??"plaintext";if(p){let u=await p.readText(c,o);return o?.throwIfAborted(),l.syncDocument(c,u,g),this._openDocs.add(c),{client:l,uri:c,languageId:g}}try{let{readFile:u}=await import("node:fs/promises"),m=await u(i,{encoding:"utf8",signal:o});o?.throwIfAborted(),l.syncDocument(c,m,g),this._openDocs.add(c)}catch(u){if(o?.throwIfAborted(),!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}return{client:l,uri:c,languageId:g}}_subscribeToPushDiagnostics(e,t){if(this._pushUnsubscribers.has(e))return;let r=t.onNotification("textDocument/publishDiagnostics",o=>{let s=ir(o);if(!s||t.hasActiveDiagnosticRequest(s.uri))return;let i=t.documentVersion(s.uri);if(s.version!==void 0&&i!==void 0&&s.version<i)return;let l=`${e}:${s.uri}`,c=s.diagnostics.map(pe),p=JSON.stringify([s.version,i,c]);if(this._pushFingerprints.get(l)===p)return;this._pushFingerprints.set(l,p);let d={cwd:t.rootUri.startsWith("ssh://")?t.rootUri:me.parse(t.rootUri).fsPath,serverId:t.serverId,uri:s.uri,diagnostics:c,...s.version!==void 0&&{version:s.version}};for(let g of this._pushHandlers)g(d)});this._pushUnsubscribers.set(e,r)}async shutdownAll(){this._disposed=!0;let e=[...this._clientStarts.values()];for(let i of e)i.controller.abort(new Error("Language server manager stopped"));let t=await Promise.allSettled(e.map(i=>i.promise)),r=[];for(let[i,l]of t.entries())l.status==="rejected"&&l.reason!==e[i]?.controller.signal.reason&&r.push(l.reason);let o=[...this._clients.values()],s=await Promise.allSettled(o.map(i=>i.shutdown()));for(let i of this._pushUnsubscribers.values())i();this._pushUnsubscribers.clear(),this._clientStarts.clear(),this._pushFingerprints.clear(),this._pushHandlers.clear(),this._clients.clear();for(let i of s)i.status==="rejected"&&r.push(i.reason);if(r.length>0)throw new AggregateError(r,"Language server cleanup failed")}dispose(){return this.shutdownAll()}};function ir(n){if(n===null||typeof n!="object")return;let e=n;if(!(typeof e.uri!="string"||!Array.isArray(e.diagnostics)))return{uri:e.uri,diagnostics:e.diagnostics,...typeof e.version=="number"&&{version:e.version}}}a(ir,"parsePushNotification");async function fe(n,e,t){if(t?.throwIfAborted(),!n.supportsCommand("typescript.tsserverRequest"))return;let r=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:n.serverDocumentPath(e),needFileNameList:!0},{isAsync:!1,expectsResult:!0}]},t);if(t?.throwIfAborted(),r?.success!==!0)throw new Error("TypeScript could not load the project for the workspace query.")}a(fe,"loadQueryProject");async function Y(n,e,t,r){return await fe(n,e,r),await n.sendRequest("textDocument/references",{textDocument:{uri:e},position:t,context:{includeDeclaration:!0}},r)??[]}a(Y,"requestReferences");async function he(n,e,t,r){let o=await n.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:e},position:t},r),s=o?.[0];if(!s)return{items:[],incoming:[],outgoing:[]};let[i,l]=await Promise.all([n.sendRequest("callHierarchy/incomingCalls",{item:s},r),n.sendRequest("callHierarchy/outgoingCalls",{item:s},r)]);return{items:o,incoming:i??[],outgoing:l??[]}}a(he,"requestCallHierarchy");function G(n,e,t){let r=e.startsWith("ssh://"),o=r?Z.posix:Z,s=a(d=>r?decodeURIComponent(new URL(k(d,e)).pathname):d,"native"),i=r?s(t.path??e):Z.resolve(e,t.path??"."),l=o.relative(i,s(n));if(l===".."||l.startsWith(`..${o.sep}`)||o.isAbsolute(l))return!1;let c=o.relative(s(e),s(n)).split(o.sep).join("/"),p=a(d=>d.split(",").some(g=>{let u=g.trim();return u.length>0&&o.matchesGlob(u.includes("/")?c:o.basename(s(n)),u)}),"matches");return(t.include===void 0||p(t.include))&&(t.exclude===void 0||!p(t.exclude))}a(G,"withinScope");function ye(n,e){let t=k(n,e);if(t.startsWith("ssh://"))return t;let r=ar.parse(t);if(r.scheme!=="file")throw new Error("Unsupported LSP source location.");return Z.resolve(r.fsPath)}a(ye,"sourceOf");function cr(n,e){return n.start.line===e.start.line&&n.start.character===e.start.character&&n.end.line===e.end.line&&n.end.character===e.end.character}a(cr,"sameRange");function ft(n,e,t){return n.flatMap(r=>[...r.name===e&&r.range!==void 0&&cr(r.range,t)&&r.selectionRange!==void 0?[r.selectionRange]:[],...ft(r.children??[],e,t)])}a(ft,"declarationNames");async function we(n,e,t,r,o={},s=W.getInstance()){r?.throwIfAborted();let i=o.resultScope;if(i!==void 0&&(await F(i,r),i.targets.length===0))return{hits:[],complete:i.complete};if(i===void 0&&o.path!==void 0&&!G(e.startsWith("ssh://")?k(o.path,e):Z.resolve(e,o.path),e,o)&&await s.isSourceFile(o.path,e,r))return{hits:[],complete:!0};let l=i?.targets.map(y=>y.source)??[o.path??e],c=new Set((await Promise.all(l.map(y=>s.prepareWorkspaceSymbols(e,y,f=>G(f,e,o),r)))).flat());if(c.size===0)throw new Error("LSP symbol search is unavailable: no provider supports workspace/symbol in this scope.");let p=new Map,d=a(async y=>{r?.throwIfAborted();let f=ye(y.uri,e),h=p.get(f);if(h===void 0){let{content:L,version:N}=await s.readSourceSnapshot(f,r);h={document:Ee(f,L),version:N},p.set(f,h)}let{document:w}=h,{start:S,end:R}=y.range,v=[S,R];for(let L of v){let N=w.lines[L.line];if(!Number.isInteger(L.line)||!Number.isInteger(L.character)||N===void 0||L.character<0||L.character>N.content.length)throw new Error("LSP range does not match its source snapshot.")}let D=_(w.lines[S.line]),re=a(L=>w.lines.slice(0,L).reduce((N,xe)=>N+xe.content.length+xe.lineEnding.length,0),"offset"),U=re(S.line)+S.character,C=re(R.line)+R.character;if(C<U)throw new Error("LSP returned a reversed source range.");return{source:f,lineNumber:S.line+1,endLineNumber:R.line+1,startColumn:S.character,endColumn:R.character,matchedText:w.content.slice(U,C),lineText:D.content}},"toMatch"),g=a(y=>G(y.source,e,o)&&(i===void 0||st(i,y)),"included"),u=[],m=new Set;for(let y of c){r?.throwIfAborted();let f=await ue(y,n,Number.MAX_SAFE_INTEGER,r);for(let h of f){if(r?.throwIfAborted(),!G(ye(h.location.uri,e),e,{}))continue;let w=await d(h.location),S=await s.openFile(w.source,e,"symbols",r);if(S===null)throw new Error("LSP references are unavailable for a discovered declaration.");let R=h.location;if(w.matchedText!==h.name){let C=await Q(S.client,S.uri,r),L=ft(C,h.name,h.location.range);if(L.length!==1)throw new Error("LSP declaration has no unique provider selectionRange; cannot search its references.");R={uri:S.uri,range:_(L[0])}}let v=await d(R),D={id:JSON.stringify([y.serverId,v.source,h.location.range]),name:h.name,kind:String(h.kind),source:v.source,range:{startLine:v.lineNumber,startColumn:v.startColumn,endLine:v.endLineNumber??v.lineNumber,endColumn:v.endColumn}},re=await Y(S.client,S.uri,R.range.start,r);r?.throwIfAborted();let U=[{...v,role:"definition",symbol:D}];for(let C of re){if(!G(ye(C.uri,e),e,{}))continue;let L=await d(C);L.source===v.source&&L.lineNumber===v.lineNumber&&L.startColumn===v.startColumn&&L.endLineNumber===v.endLineNumber&&L.endColumn===v.endColumn||U.push({...L,role:"reference",symbol:D})}if(!(o.navigation==="references"&&!U.some(g)))for(let C of U){if(o.navigation!=="references"&&!g(C)||o.navigation==="references"&&!G(C.source,e,{}))continue;let L=JSON.stringify([D.id,C.source,C.lineNumber,C.startColumn,C.endLineNumber,C.endColumn]);m.has(L)||(m.add(L),u.push(C))}}}r?.throwIfAborted();for(let[y,f]of p){let h=await s.readSourceSnapshot(y,r);if(h.version!==f.version||h.content!==f.document.content)throw new Error("LSP source changed during search.")}return i!==void 0&&await F(i,r),u.sort((y,f)=>y.source.localeCompare(f.source)||y.lineNumber-f.lineNumber||y.startColumn-f.startColumn||y.endColumn-f.endColumn||y.symbol.id.localeCompare(f.symbol.id)),{hits:u.slice(0,t),complete:(i?.complete??!0)&&u.length<=t}}a(we,"searchSymbols");import{readFile as lr}from"node:fs/promises";import ve from"node:path";import{fileURLToPath as dr}from"node:url";var pr={failureLabel:"SYMBOL_READ_FAILED",emptyReason:"no symbol source was produced."},be=10,Se=5,B=10;async function yt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath),c=await n.readSourceText(i.filePath,o);if(x(o),s!==c)throw new Error("The symbol source changed during resolution. Read it again before editing.");return{source:i.filePath,range:l.range,content:c}}a(yt,"resolveLspDeclaration");async function wt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath);if(s!==await n.readSourceText(e,o))throw new Error("The rename source changed during resolution.");return x(o),{client:i.client,uri:i.uri,position:l.selectionRange.start,content:s}}a(wt,"resolveLspRenameTarget");async function Pe(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await yr(s.filePath,n,o);x(o);let c=i.range.start.line+1,p=Math.min(i.range.end.line+1,l.lines.length),d=l.lines.slice(Math.max(0,c-1),Math.max(0,p)).map((u,m)=>{let y=c+m;return Ie({content:u,sourceLine:{source:s.filePath,lineNumber:y,content:u}})}),g={path:s.displayPath,heading:`symbol: ${M(i.selector)}`,details:[`defined in: ${s.displayPath}:${c}-${p} (${T(i.kind)})`],startLine:c,endLine:p,totalLines:l.lines.length,renderedLines:d};return De([g],pr)}a(Pe,"readLspSymbolBody");async function _e(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await Lt(s,i,o),c=new ce(r);return await ur(s,i,l,c)}a(_e,"readLspSymbolGraph");async function Ce(n,e,t,r){x(r);let o=await te(n,e,t,r),s=new ce(t),i=[`## file graph: ${o.displayPath}`,`Top-level declarations: ${o.symbols.length}`];for(let l of o.symbols){x(r);let c=await Lt(o,l,r);i.push("",...await hr(o,l,c,s))}return i.join(`
2
2
  `)}a(Ce,"readLspFileGraph");function ee(n,e,t){if(e.length===0)throw new TypeError("A symbol selector must contain at least one segment.");if(e.length===1){let s=St(n,_(e[0]));if(s.length===1)return _(s[0]);throw s.length>1?new Error(`Symbol selector "${M(e)}" is ambiguous in ${t}; use parent/child.`):ht(e,t)}let r=n,o;for(let s of e){let i=r.filter(l=>l.name===s);if(i.length===0)throw ht(e,t);if(i.length>1)throw new Error(`Symbol selector "${M(e)}" is ambiguous at "${s}" in ${t}.`);o=_(i[0]),r=o.children}return _(o)}a(ee,"resolveLspCodeSymbol");async function te(n,e,t,r){let o=E(e,t),s=await n.openFile(o,t,"symbols",r);if(!s)throw new Error(`No LSP server with symbol support is configured for ${Re(o,t)}.`);let i=await Q(s.client,s.uri,r),l=vt(i).sort(bt);return{client:s.client,uri:s.uri,filePath:o,displayPath:Re(o,t),symbols:l}}a(te,"openCodeDocument");function vt(n,e=[]){return n.flatMap(t=>{let r=t.selectionRange??t.range;if(!r)return[];let o=t.range??r,s=[...e,t.name];return[{name:t.name,kind:t.kind,range:o,selectionRange:r,selector:s,children:vt(t.children??[],s).sort(bt)}]})}a(vt,"normalizeDocumentSymbols");function bt(n,e){return n.range.start.line-e.range.start.line||n.range.start.character-e.range.start.character||n.name.localeCompare(e.name)}a(bt,"compareSymbols");function St(n,e){return n.flatMap(t=>[...t.name===e?[t]:[],...St(t.children,e)])}a(St,"collectNamedSymbols");function ht(n,e){return new Error(`Symbol "${M(n)}" was not found in ${e}.`)}a(ht,"symbolNotFound");async function Lt(n,e,t){let r=e.selectionRange.start,[o,s]=await Promise.all([Y(n.client,n.uri,r,t),he(n.client,n.uri,r,t)]);return x(t),{references:o,calls:s}}a(Lt,"queryRelations");async function ur(n,e,t,r){let o=M(e.selector),s=await r.line(n.uri,e.selectionRange.start.line+1);return[`## graph: ${o}`,`Definition: ${n.displayPath} ${s} (${T(e.kind)})`,`Source: ${J("graph",n.displayPath,e.selector)}`,"",...await gr(t.references,r),"",...await mr(t.calls.incoming,r),"",...await fr(t.calls.outgoing,r)].join(`
3
3
  `)}a(ur,"formatSymbolGraph");async function gr(n,e){let t=Rt(n),r=[`References: ${n.length} in ${t.length} file(s)`];for(let[o,s]of t.slice(0,be)){r.push(`- ${e.display(o)} (${s.length})`);for(let i of s.slice(0,Se))r.push(` - ${await e.line(o,i.range.start.line+1)}`);s.length>Se&&r.push(` - ... ${s.length-Se} more`)}return t.length>be&&r.push(`- ... ${t.length-be} more file(s)`),r}a(gr,"formatReferences");async function mr(n,e){let t=[`Incoming calls: ${n.length}`];for(let r of n.slice(0,B)){let o=r.fromRanges[0]?.start.line??r.from.selectionRange.start.line,s=await e.line(r.from.uri,o+1);t.push(`- ${T(r.from.kind)} ${r.from.name} \u2014 ${e.display(r.from.uri)} ${s}`)}return n.length>B&&t.push(`- ... ${n.length-B} more`),t}a(mr,"formatIncomingCalls");async function fr(n,e){let t=[`Outgoing calls: ${n.length}`];for(let r of n.slice(0,B)){let o=await e.line(r.to.uri,r.to.selectionRange.start.line+1);t.push(`- ${T(r.to.kind)} ${r.to.name} \u2014 ${e.display(r.to.uri)} ${o}`)}return n.length>B&&t.push(`- ... ${n.length-B} more`),t}a(fr,"formatOutgoingCalls");async function hr(n,e,t,r){let o=T(e.kind),s=await r.line(n.uri,e.selectionRange.start.line+1),i=Rt(t.references).map(([d,g])=>`${r.display(d)} (${g.length})`),l=t.calls.incoming.map(d=>`${d.from.name} (${r.display(d.from.uri)})`),c=t.calls.outgoing.map(d=>`${d.to.name} (${r.display(d.to.uri)})`),p=[`### ${o} ${e.name}`,`Selector: ${M(e.selector)}`,`Definition: ${s}`,`Used by: ${Le(i)}`,`Incoming calls: ${Le(l)}`,`Outgoing calls: ${Le(c)}`];if(e.children.length>0){p.push("Members:");for(let d of e.children){let g=J("graph",n.displayPath,d.selector);p.push(`- ${T(d.kind)} ${d.name} \u2014 ${g}`)}}return p}a(hr,"formatFileGraphSymbol");function Le(n,e=5){if(n.length===0)return"none";let t=n.slice(0,e).join(", ");return n.length>e?`${t}, ... ${n.length-e} more`:t}a(Le,"summarize");function Rt(n){let e=new Map;for(let t of n){let r=e.get(t.uri)??[];r.push(t),e.set(t.uri,r)}return[...e].map(([t,r])=>[t,r.sort((o,s)=>o.range.start.line-s.range.start.line||o.range.start.character-s.range.start.character)]).sort(([t],[r])=>t.localeCompare(r))}a(Rt,"groupLocationsByUri");async function yr(n,e,t){let r=n.startsWith("ssh://")?Buffer.from(await e.readSourceBytes(n,t)):await lr(n,{signal:t});if(r.byteLength>256*1024)throw new Error(`File exceeds the 262144-byte code-view limit: ${n}`);if(r.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${n}`);let o=r.toString("utf8").replaceAll(`\r
4
4
  `,`
@@ -1 +1 @@
1
- import{f as T,i as m,j as M}from"./chunk-DXONCYWF.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var E=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),b=o.Object({source:o.String(),effect:E,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),L={effect:E,files:o.Array(b)};function R(n){return o.Object({operation:o.Literal(n),...L,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function v(n){return T(R(n))}p(v,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,h=[]){let r=n.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:c,effect:"pending",...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(t=>t.resourceSource)),s=[],f=[],y=r.results;for(let t of y??[]){let e=t.data,k=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of k)f.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(A=>A.path===i)?"applied":e.rollback?.failedSources.includes(i)?"unknown":e.rollback?.restoredSources.includes(i)?"not-applied":r.effect??"unknown"});for(let i of e.errors??[])s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});e.ok===!1&&(e.errors?.length??0)===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed",...e.path?{source:e.path}:{}})}for(let t of g)f.some(e=>e.source===t)||f.push({source:t,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let t=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",e=typeof a.source=="string"?a.source:void 0;e&&f.push({source:e,...a.kind==="file-operation"&&a.ok===!0?{state:c==="delete"||c==="move"?"absent":"present"}:{},effect:c==="copy"&&typeof a.target=="string"&&a.target!==e?"not-applied":t}),typeof a.target=="string"&&f.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(m(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(m("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(f.map(t=>[t.source,t])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let t of r.metadata.resultFileStates){if(!u(t))continue;let e=d.find(k=>k.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let S=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(y?.length??0)===0&&!a&&g.size===0&&s.length===0&&r.effect!=="not-applied"&&s.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":S?"applied":"not-applied";return{status:s.length===0?"success":!a&&S&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:w,files:d,...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...c!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:s}}p(U,"mutationOutcome");function F(n,c,h=[],r){let l=U(n,c,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(n,R(c),l)}p(F,"structuredMutation");export{R as a,v as b,U as c,F as d};
1
+ import{f as T,i as m,j as M}from"./chunk-LCWBVOII.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var E=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),b=o.Object({source:o.String(),effect:E,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),L={effect:E,files:o.Array(b)};function R(n){return o.Object({operation:o.Literal(n),...L,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function v(n){return T(R(n))}p(v,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,h=[]){let r=n.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:c,effect:"pending",...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(t=>t.resourceSource)),s=[],f=[],y=r.results;for(let t of y??[]){let e=t.data,k=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of k)f.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(A=>A.path===i)?"applied":e.rollback?.failedSources.includes(i)?"unknown":e.rollback?.restoredSources.includes(i)?"not-applied":r.effect??"unknown"});for(let i of e.errors??[])s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});e.ok===!1&&(e.errors?.length??0)===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed",...e.path?{source:e.path}:{}})}for(let t of g)f.some(e=>e.source===t)||f.push({source:t,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let t=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",e=typeof a.source=="string"?a.source:void 0;e&&f.push({source:e,...a.kind==="file-operation"&&a.ok===!0?{state:c==="delete"||c==="move"?"absent":"present"}:{},effect:c==="copy"&&typeof a.target=="string"&&a.target!==e?"not-applied":t}),typeof a.target=="string"&&f.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(m(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(m("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(f.map(t=>[t.source,t])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let t of r.metadata.resultFileStates){if(!u(t))continue;let e=d.find(k=>k.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let S=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(y?.length??0)===0&&!a&&g.size===0&&s.length===0&&r.effect!=="not-applied"&&s.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":S?"applied":"not-applied";return{status:s.length===0?"success":!a&&S&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:w,files:d,...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...c!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:s}}p(U,"mutationOutcome");function F(n,c,h=[],r){let l=U(n,c,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(n,R(c),l)}p(F,"structuredMutation");export{R as a,v as b,U as c,F as d};
@@ -1 +1 @@
1
- import{g as u,h as E,m as a}from"./chunk-TGC2ZACO.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
1
+ import{g as u,h as E,m as a}from"./chunk-235QMMVA.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
@@ -0,0 +1 @@
1
+ import{b as n}from"./chunk-6R3Y4AD3.js";import"./chunk-6XFUICD7.js";import{a as o,b as t,c as i}from"./chunk-RIJMXO43.js";import"./chunk-VMTOFEXF.js";import"./chunk-CPELC6JE.js";import"./chunk-PJL3UVMJ.js";import{b as s}from"./chunk-HSRH76JN.js";import"./chunk-VDP5CQHM.js";import"./chunk-47SPPIXK.js";import"./chunk-4DIUPEDF.js";import"./chunk-VAXLSPPU.js";import"./chunk-I6NPILT5.js";import{c as r}from"./chunk-W7CASEO3.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.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-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as e}from"./chunk-EI7MMDWY.js";async function g(a){let m=new i(await t(o(r())));await s(a,f=>n(f,m))}e(g,"registerOwnedWeb");export{g as default};
@@ -1,4 +1,4 @@
1
- import{a as le,b as fe,c as ue}from"./chunk-LLRUJD62.js";import{a as de}from"./chunk-Q5X6OXNS.js";import{a as N,g as l}from"./chunk-4HWKBCBH.js";import{a as se}from"./chunk-47SPPIXK.js";import{a as ie,b as ae}from"./chunk-VAXLSPPU.js";import{c as ce}from"./chunk-W7CASEO3.js";import{e as q,f as Z}from"./chunk-T7I2VX3J.js";import{a as ne}from"./chunk-M4TVRCMZ.js";import{b as te,c as re,d as oe}from"./chunk-TGC2ZACO.js";import"./chunk-NNCZYO4Q.js";import{d as ee}from"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import{a as G}from"./chunk-BU7IZLKB.js";import{a as H,b as V}from"./chunk-S5PL5DFQ.js";import{F as z}from"./chunk-DXONCYWF.js";import{r as J}from"./chunk-ZPT5D4VP.js";import{a as X}from"./chunk-ZAWRSA7N.js";import{a as x,b as Q}from"./chunk-OFILFO6D.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import pe from"node:path";import{StringDecoder as Oe}from"node:string_decoder";function he(r){return(i,a)=>{let n=r.resolve(i.path??".",a.cwd);if(n===void 0)return;let{backend:c,location:w}=n,e=s((t,o=w.source)=>{let m=r.resolve(t,o);if(m===void 0||m.backend!==c)throw new l("UNSUPPORTED_SOURCE",t,"not-applied");return m.location},"own");return{resolve:s((t,o)=>e(o,t.includes("://")?t:w.source).source,"resolve"),dirname:s(t=>N(w.target,pe.posix.dirname(e(t).path)).source,"dirname"),basename:s(t=>pe.posix.basename(e(t).path),"basename"),isDirectory:s(async(t,o)=>(await c.stat(e(t).path,{signal:o})).kind==="directory","isDirectory"),byteSize:s(async(t,o)=>(await c.stat(e(t).path,{signal:o})).size,"byteSize"),readText:s(async(t,o)=>(await c.read(e(t).path,{signal:o})).bytes.toString("utf8"),"readText"),async execute(t,o,m,R){let d=await c.execute(t,o,e(m).path,{signal:R});return{code:d.exitCode,stdout:d.stdout.toString("utf8"),stderr:d.stderr.toString("utf8")}},async runLines(t,o,m,R){let d=await c.startProcess("rg",t,e(o).path,{signal:R}),g=new Oe("utf8"),u=[],p=0,f="",h,y=s(k=>{let E=k.split(`
1
+ import{a as le,b as fe,c as ue}from"./chunk-RIJMXO43.js";import{a as de}from"./chunk-CPELC6JE.js";import{a as N,g as l}from"./chunk-PJL3UVMJ.js";import{a as se}from"./chunk-47SPPIXK.js";import{a as ie,b as ae}from"./chunk-VAXLSPPU.js";import{c as ce}from"./chunk-W7CASEO3.js";import{e as q,f as Z}from"./chunk-T7I2VX3J.js";import{a as ne}from"./chunk-XXLLY66B.js";import{b as te,c as re,d as oe}from"./chunk-235QMMVA.js";import"./chunk-NNCZYO4Q.js";import{d as ee}from"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import{a as G}from"./chunk-BU7IZLKB.js";import{a as H,b as V}from"./chunk-S5PL5DFQ.js";import{F as z}from"./chunk-LCWBVOII.js";import{r as J}from"./chunk-ZPT5D4VP.js";import{a as X}from"./chunk-ZAWRSA7N.js";import{a as x,b as Q}from"./chunk-OFILFO6D.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import pe from"node:path";import{StringDecoder as Oe}from"node:string_decoder";function he(r){return(i,a)=>{let n=r.resolve(i.path??".",a.cwd);if(n===void 0)return;let{backend:c,location:w}=n,e=s((t,o=w.source)=>{let m=r.resolve(t,o);if(m===void 0||m.backend!==c)throw new l("UNSUPPORTED_SOURCE",t,"not-applied");return m.location},"own");return{resolve:s((t,o)=>e(o,t.includes("://")?t:w.source).source,"resolve"),dirname:s(t=>N(w.target,pe.posix.dirname(e(t).path)).source,"dirname"),basename:s(t=>pe.posix.basename(e(t).path),"basename"),isDirectory:s(async(t,o)=>(await c.stat(e(t).path,{signal:o})).kind==="directory","isDirectory"),byteSize:s(async(t,o)=>(await c.stat(e(t).path,{signal:o})).size,"byteSize"),readText:s(async(t,o)=>(await c.read(e(t).path,{signal:o})).bytes.toString("utf8"),"readText"),async execute(t,o,m,R){let d=await c.execute(t,o,e(m).path,{signal:R});return{code:d.exitCode,stdout:d.stdout.toString("utf8"),stderr:d.stderr.toString("utf8")}},async runLines(t,o,m,R){let d=await c.startProcess("rg",t,e(o).path,{signal:R}),g=new Oe("utf8"),u=[],p=0,f="",h,y=s(k=>{let E=k.split(`
2
2
  `);for(let[O,b]of E.entries()){if(u.push(b),p+=Buffer.byteLength(b),p>32*1024*1024)throw new l("CONTENT_LIMIT",w.source,"not-applied");O<E.length-1&&(m(u.join("")),u.length=0,p=0)}},"consume"),v=(async()=>{try{for await(let k of d.stdout)y(g.write(k));y(g.end()),p>0&&m(u.join(""))}catch(k){h=k,await d.stop()}})(),T=(async()=>{for await(let k of d.stderr)f+=k.toString("utf8"),f.length>65536&&(f=f.slice(-65536))})();try{try{await d.end()}catch(E){if(!(E instanceof l)||E.code!=="INPUT_CLOSED")throw E}let k=await d.completion;if(await Promise.all([v,T]),h!==void 0)throw h instanceof Error?h:new Error("Search output failed.",{cause:h});return R?.throwIfAborted(),{code:k.exitCode,stderr:f}}finally{await d.stop(),await Promise.allSettled([v,T])}}}}}s(he,"createSshSearchEnvironmentProvider");import{lstat as Ue,mkdir as ke,rm as Me,symlink as He,unlink as Ve,open as Ge}from"node:fs/promises";import A from"node:path";import{constants as $}from"node:fs";import{createHash as Pe,randomBytes as Te}from"node:crypto";import{constants as we}from"node:fs";import{lstat as Ie,mkdir as Ne,open as me,readFile as Ce,rename as _e,rm as Ae,unlink as Fe}from"node:fs/promises";import D from"node:path";import{fileURLToPath as Le}from"node:url";function C(r,i,a){if(a?.has(r)&&a.get(r)!==i)throw new l("CONFLICT",r,"not-applied")}s(C,"checkCapturedRevision");var Be=1024*1024,De=Ce(new URL("./ssh-transfer-worker.py",new URL("../src/backend/file-transfer.ts",import.meta.url).href),"utf8");function j(r,i){if(r.startsWith("file:"))try{return Le(r)}catch{throw new l("UNSUPPORTED_SOURCE",r,"not-applied")}if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r))throw new l("UNSUPPORTED_SOURCE",r,"not-applied");if(i.startsWith("ssh://"))throw new l("UNSUPPORTED_SOURCE",r,"not-applied");return D.resolve(i,r)}s(j,"localTransferSource");function F(r){return[r.dev,r.ino,r.mode,r.uid,r.gid,r.size,r.mtimeNs,r.ctimeNs].join(":")}s(F,"localRevision");async function U(r){let i=await Ie(r,{bigint:!0});if(!i.isFile()||i.isSymbolicLink())throw new l("INVALID_FILE_TYPE",r,"not-applied");if(i.size>BigInt(Number.MAX_SAFE_INTEGER))throw new l("CONTENT_LIMIT",r,"not-applied");return i}s(U,"localEntry");function ye(r){return r!==null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}s(ye,"missing");function ge(r){return r!==null&&typeof r=="object"&&"code"in r&&typeof r.code=="string"&&/^[A-Z][A-Z0-9_]*$/u.test(r.code)?r.code:"TRANSFER_FAILED"}s(ge,"errorCode");async function je(r,i,a,n){a.signal?.throwIfAborted();let c=r.resolve(i.path,a.cwd),w=r.resolve(i.target??"",a.cwd),e=c?.location.source??j(i.path,a.cwd),t=w?.location.source??j(i.target??"",a.cwd);if(e===t)throw new l("SAME_FILE",e,"not-applied");let o=c?await c.backend.lstat(c.location.path,a):await U(e);if("kind"in o&&o.kind!=="file")throw new l("INVALID_FILE_TYPE",e,"not-applied");let m=Number(o.size),R=Number(o.mode),d="revision"in o?o.revision:F(o);C(e,d,n);let g;try{g=w?await w.backend.lstat(w.location.path,a):await U(t)}catch(p){if(!ye(p))throw p}if(g!==void 0){if("kind"in g&&g.kind!=="file")throw new l("INVALID_FILE_TYPE",t,"not-applied");if(C(t,"revision"in g?g.revision:F(g),n),c&&w&&c.backend.target.host===w.backend.target.host&&c.backend.target.configFile===w.backend.target.configFile&&"identity"in o&&"identity"in g&&o.identity.device===g.identity.device&&o.identity.inode===g.identity.inode)throw new l("SAME_FILE",e,"not-applied")}let u=g===void 0?null:"revision"in g?g.revision:F(g);return g===void 0&&C(t,null,n),{source:e,target:t,remoteSource:c,remoteTarget:w,size:m,mode:R,sourceRevision:d,targetRevision:u}}s(je,"prepareTransfer");async function Y(r,i,a,n,c,w){let{source:e,target:t,remoteSource:o,remoteTarget:m,size:R,mode:d,sourceRevision:g,targetRevision:u}=await je(r,a,n,c);await w?.();let p=o?void 0:await me(e,we.O_RDONLY|we.O_NOFOLLOW),f,h,y,v=!1,T="",k=s(async()=>{let E=o?await o.backend.lstat(o.location.path,n):await U(e);if(("revision"in E?E.revision:F(E))!==g)throw new l("CONFLICT",e,"not-applied")},"verifySource");try{if(p&&F(await p.stat({bigint:!0}))!==g)throw new l("CONFLICT",e,"not-applied");m?(y=await de(m.backend.target,"python3",["-c",await De,JSON.stringify({destination:m.location.path,size:R,mode:d,expected:u})],"/",n),y.completion.catch(()=>{}),y.stdout.on("data",b=>{T.length<=8192&&(T+=b.toString("utf8")),T.length>8192&&y?.stop().catch(()=>{})}),y.stderr.resume()):(await Ne(D.dirname(t),{recursive:!0}),f=D.join(D.dirname(t),`.pi-ide-transfer-${Te(12).toString("hex")}`),h=await me(f,"wx",d&4095));let E=Pe("sha256");for(let b=0;b<R;){n.signal?.throwIfAborted();let S=Math.min(Be,R-b),I;if(o){let P=await o.backend.readRange(o.location.path,b,S,n);if(P.revision!==g||P.offset!==b||P.totalBytes!==R)throw new l("CONFLICT",e,"not-applied");I=P.bytes}else{if(p===void 0)throw new Error("Missing source descriptor");let P=Buffer.allocUnsafe(S),{bytesRead:B}=await p.read(P,0,S,b);I=P.subarray(0,B)}if(I.length===0)throw new l("CONFLICT",e,"not-applied");if(E.update(I),y)await y.write(I);else{if(h===void 0)throw new Error("Missing destination descriptor");for(let P=0;P<I.length;){let B=await h.write(I,P,I.length-P);if(B.bytesWritten===0)throw new l("TRANSFER_FAILED",t,"not-applied");P+=B.bytesWritten}}b+=I.length}await k(),await w?.();let O=E.digest("hex");if(n.signal?.throwIfAborted(),y){if(await y.write(Buffer.from(`${JSON.stringify({sha256:O})}
3
3
  `)),await y.end(),(await y.completion).exitCode!==0||T.length>8192)throw new l("TRANSFER_FAILED",t,"unknown");let S;try{S=JSON.parse(T)}catch{throw new l("INVALID_REPLY",t,"unknown")}if(S===null||typeof S!="object"||!("ok"in S))throw new l("INVALID_REPLY",t,"unknown");if(S.ok!==!0){let I="effect"in S&&(S.effect==="not-applied"||S.effect==="applied")?S.effect:"unknown";throw new l(ge(S),t,I)}if(!("sha256"in S)||S.sha256!==O)throw new l("CHECKSUM_MISMATCH",t,"unknown");v=!0}else{if(h===void 0||f===void 0)throw new Error("Missing staged destination");await h.chmod(d&4095),await h.sync(),await h.close(),h=void 0;let b=null;try{b=F(await U(t))}catch(S){if(!ye(S))throw S}if(b!==u)throw new l("CONFLICT",t,"not-applied");n.signal?.throwIfAborted(),await _e(f,t),f=void 0,v=!0}return i==="move"&&(await k(),o?await o.backend.removeEntry(o.location.path,g,n):await Fe(e)),{source:e,target:t}}catch(E){throw v?new l(ge(E),e,"unknown"):E}finally{await p?.close(),await h?.close(),f!==void 0&&await Ae(f,{force:!0}),y&&await y.stop().catch(()=>{})}}s(Y,"transferFile");function Re(r,i,a){let n=r.resolve(i,a.cwd);if(n===void 0){let e=j(i,a.cwd);return{path:e,source:e,cwd:a.cwd,files:te}}let c=r.resolve(a.cwd,a.cwd),w=c?.location.target===n.location.target?c.location.path:n.backend.target.workspace;return{remote:n,source:n.location.source,path:n.location.path,cwd:w,files:{owner:JSON.stringify([n.backend.target.host,n.backend.target.configFile??null]),realpath:s(e=>n.backend.realpath(e,a),"realpath"),inspect:s(e=>n.backend.lstat(e,a),"inspect"),read:s(async e=>(await n.backend.read(e,a)).bytes.toString("utf8"),"read"),git:s((e,t,o)=>n.backend.queryGit(e,t,{...a,signal:o}),"git"),source:s(e=>N(n.location.target,e).source,"source"),snapshot:s((e,t)=>n.backend.objectSnapshot(e,{...a,signal:t}),"snapshot")}}}s(Re,"endpoint");function L(r,i,a){let n=r.remote?A.posix:A;if(n.sep==="\\"&&a.split("/").some(c=>c.includes("\\")||c.includes(":")))throw new l("INVALID_TARGET",r.source,"not-applied");return n.join(i,...a.split("/"))}s(L,"leaf");function K(r,i){return r.remote?N(r.remote.location.target,i).source:i}s(K,"receiptPath");async function _(r,i,a){let n;try{n=await r.files.inspect(i)}catch(c){if(c!==null&&typeof c=="object"&&"code"in c&&c.code==="ENOENT"){if(a===void 0)return}else throw c}if(a===void 0||n?.revision!==a.revision)throw new l("TRANSFER_TARGET_CHANGED",K(r,i),"not-applied")}s(_,"checkEntry");async function M(r){let i;try{i=await Ue(r)}catch(a){if(a===null||typeof a!="object"||!("code"in a)||a.code!=="ENOENT")throw a;await M(A.dirname(r)),await ke(r);return}if(!i.isDirectory()||i.isSymbolicLink())throw new l("INVALID_FILE_TYPE",r,"not-applied");A.dirname(r)!==r&&await M(A.dirname(r))}s(M,"directoryParents");async function ve(r,i,a,n){r.remote?await r.remote.backend.removeObject(i,a.revision,n):(await _(r,i,a),a.kind==="directory"?await Me(i,{recursive:!0,force:!1}):await Ve(i))}s(ve,"remove");async function Ee(r,i,a,n,c,w){let e=Re(r,a.path,n),t=Re(r,a.target??"",n),o=await c.prepareTransfer(i,e,t),m=o.source.entries[0];if(m===void 0)throw new l("ENOENT",e.source,"not-applied");e.remote&&C(e.source,m.revision,w),t.remote&&C(t.source,o.target.entries[0]?.revision??null,w);let R=!1;try{n.signal?.throwIfAborted();for(let d of o.source.entries)L(e,o.source.path,d.relativePath),L(t,o.target.path,d.relativePath);if(o.sourceKind==="file")e.remote&&t.remote&&e.remote.location.target===t.remote.location.target?await e.remote.backend[i](o.source.path,o.target.path,m.revision,o.target.entries[0]?.revision??null,n):await Y(r,i,a,n,w,async()=>{await _(e,o.source.path,m),await _(t,o.target.path,o.target.entries[0])});else{if(i==="move"&&e.remote&&t.remote&&e.files.owner===t.files.owner&&await e.remote.backend.moveObject(o.source,o.target,n))return{kind:"file-operation",operation:i,ok:!0,effect:"applied",path:e.source,target:t.source,sourceKind:o.sourceKind};let d=new Map(o.target.entries.map(u=>[u.relativePath,u])),g=new Map;i==="move"&&o.target.entries[0]&&(R=!0,await ve(t,o.target.path,o.target.entries[0],n),d.clear());for(let u of o.source.entries){n.signal?.throwIfAborted();let p=L(e,o.source.path,u.relativePath),f=L(t,o.target.path,u.relativePath);await _(e,p,u);let h=d.get(u.relativePath);if(await _(t,f,h),u.kind==="directory")h===void 0&&(R=!0),t.remote?await t.remote.backend.ensureObjectDirectory(f,u.mode|448,h?.revision??null,n):h===void 0&&(await M(A.dirname(f)),await ke(f,{mode:u.mode|448})),h===void 0&&g.set(u.relativePath,(await t.files.inspect(f)).identity);else if(u.kind==="symlink"){if(R=!0,u.link===void 0)throw new l("INVALID_RESPONSE",e.source,"unknown");t.remote?await t.remote.backend.createObjectLink(f,u.link,n):(await M(A.dirname(f)),await He(Buffer.from(u.link,"base64"),f))}else{R=!0;let y=K(e,p),v=K(t,f);e.remote&&t.remote&&e.files.owner===t.files.owner?await e.remote.backend.copy(p,f,u.revision,h?.revision??null,n):await Y(r,"copy",{path:y,target:v},n,void 0,async()=>{await _(e,p,u),await _(t,f,h)})}}for(let u of[...o.source.entries].reverse()){if(u.kind!=="directory"||d.has(u.relativePath))continue;let p=L(t,o.target.path,u.relativePath),f=await t.files.inspect(p),h=g.get(u.relativePath);if(f.kind!=="directory"||h?.device!==f.identity.device||h.inode!==f.identity.inode)throw new l("TRANSFER_TARGET_CHANGED",t.source,"unknown");if(t.remote)await t.remote.backend.setObjectMode(p,u.mode,f.revision,n);else{let y=await Ge(p,$.O_RDONLY|$.O_DIRECTORY|$.O_NOFOLLOW);try{let v=await y.stat();if(String(v.dev)!==h.device||String(v.ino)!==h.inode)throw new l("TRANSFER_TARGET_CHANGED",t.source,"unknown");await y.chmod(u.mode&4095)}finally{await y.close()}}}await o.verifySource(),i==="move"&&await ve(e,o.source.path,m,n)}return{kind:"file-operation",operation:i,ok:!0,effect:"applied",path:e.source,target:t.source,sourceKind:o.sourceKind}}catch(d){throw R?Object.assign(d instanceof Error?d:new Error(String(d)),{effect:"unknown"}):d}}s(Ee,"transferObject");function Se(r,i){return async(a,n,c,w)=>{let e=r.resolve(n.path,c.cwd);if(e===void 0&&(n.target===void 0||r.resolve(n.target,c.cwd)===void 0))return;if(a!=="delete"){if(w===void 0)throw new l("TRANSFER_POLICY_REQUIRED",n.path,"not-applied");return Ee(r,a,n,c,w,i)}if(e===void 0)return;let t=await e.backend.lstat(e.location.path,c);C(e.location.source,t.revision,i);{if(w===void 0)throw new l("DELETE_POLICY_REQUIRED",e.location.source,"not-applied");let o=r.resolve(c.cwd,c.cwd);if(o!==void 0&&o.location.target!==e.location.target)throw new l("UNSUPPORTED_SOURCE",e.location.source,"not-applied");let m=o?.location.path??e.backend.target.workspace,R=await w.prepare(e.location.path,m,{temporaryEnvironment:s(d=>e.backend.temporaryEnvironment({...c,signal:d}),"temporaryEnvironment"),realpath:s(d=>e.backend.realpath(d,c),"realpath"),inspect:s(d=>e.backend.lstat(d,c),"inspect"),read:s(async d=>(await e.backend.read(d,c)).bytes.toString("utf8"),"read"),git:s((d,g,u)=>e.backend.queryGit(d,g,{...c,signal:u}),"git"),source:s(d=>N(e.location.target,d).source,"source")});if(R.revision!==t.revision)throw new l("DELETE_TARGET_CHANGED",e.location.source,"not-applied");return await e.backend.removeObject(R.resolvedPath,R.revision,c),{kind:"file-operation",operation:a,ok:!0,effect:"applied",path:e.location.source}}}}s(Se,"createSshFileOperationResolver");function W(r,i,a){return{id:"ssh",async tryResolve(n,c){try{let w=r.resolve(n,c.cwd);if(!w)return{kind:"not-handled"};let{backend:e,location:t}=w,o=!1;try{o=(await e.stat(t.path,c)).kind==="directory"}catch(p){if(!(p instanceof l)||p.code!=="ENOENT")throw p}let m,R,d=s(async p=>{try{let f=await e.read(t.path,p);return m=f.version,f.bytes}catch(f){throw f instanceof l&&f.code==="ENOENT"&&(m=null),f}},"snapshot"),g=s(async p=>{if(R=void 0,o){let h=(await e.list(t.path,p)).map(y=>` ${y.kind==="directory"?"\u{1F4C1}":y.kind==="file"?"\u{1F4C4}":"\u{1F517}"} ${y.name}`);return[{type:"text",text:[`\u{1F4C1} ${t.source}/`,...h.length?["",...h]:[]].join(`
4
4
  `)}]}return R=await d(p),i.convert({source:t.source,bytes:R},p)},"read"),u=s(async(p,f,h)=>{let v=await e.readRange(t.path,p,Math.min(f??4194304,4194304),h),T=[v.bytes],k=v.bytes.length,E=Math.min(f??v.totalBytes,v.totalBytes-v.offset);for(;k<E;){let O=await e.readRange(t.path,v.offset+k,Math.min(E-k,4194304),h);if(O.revision!==v.revision||O.totalBytes!==v.totalBytes||O.offset!==v.offset+k)throw new l("SOURCE_CHANGED",t.source,"not-applied");if(O.bytes.length===0)break;T.push(O.bytes),k+=O.bytes.length}return{bytes:Buffer.concat(T,k),byteOffset:v.offset,totalBytes:v.totalBytes}},"readBytes");return a==="read"||o?{kind:"resolved",resource:{source:t.source,link:t.source,read:g,get sourceBytes(){return R},...o?{}:{readBytes:u}}}:{kind:"resolved",resource:{source:t.source,link:t.source,read:g,readBytes:u,get sourceBytes(){return R},async write(p,f){let h=J(p);if(m===void 0)try{await d(f)}catch(y){if(!(y instanceof l)||y.code!=="ENOENT")throw y}if(m===void 0)throw new l("SNAPSHOT_REQUIRED",t.source,"not-applied");m=await e.write(t.path,Buffer.from(h,"utf8"),m,f)}}}}catch(w){return{kind:"failed",error:w}}}}}s(W,"createSshResourceResolver");async function be(r,i){let a=await q({id:"ssh",description:"Set up SSH targets and use remote resources",triggers:[{tool:"read",resourcePrefixes:["ssh://","raw:ssh://","ast:ssh://","web:ssh://"]},{tool:"search",resourcePrefixes:["ssh://","web:ssh://"]},{tool:"debug",resourcePrefixes:["ssh://"]},...["write","replace","insert","delete","copy","move","stage","unstage","undo"].map(o=>({tool:o,resourcePrefixes:["ssh://"]}))]});if(Z(r,[{...a,markdown:`${a.markdown}
@@ -1 +1 @@
1
- import{a as O}from"./chunk-AKNHSDGV.js";import{a as R}from"./chunk-N56WAVYA.js";import{a as v,b as S}from"./chunk-GEMDU6XW.js";import{b as y}from"./chunk-WPBQ45ZL.js";import"./chunk-WXGTU2M6.js";import{a as w,b as E,c as b}from"./chunk-LLRUJD62.js";import"./chunk-Q5X6OXNS.js";import{g as s}from"./chunk-4HWKBCBH.js";import{a as p,b as k,d as C}from"./chunk-6EDOLYOV.js";import{c as g}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-DXONCYWF.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import{c as u,l as h,m as P}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";import T from"node:path";function A(i){let l=v(i),U=R(i),d=new Map;return{async resolveProject(r,o){if(r.startsWith("ssh://")||o.startsWith("ssh://")){let e=i.resolve(r,o);if(!e)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let t=i.resolve(o);if(t&&t.location.target!==e.location.target)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");return O(e.backend,e.location.path,t?.location.path,"formatters",p)}if(r.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let n=await u(o,r,"formatters",p);return n===void 0?void 0:{cwd:n,external:n!==T.resolve(o)}},async loadRegistry(r,o){let n=JSON.stringify([r,o]),e=d.get(n);if(!e){let t=i.resolve(r);e=k.fromDirectory(r,{includeGlobal:!o,requireBuiltInEvidence:!0,...t?{layerAccess:l,executableAvailability:c(a=>y(t.backend,t.location.path,a),"executableAvailability"),recipeEvidence:c(a=>S(t.backend,t.location.path,a),"recipeEvidence")}:{}}),d.set(n,e)}return e},async run(r,o,n){let e=i.resolve(n);if(!e){if(n.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",n,"not-applied");return P(r,{projectRoot:o,filePath:n})}let t=await e.backend.read(e.location.path),a=await h(r.run,{projectRoot:o,filePath:n,processAccess:U}),m=await e.backend.read(e.location.path);if(!a.ok)return{ok:!1,changed:!m.bytes.equals(t.bytes)};if(r.output==="stdout"){if(m.version!==t.version)throw new s("CONFLICT",n,"not-applied");let f=Buffer.from(a.stdout);return f.equals(t.bytes)||await e.backend.write(e.location.path,f,t.version),{ok:!0,changed:!f.equals(t.bytes)}}return{ok:!0,changed:!m.bytes.equals(t.bytes)}}}}c(A,"createOwnedFormatterRuntime");async function F(i){let l=new b(await E(w(g())));await C(i,A(l))}c(F,"registerOwnedFormatter");export{A as createOwnedFormatterRuntime,F as default};
1
+ import{a as O}from"./chunk-QT3EAHOG.js";import{a as R}from"./chunk-SMIFCAAX.js";import{a as v,b as S}from"./chunk-VXP5BMW7.js";import{b as y}from"./chunk-RW2GTYQI.js";import{a as w,b as E,c as b}from"./chunk-RIJMXO43.js";import"./chunk-VMTOFEXF.js";import"./chunk-CPELC6JE.js";import{g as s}from"./chunk-PJL3UVMJ.js";import{a as p,b as k,d as C}from"./chunk-6EDOLYOV.js";import{c as g}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-LCWBVOII.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import{c as u,l as h,m as P}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";import T from"node:path";function A(i){let l=v(i),U=R(i),d=new Map;return{async resolveProject(r,o){if(r.startsWith("ssh://")||o.startsWith("ssh://")){let e=i.resolve(r,o);if(!e)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let t=i.resolve(o);if(t&&t.location.target!==e.location.target)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");return O(e.backend,e.location.path,t?.location.path,"formatters",p)}if(r.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let n=await u(o,r,"formatters",p);return n===void 0?void 0:{cwd:n,external:n!==T.resolve(o)}},async loadRegistry(r,o){let n=JSON.stringify([r,o]),e=d.get(n);if(!e){let t=i.resolve(r);e=k.fromDirectory(r,{includeGlobal:!o,requireBuiltInEvidence:!0,...t?{layerAccess:l,executableAvailability:c(a=>y(t.backend,t.location.path,a),"executableAvailability"),recipeEvidence:c(a=>S(t.backend,t.location.path,a),"recipeEvidence")}:{}}),d.set(n,e)}return e},async run(r,o,n){let e=i.resolve(n);if(!e){if(n.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",n,"not-applied");return P(r,{projectRoot:o,filePath:n})}let t=await e.backend.read(e.location.path),a=await h(r.run,{projectRoot:o,filePath:n,processAccess:U}),m=await e.backend.read(e.location.path);if(!a.ok)return{ok:!1,changed:!m.bytes.equals(t.bytes)};if(r.output==="stdout"){if(m.version!==t.version)throw new s("CONFLICT",n,"not-applied");let f=Buffer.from(a.stdout);return f.equals(t.bytes)||await e.backend.write(e.location.path,f,t.version),{ok:!0,changed:!f.equals(t.bytes)}}return{ok:!0,changed:!m.bytes.equals(t.bytes)}}}}c(A,"createOwnedFormatterRuntime");async function F(i){let l=new b(await E(w(g())));await C(i,A(l))}c(F,"registerOwnedFormatter");export{A as createOwnedFormatterRuntime,F as default};
package/dist/entry-0.js CHANGED
@@ -1 +1 @@
1
- import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l}from"./chunk-DUUOCBS3.js";import{a,b,c,d}from"./chunk-T4FTT3U4.js";import"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{h as addDiagnosticAnnotations,g as createDiagnosticViewContent,l as createSourceMappedTextReadHandler,i as diagnosticStatus,c as formatCodeViewReference,f as formatDiagnosticViewSource,k as formatSourceViewResults,d as formatSymbolSelector,a as parseCodeViewReference,j as renderSourceViewLine,b as resolveCodeViewPath,e as resolveDiagnosticViewPath};
1
+ import{a,b,c,d,e,f}from"./chunk-OJEIX7OZ.js";import"./chunk-EI7MMDWY.js";export{c as SETTINGS_READY_EVENT,b as SETTINGS_READ_EVENT,a as SETTINGS_REGISTER_EVENT,e as readAgentIdeSetting,d as registerAgentIdeSettings,f as validateAgentIdeSettings};
package/dist/entry-1.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import"./chunk-EI7MMDWY.js";export{a as connectIdePlugin};
1
+ import{d as p}from"./chunk-RQ7JJ7GV.js";import"./chunk-EI7MMDWY.js";export{p as confirmOperation};
package/dist/entry-10.js CHANGED
@@ -1 +1 @@
1
- import{a as o}from"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-EI7MMDWY.js";export{o as connectDoctorPlugin};
1
+ import{a as h,b as i,c as j,d as k}from"./chunk-TOYN4W4F.js";import{a,b,c,d,e,f,g}from"./chunk-S72FVLUX.js";import"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{c as DOCTOR_API_VERSION,d as DOCTOR_CORE_READY_EVENT,e as DOCTOR_PLUGIN_REGISTER_EVENT,b as DOCTOR_PROTOCOL,a as DOCTOR_TOOL_PATH_KEYS,j as doctorExecutableAvailable,i as doctorProcessAccess,h as doctorRuntimeOptions,f as isDoctorCoreReady,g as isDoctorPluginRegistrationRequest,k as withDoctorProbeCopy};