pi-agent-ide 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (603) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +24 -29
  3. package/dist/{chunk-CM3XGY72.js → chunk-2AY526TN.js} +1 -1
  4. package/dist/{chunk-LEJKDYCK.js → chunk-2TZDG2JH.js} +1 -1
  5. package/dist/{chunk-XBQR74IK.js → chunk-4GBFIGH3.js} +1 -1
  6. package/dist/{chunk-PJL3UVMJ.js → chunk-4IWEKRSP.js} +1 -1
  7. package/dist/chunk-52PFWQMU.js +5 -0
  8. package/dist/chunk-5BGWNYQS.js +1 -0
  9. package/dist/{chunk-QUYXINGZ.js → chunk-5S74Z6Y4.js} +3 -3
  10. package/dist/chunk-64JTD2DJ.js +1 -0
  11. package/dist/{chunk-XAHU42FP.js → chunk-6A3ORNW3.js} +2 -2
  12. package/dist/{chunk-ANM3Y5FO.js → chunk-6WCHBHFW.js} +5 -5
  13. package/dist/{chunk-IMGIDBCC.js → chunk-7D7PXIVV.js} +1 -1
  14. package/dist/chunk-7PVDTMEM.js +1 -0
  15. package/dist/chunk-7SG756UO.js +4 -0
  16. package/dist/{chunk-GBUJOR6V.js → chunk-7URANI6I.js} +14 -14
  17. package/dist/{chunk-Z2MNHSJ4.js → chunk-AJZVKDYC.js} +1 -1
  18. package/dist/chunk-AMIIOWFL.js +1 -0
  19. package/dist/{chunk-TOYN4W4F.js → chunk-B25LXXNV.js} +1 -1
  20. package/dist/chunk-C2JT2G5K.js +1 -0
  21. package/dist/chunk-CVOYSEBE.js +1 -0
  22. package/dist/chunk-DDH3FP4G.js +3 -0
  23. package/dist/chunk-FEZLTM4L.js +1 -0
  24. package/dist/{chunk-CPELC6JE.js → chunk-FHRHYY4M.js} +1 -1
  25. package/dist/chunk-FKKAHI62.js +11 -0
  26. package/dist/chunk-FS3KCKFX.js +9 -0
  27. package/dist/chunk-FYOU4RBH.js +2 -0
  28. package/dist/chunk-G4PRFO6G.js +1 -0
  29. package/dist/chunk-GS5ZRTUG.js +1 -0
  30. package/dist/{chunk-XXLLY66B.js → chunk-GXL4NMHR.js} +1 -1
  31. package/dist/{chunk-QT3EAHOG.js → chunk-H3GEEOOL.js} +1 -1
  32. package/dist/chunk-H5Z54BEU.js +25 -0
  33. package/dist/chunk-H7WAM5RH.js +23 -0
  34. package/dist/chunk-HT7LZN5A.js +9 -0
  35. package/dist/chunk-IG5DXVDJ.js +1 -0
  36. package/dist/chunk-K4UTEMDU.js +1 -0
  37. package/dist/chunk-KFBRL2V4.js +3 -0
  38. package/dist/chunk-KN6VPARZ.js +1 -0
  39. package/dist/{chunk-RW2GTYQI.js → chunk-LF325WYO.js} +1 -1
  40. package/dist/chunk-LTADNZKW.js +2 -0
  41. package/dist/{chunk-YJ6T3PEP.js → chunk-MDD5ORB6.js} +1 -1
  42. package/dist/{chunk-S72FVLUX.js → chunk-MLFJU2US.js} +1 -1
  43. package/dist/chunk-NA2NEU4V.js +1 -0
  44. package/dist/chunk-OBTT5INC.js +6 -0
  45. package/dist/{chunk-IICJXZBU.js → chunk-OMNKD7WW.js} +3 -3
  46. package/dist/chunk-PLMHBXWI.js +10 -0
  47. package/dist/{chunk-235QMMVA.js → chunk-PQWANILR.js} +1 -1
  48. package/dist/{chunk-QRJLIV6P.js → chunk-QJ6V5IAY.js} +6 -6
  49. package/dist/chunk-QM5WDEFI.js +1 -0
  50. package/dist/{chunk-SMIFCAAX.js → chunk-RIJRPAL2.js} +1 -1
  51. package/dist/chunk-RIOPUTUJ.js +6 -0
  52. package/dist/chunk-RVFMH77U.js +82 -0
  53. package/dist/{chunk-NJ7C4KMA.js → chunk-SRFWT562.js} +1 -1
  54. package/dist/{chunk-U22JNO6N.js → chunk-STUZZM5B.js} +1 -1
  55. package/dist/{chunk-PT35ZFLH.js → chunk-TNAUCNUT.js} +12 -12
  56. package/dist/{chunk-DUUOCBS3.js → chunk-TVH2ND35.js} +1 -1
  57. package/dist/chunk-TVSZYABY.js +5 -0
  58. package/dist/chunk-TVXZE4KW.js +4 -0
  59. package/dist/chunk-U7YDLVFL.js +1 -0
  60. package/dist/{chunk-KZC7TI5M.js → chunk-UD3DMY3Q.js} +1 -1
  61. package/dist/{chunk-VXP5BMW7.js → chunk-USG6WHAT.js} +1 -1
  62. package/dist/{chunk-RMI3NMQY.js → chunk-V4J3TLCV.js} +2 -2
  63. package/dist/{chunk-ZPT5D4VP.js → chunk-VDJSH3DQ.js} +2 -2
  64. package/dist/{chunk-VMTOFEXF.js → chunk-VMLPXSMK.js} +1 -1
  65. package/dist/{chunk-6T7PSDQW.js → chunk-VN3XBH2Q.js} +1 -1
  66. package/dist/chunk-WAJW4G4F.js +22 -0
  67. package/dist/chunk-WEE3NM6L.js +1 -0
  68. package/dist/{chunk-IM24DB3K.js → chunk-WES2E4VR.js} +1 -1
  69. package/dist/{chunk-RIJMXO43.js → chunk-WQIMM4SU.js} +1 -1
  70. package/dist/chunk-WUO3UW4J.js +17 -0
  71. package/dist/chunk-XE4W5YTE.js +2 -0
  72. package/dist/chunk-XUYIK4TX.js +1 -0
  73. package/dist/{chunk-ZJQRLVVV.js → chunk-Y74EKJOY.js} +1 -1
  74. package/dist/{chunk-AAC77UD4.js → chunk-YPYROPQF.js} +1 -1
  75. package/dist/chunk-ZXO4D5UB.js +1 -0
  76. package/dist/entry-0.js +1 -1
  77. package/dist/entry-1.js +1 -1
  78. package/dist/entry-10.js +1 -1
  79. package/dist/entry-11.js +1 -1
  80. package/dist/entry-12.js +1 -1
  81. package/dist/entry-13.js +1 -1
  82. package/dist/entry-14.js +1 -1
  83. package/dist/entry-15.js +1 -1
  84. package/dist/entry-16.js +1 -1
  85. package/dist/entry-17.js +1 -1
  86. package/dist/entry-18.js +1 -1
  87. package/dist/entry-19.js +1 -1
  88. package/dist/entry-2.js +1 -1
  89. package/dist/entry-20.js +1 -1
  90. package/dist/entry-21.js +1 -0
  91. package/dist/entry-23.js +1 -1
  92. package/dist/entry-24.js +1 -1
  93. package/dist/entry-25.js +1 -1
  94. package/dist/entry-26.js +1 -1
  95. package/dist/entry-27.js +1 -1
  96. package/dist/entry-28.js +1 -1
  97. package/dist/entry-29.js +1 -2
  98. package/dist/entry-3.js +1 -1
  99. package/dist/entry-30.js +2 -1
  100. package/dist/entry-31.js +1 -4
  101. package/dist/entry-32.js +1 -1
  102. package/dist/entry-33.js +1 -1
  103. package/dist/entry-34.js +1 -1
  104. package/dist/entry-35.js +1 -18
  105. package/dist/entry-36.js +1 -1
  106. package/dist/entry-37.js +15 -1
  107. package/dist/entry-38.js +1 -1
  108. package/dist/entry-39.js +1 -1
  109. package/dist/entry-4.js +1 -1
  110. package/dist/entry-40.js +1 -1
  111. package/dist/entry-41.js +1 -1
  112. package/dist/entry-42.js +1 -1
  113. package/dist/entry-43.js +1 -1
  114. package/dist/entry-44.js +1 -1
  115. package/dist/entry-45.js +1 -1
  116. package/dist/entry-46.js +1 -1
  117. package/dist/entry-47.js +1 -1
  118. package/dist/entry-48.js +1 -1
  119. package/dist/entry-49.js +1 -25
  120. package/dist/entry-5.js +1 -1
  121. package/dist/entry-50.js +1 -1
  122. package/dist/entry-51.js +1 -1
  123. package/dist/entry-52.js +1 -1
  124. package/dist/entry-53.js +1 -1
  125. package/dist/entry-54.js +1 -3
  126. package/dist/entry-55.js +1 -13
  127. package/dist/entry-56.js +1 -1
  128. package/dist/entry-57.js +1 -1
  129. package/dist/entry-58.js +1 -1
  130. package/dist/entry-59.js +1 -1
  131. package/dist/entry-6.js +1 -1
  132. package/dist/entry-60.js +1 -1
  133. package/dist/entry-61.js +1 -1
  134. package/dist/entry-62.js +1 -1
  135. package/dist/entry-63.js +1 -1
  136. package/dist/entry-64.js +1 -1
  137. package/dist/entry-65.js +1 -0
  138. package/dist/entry-66.js +1 -1
  139. package/dist/entry-68.js +1 -1
  140. package/dist/entry-69.js +0 -1
  141. package/dist/entry-7.js +1 -1
  142. package/dist/entry-70.js +1 -1
  143. package/dist/entry-71.js +1 -1
  144. package/dist/entry-72.js +1 -1
  145. package/dist/entry-73.js +1 -1
  146. package/dist/entry-74.js +1 -1
  147. package/dist/entry-75.js +1 -0
  148. package/dist/entry-76.js +1 -1
  149. package/dist/entry-78.js +1 -1
  150. package/dist/entry-79.js +0 -1
  151. package/dist/entry-8.js +1 -1
  152. package/dist/entry-80.js +1 -1
  153. package/dist/entry-81.js +1 -80
  154. package/dist/entry-82.js +1 -22
  155. package/dist/entry-83.js +1 -2
  156. package/dist/entry-84.js +1 -1
  157. package/dist/entry-85.js +2 -1
  158. package/dist/entry-86.js +1 -1
  159. package/dist/entry-87.js +1 -1
  160. package/dist/entry-88.js +1 -3
  161. package/dist/entry-89.js +1 -1
  162. package/dist/entry-9.js +1 -1
  163. package/dist/entry-90.js +3 -1
  164. package/dist/entry-91.js +1 -1
  165. package/dist/entry-92.js +1 -0
  166. package/dist/entry-93.js +1 -0
  167. package/dist/pi-agent-ide.js +10 -34
  168. package/docs/agent-guides/ast-search.md +58 -0
  169. package/docs/agent-guides/debugger.md +1 -1
  170. package/docs/agent-guides/editing.md +26 -58
  171. package/docs/agent-guides/git-changes.md +4 -14
  172. package/docs/agent-guides/search.md +38 -0
  173. package/docs/agent-guides/ssh.md +17 -49
  174. package/docs/agent-guides/terminal.md +9 -15
  175. package/docs/configuration.md +9 -13
  176. package/docs/extensions.md +82 -0
  177. package/docs/settings-help.md +2 -2
  178. package/docs/structured-results.md +33 -11
  179. package/docs/tools.md +23 -22
  180. package/node_modules/pi-agent-doctor/package.json +7 -7
  181. package/node_modules/pi-agent-doctor/src/workspace.ts +0 -5
  182. package/node_modules/pi-agent-documentation/package.json +2 -2
  183. package/node_modules/pi-agent-documentation/runtime/entry-29.js +1 -0
  184. package/node_modules/pi-agent-documentation/src/index.ts +26 -10
  185. package/node_modules/pi-agent-filesystem/index.ts +1 -1
  186. package/node_modules/pi-agent-filesystem/package.json +8 -8
  187. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  188. package/node_modules/pi-agent-filesystem-jq/index.ts +9 -63
  189. package/node_modules/pi-agent-filesystem-jq/package.json +12 -6
  190. package/node_modules/pi-agent-filesystem-jq/runtime/entry-32.js +1 -0
  191. package/node_modules/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  192. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  193. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-34.js +2 -0
  194. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  195. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  196. package/node_modules/pi-agent-ide-ast/src/extension.ts +8 -8
  197. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  198. package/node_modules/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  199. package/node_modules/pi-agent-ide-changes/index.ts +1 -2
  200. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  201. package/node_modules/pi-agent-ide-changes/runtime/entry-38.js +1 -0
  202. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  203. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  204. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  205. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  206. package/node_modules/pi-agent-ide-lint/runtime/entry-42.js +2 -0
  207. package/node_modules/pi-agent-ide-lsp/index.ts +22 -28
  208. package/node_modules/pi-agent-ide-lsp/package.json +14 -10
  209. package/node_modules/pi-agent-ide-lsp/runtime/entry-43.js +2 -0
  210. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  211. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  212. package/node_modules/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  213. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  214. package/node_modules/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  215. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  216. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  217. package/node_modules/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  218. package/node_modules/pi-agent-image/package.json +3 -3
  219. package/node_modules/pi-agent-image/src/image-converter.ts +24 -1
  220. package/node_modules/pi-agent-invariant/package.json +2 -2
  221. package/node_modules/pi-agent-pdf/package.json +3 -3
  222. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +23 -1
  223. package/node_modules/pi-agent-read/package.json +12 -12
  224. package/node_modules/pi-agent-read/runtime/entry-49.js +0 -1
  225. package/node_modules/pi-agent-read/runtime/entry-51.js +2 -0
  226. package/node_modules/pi-agent-read/src/api/read-parameters.ts +4 -7
  227. package/node_modules/pi-agent-read/src/api/tools/read.ts +2 -0
  228. package/node_modules/pi-agent-read/src/core/extension.ts +0 -8
  229. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  230. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  231. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  232. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  233. package/node_modules/pi-agent-resource/package.json +2 -2
  234. package/node_modules/pi-agent-resource/src/index.ts +8 -0
  235. package/node_modules/pi-agent-resource/src/resource-error-metadata.ts +89 -0
  236. package/node_modules/pi-agent-resource/src/resource-error.ts +6 -1
  237. package/node_modules/pi-agent-resource/src/result-images.ts +87 -0
  238. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -3
  239. package/node_modules/pi-agent-resource/src/tool-result.ts +17 -0
  240. package/node_modules/pi-agent-search/package.json +9 -9
  241. package/node_modules/pi-agent-search/runtime/entry-54.js +0 -1
  242. package/node_modules/pi-agent-search/runtime/entry-55.js +1 -0
  243. package/node_modules/pi-agent-search/runtime/entry-56.js +2 -0
  244. package/node_modules/pi-agent-search/src/api/glob-list.ts +35 -0
  245. package/node_modules/pi-agent-search/src/api/search-parameters.ts +8 -8
  246. package/node_modules/pi-agent-search/src/api/search.ts +14 -2
  247. package/node_modules/pi-agent-search/src/core/extension.ts +11 -20
  248. package/node_modules/pi-agent-search/src/core/search-core.ts +30 -10
  249. package/node_modules/pi-agent-search-text/index.ts +34 -12
  250. package/node_modules/pi-agent-search-text/package.json +17 -15
  251. package/node_modules/pi-agent-search-text/runtime/entry-57.js +1 -0
  252. package/node_modules/pi-agent-search-text/runtime/entry-60.js +1 -0
  253. package/node_modules/pi-agent-search-text/src/file-search.ts +59 -25
  254. package/node_modules/pi-agent-search-text/src/resolvers.ts +61 -16
  255. package/node_modules/pi-agent-search-text/src/scoped-search.ts +9 -3
  256. package/node_modules/pi-agent-search-text/src/search-backend.ts +44 -48
  257. package/node_modules/pi-agent-search-text/src/search-presentation.ts +19 -15
  258. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -1
  259. package/node_modules/pi-agent-search-text/src/search-result.ts +6 -2
  260. package/node_modules/pi-agent-search-text/src/search-session.ts +1 -0
  261. package/node_modules/pi-agent-search-text/src/tool-file-search.ts +146 -0
  262. package/node_modules/pi-agent-text/package.json +3 -3
  263. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  264. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  265. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  266. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  267. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +1 -2
  268. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  269. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-66.js +2 -0
  270. package/node_modules/pi-agent-text-editor/package.json +26 -26
  271. package/node_modules/pi-agent-text-editor/runtime/entry-81.js +0 -1
  272. package/node_modules/pi-agent-text-editor/runtime/entry-82.js +1 -0
  273. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  274. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  275. package/node_modules/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  276. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  277. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  278. package/node_modules/pi-agent-text-editor/src/core/extension.ts +13 -7
  279. package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  280. package/node_modules/pi-agent-text-editor/src/core/image-write.ts +111 -0
  281. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  282. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  283. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  284. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  285. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  286. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  287. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +43 -12
  288. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  289. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -5
  290. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +3 -7
  291. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +6 -8
  292. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -6
  293. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  294. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  295. package/node_modules/pi-agent-text-editor-renderer/index.ts +6 -1
  296. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  297. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-84.js +2 -0
  298. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  299. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -6
  300. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-85.js +2 -0
  301. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  302. package/node_modules/pi-agent-tool-ui/package.json +3 -3
  303. package/node_modules/pi-agent-tool-ui/runtime/entry-87.js +1 -0
  304. package/node_modules/pi-agent-tool-ui/runtime/entry-88.js +1 -0
  305. package/node_modules/pi-agent-web/index.ts +28 -6
  306. package/node_modules/pi-agent-web/package.json +8 -8
  307. package/node_modules/pi-agent-web-html/package.json +3 -3
  308. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  309. package/node_modules/pi-agent-web-image/package.json +4 -4
  310. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  311. package/node_modules/pi-agent-web-pdf/runtime/entry-92.js +2 -0
  312. package/node_modules/pi-agent-web-text/package.json +4 -4
  313. package/node_modules/pi-agent-web-text/runtime/entry-93.js +2 -0
  314. package/package.json +61 -58
  315. package/src/api/approval.ts +2 -0
  316. package/src/api/read.ts +2 -0
  317. package/src/api/standalone.ts +7 -0
  318. package/src/backend/doctor-workspace.ts +0 -3
  319. package/src/backend/process-metadata-worker.py +9 -18
  320. package/src/backend/process-metadata.ts +11 -44
  321. package/src/backend/registration.ts +0 -10
  322. package/src/backend/web-browser-worker.mjs +2 -17
  323. package/src/backend/web-browser.ts +1 -26
  324. package/src/composite/builtin-extensions.ts +8 -6
  325. package/src/composite/ide-alias-rendering.ts +18 -2
  326. package/src/composite/module-labels.ts +0 -4
  327. package/src/composite/preferences.ts +0 -36
  328. package/src/composite/settings-documentation.ts +1 -2
  329. package/src/composite/text-results.ts +61 -23
  330. package/src/documentation/extension.ts +39 -15
  331. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +1 -1
  332. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  333. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  334. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +9 -63
  335. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +12 -6
  336. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-32.js +1 -0
  337. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  338. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  339. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-34.js +2 -0
  340. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  341. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-35.js +2 -0
  342. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-30.js +2 -0
  343. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -6
  344. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  345. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  346. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  347. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  348. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  349. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-92.js +2 -0
  350. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  351. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-93.js +2 -0
  352. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-89.js +2 -0
  353. package/src/extensions/pi-agent-read/package.json +12 -12
  354. package/src/extensions/pi-agent-read/runtime/entry-49.js +0 -1
  355. package/src/extensions/pi-agent-read/runtime/entry-50.js +1 -0
  356. package/src/extensions/pi-agent-read/runtime/entry-51.js +2 -0
  357. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +4 -7
  358. package/src/extensions/pi-agent-read/src/api/tools/read.ts +2 -0
  359. package/src/extensions/pi-agent-read/src/core/extension.ts +0 -8
  360. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  361. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  362. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  363. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  364. package/src/extensions/pi-agent-search/package.json +9 -9
  365. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +34 -12
  366. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +17 -15
  367. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +1 -0
  368. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-59.js +1 -0
  369. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-60.js +1 -0
  370. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +59 -25
  371. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +61 -16
  372. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +9 -3
  373. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +44 -48
  374. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +19 -15
  375. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -1
  376. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +6 -2
  377. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +1 -0
  378. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/tool-file-search.ts +146 -0
  379. package/src/extensions/pi-agent-search/runtime/entry-54.js +0 -1
  380. package/src/extensions/pi-agent-search/runtime/entry-55.js +1 -0
  381. package/src/extensions/pi-agent-search/runtime/entry-56.js +2 -0
  382. package/src/extensions/pi-agent-search/src/api/glob-list.ts +35 -0
  383. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +8 -8
  384. package/src/extensions/pi-agent-search/src/api/search.ts +14 -2
  385. package/src/extensions/pi-agent-search/src/core/extension.ts +11 -20
  386. package/src/extensions/pi-agent-search/src/core/search-core.ts +30 -10
  387. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  388. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  389. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  390. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  391. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +1 -2
  392. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  393. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-65.js +1 -0
  394. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-66.js +2 -0
  395. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +6 -1
  396. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  397. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-84.js +2 -0
  398. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  399. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -6
  400. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-85.js +2 -0
  401. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +0 -1
  402. package/src/extensions/pi-agent-text-editor/runtime/entry-82.js +1 -0
  403. package/src/extensions/pi-agent-text-editor/runtime/entry-83.js +2 -0
  404. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  405. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  406. package/src/extensions/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  407. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  408. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  409. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +13 -7
  410. package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  411. package/src/extensions/pi-agent-text-editor/src/core/image-write.ts +111 -0
  412. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  413. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  414. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  415. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  416. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  417. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  418. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +43 -12
  419. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  420. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -5
  421. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +3 -7
  422. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +6 -8
  423. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -6
  424. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  425. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  426. package/src/pi-agent-ide.ts +8 -15
  427. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  428. package/src/plugins/pi-agent-ide-ast/src/extension.ts +8 -8
  429. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  430. package/src/plugins/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  431. package/src/plugins/pi-agent-ide-changes/index.ts +1 -2
  432. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  433. package/src/plugins/pi-agent-ide-changes/runtime/entry-38.js +1 -0
  434. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  435. package/src/plugins/pi-agent-ide-debugger/index.ts +17 -4
  436. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +2 -11
  437. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  438. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  439. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  440. package/src/plugins/pi-agent-ide-lint/runtime/entry-42.js +2 -0
  441. package/src/plugins/pi-agent-ide-lsp/index.ts +22 -28
  442. package/src/plugins/pi-agent-ide-lsp/package.json +14 -10
  443. package/src/plugins/pi-agent-ide-lsp/runtime/entry-43.js +2 -0
  444. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  445. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  446. package/src/plugins/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  447. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  448. package/src/plugins/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  449. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  450. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  451. package/src/plugins/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  452. package/src/plugins/pi-agent-ide-processes/src/ui.ts +61 -16
  453. package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
  454. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +10 -7
  455. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -3
  456. package/src/standalone/resource-host.ts +147 -0
  457. package/src/standalone/scoped-api.ts +457 -0
  458. package/dist/chunk-2RTCSZB3.js +0 -1
  459. package/dist/chunk-4DIUPEDF.js +0 -2
  460. package/dist/chunk-6EDOLYOV.js +0 -1
  461. package/dist/chunk-6FGLAVPJ.js +0 -1
  462. package/dist/chunk-6H32W35W.js +0 -1
  463. package/dist/chunk-6OJ565FL.js +0 -2
  464. package/dist/chunk-6R3Y4AD3.js +0 -1
  465. package/dist/chunk-6TJPMBUQ.js +0 -1
  466. package/dist/chunk-6XFUICD7.js +0 -1
  467. package/dist/chunk-BHSO2MDK.js +0 -6
  468. package/dist/chunk-GSOYVIQS.js +0 -1
  469. package/dist/chunk-HSRH76JN.js +0 -3
  470. package/dist/chunk-HSZ4AQ6L.js +0 -9
  471. package/dist/chunk-I6NPILT5.js +0 -1
  472. package/dist/chunk-K7SRNBIV.js +0 -1
  473. package/dist/chunk-LCWBVOII.js +0 -3
  474. package/dist/chunk-MKEC3U2M.js +0 -4
  475. package/dist/chunk-NUM3YQGK.js +0 -1
  476. package/dist/chunk-OM4LYD3S.js +0 -1
  477. package/dist/chunk-PLKYHUNT.js +0 -1
  478. package/dist/chunk-QIJMV2P2.js +0 -2
  479. package/dist/chunk-RVU73VKN.js +0 -2
  480. package/dist/chunk-SDAH3ECM.js +0 -5
  481. package/dist/chunk-SGQWRIRJ.js +0 -10
  482. package/dist/chunk-SWBJS3U4.js +0 -1
  483. package/dist/chunk-T7I2VX3J.js +0 -1
  484. package/dist/chunk-T7MWQQIF.js +0 -3
  485. package/dist/chunk-VDP5CQHM.js +0 -3
  486. package/dist/chunk-XG7QNAKW.js +0 -9
  487. package/dist/chunk-XLWCSJMR.js +0 -1
  488. package/dist/chunk-YFP4P2FV.js +0 -1
  489. package/dist/chunk-YIXP2ALP.js +0 -9
  490. package/dist/entry-22.js +0 -1
  491. package/docs/agent-guides/diagnostics.md +0 -5
  492. package/docs/agent-guides/json-reading.md +0 -57
  493. package/docs/agent-guides/read-resources.md +0 -17
  494. package/docs/agent-guides/search-code.md +0 -76
  495. package/docs/agent-guides/select-code.md +0 -119
  496. package/docs/agent-guides/vision.md +0 -11
  497. package/node_modules/pi-agent-doctor/runtime/entry-22.js +0 -1
  498. package/node_modules/pi-agent-filesystem/runtime/entry-29.js +0 -2
  499. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-32.js +0 -2
  500. package/node_modules/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  501. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  502. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  503. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  504. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  505. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  506. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +0 -387
  507. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +0 -41
  508. package/node_modules/pi-agent-ide-ast/src/source-text.ts +0 -92
  509. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +0 -214
  510. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +0 -277
  511. package/node_modules/pi-agent-ide-formatter/runtime/entry-38.js +0 -2
  512. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  513. package/node_modules/pi-agent-image/runtime/entry-42.js +0 -1
  514. package/node_modules/pi-agent-invariant/runtime/entry-43.js +0 -1
  515. package/node_modules/pi-agent-search/runtime/entry-51.js +0 -1
  516. package/node_modules/pi-agent-search-text/runtime/entry-55.js +0 -2
  517. package/node_modules/pi-agent-search-text/runtime/entry-56.js +0 -1
  518. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  519. package/node_modules/pi-agent-text-editor/runtime/entry-66.js +0 -1
  520. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  521. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +0 -1
  522. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +0 -1
  523. package/node_modules/pi-agent-web/runtime/entry-87.js +0 -2
  524. package/node_modules/pi-agent-web-html/runtime/entry-88.js +0 -2
  525. package/src/backend/vision-capture-worker.py +0 -319
  526. package/src/backend/vision-capture.ts +0 -165
  527. package/src/backend/vision-registration.ts +0 -104
  528. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  529. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-32.js +0 -2
  530. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +0 -2
  531. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-88.js +0 -2
  532. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +0 -2
  533. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +0 -2
  534. package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
  535. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  536. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +0 -2
  537. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +0 -1
  538. package/src/extensions/pi-agent-search/runtime/entry-51.js +0 -1
  539. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  540. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  541. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-61.js +0 -1
  542. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  543. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  544. package/src/extensions/pi-agent-text-editor/runtime/entry-65.js +0 -1
  545. package/src/extensions/pi-agent-text-editor/runtime/entry-66.js +0 -1
  546. package/src/plugins/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  547. package/src/plugins/pi-agent-ide-ast/runtime/entry-35.js +0 -2
  548. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  549. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  550. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  551. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  552. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  553. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +0 -387
  554. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +0 -41
  555. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +0 -92
  556. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +0 -214
  557. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +0 -277
  558. package/src/plugins/pi-agent-ide-formatter/runtime/entry-38.js +0 -2
  559. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  560. package/src/plugins/pi-agent-ide-vision/index.ts +0 -439
  561. package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +0 -47
  562. package/src/plugins/pi-agent-ide-vision/src/vision.ts +0 -585
  563. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +0 -30
  564. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +0 -33
  565. /package/dist/{chunk-U2JKHKLK.js → chunk-3PMHFEJY.js} +0 -0
  566. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-28.js +0 -0
  567. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-30.js +0 -0
  568. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-31.js +0 -0
  569. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-33.js +0 -0
  570. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-text}/runtime/entry-35.js +0 -0
  571. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-36.js +0 -0
  572. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-37.js +0 -0
  573. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-39.js +0 -0
  574. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-40.js +0 -0
  575. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-41.js +0 -0
  576. /package/node_modules/{pi-agent-pdf → pi-agent-image}/runtime/entry-44.js +0 -0
  577. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-45.js +0 -0
  578. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-46.js +0 -0
  579. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-50.js +0 -0
  580. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-52.js +0 -0
  581. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-59.js +0 -0
  582. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-61.js +0 -0
  583. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-62.js +0 -0
  584. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-63.js +0 -0
  585. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-64.js +0 -0
  586. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-65.js +0 -0
  587. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-83.js +0 -0
  588. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-86.js +0 -0
  589. /package/node_modules/{pi-agent-web-image → pi-agent-web}/runtime/entry-89.js +0 -0
  590. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-90.js +0 -0
  591. /package/node_modules/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-91.js +0 -0
  592. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-31.js +0 -0
  593. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-33.js +0 -0
  594. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-90.js +0 -0
  595. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-91.js +0 -0
  596. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-62.js +0 -0
  597. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-63.js +0 -0
  598. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-64.js +0 -0
  599. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-36.js +0 -0
  600. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-37.js +0 -0
  601. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-39.js +0 -0
  602. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-40.js +0 -0
  603. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-41.js +0 -0
@@ -0,0 +1 @@
1
+ import{b as T,e as x}from"./chunk-UD3DMY3Q.js";import{a as P}from"./chunk-GXL4NMHR.js";import{c as h,d as l,e as f}from"./chunk-PQWANILR.js";import{a as m}from"./chunk-BU7IZLKB.js";import{a as p,b as d}from"./chunk-S5PL5DFQ.js";import{i as u}from"./chunk-VDJSH3DQ.js";import{a}from"./chunk-EI7MMDWY.js";function g(){return{id:"line-hash",present(n,r){let o=n.lines.map(e=>{let i=(r.resolvedBy==="filesystem"||r.resolvedBy==="ssh")&&(r.purpose==="edit-diff"&&r.sourceText===void 0||r.sourceText===n.content)?{lineNumber:e.lineNumber,content:e.content}:u(e);return i===void 0?void 0:{anchor:T(i.lineNumber,i.content),lineNumber:i.lineNumber}}),c=Math.max(0,...o.map(e=>e?.anchor.value.length??0)),t=Math.max(0,...o.map(e=>String(e?.lineNumber??"").length)),E=n.lines.map((e,i)=>{let s=o[i];return s===void 0?e:{...e,anchors:[...new Set([...e.anchors??[],s.anchor.value])],presentation:{...e.presentation,prefix:`${s.anchor.value.padStart(c)}|${e.presentation?.prefix??""}`,compactPrefix:e.presentation?.compactPrefix??`${String(s.lineNumber).padStart(t)} \u2502 `}}});return{...n,lines:E}}}}a(g,"createLineHashPresenter");async function R(n){let r=g(),o={protocol:p,apiVersion:d,id:"text-anchor-line-hash",setup(t){t.addView({view:"anchors",presenter:r}),t.describe({views:"anchors \u2014 LINE#HASH references for edits."})}},c={protocol:h,apiVersion:l,id:"text-anchor-line-hash",setup(t){t.addAnchorResolver({resolver:x(),kind:f,type:"major"}),t.addTextPresenter({presenter:r})}};await Promise.all([m(n,o),P(n,c)])}a(R,"registerLineHashTextAnchor");export{R as a};
@@ -0,0 +1 @@
1
+ import{a as y}from"./chunk-SRFWT562.js";import"./chunk-AMIIOWFL.js";import{a as b}from"./chunk-H3GEEOOL.js";import{a as k,b as E}from"./chunk-USG6WHAT.js";import{b as S}from"./chunk-LF325WYO.js";import{a as u,b as w,c as v}from"./chunk-WQIMM4SU.js";import{g as c}from"./chunk-4IWEKRSP.js";import{a as p,b as h,d as P}from"./chunk-FKKAHI62.js";import{c as f}from"./chunk-W7CASEO3.js";import"./chunk-B25LXXNV.js";import"./chunk-XH5WN5XA.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-FYOU4RBH.js";import"./chunk-7PVDTMEM.js";import"./chunk-MDD5ORB6.js";import"./chunk-MLFJU2US.js";import"./chunk-PS2B6THP.js";import"./chunk-GXL4NMHR.js";import"./chunk-PQWANILR.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DDH3FP4G.js";import"./chunk-TVH2ND35.js";import"./chunk-T4FTT3U4.js";import"./chunk-VDJSH3DQ.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import"./chunk-KINKBPPX.js";import{c as m}from"./chunk-7D7PXIVV.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import R from"node:path";function g(d){let n=i(o=>{let e=d.resolve(o);if(!e)throw new c("UNSUPPORTED_SOURCE",o,"not-applied");return e},"resolve");return{transport:i(o=>y(d,o),"transport"),async readText(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes.toString("utf8")},async readSnapshot(o,e){let r=n(o),t=await r.backend.read(r.location.path,{signal:e});return{content:t.bytes.toString("utf8"),version:t.version}},async readBytes(o,e){let r=n(o);return(await r.backend.read(r.location.path,{signal:e})).bytes},async exists(o,e){let r=n(o);try{return await r.backend.stat(r.location.path,{signal:e}),!0}catch(t){if(t instanceof c&&t.code==="ENOENT")return!1;throw t}},async isFile(o,e){let r=n(o);return(await r.backend.stat(r.location.path,{signal:e})).kind==="file"},async entries(o,e){let r=n(o);return(await r.backend.list(r.location.path,{signal:e})).map(t=>({name:t.name,kind:t.kind==="symlink"?"other":t.kind}))}}}i(g,"createSshLspWorkspaceOwner");async function O(d){let n=new v(await w(u(f()))),o=g(n);await P(d,{workspace:i(e=>e.startsWith("ssh://")?o:void 0,"workspace"),async loadRegistry(e,r,t){t?.throwIfAborted();let s=n.resolve(e);if(s)return h.fromPackageDir(e,{signal:t,layerAccess:k(n,t),includeGlobal:!r,requireBuiltInEvidence:r,recipes:p,recipeEvidence:i(a=>E(s.backend,s.location.path,a,t),"recipeEvidence"),executableAvailability:i(a=>S(s.backend,s.location.path,a,t),"executableAvailability")});if(e.includes("://"))throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return h.fromPackageDir(r?e:process.env.PI_AGENT_IDE_CONFIG_DIR??e,{signal:t,includeGlobal:!r,requireBuiltInEvidence:r,recipes:p})},async resolveProject(e,r,t){if(t?.throwIfAborted(),e.startsWith("ssh://")||r.startsWith("ssh://")){let a=n.resolve(e,r);if(!a)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");let l=n.resolve(r);if(l&&l.location.target!==a.location.target)throw new c("UNSUPPORTED_SOURCE",e,"not-applied");return b(a.backend,a.location.path,l?.location.path,"lsp-servers",p,t)}let s=await m(r,e,"lsp-servers",p,t);return s===void 0?void 0:{cwd:s,external:s!==R.resolve(r)}}})}i(O,"registerOwnedLsp");export{O as default};
@@ -0,0 +1,3 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Le}from"node:async_hooks";function le(){return{pending:new Set,active:new Le}}i(le,"createSchedulerState");function $e(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i($e,"conflicts");function Ue(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Ue,"coveredAccess");async function De(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(De,"waitForDependencies");var D=class r{constructor(e=le()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let h=s.then(E=>{if(n?.throwIfAborted(),!Ue(a.accesses,E,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return E});a.nested??=new r;let y=a.nested.run(h,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(h=>{p=h}),m={accesses:c,done:l};return this.state.pending.add(m),(async()=>{try{n?.throwIfAborted();let h=await De(s.then(async E=>(await Promise.all(d.map(G=>Promise.race([G.done,G.accesses.then(_e=>$e(E,_e)?G.done:void 0)]))),E)),n);n?.throwIfAborted();let y={accesses:h,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(m),p()}})()}},Me=Symbol.for("pi-agent-resource.resource-scheduler-state"),He=globalThis,We=He[Me]??=le(),Ve=new D(We);import{realpath as ze,stat as Fe}from"node:fs/promises";import I from"node:path";import{fileURLToPath as Be}from"node:url";async function fe(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=I.resolve(e,r.startsWith("file:")?Be(r):r),[o,s]=await Promise.allSettled([ze(n),Fe(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let m=I.dirname(n);if(m===n)a=n;else{let y=(await fe(m,e,t)).find(E=>E.resource.startsWith("file:"));a=I.join(y?.resource.slice(5)??m,I.basename(n))}}let d=a.split(I.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(fe,"resourceAccesses");import{randomUUID as Ke}from"node:crypto";import{mkdir as Je,mkdtemp as Ye,readFile as qe,rm as Ge,writeFile as Xe}from"node:fs/promises";import{tmpdir as Ze}from"node:os";import pe from"node:path";var X=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#t=new Set;#o;#r;#n;constructor(e={}){this.#o=e.parentDirectory??Ze(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#n!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#t.add(n);try{return await n}finally{this.#t.delete(n)}}dispose(){return this.#n??=this.#a(),this.#n}async#i(e,t){let n=await this.#d(),o=Ke(),s=`temp:${o}`,a=pe.join(n,`${o}.txt`);return await Xe(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#t),this.#e.clear(),this.#r!==void 0&&await Ge(await this.#r,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#n!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#n!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await qe(t,"utf8")}]}async#d(){return this.#r??=(async()=>(await Je(this.#o,{recursive:!0}),Ye(pe.join(this.#o,"pi-agent-read-"))))(),this.#r}};import{Type as g}from"typebox";import{Type as S}from"typebox";var ge=["retryAfterMs","resetAt","requestsLimit","requestsRemaining","complexityLimit","complexityRemaining","endpointLimit","endpointRemaining"],Z=S.Object({rateLimit:S.Optional(S.Object({...Object.fromEntries(ge.map(r=>[r,S.Optional(S.Integer({minimum:0,maximum:r==="retryAfterMs"?864e5:Number.MAX_SAFE_INTEGER}))])),endpoint:S.Optional(S.String({maxLength:80,pattern:"^[A-Za-z0-9_:-]{1,80}$"}))},{additionalProperties:!1}))},{additionalProperties:!1});function M(r,e){if(!r||typeof r!="object"||Array.isArray(r))return;let t=Object.getOwnPropertyDescriptor(r,e);return t&&"value"in t?t.value:void 0}i(M,"own");function me(r){try{let e=M(r,"rateLimit"),t={};for(let o of ge){let s=M(e,o);typeof s=="number"&&Number.isSafeInteger(s)&&s>=0&&(o!=="retryAfterMs"||s<=864e5)&&(t[o]=s)}let n=M(e,"endpoint");if(typeof n=="string"&&/^[A-Za-z0-9_:-]{1,80}$/u.test(n)&&(t.endpoint=n),Object.keys(t).length)return Object.freeze({rateLimit:Object.freeze(t)})}catch{}}i(me,"resourceErrorMetadata");function j(r){try{return me(M(r,"metadata"))}catch{return}}i(j,"resourceErrorMetadataOf");var he=Symbol.for("pi-agent-resource.ResourceError"),_=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError";let a=j(s);a&&(this.metadata=a)}static{i(this,"ResourceError")}[he]=!0;metadata;static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&t[he]===!0}};import{Value as Qe}from"typebox/value";var H=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String()),metadata:g.Optional(Z)},{additionalProperties:!1});function ye(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(H,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(H,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(H)},required:["status","errors"],additionalProperties:!1}}i(ye,"structuredResultSchema");var Re=1024*1024;function Q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>Re)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(Q,"assertJsonData");function Ce(r,e="EXECUTION_FAILED",t){if(r instanceof _){let n=j(r);return{code:r.code,message:`${r.code}: ${r.source}`,source:t??r.source,...n?{metadata:n}:{}}}return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(Ce,"resultError");function et(r,e,t){try{if(Q(t),!Qe.Check(ye(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=Ce(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return Q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(et,"withStructuredResult");function tt(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(tt,"renderContentDescription");import{Type as f}from"typebox";import{Value as lt}from"typebox/value";import{Type as u}from"typebox";import{Value as rt}from"typebox/value";var R={additionalProperties:!0},L=u.Function([],u.Unknown()),C=u.String({minLength:1}),nt=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},R),ot=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},R),st=u.Object({type:u.Literal("custom"),kind:C,data:u.Unknown()},R),it=u.Array(u.Union([nt,ot,st]),{minItems:1}),ve=u.Union([u.Object({source:C,link:u.Optional(C),read:L,write:u.Optional(u.Never())},R),u.Object({source:C,link:u.Optional(C),read:u.Optional(u.Never()),write:L},R),u.Object({source:C,link:u.Optional(C),read:L,write:L},R)]),at=u.Object({id:C,tryResolve:L},R),ct=u.Union([u.Object({kind:u.Literal("not-handled")},R),u.Object({kind:u.Literal("resolved"),resource:ve},R),u.Object({kind:u.Literal("failed"),error:u.Unknown()},R)]);function ee(r){return W(it,r)?V(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(ee,"isAgentContent");function we(r){return W(ve,r)?V(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(we,"isResource");function ut(r){return W(at,r)}i(ut,"isResourceResolver");function dt(r){return W(ct,r)?V(()=>{let e=r;return e.kind!=="resolved"||we(e.resource)}):!1}i(dt,"isResourceResolutionAttempt");function W(r,e){return V(()=>rt.Check(r,e))}i(W,"safeCheck");function V(r){try{return r()}catch{return!1}}i(V,"safeEvaluate");var v={additionalProperties:!0},ft=f.Function([],f.Unknown()),z=f.String({minLength:1}),pt=f.Object({provider:z,capability:f.Union([f.Literal("read"),f.Literal("write")])},v),gt=f.Object({source:z,bytes:f.Unknown(),mediaType:f.Optional(f.String())},v),mt=f.Object({signal:f.Optional(f.Unknown())},v),ht=f.Object({id:z,description:z,tryConvert:ft},v),yt=f.Union([f.Object({kind:f.Literal("not-handled")},v),f.Object({kind:f.Literal("converted"),content:f.Unknown()},v),f.Object({kind:f.Literal("failed"),error:f.Unknown()},v)]),Rt=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},v);function k(r){return N(pt,r)&&x(()=>r.provider.trim().length>0)}i(k,"isContentTarget");function te(r){return N(gt,r)?x(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(te,"isContentInput");function re(r){return N(mt,r)?x(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(re,"isContentConversionContext");function be(r){return N(ht,r)?x(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(be,"isContentConverter");function ne(r){return N(yt,r)?x(()=>{let e=r;return e.kind!=="converted"||ee(e.content)}):!1}i(ne,"isContentConversionAttempt");function T(r){return N(Rt,r)?x(()=>{let e=r;return k(e.target)&&be(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(T,"isContentConverterRegistration");function N(r,e){return x(()=>lt.Check(r,e))}i(N,"safeCheck");function x(r){try{return r()}catch{return!1}}i(x,"safeEvaluate");var F=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function se(r){if(!k(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!T(o))throw new TypeError("Invalid content converter registration");if(!A(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!te(o))throw new TypeError("Invalid content input");if(!re(s))throw new TypeError("Invalid content conversion context");oe(s.signal);let a=n();for(let{converter:d}of a){oe(s.signal);let c=await d.tryConvert(o,s);if(oe(s.signal),!ne(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new F(o.source,e)}}}i(se,"createContentRunner");function A(r,e){return r.provider===e.provider&&r.capability===e.capability}i(A,"targetsEqual");function oe(r){r?.throwIfAborted()}i(oe,"throwIfAborted");import{Type as w}from"typebox";import{Value as Ct}from"typebox/value";var P="pi-agent-resource/content-conversion",B=2,$=`${P}/host/ready`,U=`${P}/converter/register`,Ee={additionalProperties:!0},vt=w.Function([],w.Unknown()),wt=w.Object({protocol:w.Literal(P),apiVersion:w.Literal(B),target:w.Unknown()},Ee),bt=w.Object({registration:w.Unknown(),accept:vt},Ee);function ie(r){return Se(wt,r)&&ce(()=>k(r.target))}i(ie,"isContentHostReady");function ae(r){return Se(bt,r)&&ce(()=>T(r.registration))}i(ae,"isContentConverterRegistrationRequest");function Se(r,e){return ce(()=>Ct.Check(r,e))}i(Se,"safeCheck");function ce(r){try{return r()}catch{return!1}}i(ce,"safeEvaluate");var Te="pi-agent-resource:content-host-lookup";function Et(r,e){let t;if(r.events.emit(Te,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return xe(r,t),t.host;let n=se(e),o=r.events.on(U,c=>{if(!ae(c))throw new Error("Invalid content converter registration request");if(!A(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(Te,c=>{if(!St(c))throw new Error("Invalid content host lookup request");A(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return xe(r,d),r.events.emit($,{protocol:P,apiVersion:B,target:n.target}),s}i(Et,"createContentHost");function St(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(St,"isHostLookup");function xe(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(xe,"retainOwner");function Tt(r,e){if(!T(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(U,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on($,s=>{if(!ie(s))throw new Error("Invalid content conversion host readiness event");if(!A(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(Tt,"connectContentConverter");import{createHash as Ae,randomUUID as ue}from"node:crypto";import{statSync as xt}from"node:fs";import{readFile as At}from"node:fs/promises";import b from"node:path";import{fileURLToPath as Ot}from"node:url";import{Type as K}from"typebox";var kt=K.Union([K.String(),K.Array(K.String())]),O="RESULT#",Oe="pi-agent-resource:result-targets",ke=/^(?:shell|debug):/u,Y=class{static{i(this,"ResultTargetStore")}#e=new Map;#t=new Map;#o=new Map;#r=new Map;clear(){this.#e.clear(),this.#t.clear(),this.#o.clear(),this.#r.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${O}${ue()}`;return this.#e.set(o,{state:"ready",targets:de(e),complete:n,cwd:b.resolve(t)}),o}reserve(e){let t=`${O}${ue()}`;return this.#e.set(t,{state:"pending",cwd:b.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==b.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:de(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#n(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==b.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:de(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#n(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await Ne(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}registerSearchReference(e,t,n){if(!/^SEARCH#[A-F\d]{4,64}:[1-9]\d*:(line|match)$/u.test(e))throw new Error("Only numbered Search references can alias a snapshot.");if(!this.#e.has(t))throw new Error("A Search reference needs a registered result target.");this.resolve(t,n),this.#t.set(e,t)}publish(e,t,n,o=[]){let s=ue();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#n(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let m of l){if(m===null||typeof m!="object"||!("target"in m)||typeof m.target!="string"||!this.#e.has(m.target)||!("references"in m))continue;let h=m.references;h!==null&&typeof h=="object"&&"match"in h&&typeof h.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(h.match)&&this.#t.set(h.match,m.target)}}}return this.#r.set(s,{cwd:b.resolve(n),digest:Ae("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#t.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(O)?e.slice(O.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#r.get(a);if(!c&&!s&&e.startsWith(O)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==b.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&Ae("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#r.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#r.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&ke.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>J(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#r)(o.resources.some(s=>J(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#r.delete(n)}refresh(e,t,n=!1){let o=J(e,t);n&&!ke.test(e)&&this.invalidate(o);let s=JSON.stringify([b.resolve(t),o]),a=Nt(e,t),d=this.#o.get(s);d&&d.stamp!==a&&this.invalidate(o),this.#o.set(s,{source:e,cwd:t,stamp:a})}refreshAll(){for(let e of[...this.#o.values()])this.refresh(e.source,e.cwd)}#n(e){if(typeof e=="string"&&e.startsWith(O))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#n(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#n(t.data)}if(typeof t.target=="string"&&t.target.startsWith(O))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#n(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function J(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return Ot(t)}catch{}return b.resolve(e,t)}i(J,"sourcePath");function Nt(r,e){try{let t=xt(J(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(Nt,"fileStamp");async function Ne(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await At(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(Ne,"verifyResultTargets");function de(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(de,"combineTargets");function Pt(r){let e;if(r.events.emit(Oe,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new Y,n=r.events.on(Oe,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(Pt,"connectResultTargets");import Pe from"node:path";var Ie="pi-agent-resource:result-images",It=64*1024*1024,q=class{static{i(this,"ResultImageStore")}#e=new Map;#t=0;clear(){this.#e.clear(),this.#t=0}keep(e,t,n){let o=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid>/u.exec(e)?.[1];if(o!==void 0){this.#e.set(o,{cwd:Pe.resolve(t),images:n}),this.#t+=je(n);for(let[s,a]of this.#e){if(this.#t<=It||s===o)break;a.images.length!==0&&(this.#e.set(s,{...a,images:[]}),this.#t-=je(a.images))}}}images(e,t){let n=/^(?:RESULT#)?([a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12})$/u.exec(e)?.[1],o=n===void 0?void 0:this.#e.get(n);if(o!==void 0){if(o.cwd!==Pe.resolve(t))throw new Error("Result belongs to another worktree.");if(o.images.length===0)throw new Error("This result has no kept images. Read the image again and pass the new result.");return o.images}}};function je(r){return r.reduce((e,t)=>e+t.data.length,0)}i(je,"imageSize");function jt(r){let e;if(r.events.emit(Ie,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new q,n=r.events.on(Ie,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(jt,"connectResultImages");export{D as a,Ve as b,fe as c,X as d,Z as e,me as f,j as g,_ as h,H as i,ye as j,Re as k,Q as l,Ce as m,et as n,tt as o,ee as p,we as q,ut as r,dt as s,k as t,te as u,re as v,be as w,ne as x,T as y,F as z,se as A,A as B,P as C,B as D,$ as E,U as F,ie as G,ae as H,Et as I,Tt as J,kt as K,Y as L,Ne as M,Pt as N,q as O,jt as P};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";function l(e,n){return typeof n=="string"&&n.length>0&&e.nonAnchorValues?.includes(n)!==!0}i(l,"isMutationAnchorValue");function u(e,n){let o=(e??[]).filter(({field:r,optional:t})=>t===!0&&n[r]==="");if(o.length===0)return n;let a={...n};for(let{field:r}of o)delete a[r];return a}i(u,"withoutEmptyOptionalAnchors");function p(e){if(typeof e.name!="string"||e.name.trim().length===0)throw new TypeError("Mutation tool name must be a non-empty string");if(typeof e.description!="string"||typeof e.mutate!="function")throw new TypeError(`Mutation tool ${e.name} has an invalid description or operation`);if(e.direct!==void 0&&(typeof e.direct.matches!="function"||typeof e.direct.execute!="function"))throw new TypeError(`Mutation tool ${e.name} has an invalid direct operation`);let n=e.intent;if(n!==void 0&&n!=="edit"&&n!=="restore")throw new TypeError(`Mutation tool ${e.name} has an invalid intent`);let o=c(e.parameters,e.name);d(o,e.source.field,`${e.name} primary source`);let a=new Set([e.source.field]);for(let t of e.source.targets??[]){if(d(o,t.field,`${e.name} target source`),!a.has(t.fallbackTo))throw new TypeError(`Mutation tool ${e.name} target ${t.field} has an unknown fallback ${t.fallbackTo}`);a.add(t.field)}let r=new Set;for(let t of e.anchors??[]){if(d(o,t.field,`${e.name} anchor`),!a.has(t.sourceField))throw new TypeError(`Mutation tool ${e.name} anchor ${t.field} has an unknown source ${t.sourceField}`);if(!Array.isArray(t.kinds)||t.kinds.length===0||t.kinds.some(s=>typeof s!="string"||s.trim().length===0))throw new TypeError(`Mutation tool ${e.name} anchor ${t.field} must accept non-empty kinds`);if(new Set(t.kinds).size!==t.kinds.length)throw new TypeError(`Mutation tool ${e.name} anchor ${t.field} declares duplicate kinds`);if(t.nonAnchorValues!==void 0&&(t.nonAnchorValues.length===0||t.nonAnchorValues.some(s=>typeof s!="string"||s.length===0)))throw new TypeError(`Mutation tool ${e.name} anchor ${t.field} must declare non-empty non-anchor values`);if(t.nonAnchorValues!==void 0&&new Set(t.nonAnchorValues).size!==t.nonAnchorValues.length)throw new TypeError(`Mutation tool ${e.name} anchor ${t.field} declares duplicate non-anchor values`);if(r.has(t.field))throw new TypeError(`Mutation tool ${e.name} declares anchor ${t.field} more than once`);r.add(t.field)}for(let t of e.pair??[])if(!r.has(t))throw new TypeError(`Mutation tool ${e.name} pair field ${t} is not an anchor`)}i(p,"assertTextMutationToolRegistration");function y(e,n){let o=n[e.source.field];return typeof o=="string"?o:""}i(y,"mutationSource");function c(e,n){let o=e.properties;if(typeof o!="object"||o===null)throw new TypeError(`Mutation tool ${n} parameters must be an object schema`);return o}i(c,"schemaProperties");function d(e,n,o){if(typeof n!="string"||n.length===0||!(n in e))throw new TypeError(`${o} field ${n} is not declared by its schema`)}i(d,"assertProperty");export{l as a,u as b,p as c,y as d};
@@ -1,2 +1,2 @@
1
- import{a as p,c as y,d as w,e as g,f as b,g as l}from"./chunk-PJL3UVMJ.js";import{a as c}from"./chunk-EI7MMDWY.js";import{spawn as v}from"node:child_process";import{PassThrough as S}from"node:stream";import{Type as r}from"typebox";import{Value as L}from"typebox/value";var I=r.Union([r.Object({kind:r.Literal("ready"),pid:r.Integer({minimum:1}),identity:r.Optional(r.String({pattern:"^[a-f0-9-]+:[0-9]+$"}))}),r.Object({kind:r.Literal("ack"),id:r.Integer({minimum:1})}),r.Object({kind:r.Union([r.Literal("stdout"),r.Literal("stderr")]),bytes:r.String({maxLength:32768})}),r.Object({kind:r.Literal("exit"),exitCode:r.Integer()}),r.Object({kind:r.Literal("error"),code:r.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:r.Union([r.Literal("not-applied"),r.Literal("unknown")])})]);async function R(a,e,t,s,i={}){y(a),i.pty&&E(i.pty.cols,i.pty.rows);let d=p(a.id,s).source,n=i.timeoutMs??3e4;if(!Number.isFinite(n)||n<=0)throw new TypeError("SSH startup deadline must be positive");i.signal?.throwIfAborted();let o=await w(new URL("./ssh-channel-worker.py",new URL("../src/backend/ssh-channel.ts",import.meta.url).href));i.signal?.throwIfAborted();let u=JSON.stringify({command:e,args:t,cwd:s,...i.pty?{pty:i.pty}:{}});if(Buffer.byteLength(u)>48*1024*1024)throw new l("FRAME_LIMIT",d,"not-applied");let h=v("ssh",g(a,o),{stdio:"pipe"}),f=new m(h,d,i.pty!==void 0,i.signal),P=setTimeout(()=>f.cancel("TIMEOUT"),n);try{return await f.sendInitial(u),await f.ready,f}finally{clearTimeout(P)}}c(R,"startSshProcess");function E(a,e){if(![a,e].every(t=>Number.isSafeInteger(t)&&t>0&&t<=1e3))throw new TypeError("PTY dimensions must be integers between 1 and 1000")}c(E,"validateDimensions");var m=class{constructor(e,t,s,i){this.child=e;this.source=t;this.pty=s;this.ready=new Promise((n,o)=>{this.#c=n,this.#l=o}),this.completion=new Promise((n,o)=>{this.#u=n,this.#f=o}),this.ready.catch(()=>{}),this.completion.catch(()=>{}),e.stdout.on("data",n=>{this.#e=Buffer.concat([this.#e,n]),this.parse()}),e.stderr.on("data",n=>{this.#d.length<16384&&(this.#d+=n.toString())}),e.stdin.on("error",()=>{}),e.once("error",()=>{this.#i="DEPENDENCY_UNAVAILABLE"});let d=c(()=>this.cancel("CANCELLED"),"abort");i?.addEventListener("abort",d,{once:!0}),e.once("close",n=>{this.#r=!0,this.#S=n,clearTimeout(this.#E),i?.removeEventListener("abort",d);let o=this.#i??(n!==0?b(n,this.#d):this.#s===void 0?"TRANSPORT_FAILED":void 0);this.stdout.end(),this.stderr.end();let u=this.error(o??"INPUT_CLOSED");for(let h of this.#t.values())h.reject(u);if(this.#t.clear(),o){let h=this.error(o);this.#l(h),this.#f(h)}else this.#s!==void 0&&this.#u({exitCode:this.#s})});for(let n of[this.stdout,this.stderr]){let o=c(()=>{this.#n.delete(n),this.parse(),this.#n.size===0&&e.stdout.resume()},"resume");n.on("drain",o),n.on("close",o)}i?.aborted&&d()}static{c(this,"ProcessChannel")}stdout=new S({highWaterMark:65536});stderr=new S({highWaterMark:65536});completion;ready;#t=new Map;#n=new Set;#c;#l;#u;#f;#e=Buffer.alloc(0);#d="";#i;#m;#p=!1;#y=!1;#w=0;#g;#r=!1;#b=!1;#o=!1;#s;#S;#P=0;#a=0;#h=Promise.resolve();#E;get pid(){return this.#w}get identity(){return this.#g}async sendInitial(e){this.#p=!0,await this.sendLine(e)}async write(e){if(this.#r||this.#b||this.#o)throw this.error("INPUT_CLOSED");if(this.#a+e.length>1024*1024)throw this.error("INPUT_LIMIT");let t=Buffer.from(e);this.#a+=t.length;let s=this.#h.then(async()=>{for(let i=0;i<t.length;i+=16384){if(this.#o||this.#r)throw this.error("INPUT_CLOSED");await this.sendAcknowledged({kind:"input",bytes:t.subarray(i,i+16384).toString("base64")})}});this.#h=s.catch(()=>{});try{await s}finally{this.#a-=t.length}}async end(){if(this.pty)throw new l("PTY_INPUT_NOT_CLOSABLE",this.source,"not-applied");this.#b=!0,await this.#h,await this.send({kind:"end"})}async resize(e,t){if(!this.pty)throw new l("PTY_REQUIRED",this.source,"not-applied");E(e,t),await this.sendAcknowledged({kind:"resize",cols:e,rows:t})}stop(){return!this.#r&&!this.#o&&(this.#o=!0,this.send({kind:"stop"}).catch(()=>{}),this.#E=setTimeout(()=>{this.#i??="TRANSPORT_FAILED",this.child.kill("SIGKILL")},5e3),this.child.stdout.resume(),this.stdout.resume(),this.stderr.resume()),this.completion.catch(e=>{if(this.#i==="CANCELLED"&&this.#S===0&&this.#s!==void 0)return{exitCode:this.#s};throw e})}cancel(e){this.#r||(this.#i??=e,this.stop().catch(()=>{}))}error(e){let t=["HOST_KEY_FAILED","AUTH_FAILED","DEPENDENCY_UNAVAILABLE"].includes(e),s=this.#m??(!this.#p||t?"not-applied":"unknown");return new l(e,this.source,s)}async sendAcknowledged(e){let t=++this.#P,s=new Promise((i,d)=>{this.#t.set(t,{resolve:i,reject:d})});s.catch(()=>{});try{await this.send({...e,id:t}),await s}finally{this.#t.delete(t)}}async send(e){await this.sendLine(JSON.stringify(e))}sendLine(e){return this.#r?Promise.reject(this.error("INPUT_CLOSED")):new Promise((t,s)=>{this.child.stdin.write(`${e}
1
+ import{a as p,c as y,d as w,e as g,f as b,g as l}from"./chunk-4IWEKRSP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{spawn as v}from"node:child_process";import{PassThrough as S}from"node:stream";import{Type as r}from"typebox";import{Value as L}from"typebox/value";var I=r.Union([r.Object({kind:r.Literal("ready"),pid:r.Integer({minimum:1}),identity:r.Optional(r.String({pattern:"^[a-f0-9-]+:[0-9]+$"}))}),r.Object({kind:r.Literal("ack"),id:r.Integer({minimum:1})}),r.Object({kind:r.Union([r.Literal("stdout"),r.Literal("stderr")]),bytes:r.String({maxLength:32768})}),r.Object({kind:r.Literal("exit"),exitCode:r.Integer()}),r.Object({kind:r.Literal("error"),code:r.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:r.Union([r.Literal("not-applied"),r.Literal("unknown")])})]);async function R(a,e,t,s,i={}){y(a),i.pty&&E(i.pty.cols,i.pty.rows);let d=p(a.id,s).source,n=i.timeoutMs??3e4;if(!Number.isFinite(n)||n<=0)throw new TypeError("SSH startup deadline must be positive");i.signal?.throwIfAborted();let o=await w(new URL("./ssh-channel-worker.py",new URL("../src/backend/ssh-channel.ts",import.meta.url).href));i.signal?.throwIfAborted();let u=JSON.stringify({command:e,args:t,cwd:s,...i.pty?{pty:i.pty}:{}});if(Buffer.byteLength(u)>48*1024*1024)throw new l("FRAME_LIMIT",d,"not-applied");let h=v("ssh",g(a,o),{stdio:"pipe"}),f=new m(h,d,i.pty!==void 0,i.signal),P=setTimeout(()=>f.cancel("TIMEOUT"),n);try{return await f.sendInitial(u),await f.ready,f}finally{clearTimeout(P)}}c(R,"startSshProcess");function E(a,e){if(![a,e].every(t=>Number.isSafeInteger(t)&&t>0&&t<=1e3))throw new TypeError("PTY dimensions must be integers between 1 and 1000")}c(E,"validateDimensions");var m=class{constructor(e,t,s,i){this.child=e;this.source=t;this.pty=s;this.ready=new Promise((n,o)=>{this.#c=n,this.#l=o}),this.completion=new Promise((n,o)=>{this.#u=n,this.#f=o}),this.ready.catch(()=>{}),this.completion.catch(()=>{}),e.stdout.on("data",n=>{this.#e=Buffer.concat([this.#e,n]),this.parse()}),e.stderr.on("data",n=>{this.#d.length<16384&&(this.#d+=n.toString())}),e.stdin.on("error",()=>{}),e.once("error",()=>{this.#i="DEPENDENCY_UNAVAILABLE"});let d=c(()=>this.cancel("CANCELLED"),"abort");i?.addEventListener("abort",d,{once:!0}),e.once("close",n=>{this.#r=!0,this.#S=n,clearTimeout(this.#E),i?.removeEventListener("abort",d);let o=this.#i??(n!==0?b(n,this.#d):this.#s===void 0?"TRANSPORT_FAILED":void 0);this.stdout.end(),this.stderr.end();let u=this.error(o??"INPUT_CLOSED");for(let h of this.#t.values())h.reject(u);if(this.#t.clear(),o){let h=this.error(o);this.#l(h),this.#f(h)}else this.#s!==void 0&&this.#u({exitCode:this.#s})});for(let n of[this.stdout,this.stderr]){let o=c(()=>{this.#n.delete(n),this.parse(),this.#n.size===0&&e.stdout.resume()},"resume");n.on("drain",o),n.on("close",o)}i?.aborted&&d()}static{c(this,"ProcessChannel")}stdout=new S({highWaterMark:65536});stderr=new S({highWaterMark:65536});completion;ready;#t=new Map;#n=new Set;#c;#l;#u;#f;#e=Buffer.alloc(0);#d="";#i;#m;#p=!1;#y=!1;#w=0;#g;#r=!1;#b=!1;#o=!1;#s;#S;#P=0;#a=0;#h=Promise.resolve();#E;get pid(){return this.#w}get identity(){return this.#g}async sendInitial(e){this.#p=!0,await this.sendLine(e)}async write(e){if(this.#r||this.#b||this.#o)throw this.error("INPUT_CLOSED");if(this.#a+e.length>1024*1024)throw this.error("INPUT_LIMIT");let t=Buffer.from(e);this.#a+=t.length;let s=this.#h.then(async()=>{for(let i=0;i<t.length;i+=16384){if(this.#o||this.#r)throw this.error("INPUT_CLOSED");await this.sendAcknowledged({kind:"input",bytes:t.subarray(i,i+16384).toString("base64")})}});this.#h=s.catch(()=>{});try{await s}finally{this.#a-=t.length}}async end(){if(this.pty)throw new l("PTY_INPUT_NOT_CLOSABLE",this.source,"not-applied");this.#b=!0,await this.#h,await this.send({kind:"end"})}async resize(e,t){if(!this.pty)throw new l("PTY_REQUIRED",this.source,"not-applied");E(e,t),await this.sendAcknowledged({kind:"resize",cols:e,rows:t})}stop(){return!this.#r&&!this.#o&&(this.#o=!0,this.send({kind:"stop"}).catch(()=>{}),this.#E=setTimeout(()=>{this.#i??="TRANSPORT_FAILED",this.child.kill("SIGKILL")},5e3),this.child.stdout.resume(),this.stdout.resume(),this.stderr.resume()),this.completion.catch(e=>{if(this.#i==="CANCELLED"&&this.#S===0&&this.#s!==void 0)return{exitCode:this.#s};throw e})}cancel(e){this.#r||(this.#i??=e,this.stop().catch(()=>{}))}error(e){let t=["HOST_KEY_FAILED","AUTH_FAILED","DEPENDENCY_UNAVAILABLE"].includes(e),s=this.#m??(!this.#p||t?"not-applied":"unknown");return new l(e,this.source,s)}async sendAcknowledged(e){let t=++this.#P,s=new Promise((i,d)=>{this.#t.set(t,{resolve:i,reject:d})});s.catch(()=>{});try{await this.send({...e,id:t}),await s}finally{this.#t.delete(t)}}async send(e){await this.sendLine(JSON.stringify(e))}sendLine(e){return this.#r?Promise.reject(this.error("INPUT_CLOSED")):new Promise((t,s)=>{this.child.stdin.write(`${e}
2
2
  `,i=>{i?s(this.error("INPUT_CLOSED")):t()})})}parse(){for(;this.#n.size===0;){let e=this.#e.indexOf(10);if(e<0){this.#e.length>65536&&this.cancel("FRAME_LIMIT");return}if(e>65536){this.cancel("FRAME_LIMIT");return}let t=this.#e.subarray(0,e);this.#e=this.#e.subarray(e+1);let s;try{s=JSON.parse(t.toString("utf8"))}catch{this.cancel("INVALID_RESPONSE");return}if(!L.Check(I,s)){this.cancel("INVALID_RESPONSE");return}this.receive(s)}this.child.stdout.pause()}receive(e){if(e.kind==="ready"){if(this.#y){this.cancel("INVALID_RESPONSE");return}this.#y=!0,this.#w=e.pid,this.#g=e.identity,this.#c()}else if(e.kind==="ack"){let t=this.#t.get(e.id);if(!t){this.cancel("INVALID_RESPONSE");return}this.#t.delete(e.id),t.resolve()}else if(e.kind==="exit")this.#s=e.exitCode;else if(e.kind==="error")this.#i=e.code,this.#m=e.effect;else{let t=Buffer.from(e.bytes,"base64");if(t.toString("base64")!==e.bytes){this.cancel("INVALID_RESPONSE");return}let s=e.kind==="stdout"?this.stdout:this.stderr;!s.destroyed&&!s.write(t)&&this.#n.add(s)}}};export{R as a};
@@ -0,0 +1,11 @@
1
+ import{a as gt,c as mt}from"./chunk-B25LXXNV.js";import{f as ze,g as Ve}from"./chunk-XH5WN5XA.js";import{a as Ke}from"./chunk-47SPPIXK.js";import{a as He,b as Ge}from"./chunk-VAXLSPPU.js";import{a as pe,b as Ze,c as et}from"./chunk-FYOU4RBH.js";import{b as Be,c as Je,d as ue}from"./chunk-7PVDTMEM.js";import{a as Ye}from"./chunk-MDD5ORB6.js";import{b as Xe,c as Qe}from"./chunk-MLFJU2US.js";import{a as te,e as Fe}from"./chunk-PS2B6THP.js";import{a as tt}from"./chunk-GXL4NMHR.js";import{c as Ue,d as We,f as qe}from"./chunk-PQWANILR.js";import{a as $e}from"./chunk-BU7IZLKB.js";import{a as Oe,b as Me}from"./chunk-S5PL5DFQ.js";import{K as Te,M as z,m as Ae,n as je}from"./chunk-DDH3FP4G.js";import{h as nt}from"./chunk-TVH2ND35.js";import{a as N,b as I,c as rt,d as V}from"./chunk-T4FTT3U4.js";import{m as Ne}from"./chunk-VDJSH3DQ.js";import{a as it}from"./chunk-ZAWRSA7N.js";import{a as ot,b as st}from"./chunk-OFILFO6D.js";import{b as ct,c as lt,g as dt,j as ut,p as pt}from"./chunk-7D7PXIVV.js";import{a as at}from"./chunk-BXGMMZT3.js";import{a as k}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Or from"node:path";var H=[{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"]}]}}},S("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}}),S("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"]}}},S("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"]),S("dart-language-server",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],{dart:[".dart"]},["dart","language-server","--protocol=lsp"],"https://dart.dev/tools/dart-language-server"),S("r-language-server",["r"],["Rscript"],["DESCRIPTION",".lintr",".Rprofile"],{r:[".r"]},["Rscript","-e","languageserver::run()"],"https://github.com/REditorSupport/languageserver"),S("zls",["zig"],["zls"],["build.zig","build.zig.zon","zls.json"],{zig:[".zig",".zon"]},["zls"],"https://zigtools.org/zls/"),S("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/"),S("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"]),S("basedpyright",["python"],["basedpyright-langserver","pyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["basedpyright-langserver","--stdio"],"https://docs.basedpyright.com/",["basedpyright"]),S("gopls",["go"],["gopls"],["go.mod","go.work"],{go:[".go"]},["gopls"],"https://go.dev/gopls/"),S("rust-analyzer",["rust"],["rust-analyzer"],["Cargo.toml","rust-project.json"],{rust:[".rs"]},["rust-analyzer"],"https://rust-analyzer.github.io/"),S("csharp-ls",["csharp"],["csharp-ls"],[".sln",".csproj"],{csharp:[".cs"]},["csharp-ls"],"https://github.com/razzmatazz/csharp-language-server"),S("jdtls",["java"],["jdtls"],["pom.xml","build.gradle",".project"],{java:[".java"]},["jdtls"],"https://projects.eclipse.org/projects/eclipse.jdt.ls"),S("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"),S("solargraph",["ruby"],["solargraph"],["Gemfile",".solargraph.yml"],{ruby:[".rb",".rake"]},["solargraph","stdio"],"https://solargraph.org/"),S("intelephense",["php"],["intelephense"],["composer.json"],{php:[".php"]},["intelephense","--stdio"],"https://intelephense.com/"),S("sourcekit-lsp",["swift"],["sourcekit-lsp"],["Package.swift"],{swift:[".swift"]},["sourcekit-lsp"],"https://github.com/swiftlang/sourcekit-lsp"),S("lua-language-server",["lua"],["lua-language-server"],[".luarc.json",".luarc.jsonc"],{lua:[".lua"]},["lua-language-server"],"https://luals.github.io/"),S("bash-language-server",["shell"],["bash-language-server"],[".shellcheckrc"],{shell:[".sh",".bash"]},["bash-language-server","start"],"https://github.com/bash-lsp/bash-language-server"),S("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:{}}),S("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"),S("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"),S("taplo-lsp",["toml"],["taplo"],["taplo.toml"],{toml:[".toml"]},["taplo","lsp","stdio"],"https://taplo.tamasfe.dev/"),S("marksman",["markdown"],["marksman"],[".marksman.toml"],{markdown:[".md",".mdx"]},["marksman","server"],"https://github.com/artempyanykh/marksman"),S("terraform-ls",["terraform"],["terraform-ls"],[".terraform.lock.hcl"],{terraform:[".tf",".tfvars"]},["terraform-ls","serve"],"https://github.com/hashicorp/terraform-ls"),S("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"),S("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"),S("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"),S("neocmakelsp",["cmake"],["neocmakelsp"],["CMakeLists.txt",".neocmake.toml",".neocmakelint.toml"],{cmake:[".cmake"]},["neocmakelsp","stdio"],"https://github.com/neocmakelsp/neocmakelsp",void 0,{cmake:["CMakeLists.txt"]}),S("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"),S("lemminx",["xml"],["lemminx"],[".lemminx.json"],{xml:[".xml",".xsd",".xsl"]},["lemminx"],"https://github.com/eclipse-lemminx/lemminx"),S("sqls",["sql"],["sqls"],[".sqls.yml"],{sql:[".sql"]},["sqls"],"https://github.com/sqls-server/sqls"),S("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 S(o,e,t,r,n,s,i,d,c,l){return{id:o,name:o,kind:"lsp",languages:e,executables:t,configFiles:r,documentation:i,...d&&{dependencies:d},lsp:{command:s,rootMarkers:r,languageIds:n,...c&&{fileNames:c},...l&&{settings:l}}}}a(S,"recipe");import{readFile as ft}from"node:fs/promises";import{URI as yt}from"vscode-uri";var X={Error:1,Warning:2,Information:3,Hint:4};var ht={command:"typescript.tsserverRequest",async request(o,e,t){return(await Promise.all(["syntacticDiagnosticsSync","semanticDiagnosticsSync","suggestionDiagnosticsSync"].map(async n=>{let s=await o.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:[n,{file:o.serverDocumentPath(e),includeLinePosition:!0},{isAsync:!1,expectsResult:!0}]},t);if(!ge(s)||s.success!==!0||!Array.isArray(s.body))throw new Error(`Invalid completed TypeScript diagnostic report: ${n}`);return s.body.map(Gt)}))).flat()}};function re(o){return o.supportsCommand(ht.command)?ht:void 0}a(re,"completedDiagnosticAdapter");function Gt(o){if(!ge(o)||typeof o.message!="string"||typeof o.code!="number"&&typeof o.code!="string"||!ge(o.startLocation)||!Number.isInteger(o.startLocation.line)||!Number.isInteger(o.startLocation.offset)||Number(o.startLocation.line)<1||Number(o.startLocation.offset)<1||!["error","warning","suggestion","message"].includes(String(o.category)))throw new Error("Invalid TypeScript diagnostic entry");return{code:String(o.code),message:o.message,line:Number(o.startLocation.line),column:Number(o.startLocation.offset),severity:o.category==="error"?"error":o.category==="warning"?"warning":o.category==="suggestion"?"hint":"info"}}a(Gt,"convertTypeScriptDiagnostic");function ge(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}a(ge,"isRecord");async function Q(o,e,t,r={}){let n=new AbortController,s=AbortSignal.any([n.signal,...r.signal?[r.signal]:[]]),i=setTimeout(()=>n.abort(new Error(`[lsp] ${o.serverId}: diagnostics timed out for ${e}`)),o.timeoutMs);try{return await Bt(o,e,t,r.content,s)}finally{clearTimeout(i)}}a(Q,"requestDiagnostics");async function Bt(o,e,t,r,n){if(n.throwIfAborted(),o.diagnosticMode!=="push"){let c=o.documentVersion(e);try{let l=await o.sendRequest("textDocument/diagnostic",{textDocument:{uri:e}},n);if(l.kind!=="full"||!Array.isArray(l.items))throw new Error("Invalid full diagnostic report");if(o.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return o.setDiagnosticMode("pull"),wt(l.items,!1,!0)}catch(l){if(!Jt(l))throw l;o.setDiagnosticMode("push")}}let s=re(o);if(s){o.documentVersion(e)===void 0&&o.syncDocument(e,r??await ft(yt.parse(e).fsPath,"utf8"),t??"plaintext");let c=o.documentVersion(e),l=await s.request(o,e,n);if(n.throwIfAborted(),o.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return{diagnostics:l,syntaxErrors:[],otherDiagnostics:l,unversioned:!1,complete:!0}}n.throwIfAborted();let i=o.documentVersion(e)!==void 0,d=i?void 0:r??await ft(yt.parse(e).fsPath,"utf8");n.throwIfAborted(),o.beginDiagnosticRequest(e);try{return await new Promise((c,l)=>{let m=o.documentVersion(e)??1,y=a(g=>{let p=g;p.uri!==e||!Array.isArray(p.diagnostics)||p.version!==void 0&&p.version!==m||o.documentVersion(e)===m&&(f(),c(wt(p.diagnostics,p.version===void 0)))},"receive"),u=o.onNotification("textDocument/publishDiagnostics",y),h=a(()=>{f(),l(n.reason)},"onAbort");function f(){u(),n.removeEventListener("abort",h)}a(f,"cleanup"),n.addEventListener("abort",h,{once:!0});try{i||o.syncDocument(e,d??"",t??"plaintext");let g=o.diagnosticPublication(e);g&&y({uri:e,...g})}catch(g){f(),l(g)}})}finally{o.endDiagnosticRequest(e)}}a(Bt,"requestCurrentDiagnostics");function me(o){return{code:String(o.code??"LSP"),message:o.message,line:o.range.start.line+1,column:o.range.start.character+1,severity:o.severity===X.Warning?"warning":o.severity===X.Information?"info":o.severity===X.Hint?"hint":"error"}}a(me,"toDiagnostic");function wt(o,e,t=!1){let r=o.map(me);return{diagnostics:r,syntaxErrors:[],otherDiagnostics:r,unversioned:e,complete:t}}a(wt,"classify");function Jt(o){return o!==null&&typeof o=="object"&&"code"in o&&o.code===-32601}a(Jt,"isMethodNotFound");function bt(o,e=(t,r)=>Promise.resolve({cwd:r,external:!1})){return{id:"lsp",async diagnose(t,r){let n=await e(t,r.cwd,r.signal);if(n===void 0)return{status:"unavailable",diagnostics:[],reason:"No local language-server project found for this file"};let s=await o(n.cwd,n.external,r.signal);r.signal.throwIfAborted();let i=await s.getOrStart(t,n.cwd,"diagnostics",r.signal);if(r.signal.throwIfAborted(),!i)return{status:"unavailable",diagnostics:[],reason:"No language server configured for this file"};let d=i.toUri(t),c=s.languageId(t);i.syncDocument(d,r.content,c,!0);let l=i.documentVersion(d),m={active:!0,queued:!1},y=a(()=>!r.signal.aborted&&i.documentVersion(d)===l,"current"),u=a(()=>Q(i,d,c,{signal:r.signal,content:r.content}),"request"),h=a(async()=>{if(m.queued=!0,!m.active){m.active=!0;try{for(;m.queued&&y();){m.queued=!1;let g=await u();y()&&r.publish(vt(g,i.commandName))}}catch(g){y()&&r.publish({status:"unavailable",diagnostics:[],reason:g instanceof Error?g.message:String(g),source:i.commandName})}finally{m.active=!1}}},"refresh"),f=s.onPushDiagnostics(g=>{!y()||g.uri!==d||g.serverId!==i.serverId||g.cwd!==n.cwd||g.version!==void 0&&g.version!==l||(i.diagnosticMode==="pull"||re(i)?h():r.publish({status:"snapshot",diagnostics:g.diagnostics,source:i.commandName,reason:St(g.version===void 0)}))});r.signal.addEventListener("abort",f,{once:!0});try{let g=await u();return l=i.documentVersion(d),vt(g,i.commandName)}catch(g){throw m.queued=!1,f(),r.signal.removeEventListener("abort",f),g}finally{m.active=!1,m.queued&&y()&&queueMicrotask(()=>{h()})}}}}a(bt,"createLspDiagnosticSource");function St(o){return`Latest push snapshot; completion is unknown${o?"; language server omitted the document version":""}`}a(St,"snapshotReason");function vt(o,e){return o.complete?{status:"ready",diagnostics:o.diagnostics,source:e}:{status:"snapshot",diagnostics:o.diagnostics,reason:St(o.unversioned),source:e}}a(vt,"toReport");import{URI as ur}from"vscode-uri";import nr from"node:path";import or from"cross-spawn";import{createMessageConnection as sr,CancellationTokenSource as ir,StreamMessageReader as ar}from"vscode-jsonrpc/node";import{URI as Rt}from"vscode-uri";import{watch as Kt}from"node:fs";import{readdir as Xt,stat as Qt}from"node:fs/promises";import G from"node:path";import{URI as he}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 n of t){let s=n.globPattern,i=typeof s=="string"?this.root:he.parse(typeof s.baseUri=="string"?s.baseUri:s.baseUri.uri).fsPath,d=typeof s=="string"?s:s.pattern,c=a(y=>G.matchesGlob(G.isAbsolute(d)?G.join(i,y):y,d),"matches"),l=new Set((await Xt(i,{recursive:!0})).filter(c));if(this.disposed)throw new Error("Language server file watchers are disposed");let m=Kt(i,{recursive:!0},(y,u)=>{!u||!c(u)||Qt(G.join(i,u)).then(()=>{if(!this.registrations.get(e)?.includes(m))return;let h=l.has(u)?2:1;l.add(u),(n.kind??7)&(h===1?1:2)&&this.changed({uri:he.file(G.join(i,u)).toString(),type:h})},h=>{if(this.registrations.get(e)?.includes(m)){if(h.code!=="ENOENT"){this.failed(h);return}l.delete(u)&&(n.kind??7)&4&&this.changed({uri:he.file(G.join(i,u)).toString(),type:3})}})});m.on("error",this.failed),r.push(m)}}catch(n){for(let s of r)s.close();throw n}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 Yt}from"vscode-jsonrpc/node";var oe=class extends Yt{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 er}from"vscode-uri";function E(o,e){if(e.startsWith("ssh://")){let t=Lt(e);if(o.includes("://")){let n=Lt(o);if(n.host!==t.host)throw new Error("Document belongs to another language server owner");return n.href}let r=Zt.posix.resolve(decodeURIComponent(t.pathname),o);return t.pathname=r.split("/").map(encodeURIComponent).join("/"),t.href}if(o.startsWith("ssh://")||o.includes("://")&&!o.startsWith("file://"))throw new Error("Document belongs to another language server owner");return o.startsWith("file://")?o:er.file(o).toString()}a(E,"documentUri");function Lt(o){let e=new URL(o);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(Lt,"checkedRemote");async function T(o,e){if(e?.aborted)throw o.catch(()=>{}),e.reason;if(!e)return o;let t;try{return await Promise.race([o,new Promise((r,n)=>{t=a(()=>n(e.reason),"onAbort"),e.addEventListener("abort",t,{once:!0})})])}finally{t&&e.removeEventListener("abort",t)}}a(T,"waitWithSignal");var B=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 T(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 tr=new Set(["uri","targetUri","target","oldUri","newUri","rootUri","documentUri","scopeUri","baseUri"]),rr=new Set(["changes","relatedDocuments"]);function O(o,e){return Array.isArray(o)?o.map(t=>O(t,e)):typeof o!="object"||o===null?o:Object.fromEntries(Object.entries(o).map(([t,r])=>tr.has(t)&&typeof r=="string"?[t,e(r)]:rr.has(t)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?[t,Object.fromEntries(Object.entries(r).map(([n,s])=>[e(n),O(s,e)]))]:[t,O(r,e)]))}a(O,"mapLspUris");var U=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 ct(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=k(this._command[0]),r=this._ownerTransport?decodeURIComponent(new URL(this.rootUri).pathname):Rt.parse(this.rootUri).fsPath,n=[{uri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,name:nr.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:or(t,this._args,{stdio:["pipe","pipe","pipe"],...e&&{signal:e},cwd:r,env:pt({command:this._command,env:this._env},r,process.env)});this._process=i??null;let d=i?cr(i):Promise.resolve(),c=k(s?.stdin??i?.stdin),l=k(s?.stdout??i?.stdout),m=k(s?.stderr??i?.stderr);c.on("error",()=>{}),l.on("error",()=>{}),m.on("error",()=>{}),this._stderr="",m.setEncoding("utf8"),m.on("data",p=>{this._stderr=(this._stderr+p).slice(-4096)}),i?.on("error",p=>{("code"in p?p.code:void 0)!=="ENOENT"&&console.error(`[lsp] ${this.serverId}: spawn failed:`,p),this._crashed=!0,this._connection?.dispose(),this._connection=null,this._process=null});let y=a(p=>{(s?this._ownedProcess!==s:this._process!==i)||(this._closeFileWatchers(),!this._disposed&&p!==0&&p!==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",y),s?.completion.then(({exitCode:p})=>y(p),()=>{this._ownedProcess===s&&(this._crashed=!0,y(null))}),await T(d,e);let u=sr(new ar(l),new oe(c,p=>{this._connection!==u||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),u.dispose(),console.error(`[lsp] ${this.serverId}: transport write failed:`,p))}));this._connection=u,this._connection.onError(p=>{console.error(`[lsp] ${this.serverId}: connection error:`,p)});let h=a(p=>{this._sendNotification("workspace/didChangeWatchedFiles",{changes:[p]})},"changed"),f=a(p=>console.error(`[lsp] ${this.serverId}: file watcher failed:`,p),"failed");this._fileWatchers=this._ownerTransport?this._ownerTransport.fileWatchers?.(this.rootUri,h,f):new ne(r,h,f),this._connection.onRequest("client/registerCapability",async p=>{for(let w of p.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 p=>{for(let w of p.unregisterations)await this._fileWatchers?.unregister(w.id);return null}),this._connection.onRequest("window/workDoneProgress/create",()=>null),this._connection.onRequest("workspace/configuration",p=>p.items.map(w=>{let v=this._settings??null;for(let L of w.section?.split(".").filter(Boolean)??[])v=typeof v=="object"&&v!==null?v[L]??null:null;return v})),this._connection.listen(),this._connection.onNotification((p,...w)=>{let v=this._ownerTransport,L=v?O(w[0],b=>v.fromServerUri(b)):w[0];if(p==="textDocument/publishDiagnostics"){let b=L;b&&typeof b.uri=="string"&&Array.isArray(b.diagnostics)&&this._documentVersions.has(b.uri)&&(b.version===void 0||b.version===this.documentVersion(b.uri))&&this._diagnosticPublications.set(b.uri,{diagnostics:b.diagnostics,...typeof b.version=="number"&&{version:b.version}})}for(let b of this._handlers.get(p)??[])b(L)}),this._connection.onRequest("workspace/workspaceFolders",()=>n);let g=await T(Pt(this._connection.sendRequest("initialize",{processId:this._ownerTransport?null:process.pid,rootUri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,workspaceFolders:n,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(p=>{let w=this._stderr.trim();throw w?new Error(`[lsp] ${this.serverId}: ${w}`,{cause:p}):p});if(await this._connection.sendNotification("initialized",{capabilities:g.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=g.capabilities,this._diagnosticMode=g.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 n=this._ownerTransport,s=n?O(t,l=>n.toServerUri(l)):t,i=a(l=>n?O(l,m=>n.fromServerUri(m)):l,"mapResult");if(!r)return i(await k(this._connection).sendRequest(e,s));let d=new ir,c;try{let l=k(this._connection).sendRequest(e,s,d.token);return i(await Promise.race([l,new Promise((m,y)=>{c=a(()=>{d.cancel(),y(r.reason)},"onAbort"),r.addEventListener("abort",c,{once:!0})})]))}finally{c&&r.removeEventListener("abort",c),d.dispose()}}sendNotification(e,t){this._assertReady(),this._sendNotification(e,t)}_sendNotification(e,t){let r=this._connection;if(!r)return;let n=this._ownerTransport,s=n?O(t,i=>n.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 n=r.indexOf(t);n!==-1&&r.splice(n,1)}}toUri(e){return E(e,this.rootUri)}serverDocumentPath(e){let t=this.toUri(e),r=this._ownerTransport?.toServerUri(t)??t;return this._ownerTransport?decodeURIComponent(new URL(r).pathname):Rt.parse(r).fsPath}openDocument(e,t,r,n=1){let s=this._documentVersions.get(e);if(s!==void 0){this.changeDocument(e,t,Math.max(n,s+1));return}this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didOpen",{textDocument:{uri:e,languageId:r,version:n,text:t}}),this._documentVersions.set(e,n),this._documentContents.set(e,t)}syncDocument(e,t,r,n=!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,d=typeof i=="object"&&i!==null?i.save:void 0;n&&d&&this.sendNotification("textDocument/didSave",{textDocument:{uri:e},...typeof d=="object"&&d.includeText&&{text:t}})}changeDocument(e,t,r){let n=this._documentVersions.get(e),s=Math.max(r,(n??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 Pt(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()),n=this._process;this._process=null,n&&!n.killed&&(n.kill("SIGTERM"),setTimeout(()=>{n.exitCode===null&&n.signalCode===null&&n.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 d of s)d.status==="rejected"&&i.push(d.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 cr(o){return new Promise((e,t)=>{let r=a(()=>{o.off("spawn",n),o.off("error",s)},"cleanup"),n=a(()=>{r(),e()},"onSpawn"),s=a(i=>{r(),t(i)},"onError");o.once("spawn",n),o.once("error",s)})}a(cr,"waitForSpawn");function Pt(o,e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{n(new Error(t))},e);o.then(i=>{clearTimeout(s),r(i)}).catch(i=>{clearTimeout(s),n(i instanceof Error?i:new Error(String(i)))})})}a(Pt,"withTimeout");import _ from"node:path";import{existsSync as lr}from"node:fs";function _t(o){let e=new Map,t=new Map;for(let[r,n]of Object.entries(o))for(let[s,i]of Object.entries(n.languages))for(let d of i.extensions){let c=d.toLowerCase(),l=e.get(c);if(l!==void 0&&l!==s)throw new Error(`[lsp] extension conflict: "${c}" claimed by "${l}" and "${s}"`);e.set(c,s);let m=t.get(c)??[];m.push(r),t.set(c,m)}return{extToLanguageId:e,extToServerIds:t}}a(_t,"buildLanguageLookup");var A=class o{constructor(e,t,r){this._projectRoot=r;this._entries=e;let n=e.filter(s=>s.layer!=="built-in"||t.has(s.id));this._servers=Object.fromEntries(n.map(s=>[s.id,s.config])),this._lookup=_t(this._servers)}static{a(this,"LspServerRegistry")}_servers;_entries;_lookup;static async fromPackageDir(e,t={}){t.signal?.throwIfAborted();let r=await dt(e,"lsp-servers",c=>dr(c).servers,t);if(t.signal?.throwIfAborted(),e.startsWith("ssh://")&&(!t.executableAvailable&&!t.executableAvailability||t.requireBuiltInEvidence&&!t.recipeEvidence))throw Object.assign(new Error("Remote language server availability needs its workspace owner"),{code:"UNSUPPORTED_SOURCE"});let n=t.environment??process.env,s=r.entries.filter(c=>c.layer==="built-in"),i=[];if(t.executableAvailability){let c=await t.executableAvailability(s.map(l=>l.config));if(c.length!==s.length||c.some(l=>typeof l!="boolean"))throw new TypeError("Invalid owner executable availability report");for(let[l,m]of s.entries())i.push({id:m.id,available:c[l]===!0})}else if(t.executableAvailable)for(let c of s)i.push({id:c.id,available:await t.executableAvailable(c.config)});else i.push(...await Promise.all(s.map(async c=>({id:c.id,available:await ut(c.config,e,n,t.signal)}))));t.signal?.throwIfAborted();let d=t.requireBuiltInEvidence?t.recipeEvidence?await t.recipeEvidence(t.recipes??[]):await at(e,t.recipes??[],void 0,t.signal):void 0;return t.signal?.throwIfAborted(),new o(r.entries,new Set(i.filter(c=>c.available&&(d===void 0||(d.get(c.id)?.score??0)>0)).map(c=>c.id)),e.startsWith("ssh://")?e:_.resolve(e))}static fromConfig(e,t=process.cwd()){return new o(Object.entries(e.servers).map(([r,n])=>({id:r,config:n,layer:"project",sourcePath:"<memory>"})),new Set,t.startsWith("ssh://")?t:_.resolve(t))}resolve(e){return this.candidates(e).filter(t=>!t.config.requireRootMarker||this.hasRootMarker(e,t.config.rootMarkers))}candidates(e){let t=_.basename(e),r=_.extname(e)||(e.startsWith(".")?e:`.${e}`),n=a(i=>process.platform==="win32"?i.toLowerCase():i,"normalizeName"),s=[];for(let i of this._entries)if(this._servers[i.id]){for(let[d,c]of Object.entries(i.config.languages))if(c.extensions.some(l=>l.toLowerCase()===r.toLowerCase())||c.fileNames?.some(l=>n(l)===n(t))){s.push({serverId:i.id,config:i.config,languageId:d,layer:i.layer,sourcePath:i.sourcePath});break}}return s}async resolveOwned(e,t){if(!this._projectRoot.startsWith("ssh://"))return this.resolve(e);let r=new URL(this._projectRoot),n=decodeURIComponent(r.pathname),s=e.startsWith(".")&&!e.includes("/"),i=e.includes("://")?new URL(e):new URL(r.href),d=e.includes("://")?decodeURIComponent(i.pathname):_.posix.resolve(n,e),c=_.posix.relative(n,d);if(i.origin!==r.origin||i.host!==r.host||i.protocol!==r.protocol||i.username||i.password||i.port||i.search||i.hash||c===".."||c.startsWith("../"))throw Object.assign(new Error("Language server resource belongs to another owner"),{code:"UNSUPPORTED_SOURCE"});let l=[];for(let m of this.candidates(s?e:d)){if(!m.config.requireRootMarker){l.push(m);continue}let y=s||d===n?n:_.posix.dirname(d);for(;;){let u=!1;for(let h of m.config.rootMarkers){let f=_.posix.resolve(y,h),g=_.posix.relative(n,f);if(g===".."||g.startsWith("../"))continue;let p=new URL(r.href);if(p.pathname=f.split("/").map(encodeURIComponent).join("/"),await t(p.href)){u=!0;break}}if(u){l.push(m);break}if(y===n)break;y=_.posix.dirname(y)}}return l}hasRootMarker(e,t){let r=_.dirname(_.resolve(this._projectRoot,e));for(e.startsWith(".")&&!e.includes(_.sep)&&(r=this._projectRoot);;){let n=_.relative(this._projectRoot,r);if(n===".."||n.startsWith(`..${_.sep}`)||_.isAbsolute(n))return!1;if(t.some(s=>lr(_.join(r,s))))return!0;if(r===this._projectRoot)return!1;r=_.dirname(r)}}get projectRoot(){return this._projectRoot}get servers(){return this._servers}get entries(){return this._entries}get knownExtensions(){return new Set(this._lookup.extToLanguageId.keys())}languageId(e){let t=e.startsWith("ssh://")?decodeURIComponent(new URL(e).pathname):e;return(this._projectRoot.startsWith("ssh://")?this.candidates(t):this.resolve(t))[0]?.languageId??e.slice(1)}};function dr(o){if(typeof o!="object"||o===null||Array.isArray(o))throw new Error("LSP config must be an object");let e=o;if(e.version!==1)throw new Error("LSP config version must be 1");if(typeof e.servers!="object"||e.servers===null||Array.isArray(e.servers))throw new Error("LSP config servers must be an object");for(let[t,r]of Object.entries(e.servers)){if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LSP server ${t} must be an object`);let n=r;if(!Array.isArray(n.command)||n.command.length===0||n.command.some(s=>typeof s!="string"||s.length===0))throw new Error(`LSP server ${t}.command must be a non-empty string array`);if(n.transport!==void 0&&n.transport!=="stdio")throw new Error(`LSP server ${t} only supports stdio transport`);if(!Array.isArray(n.rootMarkers)||n.rootMarkers.some(s=>typeof s!="string"))throw new Error(`LSP server ${t}.rootMarkers must be a string array`);if(n.requireRootMarker!==void 0&&typeof n.requireRootMarker!="boolean")throw new TypeError(`LSP server ${t}.requireRootMarker must be a boolean`);if(n.requireRootMarker&&n.rootMarkers.length===0)throw new Error(`LSP server ${t}.requireRootMarker requires rootMarkers`);if(typeof n.languages!="object"||n.languages===null||Array.isArray(n.languages))throw new Error(`LSP server ${t}.languages must be an object`);for(let[s,i]of Object.entries(n.languages)){let d=typeof i=="object"&&i!==null&&!Array.isArray(i)?i.extensions:void 0;if(!Array.isArray(d)||d.length===0||d.some(l=>typeof l!="string"))throw new Error(`LSP server ${t} language ${s} requires extensions`);let c=i.fileNames;if(c!==void 0&&(!Array.isArray(c)||c.some(l=>typeof l!="string"||l.length===0||/[/\\]/u.test(l))))throw new Error(`LSP server ${t} language ${s}.fileNames must contain basenames`)}if(!Array.isArray(n.capabilities))throw new TypeError(`LSP server ${t}.capabilities must be an array`)}return o}a(dr,"parseLspConfig");var Ct={protocol:Xe,apiVersion:Qe,id:"lsp",setup(o){for(let e of H)o.addToolRecipe(e);o.addSetupCheck({id:"effective-config",inspect:pr}),o.addCheck({id:"config",title:"LSP",async run(e){try{let t=await A.fromPackageDir(e.cwd,xt(e)),r=gr(t,e.files);return r.length===0?[{status:"skip",message:"No language server matches the inspected project files"}]:await Promise.all(r.map(async n=>{let s=`${n.serverId} [${n.layer}] command ${JSON.stringify(n.config.command)}`,i=e.workspace,d=new U({serverId:n.serverId,rootUri:i?e.cwd:ur.file(e.cwd).toString(),...i&&{ownerTransport:{start:a(c=>i.start(c.command,c.env,c.signal),"start"),toServerUri:a(c=>i.toNativeUri(c),"toServerUri"),fromServerUri:a(c=>i.fromNativeUri(c),"fromServerUri")}},command:n.config.command,env:mr(e.env,n.config.env),...n.config.initializationOptions&&{initOptions:n.config.initializationOptions},...n.config.settings&&{settings:n.config.settings},...n.config.timeoutMs&&{timeoutMs:n.config.timeoutMs}});try{return await d.start(e.signal),{status:"pass",message:`${s}: initialized`,detail:n.sourcePath}}catch(c){return{status:"fail",message:`${s}: ${c instanceof Error?c.message:String(c)}`,detail:n.sourcePath}}finally{await d.shutdown()}}))}catch(t){return e.signal?.throwIfAborted(),[{status:"fail",message:t instanceof Error?t.message:String(t)}]}}})}};async function pr(o){try{let e=await A.fromPackageDir(o.cwd,xt(o)),t=[],r=new Map;for(let[n,s]of o.detectedLanguages){let i=s.flatMap(d=>e.resolve(d)).find(d=>d.languageId===n);i!==void 0&&(t.push({kind:"lsp",languageId:n,toolId:i.serverId}),await mt(o,i.config)||r.set(i.serverId,{id:`lsp-${i.serverId}-unavailable`,message:`Configured language server ${i.serverId} cannot run ${JSON.stringify(i.config.command)}`}))}return{selections:t,actions:[...r.values()]}}catch(e){return o.signal?.throwIfAborted(),{actions:[{id:"lsp-config-invalid",message:`Language server configuration cannot load: ${e instanceof Error?e.message:String(e)}`}]}}}a(pr,"inspectLspSetup");function xt(o){let e=o.workspace;return{...gt(o),recipeEvidence:e?t=>e.evidence(t,o.signal):void 0}}a(xt,"lspOptions");function gr(o,e){let t=new Map;for(let r of e){let n=o.resolve(r)[0];n!==void 0&&!t.has(n.serverId)&&t.set(n.serverId,n)}return[...t.values()]}a(gr,"applicableServers");function mr(o,e){return Object.fromEntries(Object.entries({...o,...e}).filter(t=>t[1]!==void 0))}a(mr,"definedEnvironment");var hr={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 W(o){return hr[o]??`SymbolKind(${o})`}a(W,"symbolKindName");async function Y(o,e,t){return await o.sendRequest("textDocument/documentSymbol",{textDocument:{uri:e}},t)??[]}a(Y,"requestDocumentSymbols");async function fe(o,e,t=100,r){return(await o.sendRequest("workspace/symbol",{query:e},r)??[]).slice(0,t)}a(fe,"requestWorkspaceSymbols");async function se(o,e,t,r){return await o.sendRequest("textDocument/rename",{textDocument:{uri:e},position:t,newName:r})}a(se,"requestRename");import ee from"node:path";import{URI as vr}from"vscode-uri";import{createHash as fr}from"node:crypto";import{readdir as yr,stat as ie}from"node:fs/promises";import M from"node:path";import{URI as we}from"vscode-uri";async function ye(o,e){if(!o.supportsCommand("typescript.tsserverRequest"))return;if((await o.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(ye,"prepareProjectQuery");function kt(o,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(([n,s])=>[n,t(s)])):r,"expand");return Object.fromEntries(Object.entries(o).map(([r,n])=>[r,t(n)]))}a(kt,"resolveInitializationOptions");var q=class o{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(!o._instance)throw new Error("[lsp] LspManager not initialized");return o._instance}static getInstanceOrNull(){return o._instance}static init(e,t){let r=o._instance;return r?._disposed?(r._registry=e,r._owner=t,r._disposed=!1,r):(o._instance=new o(e,t),o._instance)}static async resetForTest(){o._instance&&(await o._instance.shutdownAll(),o._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,n){if(n?.throwIfAborted(),this._disposed)return null;let s=t.startsWith("ssh://"),i=s?this.requireOwner():void 0,d=i?await this._registry.resolveOwned(e,g=>i.exists(g,n)):this._registry.resolve(e);if(n?.throwIfAborted(),this._disposed)return null;let c=r==="symbols"?d[0]:d.find(g=>g.config.capabilities.includes(r));if(!c)return null;let l=s?t:we.file(t).toString(),m=`${c.serverId}:${l}`,y=this._clientStarts.get(m);if(y)return y.controller.signal.aborted?(await T(y.promise.catch(()=>{}),n),this.getOrStart(e,t,r,n)):y.wait(n);let u=this._clients.get(m);if(u?.ready)return u;let h=new B(g=>this._startClient(m,l,c,u,g));this._clientStarts.set(m,h);let f=a(()=>{this._clientStarts.get(m)===h&&this._clientStarts.delete(m)},"settled");return h.promise.then(f,f),h.wait(n)}async _startClient(e,t,r,n,s){let i=n??new U({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:kt(r.config.initializationOptions,t.startsWith("ssh://")?decodeURIComponent(new URL(t).pathname):we.parse(t).fsPath)},...r.config.settings&&{settings:r.config.settings},...r.config.timeoutMs&&{timeoutMs:r.config.timeoutMs}});try{n?await n.restart(s):await i.start(s),s.throwIfAborted()}catch(d){try{await i.shutdown()}catch(c){if(c!==d)throw new AggregateError([d,c],"Language server startup and cleanup failed",{cause:c})}throw d}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(E(e,t),r)}let n=await ie(M.resolve(t,e));return r?.throwIfAborted(),n.isFile()}async getWorkspaceClients(e,t="symbols",r=e,n=()=>!0,s){if(s?.throwIfAborted(),e.startsWith("ssh://")){let y=this._owner;if(!y)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});let u=new Set,h=new Set(this._registry.knownExtensions),f=new Set([".git",".cache","node_modules","dist","build"]),g=a(async w=>{if(s?.throwIfAborted(),h.size!==0)for(let v of await y.entries(w,s)){s?.throwIfAborted();let L=E(v.name,`${w}/`);if(v.kind==="directory")f.has(v.name)||await g(L);else if(v.kind==="file"){let b=M.posix.extname(v.name).toLowerCase();if(!h.has(b)||!n(L))continue;let x=await this.openFile(L,e,t,s);x&&(u.add(x.client),h.delete(b))}}},"visit"),p=E(r,e);if(await y.isFile(p,s)){if(!n(p))return[];let w=await this.openFile(p,e,t,s);return w?[w.client]:[]}return await g(p),[...u]}let i=new Set,d=new Set(this._registry.knownExtensions),c=new Set([".git",".cache","node_modules","dist","build"]),l=a(async y=>{if(s?.throwIfAborted(),d.size===0)return;let u;try{u=await yr(y,{withFileTypes:!0})}catch{return}for(let h of u){if(s?.throwIfAborted(),d.size===0)return;if(h.isDirectory()){c.has(h.name)||await l(M.join(y,h.name));continue}if(!h.isFile())continue;let f=M.extname(h.name).toLowerCase();if(!d.has(f))continue;let g=M.join(y,h.name);if(!n(g))continue;let p=await this.openFile(g,e,t,s);p&&(d.delete(f),p.client.hasWorkspaceSymbolCapability&&(await ye(p.client,g),i.add(p.client)))}},"visit"),m=M.resolve(e,r);if((await ie(m)).isFile()){if(!n(m))return[];let y=await this.openFile(m,e,t,s);return y===null||!y.client.hasWorkspaceSymbolCapability?[]:(await ye(y.client,m),[y.client])}return await l(m),s?.throwIfAborted(),[...i]}async prepareWorkspaceSymbols(e,t=e,r,n){return this.getWorkspaceClients(e,"symbols",t,r,n)}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 n=r.toUri(e);if(r.documentContent(n)===void 0)continue;let s=this.languageId(M.extname(decodeURIComponent(new URL(n).pathname)));r.syncDocument(n,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"),n=r(await ie(e)),s=await this.readSourceText(e,t);if(n!==r(await ie(e)))throw new Error("A rename source changed while reading it. No edits applied.");return{content:s,version:fr("sha256").update(n).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",n){if(n?.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?E(e,t):M.resolve(t,e),d=await this.getOrStart(i,t,r,n);if(!d)return null;let c=d.toUri(i),l=s?this.requireOwner():void 0,y=(l?await this._registry.resolveOwned(i,u=>l.exists(u,n)):this._registry.resolve(i))[0]?.languageId??"plaintext";if(l){let u=await l.readText(c,n);return n?.throwIfAborted(),d.syncDocument(c,u,y),this._openDocs.add(c),{client:d,uri:c,languageId:y}}try{let{readFile:u}=await import("node:fs/promises"),h=await u(i,{encoding:"utf8",signal:n});n?.throwIfAborted(),d.syncDocument(c,h,y),this._openDocs.add(c)}catch(u){if(n?.throwIfAborted(),!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}return{client:d,uri:c,languageId:y}}_subscribeToPushDiagnostics(e,t){if(this._pushUnsubscribers.has(e))return;let r=t.onNotification("textDocument/publishDiagnostics",n=>{let s=wr(n);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 d=`${e}:${s.uri}`,c=s.diagnostics.map(me),l=JSON.stringify([s.version,i,c]);if(this._pushFingerprints.get(d)===l)return;this._pushFingerprints.set(d,l);let m={cwd:t.rootUri.startsWith("ssh://")?t.rootUri:we.parse(t.rootUri).fsPath,serverId:t.serverId,uri:s.uri,diagnostics:c,...s.version!==void 0&&{version:s.version}};for(let y of this._pushHandlers)y(m)});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,d]of t.entries())d.status==="rejected"&&d.reason!==e[i]?.controller.signal.reason&&r.push(d.reason);let n=[...this._clients.values()],s=await Promise.allSettled(n.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 wr(o){if(o===null||typeof o!="object")return;let e=o;if(!(typeof e.uri!="string"||!Array.isArray(e.diagnostics)))return{uri:e.uri,diagnostics:e.diagnostics,...typeof e.version=="number"&&{version:e.version}}}a(wr,"parsePushNotification");async function ve(o,e,t){if(t?.throwIfAborted(),!o.supportsCommand("typescript.tsserverRequest"))return;let r=await o.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:o.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(ve,"loadQueryProject");async function Z(o,e,t,r){return await ve(o,e,r),await o.sendRequest("textDocument/references",{textDocument:{uri:e},position:t,context:{includeDeclaration:!0}},r)??[]}a(Z,"requestReferences");async function be(o,e,t,r){let n=await o.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:e},position:t},r),s=n?.[0];if(!s)return{items:[],incoming:[],outgoing:[]};let[i,d]=await Promise.all([o.sendRequest("callHierarchy/incomingCalls",{item:s},r),o.sendRequest("callHierarchy/outgoingCalls",{item:s},r)]);return{items:n,incoming:i??[],outgoing:d??[]}}a(be,"requestCallHierarchy");function J(o,e,t){let r=e.startsWith("ssh://"),n=r?ee.posix:ee,s=a(m=>r?decodeURIComponent(new URL(E(m,e)).pathname):m,"native"),i=r?s(t.path??e):ee.resolve(e,t.path??"."),d=n.relative(i,s(o));if(d===".."||d.startsWith(`..${n.sep}`)||n.isAbsolute(d))return!1;let c=n.relative(s(e),s(o)).split(n.sep).join("/"),l=a(m=>et(m).some(y=>n.matchesGlob(y.includes("/")?c:n.basename(s(o)),y)),"matches");return(t.include===void 0||l(t.include))&&(t.exclude===void 0||!l(t.exclude))}a(J,"withinScope");function Se(o,e){let t=E(o,e);if(t.startsWith("ssh://"))return t;let r=vr.parse(t);if(r.scheme!=="file")throw new Error("Unsupported LSP source location.");return ee.resolve(r.fsPath)}a(Se,"sourceOf");function br(o,e){return o.start.line===e.start.line&&o.start.character===e.start.character&&o.end.line===e.end.line&&o.end.character===e.end.character}a(br,"sameRange");function Et(o,e,t){return o.flatMap(r=>[...r.name===e&&r.range!==void 0&&br(r.range,t)&&r.selectionRange!==void 0?[r.selectionRange]:[],...Et(r.children??[],e,t)])}a(Et,"declarationNames");async function Le(o,e,t,r,n={},s=q.getInstance()){r?.throwIfAborted();let i=n.resultScope;if(i!==void 0&&(await z(i,r),i.targets.length===0))return{hits:[],complete:i.complete};if(i===void 0&&n.path!==void 0&&!J(e.startsWith("ssh://")?E(n.path,e):ee.resolve(e,n.path),e,n)&&await s.isSourceFile(n.path,e,r))return{hits:[],complete:!0};let d=i?.targets.map(f=>f.source)??[n.path??e],c=new Set((await Promise.all(d.map(f=>s.prepareWorkspaceSymbols(e,f,g=>J(g,e,n),r)))).flat());if(c.size===0)throw new Error("LSP symbol search is unavailable: no provider supports workspace/symbol in this scope.");let l=new Map,m=a(async f=>{r?.throwIfAborted();let g=Se(f.uri,e),p=l.get(g);if(p===void 0){let{content:R,version:F}=await s.readSourceSnapshot(g,r);p={document:Ne(g,R),version:F},l.set(g,p)}let{document:w}=p,{start:v,end:L}=f.range,b=[v,L];for(let R of b){let F=w.lines[R.line];if(!Number.isInteger(R.line)||!Number.isInteger(R.character)||F===void 0||R.character<0||R.character>F.content.length)throw new Error("LSP range does not match its source snapshot.")}let x=k(w.lines[v.line]),D=a(R=>w.lines.slice(0,R).reduce((F,De)=>F+De.content.length+De.lineEnding.length,0),"offset"),j=D(v.line)+v.character,P=D(L.line)+L.character;if(P<j)throw new Error("LSP returned a reversed source range.");return{source:g,lineNumber:v.line+1,endLineNumber:L.line+1,startColumn:v.character,endColumn:L.character,matchedText:w.content.slice(j,P),lineText:x.content}},"toMatch"),y=a(f=>J(f.source,e,n)&&(i===void 0||Ze(i,f)),"included"),u=[],h=new Set;for(let f of c){r?.throwIfAborted();let g=await fe(f,o,Number.MAX_SAFE_INTEGER,r);for(let p of g){if(r?.throwIfAborted(),!J(Se(p.location.uri,e),e,{}))continue;let w=await m(p.location),v=await s.openFile(w.source,e,"symbols",r);if(v===null)throw new Error("LSP references are unavailable for a discovered declaration.");let L=p.location;if(w.matchedText!==p.name){let P=await Y(v.client,v.uri,r),R=Et(P,p.name,p.location.range);if(R.length!==1)throw new Error("LSP declaration has no unique provider selectionRange; cannot search its references.");L={uri:v.uri,range:k(R[0])}}let b=await m(L),x={id:JSON.stringify([f.serverId,b.source,p.location.range]),name:p.name,kind:String(p.kind),source:b.source,range:{startLine:b.lineNumber,startColumn:b.startColumn,endLine:b.endLineNumber??b.lineNumber,endColumn:b.endColumn}},D=await Z(v.client,v.uri,L.range.start,r);r?.throwIfAborted();let j=[{...b,role:"definition",symbol:x}];for(let P of D){if(!J(Se(P.uri,e),e,{}))continue;let R=await m(P);R.source===b.source&&R.lineNumber===b.lineNumber&&R.startColumn===b.startColumn&&R.endLineNumber===b.endLineNumber&&R.endColumn===b.endColumn||j.push({...R,role:"reference",symbol:x})}if(!(n.navigation==="references"&&!j.some(y)))for(let P of j){if(n.navigation!=="references"&&!y(P)||n.navigation==="references"&&!J(P.source,e,{}))continue;let R=JSON.stringify([x.id,P.source,P.lineNumber,P.startColumn,P.endLineNumber,P.endColumn]);h.has(R)||(h.add(R),u.push(P))}}}r?.throwIfAborted();for(let[f,g]of l){let p=await s.readSourceSnapshot(f,r);if(p.version!==g.version||p.content!==g.document.content)throw new Error("LSP source changed during search.")}return i!==void 0&&await z(i,r),u.sort((f,g)=>f.source.localeCompare(g.source)||f.lineNumber-g.lineNumber||f.startColumn-g.startColumn||f.endColumn-g.endColumn||f.symbol.id.localeCompare(g.symbol.id)),{hits:u.slice(0,t),complete:(i?.complete??!0)&&u.length<=t}}a(Le,"searchSymbols");import Re from"node:path";import{fileURLToPath as Sr}from"node:url";var Pe=10,_e=5,K=10;async function ce(o,e,t,r,n){$(n);let s=await o.readSourceText(e,n),i=await de(o,e,r,n),d=le(i.symbols,t,i.displayPath),c=await o.readSourceText(i.filePath,n);if($(n),s!==c)throw new Error("The symbol source changed during resolution. Read it again before editing.");return{source:i.filePath,range:d.range,content:c}}a(ce,"resolveLspDeclaration");async function Dt(o,e,t,r,n){$(n);let s=await o.readSourceText(e,n),i=await de(o,e,r,n),d=le(i.symbols,t,i.displayPath);if(s!==await o.readSourceText(e,n))throw new Error("The rename source changed during resolution.");return $(n),{client:i.client,uri:i.uri,position:d.selectionRange.start,content:s}}a(Dt,"resolveLspRenameTarget");async function ke(o,e,t,r,n){$(n);let s=await de(o,e,r,n),i=le(s.symbols,t,s.displayPath),d=await Ot(s,i,n),c=new ae(r);return await Lr(s,i,d,c)}a(ke,"readLspSymbolGraph");async function Ee(o,e,t,r){$(r);let n=await de(o,e,t,r),s=new ae(t),i=[`## file graph: ${n.displayPath}`,`Top-level declarations: ${n.symbols.length}`];for(let d of n.symbols){$(r);let c=await Ot(n,d,r);i.push("",...await Cr(n,d,c,s))}return i.join(`
2
+ `)}a(Ee,"readLspFileGraph");function le(o,e,t){if(e.length===0)throw new TypeError("A symbol selector must contain at least one segment.");if(e.length===1){let s=Tt(o,k(e[0]));if(s.length===1)return k(s[0]);throw s.length>1?new Error(`Symbol selector "${V(e)}" is ambiguous in ${t}; use parent/child.`):It(e,t)}let r=o,n;for(let s of e){let i=r.filter(d=>d.name===s);if(i.length===0)throw It(e,t);if(i.length>1)throw new Error(`Symbol selector "${V(e)}" is ambiguous at "${s}" in ${t}.`);n=k(i[0]),r=n.children}return k(n)}a(le,"resolveLspCodeSymbol");async function de(o,e,t,r){let n=I(e,t),s=await o.openFile(n,t,"symbols",r);if(!s)throw new Error(`No LSP server with symbol support is configured for ${xe(n,t)}.`);let i=await Y(s.client,s.uri,r),d=At(i).sort(jt);return{client:s.client,uri:s.uri,filePath:n,displayPath:xe(n,t),symbols:d}}a(de,"openCodeDocument");function At(o,e=[]){return o.flatMap(t=>{let r=t.selectionRange??t.range;if(!r)return[];let n=t.range??r,s=[...e,t.name];return[{name:t.name,kind:t.kind,range:n,selectionRange:r,selector:s,children:At(t.children??[],s).sort(jt)}]})}a(At,"normalizeDocumentSymbols");function jt(o,e){return o.range.start.line-e.range.start.line||o.range.start.character-e.range.start.character||o.name.localeCompare(e.name)}a(jt,"compareSymbols");function Tt(o,e){return o.flatMap(t=>[...t.name===e?[t]:[],...Tt(t.children,e)])}a(Tt,"collectNamedSymbols");function It(o,e){return new Error(`Symbol "${V(o)}" was not found in ${e}.`)}a(It,"symbolNotFound");async function Ot(o,e,t){let r=e.selectionRange.start,[n,s]=await Promise.all([Z(o.client,o.uri,r,t),be(o.client,o.uri,r,t)]);return $(t),{references:n,calls:s}}a(Ot,"queryRelations");async function Lr(o,e,t,r){let n=V(e.selector),s=await r.line(o.uri,e.selectionRange.start.line+1);return[`## graph: ${n}`,`Definition: ${o.displayPath} ${s} (${W(e.kind)})`,`Source: calls ${Mt(o.displayPath,e.selector)}`,"",...await Rr(t.references,r),"",...await Pr(t.calls.incoming,r),"",...await _r(t.calls.outgoing,r)].join(`
3
+ `)}a(Lr,"formatSymbolGraph");async function Rr(o,e){let t=$t(o),r=[`References: ${o.length} in ${t.length} file(s)`];for(let[n,s]of t.slice(0,Pe)){r.push(`- ${e.display(n)} (${s.length})`);for(let i of s.slice(0,_e))r.push(` - ${await e.line(n,i.range.start.line+1)}`);s.length>_e&&r.push(` - ... ${s.length-_e} more`)}return t.length>Pe&&r.push(`- ... ${t.length-Pe} more file(s)`),r}a(Rr,"formatReferences");async function Pr(o,e){let t=[`Incoming calls: ${o.length}`];for(let r of o.slice(0,K)){let n=r.fromRanges[0]?.start.line??r.from.selectionRange.start.line,s=await e.line(r.from.uri,n+1);t.push(`- ${W(r.from.kind)} ${r.from.name} \u2014 ${e.display(r.from.uri)} ${s}`)}return o.length>K&&t.push(`- ... ${o.length-K} more`),t}a(Pr,"formatIncomingCalls");async function _r(o,e){let t=[`Outgoing calls: ${o.length}`];for(let r of o.slice(0,K)){let n=await e.line(r.to.uri,r.to.selectionRange.start.line+1);t.push(`- ${W(r.to.kind)} ${r.to.name} \u2014 ${e.display(r.to.uri)} ${n}`)}return o.length>K&&t.push(`- ... ${o.length-K} more`),t}a(_r,"formatOutgoingCalls");async function Cr(o,e,t,r){let n=W(e.kind),s=await r.line(o.uri,e.selectionRange.start.line+1),i=$t(t.references).map(([m,y])=>`${r.display(m)} (${y.length})`),d=t.calls.incoming.map(m=>`${m.from.name} (${r.display(m.from.uri)})`),c=t.calls.outgoing.map(m=>`${m.to.name} (${r.display(m.to.uri)})`),l=[`### ${n} ${e.name}`,`Selector: ${V(e.selector)}`,`Definition: ${s}`,`Used by: ${Ce(i)}`,`Incoming calls: ${Ce(d)}`,`Outgoing calls: ${Ce(c)}`];if(e.children.length>0){l.push("Members:");for(let m of e.children){let y=Mt(o.displayPath,m.selector);l.push(`- ${W(m.kind)} ${m.name} \u2014 calls ${y}`)}}return l}a(Cr,"formatFileGraphSymbol");function Mt(o,e){return rt("graph",o,e).slice(6)}a(Mt,"callsReference");function Ce(o,e=5){if(o.length===0)return"none";let t=o.slice(0,e).join(", ");return o.length>e?`${t}, ... ${o.length-e} more`:t}a(Ce,"summarize");function $t(o){let e=new Map;for(let t of o){let r=e.get(t.uri)??[];r.push(t),e.set(t.uri,r)}return[...e].map(([t,r])=>[t,r.sort((n,s)=>n.range.start.line-s.range.start.line||n.range.start.character-s.range.start.character)]).sort(([t],[r])=>t.localeCompare(r))}a($t,"groupLocationsByUri");var ae=class{static{a(this,"LocationPresenter")}#e;constructor(e){this.#e=e}display(e){return xe(xr(e),this.#e)}line(e,t){return Promise.resolve(String(t))}};function xr(o){if(!o.startsWith("file://"))return o;try{return Sr(o)}catch{return decodeURIComponent(o.slice(7))}}a(xr,"filePathFromUri");function xe(o,e){if(o.startsWith("ssh://"))return o;let t=Re.relative(e,o);return t.length===0||t.startsWith("..")||Re.isAbsolute(t)?o:t.replaceAll(Re.sep,"/")}a(xe,"displayFilePath");function $(o){if(o?.aborted===!0)throw kr(o)}a($,"throwIfAborted");function kr(o,e){if(o.reason instanceof Error)return o.reason;if(e instanceof Error)return e;let t=new Error("The operation was aborted");return t.name="AbortError",t}a(kr,"abortReason");function Ie(o){let e=null;return{kind:"compiler",name:"lsp",priority:100,extensions:["*"],detect:a(()=>Promise.resolve(!0),"detect"),async compile({filePath:t},r){r.signal?.throwIfAborted();let n=await o(r.cwd,t,r.signal);r.signal?.throwIfAborted();let s=await Er(t,r,n);if(!s)throw new Error("No diagnostic language server for this source");let{client:i,diagnostics:d,syntaxErrors:c,otherDiagnostics:l}=s;return e=i,{ok:!d.some(m=>m.severity==="error"),diagnostics:d,syntaxErrors:c,otherDiagnostics:l}},async restart(){e&&(await e.restart(),e=null)}}}a(Ie,"createLspCompiler");async function Er(o,e,t){let r=await t.openFile(o,e.cwd,"diagnostics",e.signal);if(e.signal?.throwIfAborted(),!r)return null;let n=await Q(r.client,r.uri,r.languageId,{signal:e.signal});if(e.signal?.throwIfAborted(),!n.complete)throw new Error("Language server diagnostics are a snapshot, not a completed report");return{client:r.client,...n}}a(Er,"openAndDiagnose");import Ir from"node:path";function Nt(o){let e=o.options?.lsp;return typeof e=="object"&&e!==null?e:void 0}a(Nt,"lspOptions");var Dr={resolveLspDeclaration:ce,readLspFileGraph:Ee,readLspSymbolGraph:ke,searchSymbols:Le};function Ut(o,e,t=Dr){return{id:"lsp",supportsResultScope:!0,readResources:a(r=>Nt(r)===void 0?[]:void 0,"readResources"),toScriptData(r){let n=r;return n.mode==="calls"?{kind:"custom",resolverId:"lsp",value:{calls:n.text}}:n.data},async tryResolve(r,n){let s=Nt(r);if(s===void 0)return{kind:"not-handled"};if([s.query,s.declaration,s.calls].filter(p=>p!==void 0).length!==1)return{kind:"failed",error:new Error("Pass exactly one of query, declaration or calls.")};if(s.calls!==void 0){let p=N(`graph:${s.calls}`,"graph");if(p===void 0)throw new Error("calls requires a file path.");let w=I(p.path,n.cwd),v=await o(n.cwd,w,n.signal);return{kind:"resolved",payload:{mode:"calls",text:p.selector===void 0?await t.readLspFileGraph(v,w,n.cwd,n.signal):await t.readLspSymbolGraph(v,w,p.selector,n.cwd,n.signal)}}}if(s.declaration!==void 0){let p=s.declaration.includes("#")?N(`symbol:${s.declaration}`,"symbol"):void 0;if(p?.selector===void 0)throw new Error("declaration requires file#selector, such as src/app.ts#App/start.");let w=I(p.path,n.cwd),v=p.selector,L=a(async D=>{let j=await o(n.cwd,w,D),P=await t.resolveLspDeclaration(j,w,v,n.cwd,D);return Ar(P.source,P.content,P.range)},"resolve"),b=await L(n.signal),x=await e({request:r,matches:[b],complete:!0,refresh:a(async D=>({matches:[await L(D)],complete:!0}),"refresh")},n);return{kind:"resolved",payload:{mode:"declaration",sessionId:x.id,selector:s.declaration,match:b,data:ue([b],!0,x.id,x)}}}let d=(s.query??"").trim();if(d.length===0)return{kind:"failed",error:new Error("query must not be empty")};let c=s.references===!0,l=n.scope,m=new Map;if(l!==void 0){await z(l,n.signal);for(let p of l.targets){let w=await o(n.cwd,p.source,n.signal),v=m.get(w)??[];v.push(p),m.set(w,v)}}else m.set(await o(n.cwd,r.path,n.signal),[]);let y=r.limit??100,u=a(async p=>{let w=[],v=l?.complete??!0;for(let[L,b]of m){let x=await t.searchSymbols(d,L.workspaceRoot,y,p,{...r.path===void 0?{}:{path:r.path},...r.include===void 0?{}:{include:r.include},...r.exclude===void 0?{}:{exclude:r.exclude},...c?{navigation:"references"}:{},...l===void 0?{}:{resultScope:{targets:b,complete:l.complete}}},L);w.push(...x.hits),v=v&&x.complete}return l!==void 0&&await z(l,p),{hits:w.slice(0,y),complete:v&&w.length<=y}},"collect"),h=await u(n.signal),f=await e({request:r,matches:h.hits,complete:h.complete,refresh:a(async p=>{let w=await u(p);return{matches:w.hits,complete:w.complete}},"refresh")},n),g=ue(h.hits,h.complete,f.id,f);return{kind:"resolved",payload:{mode:"symbols",sessionId:f.id,hits:h.hits,complete:h.complete,references:c,data:{...g,matches:g.matches.map((p,w)=>({...p,role:h.hits[w]?.role,symbol:h.hits[w]?.symbol}))}}}},renderResult(r,n,s){let i=r.details;return i.mode==="calls"?new te({summary:i.text.split(`
4
+ `,1)[0]??"Calls",rows:i.text.split(`
5
+ `).slice(1).map(d=>({kind:"note",text:d}))},s,n.expanded):i.mode==="declaration"?pe([i.match],!0,s,n.expanded,i.cwd,[],[i.selector]):pe(i.hits,i.complete,s,n.expanded,i.cwd,i.references?["LSP reference navigation \xB7 may leave input scope"]:[],i.hits.map(d=>`${d.role} ${d.symbol.name}`))},format(r,n){let s=r,i=a(l=>l.startsWith("ssh://")?l:Ir.relative(n.cwd,l),"display");if(s.mode==="calls")return{content:[{type:"text",text:s.text}],details:s};if(s.mode==="declaration"){let{match:l}=s,m=l.endLineNumber??l.lineNumber,y=m>l.lineNumber&&l.endColumn===0?m-1:m;return{content:[{type:"text",text:[`SEARCH#${s.sessionId}:1:match ${i(l.source)}:${l.lineNumber}-${y} declaration ${s.selector}`,l.matchedText.replace(/\r?\n$/u,"")].join(`
6
+ `)}],details:{...s,cwd:n.cwd}}}let d=s.references?"LSP reference navigation (may leave input scope)":"LSP symbols inside scope",c=s.hits.length===0?["No symbols found."]:s.hits.slice(0,100).map((l,m)=>`SEARCH#${s.sessionId}:${m+1}:match ${i(l.source)}:${l.lineNumber}:${l.startColumn+1} ${l.role} ${l.symbol.name} \xB7 declared at ${i(l.symbol.source)}:${l.symbol.range.startLine}:${l.symbol.range.startColumn+1}`);return s.complete&&s.hits.length&&c.unshift(`SEARCH#${s.sessionId}:all:match selects all exact symbol matches.`),s.hits.length>100&&c.push("Preview shortened; full source targets retained."),{content:[{type:"text",text:[d,...c].join(`
7
+ `)}],details:{...s,cwd:n.cwd}}}}}a(Ut,"createLspSearchResolver");function Ar(o,e,t){let r=e.split(`
8
+ `),n=r.map(u=>u.replace(/\r$/u,"")),s=[0];for(let u of r)s.push((s.at(-1)??0)+u.length+1);let i=t.start.line,d=t.end.line+1<r.length,c=d?t.end.line+1:t.end.line,l=d?0:(n[t.end.line]??"").length,m=s[i]??e.length,y=Math.min(e.length,(s[c]??e.length)+l);return{source:o,lineNumber:i+1,startColumn:0,...c===i?{}:{endLineNumber:c+1},endColumn:l,matchedText:e.slice(m,y),lineText:n[i]??""}}a(Ar,"declarationMatch");import{Type as C}from"typebox";var jr=C.Object({query:C.Optional(C.String({minLength:1,description:"Symbol name to find in the workspace."})),declaration:C.Optional(C.String({minLength:1,description:"file#selector, such as src/app.ts#App/start: returns that declaration as an editable selection."})),calls:C.Optional(C.String({minLength:1,description:"file or file#selector: references and incoming/outgoing calls."})),path:C.Optional(C.Union(Te.anyOf,{description:"For query: file, directory, unchanged Read/Search/edit result, its UUID, or an array of such results."})),references:C.Optional(C.Boolean({description:"For query: also follow symbols found inside path to their references outside it."})),include:C.Optional(C.String({description:"Include glob for query"})),exclude:C.Optional(C.String({description:"Exclude glob for query"})),limit:C.Optional(C.Integer({minimum:1,maximum:1e3,description:"Maximum matches (default 100)."}))},{additionalProperties:!1});async function qt(o,e){let t;e.then(r=>t=r),o.registerTool(Ve({name:"lsp_search",label:"lsp_search",exposure:"direct",namespace:{name:"ide_lsp_search",description:"Find code through language servers."},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:"Use lsp_search to find symbol declarations and references, read one declaration, or list a symbol's calls and references through the project's language servers. Matches and declarations are editable selections.",promptSnippet:"Find symbols, references, declarations and call graphs through language servers",parameters:jr,outputSchema:Je,renderCall(r,n,s){return Fe(s.lastComponent,{tool:"lsp_search",primary:{text:r.query??r.declaration??r.calls??"",color:"accent",truncate:"end"},qualifiers:[...r.declaration===void 0?[]:[{text:"declaration"}],...r.calls===void 0?[]:[{text:"calls"}],...r.path===void 0?[]:[{text:typeof r.path=="string"?`in ${r.path}`:"in result scope",color:"accent",truncate:"start"}],...r.references===!0?[{text:"references",color:"warning"}]:[]],expanded:s.expanded},n)},renderResult(r,n,s,i){let d=r.details;if(t?.resolver.renderResult!==void 0&&d?.payload!==void 0&&!i.isError&&!n.isPartial)return t.resolver.renderResult({...r,details:d.payload},n,s,i);let c=r.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
9
+ `);return new te({summary:i.isError?"lsp_search failed":"lsp_search",rows:c.split(`
10
+ `).map(l=>({kind:"note",text:l}))},s,n.expanded)},async execute(r,n,s,i,d){let c=n.query??n.declaration??n.calls,l=[n.query,n.declaration,n.calls].filter(h=>h!==void 0);if(c===void 0||l.length!==1)return Wt("Pass exactly one of query, declaration or calls.");let m={...n.query===void 0?{}:{query:n.query},...n.declaration===void 0?{}:{declaration:n.declaration},...n.calls===void 0?{}:{calls:n.calls},...n.references===!0?{references:!0}:{}};if(t===void 0)return Wt("lsp_search needs the Search module (search.core), which is not loaded.");let{api:y,resolver:u}=t;return await y.searchWith(u,{query:c,...n.path===void 0?{}:{path:n.path},...n.include===void 0?{}:{include:n.include},...n.exclude===void 0?{}:{exclude:n.exclude},...n.limit===void 0?{}:{limit:n.limit},options:{lsp:m}},{cwd:d.cwd,...s!==void 0&&{signal:s},...i!==void 0&&{onUpdate:i}})}},new ze))}a(qt,"registerLspSearchTool");function Wt(o){return je({content:[{type:"text",text:o}],details:{failure:{code:"INVALID_REQUEST",message:o}}},Be,{status:"error",errors:[Ae(new Error(o),"SEARCH_FAILED")]})}a(Wt,"failure");function Ft(o){return{id:"lsp-declaration-target",async tryResolve(e,t){let r=N(e,"symbol");if(r===void 0||e.endsWith("#name"))return{kind:"not-handled"};if(r.selector===void 0)return{kind:"rejected",rejection:{code:"invalid",reason:"Use symbol:<file>#<selector> to choose one declaration"}};try{let n=await ce(await o(t.cwd,I(r.path,t.cwd),t.signal),I(r.path,t.cwd),r.selector,t.cwd,t.signal);return{kind:"resolved",targets:[{source:n.source,expectedContent:n.content,ranges:[{start:{lineNumber:n.range.start.line+1,column:n.range.start.character},end:{lineNumber:n.range.end.line+1,column:n.range.end.character}}]}]}}catch(n){return{kind:"failed",error:new Error(`${n instanceof Error?n.message:String(n)} Read the physical file and use explicit text anchors if declaration resolution is unavailable.`,{cause:n})}}}}}a(Ft,"createDeclarationTargets");import{fileURLToPath as Tr}from"node:url";function zt(o,e){if(o===null)throw new Error("The language server did not provide rename edits. No text fallback was applied.");let t=new Map(Object.entries(o.changes??{}));for(let r of o.documentChanges??[]){if(!("textDocument"in r)||!("edits"in r))throw new Error("Rename returned an unsupported file operation. No edits applied.");if(r.textDocument.version!=null&&r.textDocument.version!==e.documentVersion(r.textDocument.uri))throw new Error("Rename refers to an unavailable document revision. No edits applied.");if(t.has(r.textDocument.uri))throw new Error("Rename returned duplicate document edits.");t.set(r.textDocument.uri,r.edits)}return t}a(zt,"renameEntries");function Vt(o,e){let t=o.split(`
11
+ `),r=t[e.line];if(!Number.isInteger(e.line)||e.line<0||r===void 0||!Number.isInteger(e.character)||e.character<0||e.character>r.replace(/\r$/u,"").length)throw new Error("The language server returned an invalid text position.");return t.slice(0,e.line).reduce((n,s)=>n+s.length+1,0)+e.character}a(Vt,"offset");async function Ht(o,e){let t=o.input;if(typeof t.path!="string"||!t.path.startsWith("symbol:")||!t.path.endsWith("#name"))return;if(typeof t.text!="string"||t.text.trim()===""||t.start!==void 0||t.end!==void 0)throw new Error("Rename needs a symbol #name path and a non-empty new name in text, without start/end.");let r=N(t.path.slice(0,-5),"symbol");if(r?.selector===void 0)throw new Error("Rename needs an exact symbol selector before #name.");let n=I(r.path,o.cwd),s=await e(o.cwd,n,o.signal),i=await Dt(s,n,r.selector,o.cwd,o.signal);await ve(i.client,i.uri,o.signal);let d=zt(await se(i.client,i.uri,i.position,t.text),i.client),c=new Map;for(let y of new Set([i.uri,...d.keys()])){o.signal?.throwIfAborted();let u=E(y,i.client.rootUri);if(u!==y)throw new Error("Rename returned a non-canonical participant. No edits applied.");let h=u.startsWith("ssh://")?u:Tr(u),f=await s.readSourceSnapshot(h,o.signal);if(h===n&&f.content!==i.content)throw new Error("The rename source changed. Read the symbol again before retrying.");let g=await s.openFile(h,o.cwd,"symbols",o.signal);if(g?.client!==i.client||g.uri!==y)throw new Error("A rename participant has a different language server owner. No edits applied.");if(i.client.documentContent(y)!==f.content)throw new Error("A rename participant changed during synchronization. No edits applied.");c.set(y,{file:h,...f})}let l=zt(await se(i.client,i.uri,i.position,t.text),i.client);o.signal?.throwIfAborted();for(let[y,u]of c){o.signal?.throwIfAborted();let h=await s.readSourceSnapshot(u.file,o.signal);if(u.version!==h.version||i.client.documentContent(y)!==u.content)throw new Error("A rename participant changed during the server request. No edits applied.")}let m=[];for(let[y,u]of l){let h=c.get(y);if(!h)throw new Error("Rename discovered a new participant after preflight. No edits applied.");m.push({source:h.file,expectedContent:h.content,changes:u.map(f=>({from:Vt(h.content,f.range.start),to:Vt(h.content,f.range.end),insert:f.newText}))})}return{...o,editPlan:{files:m},metadata:{...o.metadata,semanticEdit:{mode:"lsp-rename",server:i.client.serverId,referencesUpdated:!0},diffStatuses:[{text:"Renamed through LSP",tone:"success"}]}}}a(Ht,"prepareSymbolRename");async function Mr(o){await $r(o)}a(Mr,"registerLsp");async function $r(o,e){let t,r=new Promise(u=>t=u),n=new Map,s=!1,i=a(async(u,h=!1,f)=>{if(f?.throwIfAborted(),s)throw new Error("LSP session has ended");let g=JSON.stringify([u,h]),p=n.get(g);if(p?.controller.signal.aborted)return await T(p.promise.catch(()=>{}),f),n.get(g)===p&&n.delete(g),i(u,h,f);if(!p){p=new B(async v=>{let L=e?await e.loadRegistry(u,h,v):await Nr(u,h,v);if(v.throwIfAborted(),s)throw new Error("LSP session has ended");return q.init(L,e?.workspace(u))});let w=p;n.set(g,w),w.promise.catch(()=>{n.get(g)===w&&n.delete(g)})}return p.wait(f)},"managerFor"),d=a(async(u,h,f)=>{if(f?.throwIfAborted(),e)return e.resolveProject(u,h,f);let g=await lt(h,u,"lsp-servers",H,f);return f?.throwIfAborted(),g===void 0?void 0:{cwd:g,external:g!==Or.resolve(h)}},"resolveLspProject"),c=a(async(u,h,f)=>{if(f?.throwIfAborted(),!h)return i(u,!1,f);let g=await d(h,u,f);if(f?.throwIfAborted(),!g)throw new Error("No language server project for this source");return i(g.cwd,g.external,f)},"managerForFile"),l={...Ie(c),name:"pi-agent-ide-lsp",priority:200},m={protocol:ot,apiVersion:5,id:"lsp",setup(u){u.addTool(l),u.addDiagnosticSource(bt(i,d))}};o.on("session_shutdown",async()=>{s=!0,await Promise.allSettled([...n.values()].map(async u=>{u.settled||u.controller.abort(new Error("LSP session has ended")),await(await u.promise).shutdownAll()})),n.clear()});let y={protocol:Oe,apiVersion:Me,id:"lsp",setup(u){u.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler:nt()})}};await Promise.all([it(o,m),tt(o,{protocol:Ue,apiVersion:We,id:"lsp-declarations",setup(u){u.onDidEdit(async h=>{await Promise.all([...n.values()].filter(f=>f.settled).map(f=>f.promise.then(g=>g.syncEditedSource(h.source,h.after.content),()=>{})))}),u.addAnchorResolver({kind:qe,type:"auxiliary",resolver:{id:"lsp-declaration",description:"symbol:<file>#<selector> selects an exact declaration for text fallback editing; imports and references are not rewritten.",renderFull:a(h=>h,"renderFull"),renderCompact:a(h=>h,"renderCompact"),tryResolve:a(()=>Promise.resolve({kind:"not-handled"}),"tryResolve")},resources:Ft(c),describeInPrompt:!1});for(let h of["copy","move","delete","replace"])u.tool(h).describeField("path","symbol:<file>#<selector> selects one declaration without start; imports and references are not updated."+(h==="replace"?" symbol:<file>#<selector>#name renames it, with the new name in text.":"")),h==="replace"&&u.tool(h).describe("Use replace with a symbol:\u2026#name path to rename a symbol across the project."),u.tool(h).addHandler({stage:"text-pre-edit",async handler(f){if(h==="replace"){let w=await Ht(f,c);if(w!==void 0)return w}let g=f.input;if(![g.path,g.start,g.end,g.target,g.targetStart,g.targetEnd].some(w=>typeof w=="string"&&w.startsWith("symbol:")))return f;if((h==="copy"||h==="move")&&typeof g.target!="string")throw new Error("Copying or moving a symbol requires an explicit target file and destination anchor.");return{...f,metadata:{...f.metadata,semanticEdit:{mode:"declaration-text",referencesUpdated:!1,importsUpdated:!1},diffStatuses:[{text:"Text fallback: imports and references unchanged",tone:"warning"}]}}}});u.tool("insert").describeField("anchor","Symbol targets are not supported."),u.tool("insert").addHandler({stage:"text-pre-edit",handler(h){let f=h.input;if([f.path,f.anchor].some(g=>typeof g=="string"&&g.startsWith("symbol:")))throw new Error("Semantic insert is not supported. Get the declaration with lsp_search and use an explicit text line anchor instead.");return h}})}}),$e(o,y),Ye(o,Ct),Ke(o,{protocol:He,apiVersion:Ge,id:"lsp-search",setup(u){t({api:u,resolver:Ut(c,u.registerSelection)})}}),qt(o,r)])}a($r,"registerLspWithOwner");async function Nr(o,e,t){let r=e?o:process.env.PI_AGENT_IDE_CONFIG_DIR??o;return A.fromPackageDir(r,{signal:t,includeGlobal:!e,requireBuiltInEvidence:e,recipes:H})}a(Nr,"loadRegistry");export{H as a,A as b,Mr as c,$r as d};
@@ -0,0 +1,9 @@
1
+ import{a as le,b as fe,c as ue}from"./chunk-WQIMM4SU.js";import{a as de}from"./chunk-FHRHYY4M.js";import{a as N,g as l}from"./chunk-4IWEKRSP.js";import{c as ce}from"./chunk-W7CASEO3.js";import"./chunk-NNCZYO4Q.js";import{a as ne}from"./chunk-47SPPIXK.js";import{a as te,b as re}from"./chunk-VAXLSPPU.js";import{f as Z,g as ee}from"./chunk-KN6VPARZ.js";import{d as q}from"./chunk-OMNKD7WW.js";import"./chunk-PS2B6THP.js";import{a as ie}from"./chunk-GXL4NMHR.js";import{b as x,c as Q,d as X}from"./chunk-PQWANILR.js";import{a as W}from"./chunk-BU7IZLKB.js";import{a as $,b as K}from"./chunk-S5PL5DFQ.js";import{I as H}from"./chunk-DDH3FP4G.js";import{r as J}from"./chunk-VDJSH3DQ.js";import{a as se}from"./chunk-ZAWRSA7N.js";import{a as oe,b as ae}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(o,a)=>{let i=r.resolve(o.path??".",a.cwd);if(i===void 0)return;let{backend:c,location:w}=i,e=s((t,n=w.source)=>{let m=r.resolve(t,n);if(m===void 0||m.backend!==c)throw new l("UNSUPPORTED_SOURCE",t,"not-applied");return m.location},"own");return{resolve:s((t,n)=>e(n,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,n)=>(await c.stat(e(t).path,{signal:n})).kind==="directory","isDirectory"),byteSize:s(async(t,n)=>(await c.stat(e(t).path,{signal:n})).size,"byteSize"),readText:s(async(t,n)=>(await c.read(e(t).path,{signal:n})).bytes.toString("utf8"),"readText"),async execute(t,n,m,R){let d=await c.execute(t,n,e(m).path,{signal:R});return{code:d.exitCode,stdout:d.stdout.toString("utf8"),stderr:d.stderr.toString("utf8")}},async runLines(t,n,m,R){let d=await c.startProcess("rg",t,e(n).path,{signal:R}),g=new Oe("utf8"),u=[],p=0,f="",h,y=s(E=>{let k=E.split(`
2
+ `);for(let[O,b]of k.entries()){if(u.push(b),p+=Buffer.byteLength(b),p>32*1024*1024)throw new l("CONTENT_LIMIT",w.source,"not-applied");O<k.length-1&&(m(u.join("")),u.length=0,p=0)}},"consume"),v=(async()=>{try{for await(let E of d.stdout)y(g.write(E));y(g.end()),p>0&&m(u.join(""))}catch(E){h=E,await d.stop()}})(),T=(async()=>{for await(let E of d.stderr)f+=E.toString("utf8"),f.length>65536&&(f=f.slice(-65536))})();try{try{await d.end()}catch(k){if(!(k instanceof l)||k.code!=="INPUT_CLOSED")throw k}let E=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:E.exitCode,stderr:f}}finally{await d.stop(),await Promise.allSettled([v,T])}}}}}s(he,"createSshSearchEnvironmentProvider");import{lstat as Ue,mkdir as Ee,rm as Me,symlink as He,unlink as Ve,open as ze}from"node:fs/promises";import A from"node:path";import{constants as z}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,o,a){if(a?.has(r)&&a.get(r)!==o)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,o){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(o.startsWith("ssh://"))throw new l("UNSUPPORTED_SOURCE",r,"not-applied");return D.resolve(o,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 o=await Ie(r,{bigint:!0});if(!o.isFile()||o.isSymbolicLink())throw new l("INVALID_FILE_TYPE",r,"not-applied");if(o.size>BigInt(Number.MAX_SAFE_INTEGER))throw new l("CONTENT_LIMIT",r,"not-applied");return o}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,o,a,i){a.signal?.throwIfAborted();let c=r.resolve(o.path,a.cwd),w=r.resolve(o.target??"",a.cwd),e=c?.location.source??j(o.path,a.cwd),t=w?.location.source??j(o.target??"",a.cwd);if(e===t)throw new l("SAME_FILE",e,"not-applied");let n=c?await c.backend.lstat(c.location.path,a):await U(e);if("kind"in n&&n.kind!=="file")throw new l("INVALID_FILE_TYPE",e,"not-applied");let m=Number(n.size),R=Number(n.mode),d="revision"in n?n.revision:F(n);C(e,d,i);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),i),c&&w&&c.backend.target.host===w.backend.target.host&&c.backend.target.configFile===w.backend.target.configFile&&"identity"in n&&"identity"in g&&n.identity.device===g.identity.device&&n.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,i),{source:e,target:t,remoteSource:c,remoteTarget:w,size:m,mode:R,sourceRevision:d,targetRevision:u}}s(je,"prepareTransfer");async function V(r,o,a,i,c,w){let{source:e,target:t,remoteSource:n,remoteTarget:m,size:R,mode:d,sourceRevision:g,targetRevision:u}=await je(r,a,i,c);await w?.();let p=n?void 0:await me(e,we.O_RDONLY|we.O_NOFOLLOW),f,h,y,v=!1,T="",E=s(async()=>{let k=n?await n.backend.lstat(n.location.path,i):await U(e);if(("revision"in k?k.revision:F(k))!==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})],"/",i),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 k=Pe("sha256");for(let b=0;b<R;){i.signal?.throwIfAborted();let S=Math.min(Be,R-b),I;if(n){let P=await n.backend.readRange(n.location.path,b,S,i);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(k.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 E(),await w?.();let O=k.digest("hex");if(i.signal?.throwIfAborted(),y){if(await y.write(Buffer.from(`${JSON.stringify({sha256:O})}
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");i.signal?.throwIfAborted(),await _e(f,t),f=void 0,v=!0}return o==="move"&&(await E(),n?await n.backend.removeEntry(n.location.path,g,i):await Fe(e)),{source:e,target:t}}catch(k){throw v?new l(ge(k),e,"unknown"):k}finally{await p?.close(),await h?.close(),f!==void 0&&await Ae(f,{force:!0}),y&&await y.stop().catch(()=>{})}}s(V,"transferFile");function Re(r,o,a){let i=r.resolve(o,a.cwd);if(i===void 0){let e=j(o,a.cwd);return{path:e,source:e,cwd:a.cwd,files:x}}let c=r.resolve(a.cwd,a.cwd),w=c?.location.target===i.location.target?c.location.path:i.backend.target.workspace;return{remote:i,source:i.location.source,path:i.location.path,cwd:w,files:{owner:JSON.stringify([i.backend.target.host,i.backend.target.configFile??null]),realpath:s(e=>i.backend.realpath(e,a),"realpath"),inspect:s(e=>i.backend.lstat(e,a),"inspect"),read:s(async e=>(await i.backend.read(e,a)).bytes.toString("utf8"),"read"),git:s((e,t,n)=>i.backend.queryGit(e,t,{...a,signal:n}),"git"),source:s(e=>N(i.location.target,e).source,"source"),snapshot:s((e,t)=>i.backend.objectSnapshot(e,{...a,signal:t}),"snapshot")}}}s(Re,"endpoint");function L(r,o,a){let i=r.remote?A.posix:A;if(i.sep==="\\"&&a.split("/").some(c=>c.includes("\\")||c.includes(":")))throw new l("INVALID_TARGET",r.source,"not-applied");return i.join(o,...a.split("/"))}s(L,"leaf");function G(r,o){return r.remote?N(r.remote.location.target,o).source:o}s(G,"receiptPath");async function _(r,o,a){let i;try{i=await r.files.inspect(o)}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||i?.revision!==a.revision)throw new l("TRANSFER_TARGET_CHANGED",G(r,o),"not-applied")}s(_,"checkEntry");async function M(r){let o;try{o=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 Ee(r);return}if(!o.isDirectory()||o.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,o,a,i){r.remote?await r.remote.backend.removeObject(o,a.revision,i):(await _(r,o,a),a.kind==="directory"?await Me(o,{recursive:!0,force:!1}):await Ve(o))}s(ve,"remove");async function ke(r,o,a,i,c,w){let e=Re(r,a.path,i),t=Re(r,a.target??"",i),n=await c.prepareTransfer(o,e,t),m=n.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,n.target.entries[0]?.revision??null,w);let R=!1;try{i.signal?.throwIfAborted();for(let d of n.source.entries)L(e,n.source.path,d.relativePath),L(t,n.target.path,d.relativePath);if(n.sourceKind==="file")e.remote&&t.remote&&e.remote.location.target===t.remote.location.target?await e.remote.backend[o](n.source.path,n.target.path,m.revision,n.target.entries[0]?.revision??null,i):await V(r,o,a,i,w,async()=>{await _(e,n.source.path,m),await _(t,n.target.path,n.target.entries[0])});else{if(o==="move"&&e.remote&&t.remote&&e.files.owner===t.files.owner&&await e.remote.backend.moveObject(n.source,n.target,i))return{kind:"file-operation",operation:o,ok:!0,effect:"applied",path:e.source,target:t.source,sourceKind:n.sourceKind};let d=new Map(n.target.entries.map(u=>[u.relativePath,u])),g=new Map;o==="move"&&n.target.entries[0]&&(R=!0,await ve(t,n.target.path,n.target.entries[0],i),d.clear());for(let u of n.source.entries){i.signal?.throwIfAborted();let p=L(e,n.source.path,u.relativePath),f=L(t,n.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,i):h===void 0&&(await M(A.dirname(f)),await Ee(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,i):(await M(A.dirname(f)),await He(Buffer.from(u.link,"base64"),f))}else{R=!0;let y=G(e,p),v=G(t,f);e.remote&&t.remote&&e.files.owner===t.files.owner?await e.remote.backend.copy(p,f,u.revision,h?.revision??null,i):await V(r,"copy",{path:y,target:v},i,void 0,async()=>{await _(e,p,u),await _(t,f,h)})}}for(let u of[...n.source.entries].reverse()){if(u.kind!=="directory"||d.has(u.relativePath))continue;let p=L(t,n.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,i);else{let y=await ze(p,z.O_RDONLY|z.O_DIRECTORY|z.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 n.verifySource(),o==="move"&&await ve(e,n.source.path,m,i)}return{kind:"file-operation",operation:o,ok:!0,effect:"applied",path:e.source,target:t.source,sourceKind:n.sourceKind}}catch(d){throw R?Object.assign(d instanceof Error?d:new Error(String(d)),{effect:"unknown"}):d}}s(ke,"transferObject");function Se(r,o){return async(a,i,c,w)=>{let e=r.resolve(i.path,c.cwd);if(e===void 0&&(i.target===void 0||r.resolve(i.target,c.cwd)===void 0))return;if(a!=="delete"){if(w===void 0)throw new l("TRANSFER_POLICY_REQUIRED",i.path,"not-applied");return ke(r,a,i,c,w,o)}if(e===void 0)return;let t=await e.backend.lstat(e.location.path,c);C(e.location.source,t.revision,o);{if(w===void 0)throw new l("DELETE_POLICY_REQUIRED",e.location.source,"not-applied");let n=r.resolve(c.cwd,c.cwd);if(n!==void 0&&n.location.target!==e.location.target)throw new l("UNSUPPORTED_SOURCE",e.location.source,"not-applied");let m=n?.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 Y(r,o,a){return{id:"ssh",async tryResolve(i,c){try{let w=r.resolve(i,c.cwd);if(!w)return{kind:"not-handled"};let{backend:e,location:t}=w,n=!1;try{n=(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,n){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
+ `)}]}return R=await d(p),o.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],E=v.bytes.length,k=Math.min(f??v.totalBytes,v.totalBytes-v.offset);for(;E<k;){let O=await e.readRange(t.path,v.offset+E,Math.min(k-E,4194304),h);if(O.revision!==v.revision||O.totalBytes!==v.totalBytes||O.offset!==v.offset+E)throw new l("SOURCE_CHANGED",t.source,"not-applied");if(O.bytes.length===0)break;T.push(O.bytes),E+=O.bytes.length}return{bytes:Buffer.concat(T,E),byteOffset:v.offset,totalBytes:v.totalBytes}},"readBytes");return a==="read"||n?{kind:"resolved",resource:{source:t.source,link:t.source,read:g,get sourceBytes(){return R},...n?{}:{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(Y,"createSshResourceResolver");async function be(r,o){let a=await Z({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(n=>({tool:n,resourcePrefixes:["ssh://"]}))]});if(ee(r,[{...a,markdown:`${a.markdown}
5
+ ## Configured workspaces
6
+
7
+ ${o.length===0?"No SSH targets are configured. Follow the setup steps above.":o.map(n=>`- \`${N(n.id,n.workspace).source}\``).join(`
8
+ `)}
9
+ `}]),o.length===0)return;let i=new ue(o),c=H(r,{provider:"filesystem",capability:"read"}),w=H(r,{provider:"filesystem",capability:"write"}),e={protocol:$,apiVersion:K,id:"ssh",setup(n){n.addResolver({resolver:Y(i,c,"read"),priority:-50,preserveTruncatedOutput:!0,renderResult:q({kind:"source"})})}},t={protocol:Q,apiVersion:X,id:"ssh",setup(n){n.addFileOperationResolver(Se(i)),n.addResolver({resolver:Y(i,w,"write"),priority:-50})}};await Promise.all([se(r,{protocol:oe,apiVersion:5,id:"ssh-diagnostic-files",setup(n){n.addDiagnosticFileReader({id:"ssh",async readText(m,R){let d=i.resolve(m,R.cwd);if(d)return(await d.backend.read(d.location.path,{signal:R.signal})).bytes.toString("utf8")}})}}),W(r,e),ie(r,t),ne(r,{protocol:te,apiVersion:re,id:"ssh",setup(n){n.addEnvironmentProvider(he(i))}})])}s(be,"registerSshResources");async function Ge(r){let o=await fe(le(ce()));await be(r,o)}s(Ge,"registerSshModule");export{Ge as default};
@@ -0,0 +1,2 @@
1
+ import{a as k,d as m}from"./chunk-7PVDTMEM.js";import{a as v,b}from"./chunk-PS2B6THP.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{pathToFileURL as T}from"node:url";function P(e,n,t,r,i,a=[],l=[]){let c=a.map(o=>({kind:"note",text:o}));c.push(...b(e.flatMap(o=>{let y=h.isAbsolute(o.source),D=y&&i?h.relative(i,o.source)||h.basename(o.source):o.source,z=y?T(o.source).href:/^https?:/iu.test(o.source)?o.source:void 0,x=o.endLineNumber??o.lineNumber;return(x===o.lineNumber?[o.lineText]:[o.lineText,...o.matchedText.split(/\r\n|\n|\r/u).slice(1)]).slice(0,20).map((R,f)=>({source:o.source,label:D,...z===void 0?{}:{link:z},...y?{}:{badge:o.source.startsWith("docs:")?"DOC":/^https?:/iu.test(o.source)?"WEB":"SH"},lineNumber:o.lineNumber+f,text:R,ranges:[{from:f?0:o.startColumn,to:o.lineNumber+f===x?o.endColumn:R.length}]}))}))),e.length||c.push({kind:"note",text:"No matches found"}),e.some(o=>(o.endLineNumber??o.lineNumber)-o.lineNumber>=20)&&c.push({kind:"note",text:"\u2026 source preview shortened"}),c.push(...l.map(o=>({kind:"note",text:o,expandedOnly:!0})));let u=`${e.length}${n?"":"+"}`,p=new Set(e.map(o=>o.source)),F=e.length>0&&e.every(o=>h.isAbsolute(o.source));return new v({summary:`${u} ${e.length===1?"match":"matches"} in ${p.size} ${F?p.size===1?"file":"files":p.size===1?"source":"sources"}`,rows:c},t,r)}s(P,"renderSearchMatches");function $(e,n){return e.targets.some(t=>t.source===n.source&&t.ranges.some(r=>(r.start.lineNumber<n.lineNumber||r.start.lineNumber===n.lineNumber&&r.start.column<=n.startColumn)&&(r.end.lineNumber>(n.endLineNumber??n.lineNumber)||r.end.lineNumber===(n.endLineNumber??n.lineNumber)&&r.end.column>=n.endColumn)))}s($,"containsSearchMatch");function I(e){if(e===void 0)return[];let n=[],t=0,r="";for(let i of e){if(i==="{"?t+=1:i==="}"&&(t=Math.max(0,t-1)),t===0&&(i===","||/\s/u.test(i))){r.length>0&&(n.push(r),r="");continue}r+=i}return r.length>0&&n.push(r),n}s(I,"splitGlobList");import{Value as N}from"typebox/value";var d={candidates:5,previewMatches:3,identifiers:2e4,identifierLength:80,vocabularyBytes:8*1024*1024,matchesPerCandidate:200,verificationBytes:4*1024*1024,timeoutMs:2e3};function L(e){return N.Check(k,e)}s(L,"isFuzzyResultData");function g(e){return e.length>=5&&e.length<=d.identifierLength&&/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)&&/[A-Za-z]/u.test(e)}s(g,"isFuzzyQuery");var S=class{static{s(this,"FuzzyVocabulary")}names=new Set;bytes=0;limited=!1;account(n){return this.bytes+=n,this.bytes>d.vocabularyBytes&&(this.limited=!0),!this.limited}add(n){if(!(this.limited||!g(n)||this.names.has(n))){if(this.names.size===d.identifiers){this.limited=!0;return}this.names.add(n)}}addText(n){if(this.account(Buffer.byteLength(n))){for(let t of n.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/gu))if(this.add(t[0]),this.limited)break}}};function w(e){return e.replace(/([A-Z]+)([A-Z][a-z])/gu,"$1 $2").replace(/([a-z0-9])([A-Z])/gu,"$1 $2").split(/[^A-Za-z0-9]+/u).filter(Boolean).map(n=>n.toLowerCase())}s(w,"splitName");function C(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}s(C,"same");function M(e,n){if(e.length<5||n.length<5||Math.abs(e.length-n.length)>1||/\d/u.test(e+n))return!1;let t=0;for(;t<Math.min(e.length,n.length)&&e[t]===n[t];)t++;if(e.length===n.length)return e.slice(t+1)===n.slice(t+1)||e[t]===n[t+1]&&e[t+1]===n[t]&&e.slice(t+2)===n.slice(t+2);let r=e.length<n.length?e:n,i=e.length<n.length?n:e;return r.slice(t)===i.slice(t+1)}s(M,"oneTypo");function E(e,n){if(e.join("")===n.join(""))return{kind:"normalized",reason:"same spelling with different case or separators"};let t=e.length<n.length?e:n,r=e.length<n.length?n:e;if(r.length===t.length+1&&t.length>=2&&t.every(l=>l.length>=3)){let l=C(t,r.slice(1)),c=C(t,r.slice(0,-1));if(l||c)return{kind:"component",reason:`${e.length>n.length?"remove":"add"} ${l?"leading":"trailing"} component '${l?r[0]:r.at(-1)}'`}}if(e.length!==n.length)return;let i=e.flatMap((l,c)=>{let u=n[c];return u!==void 0&&l!==u?[{word:l,other:u}]:[]}),a=i[0];if(!(i.length!==1||!a||!M(a.word,a.other)))return{kind:"typo",reason:`one character edit: '${a.word}' \u2192 '${a.other}'`}}s(E,"relation");var A={normalized:0,component:1,typo:2};function _(e,n){if(!g(e))return[];let t=w(e);if(t.length===0)return[];let r=[];for(let i of new Set(n)){if(i===e||!g(i))continue;let a=E(t,w(i));a&&r.push({identifier:i,...a})}return r.sort((i,a)=>A[i.kind]-A[a.kind]||(i.identifier<a.identifier?-1:i.identifier>a.identifier?1:0)).slice(0,d.candidates)}s(_,"rankFuzzyIdentifiers");function O(e,n,t){return{identifier:e.identifier,kind:e.kind,reason:e.reason,matchCount:e.matches.length,fileCount:new Set(e.matches.map(r=>r.source)).size,selection:{...m(e.matches.slice(0,d.previewMatches),e.complete,n,t),truncated:e.matches.length>d.previewMatches}}}s(O,"fuzzyCandidateData");function Z(e){let n=e.selection.complete?"":"+",t=e.selection.all?.line??e.selection.matches[0]?.references?.line,r=e.selection.matches[0],i=t??r?.source;return[`Possible name: ${e.identifier} (${e.reason})`,`${e.matchCount}${n} ${e.matchCount===1&&e.selection.complete?"match":"matches"} in ${e.fileCount}${n} ${e.fileCount===1&&e.selection.complete?"file":"files"}`,`Exact alternative: ${JSON.stringify(e.identifier)} (case-sensitive, whole identifier)`,...e.selection.complete?[]:["Capture limit reached; no complete all reference. Inspect the returned location; do not treat this candidate as a complete match set."],...i?[`Read: ${i}${t||!r?"":` \xB7 line ${r.range.startLine}`}`]:[]].join(`
2
+ `)}s(Z,"formatFuzzyCandidate");export{P as a,$ as b,I as c,d,L as e,g as f,S as g,_ as h,O as i,Z as j};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-VMLPXSMK.js";import"./chunk-FHRHYY4M.js";import"./chunk-4IWEKRSP.js";import"./chunk-DDH3FP4G.js";import"./chunk-EI7MMDWY.js";export{a as runOwnedSshCommand};
@@ -0,0 +1 @@
1
+ import{g as M,j as E,m as h,n as R}from"./chunk-DDH3FP4G.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var w=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),L=o.Object({source:o.String(),effect:w,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),O={effect:w,files:o.Array(L)};function A(n){return o.Object({operation:o.Literal(n),...O,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(A,"mutationDataSchema");function F(n){return E(A(n))}p(F,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,k=[]){let r=n.details,f=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 f.source=="string"?[{source:f.source,effect:"pending"}]:[]}};let g=new Set(k.map(t=>t.resourceSource)),s=[],l=[],S=r.results;for(let t of S??[]){let e=t.data,y=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of y)l.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(m=>m.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??[]){let m=M(i);s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path,...m===void 0?{}:{metadata:m}})}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)l.some(e=>e.source===t)||l.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&&l.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"&&l.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(h(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(h(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(h("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(l.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(y=>y.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let T=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(S?.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 b=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":T?"applied":"not-applied";return{status:s.length===0?"success":!a&&T&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:b,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 N(n,c,k=[],r){let f=U(n,c,k);return f.data&&r!==void 0&&(f.data.operationId=r),R(n,A(c),f)}p(N,"structuredMutation");export{A as a,F as b,U as c,N as d};
@@ -1 +1 @@
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};
1
+ import{g as u,h as E,m as a}from"./chunk-PQWANILR.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 +1 @@
1
- import{b as y}from"./chunk-VXP5BMW7.js";import{a as c,g as m}from"./chunk-PJL3UVMJ.js";import{q as w}from"./chunk-IMGIDBCC.js";import{a as p}from"./chunk-EI7MMDWY.js";import a from"node:path";async function C(e,f,t,v,h,n){n?.throwIfAborted();let i=c(e.target.id,f).path;if(t&&x(t,i))return{cwd:c(e.target.id,t).source,external:!1};let d=!1;try{d=(await e.stat(i,{signal:n})).kind==="directory"}catch(r){if(!(r instanceof m)||r.code!=="ENOENT")throw r}let g=d?h:h.filter(r=>w(r,i)),T=t===void 0&&x(e.target.workspace,i)?e.target.workspace:void 0,o=d?i:a.posix.dirname(i);for(;;){n?.throwIfAborted();let r=a.posix.join(o,".pi","pi-agent-ide",`${v}.json`),l=!1;try{await e.stat(r,{signal:n}),l=!0}catch(s){if(!(s instanceof m)||s.code!=="ENOENT")throw s}let E=!l&&g.length>0?[...(await y(e,o,g,n)).values()].some(s=>s.score>0):!1;if(l||E||o===T)return{cwd:c(e.target.id,o).source,external:t!==void 0};let u=a.posix.dirname(o);if(u===o)return;o=u}}p(C,"resolveSshToolProject");function x(e,f){let t=a.posix.relative(e,f);return t===""||t!==".."&&!t.startsWith("../")&&!a.posix.isAbsolute(t)}p(x,"inside");export{C as a};
1
+ import{b as y}from"./chunk-USG6WHAT.js";import{a as c,g as m}from"./chunk-4IWEKRSP.js";import{q as w}from"./chunk-7D7PXIVV.js";import{a as p}from"./chunk-EI7MMDWY.js";import a from"node:path";async function C(e,f,t,v,h,n){n?.throwIfAborted();let i=c(e.target.id,f).path;if(t&&x(t,i))return{cwd:c(e.target.id,t).source,external:!1};let d=!1;try{d=(await e.stat(i,{signal:n})).kind==="directory"}catch(r){if(!(r instanceof m)||r.code!=="ENOENT")throw r}let g=d?h:h.filter(r=>w(r,i)),T=t===void 0&&x(e.target.workspace,i)?e.target.workspace:void 0,o=d?i:a.posix.dirname(i);for(;;){n?.throwIfAborted();let r=a.posix.join(o,".pi","pi-agent-ide",`${v}.json`),l=!1;try{await e.stat(r,{signal:n}),l=!0}catch(s){if(!(s instanceof m)||s.code!=="ENOENT")throw s}let E=!l&&g.length>0?[...(await y(e,o,g,n)).values()].some(s=>s.score>0):!1;if(l||E||o===T)return{cwd:c(e.target.id,o).source,external:t!==void 0};let u=a.posix.dirname(o);if(u===o)return;o=u}}p(C,"resolveSshToolProject");function x(e,f){let t=a.posix.relative(e,f);return t===""||t!==".."&&!t.startsWith("../")&&!a.posix.isAbsolute(t)}p(x,"inside");export{C as a};
@@ -0,0 +1,25 @@
1
+ import{a as W}from"./chunk-BU7IZLKB.js";import{a as J,b as H}from"./chunk-S5PL5DFQ.js";import{N as D,P as q,d as B,i as U}from"./chunk-DDH3FP4G.js";import{a as d}from"./chunk-EI7MMDWY.js";import{createHash as le}from"node:crypto";import{Type as L}from"typebox";import{Value as ue}from"typebox/value";import{createCanvas as re,loadImage as se}from"@napi-rs/canvas";import{DEFAULT_MAX_BYTES as oe,DEFAULT_MAX_LINES as ae,truncateHead as ie}from"@earendil-works/pi-coding-agent";var E={bytes:oe,lines:ae,pixels:4e6,images:20,imageBytes:20*1024*1024};async function M(t,n="",l){let s=typeof n=="string"?[n]:n,u=[],g=t.flatMap(e=>{if(e.type!=="text")return[];let a=s.find(o=>o.length>0&&e.text.endsWith(o));return a?(u.push(a),[e.text.slice(0,-a.length)]):[e.text]}).join(`
2
+ `),T=u.join(""),S=ie(g,{maxBytes:E.bytes,maxLines:E.lines}),R=[],I;if(S.truncated&&l!==void 0)try{I=await l(g)}catch{R.push("[Full output could not be saved. Narrow the request to inspect it.]")}S.truncated&&R.push(`[Output truncated: useful content is limited to ${E.bytes} bytes / ${E.lines} lines. Narrow the request or read a smaller source range.]`),I!==void 0&&R.push(`[Full output: ${JSON.stringify(I)}. Read with offset/limit, or read ${JSON.stringify("raw:"+I)} for byte ranges. Available until this runtime is disposed.]`);let j=t.filter(e=>e.type==="image"),b=j.slice(0,E.images),k=[],C=Math.floor(E.pixels/Math.max(1,b.length)),O=0,_=j.length-b.length;for(let[e,a]of b.entries())try{let o=Buffer.from(a.data,"base64"),r=await se(o),i=Math.min(1,Math.sqrt(C/(r.width*r.height))),c=Math.min(C,Math.max(1,Math.floor(r.height*i))),f=Math.min(Math.floor(C/c),Math.max(1,Math.floor(r.width*i))),p=o,m=a.mimeType;if(i<1||O+p.byteLength>E.imageBytes){let y=re(f,c);y.getContext("2d").drawImage(r,0,0,f,c),p=await y.encode("png"),m="image/png"}if(O+p.byteLength>E.imageBytes){_++;continue}O+=p.byteLength,k.push({type:"image",data:p.toString("base64"),mimeType:m}),i<1&&R.push(`[Image ${e+1} resized from ${r.width}x${r.height} to ${f}x${c} to fit the shared media budget.]`)}catch{_++,R.push(`[Image ${e+1} could not be decoded and was not returned.]`)}return _>0&&R.push(`[${_} images omitted from the result. Read fewer frames or a smaller image region.]`),{text:S.firstLineExceedsLimit?ce(g):S.content,textTruncated:S.truncated,images:k,notices:R,metadataSuffix:T,fullOutput:I}}d(M,"limitIdeOutput");function ce(t){let n=0,l=0;for(let s of t){let u=Buffer.byteLength(s);if(n+u>E.bytes)break;n+=u,l+=s.length}return t.slice(0,l)}d(ce,"bytePrefix");var X={type:"object",properties:{result:{type:"string",description:"Unchanged registered Search result. Pass this string to other tools to reuse its exact selection."},hasMatches:{anyOf:[{type:"boolean"},{type:"null"}],description:"Whether the original query reported matches, excluding spelling alternatives. Null means unknown. False proves absence only when complete is true."},complete:{anyOf:[{type:"boolean"},{type:"null"}],description:"Whether the search covered its requested scope, independent of display truncation. Null means unknown."}},required:["result","hasMatches","complete"],additionalProperties:!1};function G(t,n){let l={result:n,hasMatches:null,complete:null};if(!z(t)||t.status!=="success"||!z(t.data))return l;let s=t.data,u=s.kind==="matches"?s.matches:s.kind==="files"?s.files:void 0;return!Array.isArray(u)||typeof s.complete!="boolean"?l:{result:n,hasMatches:u.length>0,complete:s.complete}}d(G,"searchFacts");function z(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}d(z,"record");var Y=new Set(["search","ast_search","lsp_search","file_search"]),Q={read:["path"],search:["path"],ast_search:["path"],lsp_search:["path"],file_search:["path"],replace:["path"],insert:["path"],delete:["path"],write:["path"],copy:["path","target"],move:["path","target"],undo:["file"],diff:["before","after"]},de=new Set(["write","replace","insert","delete","copy","move"]),pe={anyOf:[{type:"string"},{type:"object",description:"Value returned by a resource provider, such as a computer action outcome.",additionalProperties:!0}]},K={type:"object",properties:{type:{const:"image"},data:{type:"string"},mimeType:{type:"string"},note:{type:"string"}},required:["type","data","mimeType","note"]},Z=L.Object({status:L.Literal("error"),errors:L.Array(U,{minItems:1})},{additionalProperties:!1}),fe={anyOf:[Z,{type:"string"},K,{type:"object",description:"Several images, such as sequence frames, in source order.",properties:{type:{const:"images"},note:{type:"string"},images:{type:"array",items:{type:"object",properties:K.properties}}},required:["type","note","images"]}]};function me(t,n){let l=t.filter(u=>u.type==="image").map(({data:u,mimeType:g})=>({type:"image",data:u,mimeType:g}));if(l.length===0)return;let[s]=l;return l.length===1&&s!==void 0?{...s,note:n}:{type:"images",note:n,images:l}}d(me,"readValue");function ge(t){let n=P(t)?t.metadata:void 0,l=P(n)?n.semanticAction:void 0,s=P(l)?l.script:void 0;return P(s)&&!Array.isArray(s)?s:void 0}d(ge,"providerValue");function P(t){return t!==null&&typeof t=="object"}d(P,"record");function he(t){if(!P(t)||t.status!=="error")return;let n={status:"error",errors:t.errors};return ue.Check(Z,n)?n:void 0}d(he,"readFailure");function Oe(t,n={}){let l=D(t),s=q(t),u=new Set,g=new B,T=d(e=>n.resourceOutput?g.save(e):g.saveFile(e),"saveFullOutput"),S=new Map,R=d(e=>le("sha256").update(JSON.stringify(e)).digest("hex"),"signature"),I=d(async(e,a)=>{let o=R(a),r=S.get(e);if(r&&(r.source===o||R(await r.content)===o))return r.content;let i=M(a,"",T).then(c=>[{type:"text",text:c.text+(c.notices.length?`
3
+
4
+ ${c.notices.join(`
5
+ `)}`:"")},...c.images]);return S.set(e,{source:o,content:i}),i},"limitError");W(t,{protocol:J,apiVersion:H,id:"ide-output-retention",setup(e){e.setOutputSaver(T),n.resourceOutput&&e.addResolver({priority:-1e3,resolver:{id:"ide-output-retention",async tryResolve(a,o){let r=await g.resolver.tryResolve(a,o);return r.kind==="failed"?{kind:"not-handled"}:r}}})}}),t.on("session_shutdown",()=>g.dispose());let j=d((e,a)=>{if(e==="message_end"){let r=a;return t.on("message_end",async(i,c)=>{let f=await r(i,c),p=f?.message??i.message;return p.role!=="toolResult"||!p.isError||!u.has(p.toolName)||p.content.some(m=>m.type==="text"&&m.text.startsWith("<system-result"))?f:{...f,message:{...p,content:await I(p.toolCallId,p.content)}}})}let o=a;return e!=="tool_call"?t.on(e,o):t.on("tool_call",async(r,i)=>{let c=await o(r,i);if(!c?.block||!u.has(r.toolName)||c.reason===void 0)return c;let f=await M([{type:"text",text:c.reason}],"",T);return{...c,reason:f.text+(f.notices.length?`
6
+
7
+ ${f.notices.join(`
8
+ `)}`:"")}})},"on"),b=new Map,k=new Map,C=d(()=>{b.clear(),k.clear(),S.clear()},"clear");t.on("session_start",C),t.on("session_shutdown",C),t.on("before_agent_start",e=>{e.systemPromptOptions.sections[n.promptSection??"ide_results"]='Direct IDE calls return readable text. In Codemode, search tools return { result, hasMatches, complete }; pass its result string to other tools for composition. An image Read returns an image block: show it with image(), pass it to models.classify() images, and pass its note string to other tools. A completed Read failure returns { status: "error", errors }; inspect errors before using its value. Successful text Reads and other text tools return strings. The leading system-result envelope is an internal reference, not file content; do not edit it. Compose tools by passing the unchanged result string to a source parameter. Outside Codemode, pass the same text or its UUID. Store/load preserves results within the session. Use returned anchors to choose individual selections. Changed snapshots and previous sessions cannot be reused.'}),t.on("tool_execution_start",e=>{e.parentToolCallId!==void 0&&b.set(e.toolCallId,b.get(e.parentToolCallId)??e.parentToolCallId)}),j("tool_call",(e,a)=>{if(!u.has(e.toolName))return;let o={...e.input};try{for(let r of Q[e.toolName]??[]){let i=o[r];if(i!==void 0)if(e.toolName==="diff"&&i!==null&&typeof i=="object"&&"path"in i)o[r]={...i,path:l.source(i.path,a.cwd,!0)};else{let c=l.source(i,a.cwd,e.toolName==="read"?!0:["write","insert","delete"].includes(e.toolName)?"live":!1);if(e.toolName==="read"&&Array.isArray(c)){let f=l.resolve(c,a.cwd);o[r]=l.register(f.targets,a.cwd,f.complete)}else o[r]=c}}for(let r of["text","content"]){let i=o[r];if(typeof i=="string"&&(i.trimStart().startsWith("<system-result")||/<system-result\b[^>]*><uuid>[a-f\d-]{36}<\/uuid><\/system-result>/iu.test(i)))return{block:!0,reason:"A system result reference is not file content. Do not insert it into a file."}}Object.assign(e.input,o)}catch(r){return{block:!0,reason:r instanceof Error?r.message:String(r)}}});let O=d(e=>{u.add(e.name);let a={},o=Object.getOwnPropertyDescriptors(e);delete o.outputSchema,Y.has(e.name)&&(o.outputSchema={value:X,enumerable:!0,configurable:!0,writable:!0}),e.name==="read"&&(o.outputSchema={value:fe,enumerable:!0,configurable:!0,writable:!0}),de.has(e.name)&&(o.outputSchema={value:pe,enumerable:!0,configurable:!0,writable:!0});let r=d(async(...f)=>{let p=await e.execute(...f).catch(async w=>{let A=await M([{type:"text",text:w instanceof Error?w.message:String(w)}],"",T);throw A.notices.length===0?w:new Error(A.text+`
9
+
10
+ ${A.notices.join(`
11
+ `)}`,{cause:w})}),m=await M(p.content,ee(p.details),T),y=m.text+m.metadataSuffix;return{...p,content:[{type:"text",text:y+(m.notices.length?`
12
+
13
+ ${m.notices.join(`
14
+ `)}`:"")},...m.images]}},"execute");o.execute={value:r,enumerable:!0,configurable:!0,writable:!0};let i=e.renderCall;if(i){let f=d((p,m,y)=>i(ye(e.name,p),m,y),"renderCall");o.renderCall={value:f,enumerable:!0,configurable:!0,writable:!0}}let c=e.renderResult;if(c){let f=d((p,m,y,w)=>c({...p,content:p.content.map(A=>A.type==="text"?{...A,text:A.text.replace(/^<system-result\b[^>]*><uuid>[a-f\d-]{36}<\/uuid><\/system-result>\n/u,"")}:A)},m,y,w),"renderer");o.renderResult={value:f,enumerable:!0,configurable:!0,writable:!0}}Object.defineProperties(a,o),t.registerTool(a)},"registerTool"),_=d(()=>{t.on("context",async e=>({messages:await Promise.all(e.messages.map(async a=>a.role!=="toolResult"||!a.isError||!u.has(a.toolName)||a.content.some(o=>o.type==="text"&&o.text.startsWith("<system-result"))?a:{...a,content:await I(a.toolCallId,a.content)}))})),t.on("tool_result",async(e,a)=>{if(e.toolName==="codemode"){l.refreshAll();let x=new Set(e.content.flatMap(h=>h.type==="image"?[h.data]:[])),F=(k.get(e.toolCallId)??[]).filter(h=>!x.has(h.data));k.delete(e.toolCallId);for(let[h,ne]of b)ne===e.toolCallId&&b.delete(h);let V=e.content.filter(h=>h.type==="text"&&h.text.startsWith(`
15
+
16
+ ---
17
+
18
+ # Guide:`)),v=e.content.filter(h=>!V.includes(h)),N=await M([...v,...F],"",T);return{content:[...N.textTruncated?[{type:"text",text:N.text}]:v.filter(h=>h.type==="text"),...N.images,...N.notices.length?[{type:"text",text:`
19
+
20
+ ${N.notices.join(`
21
+ `)}`}]:[],...V]}}if(!u.has(e.toolName))return;let o=e.content.filter(x=>x.type==="text").map(x=>x.text).join(`
22
+ `),r=e.structuredContent,i=r!==null&&typeof r=="object"&&"data"in r?r:{status:e.isError?"error":"success",data:r},c=i.data,f=c!==null&&typeof c=="object"&&"effect"in c&&c.effect==="applied"&&"targetUnavailable"in c&&typeof c.targetUnavailable=="string"?c.targetUnavailable:void 0,p=f===void 0?o:`${o}
23
+
24
+ This result has no verified text selection: ${f}
25
+ Read/Search the file before the next edit; do not repeat the applied edit.`,m=te(i),y=!e.isError&&i.status!=="error",w=l.publish(i,p,a.cwd,m);s.keep(w,a.cwd,e.toolName==="read"&&y?e.content.filter(x=>x.type==="image"):[]);let A=Y.has(e.toolName)&&y?G(i,w):e.toolName==="read"?y?me(e.content,w):he(r):ge(e.details),$=b.get(e.toolCallId);if(b.delete(e.toolCallId),$!==void 0){let x=e.content.filter(F=>F.type==="image");x.length&&k.set($,[...k.get($)??[],...x])}return{content:[{type:"text",text:w},...e.content.filter(x=>x.type!=="text")],...A!==void 0&&{structuredContent:A}}})},"finalize");return{api:{...t,on:j,registerTool:O},finalize:_}}d(Oe,"createIdeTextResults");function ee(t){if(t===null||typeof t!="object")return[];let n="outputNotice"in t&&typeof t.outputNotice=="string"?[t.outputNotice]:[];if("resources"in t&&Array.isArray(t.resources)){let l=t.resources;for(let s of l)s!==null&&typeof s=="object"&&"details"in s&&n.push(...ee(s.details))}return n}d(ee,"outputNotices");function ye(t,n){let l=d(u=>{if(Array.isArray(u))return u.map(l);if(typeof u!="string")return u;let g=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid>/u.exec(u)?.[1];return g?`RESULT#${g}`:u},"label"),s={...n};for(let u of Q[t]??[])Object.assign(s,{[u]:l(n[u])});return s}d(ye,"displaySources");function te(t){if(t===null||typeof t!="object"||!("data"in t))return[];let n=t.data;return n===null||typeof n!="object"?[]:"resources"in n&&Array.isArray(n.resources)?n.resources.flatMap(s=>te({data:s})):"files"in n&&Array.isArray(n.files)?n.files.flatMap(s=>s!==null&&typeof s=="object"&&"source"in s&&typeof s.source=="string"&&/^(?:shell|debug):/u.test(s.source)?[s.source]:[]):"source"in n&&typeof n.source=="string"?[n.source]:[]}d(te,"resultResources");export{Oe as a};