pi-agent-ide 0.8.0 → 0.8.1

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 (377) hide show
  1. package/CHANGELOG.md +26 -40
  2. package/README.md +12 -7
  3. package/dist/{chunk-MOJ5RR35.js → chunk-246NTPOS.js} +1 -1
  4. package/dist/{chunk-NULNW6GK.js → chunk-2ITKAXHO.js} +1 -1
  5. package/dist/{chunk-SBNR4WZF.js → chunk-3WO2NOEQ.js} +1 -1
  6. package/dist/{chunk-N7LMRL64.js → chunk-47SPPIXK.js} +1 -1
  7. package/dist/{chunk-EY65TFHJ.js → chunk-4HWKBCBH.js} +1 -1
  8. package/dist/{chunk-JMVDFOTQ.js → chunk-57F5GTHO.js} +1 -1
  9. package/dist/{chunk-KL776TGR.js → chunk-7LOVUWNI.js} +1 -1
  10. package/dist/{chunk-7JV4VN73.js → chunk-A64JRDZK.js} +1 -1
  11. package/dist/{chunk-Z3PGADVA.js → chunk-AIT3YWR5.js} +1 -1
  12. package/dist/{chunk-E4HPRLRB.js → chunk-AKNHSDGV.js} +1 -1
  13. package/dist/{chunk-4XPUN4QN.js → chunk-AUL5FGGK.js} +1 -1
  14. package/dist/chunk-BB4A5UI3.js +5 -0
  15. package/dist/{chunk-CTJV77FR.js → chunk-BQAKA3FU.js} +1 -1
  16. package/dist/{chunk-PNP2KNGP.js → chunk-BR7GRH4A.js} +1 -1
  17. package/dist/{chunk-4OYVLXWD.js → chunk-D4IA2MTA.js} +1 -1
  18. package/dist/{chunk-R5XJSEOE.js → chunk-DXONCYWF.js} +3 -3
  19. package/dist/{chunk-TWWND6NI.js → chunk-E2PHA4SQ.js} +1 -1
  20. package/dist/{chunk-MZXX353D.js → chunk-EMRJP6EM.js} +1 -1
  21. package/dist/{chunk-7HDK3NRQ.js → chunk-GEMDU6XW.js} +1 -1
  22. package/dist/chunk-GNACBJM3.js +1 -0
  23. package/dist/{chunk-3G54ZL2L.js → chunk-HCK7OIQ3.js} +1 -1
  24. package/dist/chunk-HFJGCYFO.js +11 -0
  25. package/dist/{chunk-CSXHCSTH.js → chunk-ID4RJIVZ.js} +1 -1
  26. package/dist/{chunk-SBLKPTL3.js → chunk-JKMXND6V.js} +1 -1
  27. package/dist/{chunk-WE42GBGU.js → chunk-LAJQSHEI.js} +1 -1
  28. package/dist/{chunk-HCN5W76B.js → chunk-LLRUJD62.js} +1 -1
  29. package/dist/{chunk-2K65BSXS.js → chunk-M4TVRCMZ.js} +1 -1
  30. package/dist/{chunk-IUSLSROY.js → chunk-N56WAVYA.js} +1 -1
  31. package/dist/chunk-OI3HBIPK.js +2 -0
  32. package/dist/{chunk-GW6NZQTQ.js → chunk-PRLIHLCS.js} +1 -1
  33. package/dist/{chunk-7TJ6DWW3.js → chunk-Q5X6OXNS.js} +1 -1
  34. package/dist/{chunk-75SWXD2Z.js → chunk-SWA5B5B2.js} +1 -1
  35. package/dist/chunk-T7MWQQIF.js +3 -0
  36. package/dist/{chunk-ICDI27GZ.js → chunk-TGC2ZACO.js} +1 -1
  37. package/dist/{chunk-7NS3QUIE.js → chunk-TXG2H7YQ.js} +1 -1
  38. package/dist/{chunk-RAZP42IQ.js → chunk-VAXLSPPU.js} +1 -1
  39. package/dist/chunk-VMGZMXEM.js +10 -0
  40. package/dist/{chunk-CPZJPGLG.js → chunk-VNTY7BKC.js} +1 -1
  41. package/dist/chunk-W3YFF6OO.js +1 -0
  42. package/dist/{chunk-OLI3JPHJ.js → chunk-W7M3V7FR.js} +1 -1
  43. package/dist/{chunk-UUJJRXHG.js → chunk-WMHSVEIT.js} +1 -1
  44. package/dist/{chunk-OJX3RJ5A.js → chunk-WPBQ45ZL.js} +1 -1
  45. package/dist/{chunk-XZDOVPRC.js → chunk-WXGTU2M6.js} +1 -1
  46. package/dist/{chunk-3ZGDMTMD.js → chunk-XSIKDVAR.js} +1 -1
  47. package/dist/{chunk-QP2QSQ4U.js → chunk-YHREORHH.js} +1 -1
  48. package/dist/chunk-YTYLS2UM.js +1 -0
  49. package/dist/chunk-Z2QGNTGQ.js +1 -0
  50. package/dist/{chunk-UBH6X3D3.js → chunk-ZV5ETNLQ.js} +1 -1
  51. package/dist/entry-11.js +1 -1
  52. package/dist/entry-13.js +1 -1
  53. package/dist/entry-14.js +1 -1
  54. package/dist/entry-15.js +1 -1
  55. package/dist/entry-16.js +1 -1
  56. package/dist/entry-17.js +1 -1
  57. package/dist/entry-18.js +1 -0
  58. package/dist/entry-20.js +1 -1
  59. package/dist/entry-21.js +1 -1
  60. package/dist/entry-22.js +1 -1
  61. package/dist/entry-23.js +1 -1
  62. package/dist/entry-24.js +1 -1
  63. package/dist/entry-25.js +1 -1
  64. package/dist/entry-26.js +1 -2
  65. package/dist/entry-27.js +2 -1
  66. package/dist/entry-28.js +1 -4
  67. package/dist/entry-29.js +4 -1
  68. package/dist/entry-30.js +1 -1
  69. package/dist/entry-31.js +1 -1
  70. package/dist/entry-32.js +1 -18
  71. package/dist/entry-33.js +18 -1
  72. package/dist/entry-34.js +1 -1
  73. package/dist/entry-35.js +1 -1
  74. package/dist/entry-36.js +1 -1
  75. package/dist/entry-37.js +1 -1
  76. package/dist/entry-38.js +1 -1
  77. package/dist/entry-39.js +1 -1
  78. package/dist/entry-40.js +1 -1
  79. package/dist/entry-41.js +1 -1
  80. package/dist/entry-42.js +1 -1
  81. package/dist/entry-43.js +1 -1
  82. package/dist/entry-44.js +1 -1
  83. package/dist/entry-45.js +1 -1
  84. package/dist/entry-46.js +1 -25
  85. package/dist/entry-47.js +25 -1
  86. package/dist/entry-48.js +1 -1
  87. package/dist/entry-49.js +1 -1
  88. package/dist/entry-50.js +1 -1
  89. package/dist/entry-51.js +1 -3
  90. package/dist/entry-52.js +3 -13
  91. package/dist/entry-53.js +13 -1
  92. package/dist/entry-54.js +1 -1
  93. package/dist/entry-55.js +1 -1
  94. package/dist/entry-56.js +1 -1
  95. package/dist/entry-57.js +1 -1
  96. package/dist/entry-58.js +1 -1
  97. package/dist/entry-59.js +1 -1
  98. package/dist/entry-6.js +1 -1
  99. package/dist/entry-60.js +1 -1
  100. package/dist/entry-61.js +1 -1
  101. package/dist/entry-62.js +1 -0
  102. package/dist/entry-63.js +0 -1
  103. package/dist/entry-64.js +1 -0
  104. package/dist/entry-65.js +0 -1
  105. package/dist/entry-66.js +1 -1
  106. package/dist/entry-67.js +1 -1
  107. package/dist/entry-68.js +1 -1
  108. package/dist/entry-69.js +1 -1
  109. package/dist/entry-7.js +1 -1
  110. package/dist/entry-70.js +1 -1
  111. package/dist/entry-71.js +1 -1
  112. package/dist/entry-72.js +1 -0
  113. package/dist/entry-73.js +0 -1
  114. package/dist/entry-74.js +1 -0
  115. package/dist/entry-75.js +0 -1
  116. package/dist/entry-76.js +1 -1
  117. package/dist/entry-77.js +1 -1
  118. package/dist/entry-78.js +1 -80
  119. package/dist/entry-79.js +76 -17
  120. package/dist/entry-80.js +22 -2
  121. package/dist/entry-81.js +2 -1
  122. package/dist/entry-82.js +1 -1
  123. package/dist/entry-83.js +1 -1
  124. package/dist/entry-84.js +1 -3
  125. package/dist/entry-85.js +3 -1
  126. package/dist/entry-86.js +1 -1
  127. package/dist/entry-87.js +1 -1
  128. package/dist/entry-88.js +1 -0
  129. package/dist/pi-agent-ide.js +53 -24
  130. package/docs/agent-guides/search-code.md +3 -1
  131. package/docs/agent-guides/ssh.md +1 -1
  132. package/docs/configuration.md +18 -6
  133. package/docs/development.md +1 -13
  134. package/docs/extensions.md +1 -1
  135. package/docs/releases.md +1 -1
  136. package/docs/settings-help.md +39 -0
  137. package/docs/tools.md +1 -0
  138. package/docs/user-hooks.md +3 -1
  139. package/node_modules/pi-agent-doctor/package.json +7 -10
  140. package/node_modules/pi-agent-documentation/package.json +2 -2
  141. package/node_modules/pi-agent-documentation/runtime/entry-26.js +1 -0
  142. package/node_modules/pi-agent-filesystem/package.json +8 -8
  143. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  144. package/node_modules/pi-agent-filesystem-jq/package.json +6 -7
  145. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  146. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  147. package/node_modules/pi-agent-filesystem-text/runtime/entry-31.js +2 -0
  148. package/node_modules/pi-agent-ide-ast/package.json +15 -41
  149. package/node_modules/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  150. package/node_modules/pi-agent-ide-ast/runtime/entry-33.js +2 -0
  151. package/node_modules/pi-agent-ide-changes/package.json +10 -11
  152. package/node_modules/pi-agent-ide-changes/runtime/entry-34.js +0 -1
  153. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  154. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  155. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  156. package/node_modules/pi-agent-ide-lsp/package.json +10 -13
  157. package/node_modules/pi-agent-ide-lsp/runtime/entry-39.js +2 -0
  158. package/node_modules/pi-agent-image/package.json +3 -3
  159. package/node_modules/pi-agent-invariant/package.json +2 -2
  160. package/node_modules/pi-agent-pdf/package.json +3 -4
  161. package/node_modules/pi-agent-read/package.json +12 -12
  162. package/node_modules/pi-agent-read/runtime/entry-46.js +0 -1
  163. package/node_modules/pi-agent-read/runtime/entry-47.js +2 -0
  164. package/node_modules/pi-agent-resource/package.json +2 -2
  165. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -0
  166. package/node_modules/pi-agent-search/package.json +9 -9
  167. package/node_modules/pi-agent-search/runtime/entry-51.js +0 -1
  168. package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  169. package/node_modules/pi-agent-search/src/api/presentation.ts +10 -2
  170. package/node_modules/pi-agent-search/src/api/search-parameters.ts +1 -1
  171. package/node_modules/pi-agent-search/src/api/search.ts +7 -0
  172. package/node_modules/pi-agent-search/src/core/search-core.ts +23 -3
  173. package/node_modules/pi-agent-search-text/index.ts +2 -0
  174. package/node_modules/pi-agent-search-text/package.json +14 -14
  175. package/node_modules/pi-agent-search-text/runtime/entry-53.js +1 -0
  176. package/node_modules/pi-agent-search-text/src/search-backend.ts +18 -10
  177. package/node_modules/pi-agent-search-text/src/search-session.ts +68 -9
  178. package/node_modules/pi-agent-text/package.json +3 -3
  179. package/node_modules/pi-agent-text/runtime/entry-57.js +1 -0
  180. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  181. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-58.js +2 -0
  182. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -6
  183. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -1
  184. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-60.js +2 -0
  185. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  186. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-61.js +0 -1
  187. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-62.js +2 -0
  188. package/node_modules/pi-agent-text-editor/package.json +26 -34
  189. package/node_modules/pi-agent-text-editor/runtime/entry-78.js +0 -1
  190. package/node_modules/pi-agent-text-editor/src/api/delete-guard.ts +1 -1
  191. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  192. package/node_modules/pi-agent-text-editor/src/core/delete-policy.ts +6 -12
  193. package/node_modules/pi-agent-text-editor/src/core/extension.ts +1 -0
  194. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +49 -21
  195. package/node_modules/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  196. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +2 -2
  197. package/node_modules/pi-agent-text-editor/src/core/temporary-directories.ts +13 -9
  198. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  199. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +118 -36
  200. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  201. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +6 -8
  202. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  203. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -8
  204. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +22 -0
  205. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  206. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +2 -0
  207. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  208. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  209. package/node_modules/pi-agent-tool-ui/runtime/entry-83.js +1 -0
  210. package/node_modules/pi-agent-web/package.json +8 -11
  211. package/node_modules/pi-agent-web-html/package.json +3 -5
  212. package/node_modules/pi-agent-web-image/package.json +4 -4
  213. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  214. package/node_modules/pi-agent-web-text/package.json +4 -4
  215. package/node_modules/pi-agent-web-text/runtime/entry-88.js +2 -0
  216. package/package.json +43 -39
  217. package/skills/configure-agent-ide/SKILL.md +38 -0
  218. package/src/api/content.ts +6 -0
  219. package/src/api/tips.ts +3 -0
  220. package/src/composite/nested-tool-rendering.ts +16 -5
  221. package/src/composite/preferences.ts +13 -0
  222. package/src/composite/settings-documentation.ts +59 -0
  223. package/src/composite/settings-help.ts +106 -0
  224. package/src/composite/text-results.ts +50 -22
  225. package/src/documentation/extension.ts +12 -0
  226. package/src/documentation/search.ts +166 -0
  227. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  228. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  229. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -7
  230. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  231. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  232. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-31.js +2 -0
  233. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-27.js +2 -0
  234. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -11
  235. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -5
  236. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  237. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  238. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  239. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-88.js +2 -0
  240. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-84.js +2 -0
  241. package/src/extensions/pi-agent-read/package.json +12 -12
  242. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  243. package/src/extensions/pi-agent-read/runtime/entry-47.js +2 -0
  244. package/src/extensions/pi-agent-search/package.json +9 -9
  245. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +2 -0
  246. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -14
  247. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +1 -0
  248. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +1 -0
  249. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +18 -10
  250. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +68 -9
  251. package/src/extensions/pi-agent-search/runtime/entry-51.js +0 -1
  252. package/src/extensions/pi-agent-search/runtime/entry-52.js +2 -0
  253. package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  254. package/src/extensions/pi-agent-search/src/api/presentation.ts +10 -2
  255. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +1 -1
  256. package/src/extensions/pi-agent-search/src/api/search.ts +7 -0
  257. package/src/extensions/pi-agent-search/src/core/search-core.ts +23 -3
  258. package/src/extensions/pi-agent-text-editor/package.json +26 -34
  259. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  260. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-58.js +2 -0
  261. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -6
  262. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -1
  263. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-60.js +2 -0
  264. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  265. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-61.js +0 -1
  266. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-62.js +2 -0
  267. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -8
  268. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +22 -0
  269. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  270. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +2 -0
  271. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +0 -1
  272. package/src/extensions/pi-agent-text-editor/runtime/entry-79.js +2 -0
  273. package/src/extensions/pi-agent-text-editor/src/api/delete-guard.ts +1 -1
  274. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  275. package/src/extensions/pi-agent-text-editor/src/core/delete-policy.ts +6 -12
  276. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +1 -0
  277. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +49 -21
  278. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  279. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +2 -2
  280. package/src/extensions/pi-agent-text-editor/src/core/temporary-directories.ts +13 -9
  281. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  282. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +118 -36
  283. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  284. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +6 -8
  285. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  286. package/src/pi-agent-ide.ts +14 -2
  287. package/src/plugins/pi-agent-ide-ast/package.json +15 -41
  288. package/src/plugins/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  289. package/src/plugins/pi-agent-ide-ast/runtime/entry-33.js +2 -0
  290. package/src/plugins/pi-agent-ide-changes/package.json +10 -11
  291. package/src/plugins/pi-agent-ide-changes/runtime/entry-34.js +0 -1
  292. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  293. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  294. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  295. package/src/plugins/pi-agent-ide-lsp/package.json +10 -13
  296. package/src/plugins/pi-agent-ide-lsp/runtime/entry-39.js +2 -0
  297. package/src/tips/core.ts +5 -2
  298. package/src/tips/extension.ts +30 -2
  299. package/src/tips/persistence.ts +29 -27
  300. package/src/tips/setup-hint.ts +19 -0
  301. package/dist/chunk-5KFVDYCI.js +0 -1
  302. package/dist/chunk-ABFCAOU5.js +0 -1
  303. package/dist/chunk-BIG45IPN.js +0 -2
  304. package/dist/chunk-BMOJTJJJ.js +0 -3
  305. package/dist/chunk-BQ67M4NC.js +0 -3
  306. package/dist/chunk-IH5NW5JX.js +0 -11
  307. package/dist/chunk-NRZO5KJT.js +0 -9
  308. package/dist/chunk-O36UC74T.js +0 -1
  309. package/dist/chunk-SSWUUBIR.js +0 -1
  310. package/dist/entry-19.js +0 -1
  311. package/docs/research/apply-native-capability-matrix.md +0 -174
  312. package/docs/research/apply-read-latency.md +0 -221
  313. package/docs/research/codemode-write-context.md +0 -56
  314. package/docs/research/lpt-393-fuzzy-results/file.json +0 -152
  315. package/docs/research/lpt-393-fuzzy-results/repo.json +0 -122
  316. package/docs/research/lpt-393-search-fuzzy-fallback.md +0 -97
  317. package/docs/research/native-codemode-batch-decision.md +0 -31
  318. package/docs/research/native-codemode-batching.md +0 -65
  319. package/node_modules/pi-agent-doctor/runtime/entry-19.js +0 -1
  320. package/node_modules/pi-agent-filesystem/runtime/entry-26.js +0 -2
  321. package/node_modules/pi-agent-ide-ast/runtime/entry-31.js +0 -1
  322. package/node_modules/pi-agent-ide-changes/runtime/entry-33.js +0 -1
  323. package/node_modules/pi-agent-image/runtime/entry-39.js +0 -1
  324. package/node_modules/pi-agent-resource/runtime/entry-47.js +0 -1
  325. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-57.js +0 -2
  326. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-58.js +0 -1
  327. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
  328. package/node_modules/pi-agent-text-editor/runtime/entry-62.js +0 -1
  329. package/node_modules/pi-agent-tool-call-interception/runtime/entry-81.js +0 -1
  330. package/node_modules/pi-agent-web/runtime/entry-83.js +0 -2
  331. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-27.js +0 -2
  332. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-26.js +0 -2
  333. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-84.js +0 -2
  334. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +0 -2
  335. package/src/extensions/pi-agent-read/runtime/entry-42.js +0 -1
  336. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-52.js +0 -2
  337. package/src/extensions/pi-agent-search/runtime/entry-48.js +0 -1
  338. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-57.js +0 -2
  339. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-58.js +0 -1
  340. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
  341. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-79.js +0 -2
  342. package/src/extensions/pi-agent-text-editor/runtime/entry-62.js +0 -1
  343. package/src/plugins/pi-agent-ide-ast/runtime/entry-31.js +0 -1
  344. package/src/plugins/pi-agent-ide-changes/runtime/entry-33.js +0 -1
  345. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-25.js +0 -0
  346. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-27.js +0 -0
  347. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-28.js +0 -0
  348. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-jq}/runtime/entry-29.js +0 -0
  349. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-30.js +0 -0
  350. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-35.js +0 -0
  351. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-36.js +0 -0
  352. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-37.js +0 -0
  353. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-38.js +0 -0
  354. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-40.js +0 -0
  355. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-41.js +0 -0
  356. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-42.js +0 -0
  357. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-48.js +0 -0
  358. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-52.js +0 -0
  359. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-56.js +0 -0
  360. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-79.js +0 -0
  361. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-80.js +0 -0
  362. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-82.js +0 -0
  363. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-84.js +0 -0
  364. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-85.js +0 -0
  365. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-86.js +0 -0
  366. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-87.js +0 -0
  367. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-28.js +0 -0
  368. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-jq}/runtime/entry-29.js +0 -0
  369. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-30.js +0 -0
  370. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-85.js +0 -0
  371. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-86.js +0 -0
  372. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-87.js +0 -0
  373. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-80.js +0 -0
  374. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-35.js +0 -0
  375. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-36.js +0 -0
  376. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-37.js +0 -0
  377. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-38.js +0 -0
@@ -1,3 +1,3 @@
1
- import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Se}from"node:async_hooks";function ie(){return{pending:new Set,active:new Se}}i(ie,"createSchedulerState");function be(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(be,"conflicts");function Ee(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Ee,"coveredAccess");async function xe(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(xe,"waitForDependencies");var U=class r{constructor(e=ie()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(S=>{if(n?.throwIfAborted(),!Ee(a.accesses,S,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return S});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(m=>{p=m}),h={accesses:c,done:l};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await xe(s.then(async S=>(await Promise.all(d.map(F=>Promise.race([F.done,F.accesses.then(Te=>be(S,Te)?F.done:void 0)]))),S)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Ae=Symbol.for("pi-agent-resource.resource-scheduler-state"),Oe=globalThis,ke=Oe[Ae]??=ie(),Ne=new U(ke);import{realpath as Pe,stat as je}from"node:fs/promises";import P from"node:path";import{fileURLToPath as Ie}from"node:url";async function ae(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=P.resolve(e,r.startsWith("file:")?Ie(r):r),[o,s]=await Promise.allSettled([Pe(n),je(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let h=P.dirname(n);if(h===n)a=n;else{let y=(await ae(h,e,t)).find(S=>S.resource.startsWith("file:"));a=P.join(y?.resource.slice(5)??h,P.basename(n))}}let d=a.split(P.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(ae,"resourceAccesses");import{randomUUID as _e}from"node:crypto";import{mkdir as Ue,mkdtemp as $e,readFile as Le,rm as De,writeFile as He}from"node:fs/promises";import{tmpdir as We}from"node:os";import ce from"node:path";var K=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#o=new Set;#n;#t;#r;constructor(e={}){this.#n=e.parentDirectory??We(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#r!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#o.add(n);try{return await n}finally{this.#o.delete(n)}}dispose(){return this.#r??=this.#a(),this.#r}async#i(e,t){let n=await this.#d(),o=_e(),s=`temp:${o}`,a=ce.join(n,`${o}.txt`);return await He(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#o),this.#e.clear(),this.#t!==void 0&&await De(await this.#t,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#r!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#r!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await Le(t,"utf8")}]}async#d(){return this.#t??=(async()=>(await Ue(this.#n,{recursive:!0}),$e(ce.join(this.#n,"pi-agent-read-"))))(),this.#t}};import{Type as g}from"typebox";import{Value as Ve}from"typebox/value";var $=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ue(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array($,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array($,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array($)},required:["status","errors"],additionalProperties:!1}}i(ue,"structuredResultSchema");var de=1024*1024;function q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>de)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function le(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(le,"resultError");function Me(r,e,t){try{if(q(t),!Ve.Check(ue(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=le(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Me,"withStructuredResult");var J=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError"}static{i(this,"ResourceError")}};function ze(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
- `)}i(ze,"renderContentDescription");import{Type as f}from"typebox";import{Value as Qe}from"typebox/value";import{Type as u}from"typebox";import{Value as Be}from"typebox/value";var C={additionalProperties:!0},j=u.Function([],u.Unknown()),v=u.String({minLength:1}),Fe=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},C),Ke=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},C),qe=u.Object({type:u.Literal("custom"),kind:v,data:u.Unknown()},C),Je=u.Array(u.Union([Fe,Ke,qe]),{minItems:1}),fe=u.Union([u.Object({source:v,link:u.Optional(v),read:j,write:u.Optional(u.Never())},C),u.Object({source:v,link:u.Optional(v),read:u.Optional(u.Never()),write:j},C),u.Object({source:v,link:u.Optional(v),read:j,write:j},C)]),Ye=u.Object({id:v,tryResolve:j},C),Ge=u.Union([u.Object({kind:u.Literal("not-handled")},C),u.Object({kind:u.Literal("resolved"),resource:fe},C),u.Object({kind:u.Literal("failed"),error:u.Unknown()},C)]);function Y(r){return L(Je,r)?D(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(Y,"isAgentContent");function pe(r){return L(fe,r)?D(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(pe,"isResource");function Xe(r){return L(Ye,r)}i(Xe,"isResourceResolver");function Ze(r){return L(Ge,r)?D(()=>{let e=r;return e.kind!=="resolved"||pe(e.resource)}):!1}i(Ze,"isResourceResolutionAttempt");function L(r,e){return D(()=>Be.Check(r,e))}i(L,"safeCheck");function D(r){try{return r()}catch{return!1}}i(D,"safeEvaluate");var R={additionalProperties:!0},et=f.Function([],f.Unknown()),H=f.String({minLength:1}),tt=f.Object({provider:H,capability:f.Union([f.Literal("read"),f.Literal("write")])},R),rt=f.Object({source:H,bytes:f.Unknown(),mediaType:f.Optional(f.String())},R),nt=f.Object({signal:f.Optional(f.Unknown())},R),ot=f.Object({id:H,description:H,tryConvert:et},R),st=f.Union([f.Object({kind:f.Literal("not-handled")},R),f.Object({kind:f.Literal("converted"),content:f.Unknown()},R),f.Object({kind:f.Literal("failed"),error:f.Unknown()},R)]),it=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},R);function O(r){return k(tt,r)&&E(()=>r.provider.trim().length>0)}i(O,"isContentTarget");function G(r){return k(rt,r)?E(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(G,"isContentInput");function X(r){return k(nt,r)?E(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(X,"isContentConversionContext");function ge(r){return k(ot,r)?E(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(ge,"isContentConverter");function Z(r){return k(st,r)?E(()=>{let e=r;return e.kind!=="converted"||Y(e.content)}):!1}i(Z,"isContentConversionAttempt");function b(r){return k(it,r)?E(()=>{let e=r;return O(e.target)&&ge(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(b,"isContentConverterRegistration");function k(r,e){return E(()=>Qe.Check(r,e))}i(k,"safeCheck");function E(r){try{return r()}catch{return!1}}i(E,"safeEvaluate");var W=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function ee(r){if(!O(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!b(o))throw new TypeError("Invalid content converter registration");if(!x(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!G(o))throw new TypeError("Invalid content input");if(!X(s))throw new TypeError("Invalid content conversion context");Q(s.signal);let a=n();for(let{converter:d}of a){Q(s.signal);let c=await d.tryConvert(o,s);if(Q(s.signal),!Z(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new W(o.source,e)}}}i(ee,"createContentRunner");function x(r,e){return r.provider===e.provider&&r.capability===e.capability}i(x,"targetsEqual");function Q(r){r?.throwIfAborted()}i(Q,"throwIfAborted");import{Type as w}from"typebox";import{Value as at}from"typebox/value";var N="pi-agent-resource/content-conversion",V=2,I=`${N}/host/ready`,_=`${N}/converter/register`,he={additionalProperties:!0},ct=w.Function([],w.Unknown()),ut=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(V),target:w.Unknown()},he),dt=w.Object({registration:w.Unknown(),accept:ct},he);function te(r){return me(ut,r)&&ne(()=>O(r.target))}i(te,"isContentHostReady");function re(r){return me(dt,r)&&ne(()=>b(r.registration))}i(re,"isContentConverterRegistrationRequest");function me(r,e){return ne(()=>at.Check(r,e))}i(me,"safeCheck");function ne(r){try{return r()}catch{return!1}}i(ne,"safeEvaluate");var ye="pi-agent-resource:content-host-lookup";function lt(r,e){let t;if(r.events.emit(ye,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return Ce(r,t),t.host;let n=ee(e),o=r.events.on(_,c=>{if(!re(c))throw new Error("Invalid content converter registration request");if(!x(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(ye,c=>{if(!ft(c))throw new Error("Invalid content host lookup request");x(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return Ce(r,d),r.events.emit(I,{protocol:N,apiVersion:V,target:n.target}),s}i(lt,"createContentHost");function ft(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(ft,"isHostLookup");function Ce(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(Ce,"retainOwner");function pt(r,e){if(!b(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!te(s))throw new Error("Invalid content conversion host readiness event");if(!x(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(pt,"connectContentConverter");import{createHash as ve,randomUUID as oe}from"node:crypto";import{statSync as gt}from"node:fs";import{readFile as ht}from"node:fs/promises";import T from"node:path";import{fileURLToPath as mt}from"node:url";import{Type as M}from"typebox";var yt=M.Union([M.String(),M.Array(M.String())]),A="RESULT#",Re="pi-agent-resource:result-targets",B=class{static{i(this,"ResultTargetStore")}#e=new Map;#o=new Map;#n=new Map;#t=new Map;clear(){this.#e.clear(),this.#o.clear(),this.#n.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${A}${oe()}`;return this.#e.set(o,{state:"ready",targets:se(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${A}${oe()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:se(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:se(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await we(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}publish(e,t,n,o=[]){let s=oe();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
- ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let h of l){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#o.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ve("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#o.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(A)?e.slice(A.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#t.get(a);if(!c&&!s&&e.startsWith(A)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ve("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#t.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#t.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>z(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>z(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=z(e,t),o=JSON.stringify([T.resolve(t),n]),s=Ct(e,t),a=this.#n.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#n.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#n.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(A))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(A))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function z(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return mt(t)}catch{}return T.resolve(e,t)}i(z,"sourcePath");function Ct(r,e){try{let t=gt(z(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(Ct,"fileStamp");async function we(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await ht(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(we,"verifyResultTargets");function se(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(se,"combineTargets");function vt(r){let e;if(r.events.emit(Re,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new B,n=r.events.on(Re,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(vt,"connectResultTargets");export{U as a,Ne as b,ae as c,K as d,$ as e,ue as f,de as g,q as h,le as i,Me as j,J as k,ze as l,Y as m,pe as n,Xe as o,Ze as p,O as q,G as r,X as s,ge as t,Z as u,b as v,W as w,ee as x,x as y,N as z,V as A,I as B,_ as C,te as D,re as E,lt as F,pt as G,yt as H,B as I,we as J,vt as K};
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Se}from"node:async_hooks";function ie(){return{pending:new Set,active:new Se}}i(ie,"createSchedulerState");function be(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(be,"conflicts");function Ee(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Ee,"coveredAccess");async function xe(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(xe,"waitForDependencies");var $=class r{constructor(e=ie()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(S=>{if(n?.throwIfAborted(),!Ee(a.accesses,S,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return S});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(m=>{p=m}),h={accesses:c,done:l};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await xe(s.then(async S=>(await Promise.all(d.map(B=>Promise.race([B.done,B.accesses.then(Te=>be(S,Te)?B.done:void 0)]))),S)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Ae=Symbol.for("pi-agent-resource.resource-scheduler-state"),Oe=globalThis,ke=Oe[Ae]??=ie(),Ne=new $(ke);import{realpath as Pe,stat as je}from"node:fs/promises";import P from"node:path";import{fileURLToPath as Ie}from"node:url";async function ae(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=P.resolve(e,r.startsWith("file:")?Ie(r):r),[o,s]=await Promise.allSettled([Pe(n),je(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let h=P.dirname(n);if(h===n)a=n;else{let y=(await ae(h,e,t)).find(S=>S.resource.startsWith("file:"));a=P.join(y?.resource.slice(5)??h,P.basename(n))}}let d=a.split(P.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(ae,"resourceAccesses");import{randomUUID as _e}from"node:crypto";import{mkdir as $e,mkdtemp as Ue,readFile as Le,rm as De,writeFile as He}from"node:fs/promises";import{tmpdir as We}from"node:os";import ce from"node:path";var K=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#n=new Set;#o;#t;#r;constructor(e={}){this.#o=e.parentDirectory??We(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#r!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#n.add(n);try{return await n}finally{this.#n.delete(n)}}dispose(){return this.#r??=this.#a(),this.#r}async#i(e,t){let n=await this.#d(),o=_e(),s=`temp:${o}`,a=ce.join(n,`${o}.txt`);return await He(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#n),this.#e.clear(),this.#t!==void 0&&await De(await this.#t,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#r!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#r!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await Le(t,"utf8")}]}async#d(){return this.#t??=(async()=>(await $e(this.#o,{recursive:!0}),Ue(ce.join(this.#o,"pi-agent-read-"))))(),this.#t}};import{Type as g}from"typebox";import{Value as Ve}from"typebox/value";var U=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ue(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(U,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U)},required:["status","errors"],additionalProperties:!1}}i(ue,"structuredResultSchema");var de=1024*1024;function q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>de)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function le(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(le,"resultError");function Me(r,e,t){try{if(q(t),!Ve.Check(ue(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=le(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Me,"withStructuredResult");var J=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError"}static{i(this,"ResourceError")}};function Fe(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(Fe,"renderContentDescription");import{Type as f}from"typebox";import{Value as Qe}from"typebox/value";import{Type as u}from"typebox";import{Value as ze}from"typebox/value";var C={additionalProperties:!0},j=u.Function([],u.Unknown()),v=u.String({minLength:1}),Be=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},C),Ke=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},C),qe=u.Object({type:u.Literal("custom"),kind:v,data:u.Unknown()},C),Je=u.Array(u.Union([Be,Ke,qe]),{minItems:1}),fe=u.Union([u.Object({source:v,link:u.Optional(v),read:j,write:u.Optional(u.Never())},C),u.Object({source:v,link:u.Optional(v),read:u.Optional(u.Never()),write:j},C),u.Object({source:v,link:u.Optional(v),read:j,write:j},C)]),Ye=u.Object({id:v,tryResolve:j},C),Ge=u.Union([u.Object({kind:u.Literal("not-handled")},C),u.Object({kind:u.Literal("resolved"),resource:fe},C),u.Object({kind:u.Literal("failed"),error:u.Unknown()},C)]);function Y(r){return L(Je,r)?D(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(Y,"isAgentContent");function pe(r){return L(fe,r)?D(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(pe,"isResource");function Xe(r){return L(Ye,r)}i(Xe,"isResourceResolver");function Ze(r){return L(Ge,r)?D(()=>{let e=r;return e.kind!=="resolved"||pe(e.resource)}):!1}i(Ze,"isResourceResolutionAttempt");function L(r,e){return D(()=>ze.Check(r,e))}i(L,"safeCheck");function D(r){try{return r()}catch{return!1}}i(D,"safeEvaluate");var R={additionalProperties:!0},et=f.Function([],f.Unknown()),H=f.String({minLength:1}),tt=f.Object({provider:H,capability:f.Union([f.Literal("read"),f.Literal("write")])},R),rt=f.Object({source:H,bytes:f.Unknown(),mediaType:f.Optional(f.String())},R),nt=f.Object({signal:f.Optional(f.Unknown())},R),ot=f.Object({id:H,description:H,tryConvert:et},R),st=f.Union([f.Object({kind:f.Literal("not-handled")},R),f.Object({kind:f.Literal("converted"),content:f.Unknown()},R),f.Object({kind:f.Literal("failed"),error:f.Unknown()},R)]),it=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},R);function O(r){return k(tt,r)&&E(()=>r.provider.trim().length>0)}i(O,"isContentTarget");function G(r){return k(rt,r)?E(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(G,"isContentInput");function X(r){return k(nt,r)?E(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(X,"isContentConversionContext");function ge(r){return k(ot,r)?E(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(ge,"isContentConverter");function Z(r){return k(st,r)?E(()=>{let e=r;return e.kind!=="converted"||Y(e.content)}):!1}i(Z,"isContentConversionAttempt");function b(r){return k(it,r)?E(()=>{let e=r;return O(e.target)&&ge(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(b,"isContentConverterRegistration");function k(r,e){return E(()=>Qe.Check(r,e))}i(k,"safeCheck");function E(r){try{return r()}catch{return!1}}i(E,"safeEvaluate");var W=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function ee(r){if(!O(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!b(o))throw new TypeError("Invalid content converter registration");if(!x(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!G(o))throw new TypeError("Invalid content input");if(!X(s))throw new TypeError("Invalid content conversion context");Q(s.signal);let a=n();for(let{converter:d}of a){Q(s.signal);let c=await d.tryConvert(o,s);if(Q(s.signal),!Z(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new W(o.source,e)}}}i(ee,"createContentRunner");function x(r,e){return r.provider===e.provider&&r.capability===e.capability}i(x,"targetsEqual");function Q(r){r?.throwIfAborted()}i(Q,"throwIfAborted");import{Type as w}from"typebox";import{Value as at}from"typebox/value";var N="pi-agent-resource/content-conversion",V=2,I=`${N}/host/ready`,_=`${N}/converter/register`,he={additionalProperties:!0},ct=w.Function([],w.Unknown()),ut=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(V),target:w.Unknown()},he),dt=w.Object({registration:w.Unknown(),accept:ct},he);function te(r){return me(ut,r)&&ne(()=>O(r.target))}i(te,"isContentHostReady");function re(r){return me(dt,r)&&ne(()=>b(r.registration))}i(re,"isContentConverterRegistrationRequest");function me(r,e){return ne(()=>at.Check(r,e))}i(me,"safeCheck");function ne(r){try{return r()}catch{return!1}}i(ne,"safeEvaluate");var ye="pi-agent-resource:content-host-lookup";function lt(r,e){let t;if(r.events.emit(ye,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return Ce(r,t),t.host;let n=ee(e),o=r.events.on(_,c=>{if(!re(c))throw new Error("Invalid content converter registration request");if(!x(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(ye,c=>{if(!ft(c))throw new Error("Invalid content host lookup request");x(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return Ce(r,d),r.events.emit(I,{protocol:N,apiVersion:V,target:n.target}),s}i(lt,"createContentHost");function ft(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(ft,"isHostLookup");function Ce(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(Ce,"retainOwner");function pt(r,e){if(!b(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!te(s))throw new Error("Invalid content conversion host readiness event");if(!x(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(pt,"connectContentConverter");import{createHash as ve,randomUUID as oe}from"node:crypto";import{statSync as gt}from"node:fs";import{readFile as ht}from"node:fs/promises";import T from"node:path";import{fileURLToPath as mt}from"node:url";import{Type as M}from"typebox";var yt=M.Union([M.String(),M.Array(M.String())]),A="RESULT#",Re="pi-agent-resource:result-targets",z=class{static{i(this,"ResultTargetStore")}#e=new Map;#n=new Map;#o=new Map;#t=new Map;clear(){this.#e.clear(),this.#n.clear(),this.#o.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${A}${oe()}`;return this.#e.set(o,{state:"ready",targets:se(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${A}${oe()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:se(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:se(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await we(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}registerSearchReference(e,t,n){if(!/^SEARCH#[A-F\d]{4,64}:[1-9]\d*:(line|match)$/u.test(e))throw new Error("Only numbered Search references can alias a snapshot.");if(!this.#e.has(t))throw new Error("A Search reference needs a registered result target.");this.resolve(t,n),this.#n.set(e,t)}publish(e,t,n,o=[]){let s=oe();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let h of l){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#n.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ve("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#n.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(A)?e.slice(A.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#t.get(a);if(!c&&!s&&e.startsWith(A)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ve("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#t.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#t.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>F(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>F(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=F(e,t),o=JSON.stringify([T.resolve(t),n]),s=Ct(e,t),a=this.#o.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#o.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#o.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(A))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(A))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function F(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return mt(t)}catch{}return T.resolve(e,t)}i(F,"sourcePath");function Ct(r,e){try{let t=gt(F(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(Ct,"fileStamp");async function we(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await ht(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(we,"verifyResultTargets");function se(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(se,"combineTargets");function vt(r){let e;if(r.events.emit(Re,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new z,n=r.events.on(Re,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(vt,"connectResultTargets");export{$ as a,Ne as b,ae as c,K as d,U as e,ue as f,de as g,q as h,le as i,Me as j,J as k,Fe as l,Y as m,pe as n,Xe as o,Ze as p,O as q,G as r,X as s,ge as t,Z as u,b as v,W as w,ee as x,x as y,N as z,V as A,I as B,_ as C,te as D,re as E,lt as F,pt as G,yt as H,z as I,we as J,vt as K};
@@ -1 +1 @@
1
- import{a as f,b as u}from"./chunk-SBLKPTL3.js";import{g as o}from"./chunk-EY65TFHJ.js";import{b as w}from"./chunk-VDP5CQHM.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as R}from"node:fs/promises";import{Type as i}from"typebox";import{Value as g}from"typebox/value";var y=i.Object({url:i.String(),status:i.Integer({minimum:200,maximum:599}),statusText:i.String(),headers:i.Array(i.Tuple([i.String(),i.String()])),body:i.String()}),b=new Set(["INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED"]),m;async function S(n,s,t,c){c?.throwIfAborted(),m??=R(new URL("./web-http-worker.py",new URL("../src/backend/web-http.ts",import.meta.url).href),"utf8");try{let e=await f(n,"python3",["-c",await m,JSON.stringify({url:s.href,timeoutSeconds:30})],t,{signal:c,timeoutMs:3e4,maxBytes:33554432});if(e.exitCode!==0)throw new o("HTTP_FAILED",t,"not-applied");let r;try{r=JSON.parse(e.stdout.toString("utf8"))}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}if(typeof r=="object"&&r!==null&&"error"in r)throw new o(typeof r.error=="string"&&b.has(r.error)?r.error:"INVALID_RESPONSE",t,"not-applied");if(!g.Check(y,r))throw new o("INVALID_RESPONSE",t,"not-applied");let h=Buffer.from(r.body,"base64");if(h.toString("base64")!==r.body||h.length>16*1024*1024)throw new o("INVALID_RESPONSE",t,"not-applied");let a;try{let p=new URL(r.url);if(!["http:","https:"].includes(p.protocol)||p.username||p.password)throw new Error("Invalid native HTTP redirect");a=new Response([204,205,304].includes(r.status)?null:h,{status:r.status,statusText:r.statusText,headers:r.headers}),Object.defineProperty(a,"url",{value:p.href})}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}return a}catch(e){throw e instanceof o?new o(e.code,t,e.effect):e}}d(S,"fetchSshWebResponse");function I(n){if(!/^web:/iu.test(n))return;let s=/^web:ssh:\/\/([a-z0-9._-]+)\/(https?:\/\/.+)$/iu.exec(n);if(!s?.[1]||!s[2])throw new o("INVALID_SOURCE",n,"not-applied");let t;try{t=new URL(s[2])}catch{throw new o("INVALID_SOURCE",n,"not-applied")}if(t.username||t.password)throw new o("INVALID_SOURCE",n,"not-applied");return{target:s[1],url:t,source:`web:ssh://${s[1]}/${t.href}`}}d(I,"parseSshWebSource");function D(n,s){return{id:"ssh-web",async tryResolve(t,c){try{let e=I(t);if(!e)return{kind:"not-handled"};c.signal?.throwIfAborted();let r=s.resolve(`ssh://${e.target}/`);if(!r)throw new o("UNSUPPORTED_SOURCE",e.source,"not-applied");let a=await w(n,{fetch:d(async(p,l)=>S(r.backend.target,e.url,e.source,l?.signal??void 0),"fetch"),browser:{load(p,l){return u(r.backend.target,p,e.source,l)}}}).tryResolve(e.url.href,c);return a.kind!=="resolved"?a:{kind:"resolved",resource:{...a.resource,source:e.source}}}catch(e){return{kind:"failed",error:e instanceof o?new o(e.code,t,e.effect):e}}}}}d(D,"createSshWebResolver");export{I as a,D as b};
1
+ import{a as f,b as u}from"./chunk-JKMXND6V.js";import{g as o}from"./chunk-4HWKBCBH.js";import{b as w}from"./chunk-VDP5CQHM.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as R}from"node:fs/promises";import{Type as i}from"typebox";import{Value as g}from"typebox/value";var y=i.Object({url:i.String(),status:i.Integer({minimum:200,maximum:599}),statusText:i.String(),headers:i.Array(i.Tuple([i.String(),i.String()])),body:i.String()}),b=new Set(["INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED"]),m;async function S(n,s,t,c){c?.throwIfAborted(),m??=R(new URL("./web-http-worker.py",new URL("../src/backend/web-http.ts",import.meta.url).href),"utf8");try{let e=await f(n,"python3",["-c",await m,JSON.stringify({url:s.href,timeoutSeconds:30})],t,{signal:c,timeoutMs:3e4,maxBytes:33554432});if(e.exitCode!==0)throw new o("HTTP_FAILED",t,"not-applied");let r;try{r=JSON.parse(e.stdout.toString("utf8"))}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}if(typeof r=="object"&&r!==null&&"error"in r)throw new o(typeof r.error=="string"&&b.has(r.error)?r.error:"INVALID_RESPONSE",t,"not-applied");if(!g.Check(y,r))throw new o("INVALID_RESPONSE",t,"not-applied");let h=Buffer.from(r.body,"base64");if(h.toString("base64")!==r.body||h.length>16*1024*1024)throw new o("INVALID_RESPONSE",t,"not-applied");let a;try{let p=new URL(r.url);if(!["http:","https:"].includes(p.protocol)||p.username||p.password)throw new Error("Invalid native HTTP redirect");a=new Response([204,205,304].includes(r.status)?null:h,{status:r.status,statusText:r.statusText,headers:r.headers}),Object.defineProperty(a,"url",{value:p.href})}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}return a}catch(e){throw e instanceof o?new o(e.code,t,e.effect):e}}d(S,"fetchSshWebResponse");function I(n){if(!/^web:/iu.test(n))return;let s=/^web:ssh:\/\/([a-z0-9._-]+)\/(https?:\/\/.+)$/iu.exec(n);if(!s?.[1]||!s[2])throw new o("INVALID_SOURCE",n,"not-applied");let t;try{t=new URL(s[2])}catch{throw new o("INVALID_SOURCE",n,"not-applied")}if(t.username||t.password)throw new o("INVALID_SOURCE",n,"not-applied");return{target:s[1],url:t,source:`web:ssh://${s[1]}/${t.href}`}}d(I,"parseSshWebSource");function D(n,s){return{id:"ssh-web",async tryResolve(t,c){try{let e=I(t);if(!e)return{kind:"not-handled"};c.signal?.throwIfAborted();let r=s.resolve(`ssh://${e.target}/`);if(!r)throw new o("UNSUPPORTED_SOURCE",e.source,"not-applied");let a=await w(n,{fetch:d(async(p,l)=>S(r.backend.target,e.url,e.source,l?.signal??void 0),"fetch"),browser:{load(p,l){return u(r.backend.target,p,e.source,l)}}}).tryResolve(e.url.href,c);return a.kind!=="resolved"?a:{kind:"resolved",resource:{...a.resource,source:e.source}}}catch(e){return{kind:"failed",error:e instanceof o?new o(e.code,t,e.effect):e}}}}}d(D,"createSshWebResolver");export{I as a,D as b};
@@ -1,2 +1,2 @@
1
- import{d as R}from"./chunk-4OYVLXWD.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as T}from"@earendil-works/pi-coding-agent";import{Text as $}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,C=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
1
+ import{d as R}from"./chunk-D4IA2MTA.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as T}from"@earendil-works/pi-coding-agent";import{Text as $}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,C=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
2
2
  `)),k.set(e.details,a)),e={...e,details:a}}if(r.isPartial||t.isError||!R(e.details)){let a=e.content[0],n=a?.type==="text"?a.text:"",i=t.isError?"error":r.isPartial?"dim":"toolOutput";return new $(o.fg(i,n),0,0)}let l=(t.lastComponent instanceof m?t.lastComponent:void 0)??new m(e.details,o,r.expanded);return l.updateSearch(e.details,o,r.expanded),l}c(v,"renderSearchResult");var m=class extends S{static{c(this,"SearchResultPanel")}constructor(r,o,t){super(z(r,t),o,t)}updateSearch(r,o,t){super.update(z(r,t),o,t)}};function z(e,r){let o=D(e,r).map(t=>t.kind==="file"?{kind:"source",label:t.file.path,link:t.file.link,count:t.file.matchCount}:t.kind==="line"?{kind:"line",...t.line}:t.kind==="candidate"?{kind:"note",text:t.identifier}:t.kind==="summary"?{kind:"note",text:t.text}:t.kind==="omitted"?{kind:"note",text:`\u2026 ${t.matches} more ${d(t.matches,"match","matches")} \xB7 ${T("app.tools.expand")} to expand`}:{kind:"note",text:"No matches found"});return{summary:P(e),rows:o}}c(z,"searchModel");function D(e,r){let o=e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0,t=e.files.length===0?o?[]:[{kind:"empty"}]:e.files.flatMap(n=>[{kind:"file",file:n},...n.uniqueLineCount===void 0?n.lines.map(i=>({kind:"line",file:n,line:i})):[{kind:"summary",text:`${String(n.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(n.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(e.fuzzy!==void 0&&(e.fuzzy.status==="skipped"?t.push({kind:"summary",text:"Fuzzy search unavailable"}):e.fuzzy.candidates.length>0&&t.push(...e.fuzzy.candidates.flatMap(n=>{let i=e.fuzzyPresentation?.groups.find(u=>u.identifier===n.identifier)?.files??[],h=i.reduce((u,f)=>u+f.matchCount,0);return[{kind:"candidate",identifier:n.identifier},...i.length===0?[]:[{kind:"summary",text:`Shown ${String(h)} of ${String(n.matchCount)}${n.selection.complete?"":"+"}`},...i.flatMap(u=>[{kind:"file",file:u},...u.lines.map(f=>({kind:"line",file:u,line:f}))])]]}))),(e.omittedFileCount??0)>0&&t.push({kind:"summary",text:`\u2026 ${e.omittedFileCount} more files (${e.omittedMatchCount} matches) \xB7 narrow path, include, or query`}),e.fuzzy!==void 0||r||t.length<=C)return t;let s=t.slice(0,C-1);for(;s.at(-1)?.kind==="file";)s.pop();let l=new Set(s.flatMap(n=>n.kind==="line"?n.line.logicalMatchIds??[]:[])),a=l.size>0?l.size:s.reduce((n,i)=>n+(i.kind==="line"?i.line.matchCount:0),0);return[...s,{kind:"omitted",matches:Math.max(0,e.matchCount-a)}]}c(D,"searchViewport");function P(e){if(e.matchCount===0&&e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0&&e.fuzzyPresentation!==void 0){let o=e.fuzzy.candidates.reduce((l,a)=>l+a.matchCount,0),t=e.fuzzy.candidates.every(l=>l.selection.complete)?"":"+",s=e.fuzzyPresentation.fileCount;return`0 exact \xB7 ${String(o)}${t} fuzzy ${d(o,"match","matches")} \xB7 ${String(s)}${t} ${d(s,"file","files")}`}return e.matchCount===0?e.complete?"No matches":"No matches \xB7 incomplete":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${d(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${d(e.fileCount,"file","files")}`}c(P,"searchSummary");function d(e,r,o){return e===1?r:o}c(d,"plural");export{w as a,v as b,m as c};
@@ -1 +1 @@
1
- import{a as u,g as p}from"./chunk-EY65TFHJ.js";import{a as S}from"./chunk-BXGMMZT3.js";import{a as l}from"./chunk-EI7MMDWY.js";import d from"node:path";function k(m,n){return{async paths(i,s,a=n){a?.throwIfAborted();let r=m.resolve(i);if(!r)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");let f=await r.backend.execute("python3",["-c","import json,os;print(json.dumps({'home':os.environ.get('HOME',''),'agent':os.environ.get('PI_CODING_AGENT_DIR','')}))"],r.location.path,{signal:a});if(f.exitCode!==0)throw new p("CONFIG_ENVIRONMENT_FAILED",i,"not-applied");let o=JSON.parse(f.stdout.toString("utf8"));if(typeof o!="object"||o===null||!("home"in o)||!("agent"in o)||typeof o.home!="string"||typeof o.agent!="string"||!o.home.startsWith("/"))throw new TypeError("Invalid remote configuration environment");let c=o.agent.trim()?d.posix.resolve(r.location.path,o.agent.trim()):d.posix.join(o.home,".pi","agent");return{project:u(r.location.target,d.posix.join(r.location.path,".pi","pi-agent-ide",`${s}.json`)).source,global:u(r.location.target,d.posix.join(c,"extensions","pi-agent-ide",`${s}.json`)).source}},async readText(i,s=n){s?.throwIfAborted();let a=m.resolve(i);if(!a)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");return(await a.backend.read(a.location.path,{signal:s})).bytes.toString("utf8")}}}l(k,"createSshToolConfigAccess");import{readFile as E}from"node:fs/promises";import g from"node:path";import{Type as t}from"typebox";import{Value as y}from"typebox/value";var w=t.Object({content:t.Record(t.String(),t.Union([t.String(),t.Null()])),markers:t.Record(t.String(),t.Boolean()),names:t.Array(t.String())});async function U(m,n,i,s){s?.throwIfAborted();let a=[...new Set(["package.json",...i.flatMap(e=>Object.keys(e.configSections??{}))])],r=[...new Set(i.flatMap(e=>e.configFiles??[]))];for(let e of[...a,...r]){let h=g.posix.relative(n,g.posix.resolve(n,e));if(h===".."||h.startsWith("../")||g.posix.isAbsolute(e))throw new p("UNSUPPORTED_SOURCE",n,"not-applied")}let f=await E(new URL("./recipe-evidence-worker.py",new URL("../src/backend/recipe-evidence.ts",import.meta.url).href),{encoding:"utf8",signal:s}),o=await m.execute("python3",["-c",f,n,JSON.stringify({files:a,markers:r.filter(e=>!e.includes("*")),listNames:r.some(e=>e.includes("*"))})],n,{signal:s});if(o.exitCode!==0)throw new p("EVIDENCE_FAILED",n,"not-applied");let c=JSON.parse(o.stdout.toString("utf8"));if(y.Check(t.Object({error:t.Literal("CONTENT_LIMIT")}),c))throw new p("CONTENT_LIMIT",n,"not-applied");if(!y.Check(w,c))throw new p("INVALID_RESPONSE",n,"not-applied");return S(n,i,{readText:l(e=>Promise.resolve(c.content[e]??void 0),"readText"),hasMarker:l(e=>Promise.resolve(e.includes("*")?c.names.some(h=>g.matchesGlob(h,e)):c.markers[e]===!0),"hasMarker")},s)}l(U,"inspectSshRecipeEvidence");export{k as a,U as b};
1
+ import{a as u,g as p}from"./chunk-4HWKBCBH.js";import{a as S}from"./chunk-BXGMMZT3.js";import{a as l}from"./chunk-EI7MMDWY.js";import d from"node:path";function k(m,n){return{async paths(i,s,a=n){a?.throwIfAborted();let r=m.resolve(i);if(!r)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");let f=await r.backend.execute("python3",["-c","import json,os;print(json.dumps({'home':os.environ.get('HOME',''),'agent':os.environ.get('PI_CODING_AGENT_DIR','')}))"],r.location.path,{signal:a});if(f.exitCode!==0)throw new p("CONFIG_ENVIRONMENT_FAILED",i,"not-applied");let o=JSON.parse(f.stdout.toString("utf8"));if(typeof o!="object"||o===null||!("home"in o)||!("agent"in o)||typeof o.home!="string"||typeof o.agent!="string"||!o.home.startsWith("/"))throw new TypeError("Invalid remote configuration environment");let c=o.agent.trim()?d.posix.resolve(r.location.path,o.agent.trim()):d.posix.join(o.home,".pi","agent");return{project:u(r.location.target,d.posix.join(r.location.path,".pi","pi-agent-ide",`${s}.json`)).source,global:u(r.location.target,d.posix.join(c,"extensions","pi-agent-ide",`${s}.json`)).source}},async readText(i,s=n){s?.throwIfAborted();let a=m.resolve(i);if(!a)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");return(await a.backend.read(a.location.path,{signal:s})).bytes.toString("utf8")}}}l(k,"createSshToolConfigAccess");import{readFile as E}from"node:fs/promises";import g from"node:path";import{Type as t}from"typebox";import{Value as y}from"typebox/value";var w=t.Object({content:t.Record(t.String(),t.Union([t.String(),t.Null()])),markers:t.Record(t.String(),t.Boolean()),names:t.Array(t.String())});async function U(m,n,i,s){s?.throwIfAborted();let a=[...new Set(["package.json",...i.flatMap(e=>Object.keys(e.configSections??{}))])],r=[...new Set(i.flatMap(e=>e.configFiles??[]))];for(let e of[...a,...r]){let h=g.posix.relative(n,g.posix.resolve(n,e));if(h===".."||h.startsWith("../")||g.posix.isAbsolute(e))throw new p("UNSUPPORTED_SOURCE",n,"not-applied")}let f=await E(new URL("./recipe-evidence-worker.py",new URL("../src/backend/recipe-evidence.ts",import.meta.url).href),{encoding:"utf8",signal:s}),o=await m.execute("python3",["-c",f,n,JSON.stringify({files:a,markers:r.filter(e=>!e.includes("*")),listNames:r.some(e=>e.includes("*"))})],n,{signal:s});if(o.exitCode!==0)throw new p("EVIDENCE_FAILED",n,"not-applied");let c=JSON.parse(o.stdout.toString("utf8"));if(y.Check(t.Object({error:t.Literal("CONTENT_LIMIT")}),c))throw new p("CONTENT_LIMIT",n,"not-applied");if(!y.Check(w,c))throw new p("INVALID_RESPONSE",n,"not-applied");return S(n,i,{readText:l(e=>Promise.resolve(c.content[e]??void 0),"readText"),hasMarker:l(e=>Promise.resolve(e.includes("*")?c.names.some(h=>g.matchesGlob(h,e)):c.markers[e]===!0),"hasMarker")},s)}l(U,"inspectSshRecipeEvidence");export{k as a,U as b};
@@ -0,0 +1 @@
1
+ import{b as n}from"./chunk-E2PHA4SQ.js";import"./chunk-JKMXND6V.js";import"./chunk-WXGTU2M6.js";import{a as o,b as t,c as i}from"./chunk-LLRUJD62.js";import"./chunk-Q5X6OXNS.js";import"./chunk-4HWKBCBH.js";import{b as s}from"./chunk-AIT3YWR5.js";import"./chunk-VDP5CQHM.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-OI3HBIPK.js";import"./chunk-YTYLS2UM.js";import{c as r}from"./chunk-W7CASEO3.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as e}from"./chunk-EI7MMDWY.js";async function g(a){let m=new i(await t(o(r())));await s(a,f=>n(f,m))}e(g,"registerOwnedWeb");export{g as default};
@@ -1 +1 @@
1
- import{a as _}from"./chunk-KL776TGR.js";import{a as A}from"./chunk-OJX3RJ5A.js";import{a as W,g as n}from"./chunk-EY65TFHJ.js";import{a as u}from"./chunk-EI7MMDWY.js";import{Writable as M}from"node:stream";import{callbackify as N}from"node:util";import{fileURLToPath as $,pathToFileURL as G}from"node:url";import{readFile as x}from"node:fs/promises";import U from"node:path";import{createInterface as H}from"node:readline";import{fileURLToPath as j}from"node:url";import{Type as i}from"typebox";import{Value as B}from"typebox/value";var V=i.Union([i.Object({kind:i.Literal("ready")}),i.Object({kind:i.Literal("change"),path:i.String(),type:i.Union([i.Literal(1),i.Literal(2),i.Literal(3)])}),i.Object({kind:i.Literal("error"),code:i.Union([i.Literal("WATCH_FAILED"),i.Literal("WATCH_LIMIT"),i.Literal("WATCH_OVERFLOW")])})]);function J(h,s){let c=U.posix.relative(h,s);return c===""||c!==".."&&!c.startsWith("../")&&!U.posix.isAbsolute(c)}u(J,"inside");function I(h,s,c,e){let r=h.resolve(s);if(!r)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");let d=!1,m=new Map,l=new Set,P=u(o=>d||o.closed,"closed"),p=u(o=>(o.closed=!0,o.channel&&(o.stopping??=o.channel.stop().then(()=>{})),o.stopping??Promise.resolve()),"release"),y={async register(o,w){if(d)throw new n("WATCH_DISPOSED",s,"not-applied");let E=w.map(L=>{let f=L.globPattern,S=typeof f=="string"?s:typeof f.baseUri=="string"?f.baseUri:f.baseUri.uri,g=S.startsWith("file://")?W(r.location.target,j(S)).source:S,v=h.resolve(g);if(!v||v.location.target!==r.location.target)throw new n("UNSUPPORTED_SOURCE",g,"not-applied");let O=L.kind??7;if(!Number.isInteger(O)||O<0||O>7)throw new TypeError("Invalid file watcher event mask");return{root:v.location.path,expression:typeof f=="string"?f:f.pattern,kind:O}});if(E.length===0){await y.unregister(o);return}let t={id:o,closed:!1,starting:Promise.resolve()};l.add(t),t.starting=(async()=>{let L=await x(new URL("./file-watch-worker.py",new URL("../src/backend/lsp-file-watchers.ts",import.meta.url).href),"utf8");if(P(t))throw new n("WATCH_DISPOSED",s,"not-applied");let f=await r.backend.startProcess("python3",["-u","-c",L,JSON.stringify([...new Set(E.map(k=>k.root))])],r.location.path);if(t.channel=f,f.stderr.resume(),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let S=H({input:f.stdout}),g=!1,v=!1;if(await new Promise((k,b)=>{let R=u(C=>{if(v||t.closed)return;v=!0;let a=new n(C,s,"not-applied");g?e(a):b(a),p(t).catch(e)},"fail");S.on("line",C=>{if(t.closed)return;let a;try{a=JSON.parse(C)}catch{R("INVALID_RESPONSE");return}if(!B.Check(V,a)){R("INVALID_RESPONSE");return}if(a.kind==="ready"){g=!0,k();return}if(a.kind==="error"){R(a.code);return}if(!g){R("INVALID_RESPONSE");return}if(m.get(o)!==t)return;E.some(T=>{if(!J(T.root,a.path))return!1;let F=U.posix.relative(T.root,a.path);return(T.kind&(a.type===1?1:a.type===2?2:4))!==0&&U.matchesGlob(U.posix.isAbsolute(T.expression)?a.path:F,T.expression)})&&c({uri:W(r.location.target,a.path).source,type:a.type})}),f.completion.then(()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))},()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))})}),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let D=m.get(o);m.set(o,t),D&&await p(D)})();try{await t.starting}catch(L){throw await p(t),L}finally{l.delete(t)}},async unregister(o){let w=m.get(o);m.delete(o);let E=[...l].filter(t=>t.id===o);await Promise.all([...E,...w?[w]:[]].map(p)),await Promise.allSettled(E.map(t=>t.starting))},async dispose(){d=!0;let o=new Set([...m.keys(),...[...l].map(w=>w.id)]);await Promise.all([...o].map(w=>y.unregister(w)))}};return y}u(I,"createSshLspFileWatchers");function he(h,s){let c=h.resolve(s);if(!c)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");return{async start(e){let r=h.resolve(e.rootUri);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e.rootUri,"not-applied");let d=e.command.map(p=>p.replaceAll("{project}",r.location.path));if(!d[0])throw new TypeError("Language server command is empty");let m=Object.entries(await A(r.backend,r.location.path,e.env,e.signal)).map(([p,y])=>`${p}=${y}`),l=await r.backend.startProcess("env",[...m,...d],r.location.path,{signal:e.signal}),P=new M({write:N(async(p,y)=>{await l.write(p)}),final:N(async()=>{await l.end()})});return{stdin:P,stdout:l.stdout,stderr:l.stderr,completion:l.completion,remote:{target:r.location.target,pid:l.pid},async stop(){try{await _(l,h,e.rootUri)}finally{P.destroy()}}}},fileWatchers(e,r,d){let m=h.resolve(e);if(!m||m.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return I(h,e,r,d)},toServerUri(e){if(!e.startsWith("ssh://")){if(e.startsWith("file://"))throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return e}let r=h.resolve(e);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return G(r.location.path).href},fromServerUri(e){return e.startsWith("file://")?W(c.location.target,$(e)).source:e}}}u(he,"createSshLspTransport");export{he as a};
1
+ import{a as _}from"./chunk-7LOVUWNI.js";import{a as A}from"./chunk-WPBQ45ZL.js";import{a as W,g as n}from"./chunk-4HWKBCBH.js";import{a as u}from"./chunk-EI7MMDWY.js";import{Writable as M}from"node:stream";import{callbackify as N}from"node:util";import{fileURLToPath as $,pathToFileURL as G}from"node:url";import{readFile as x}from"node:fs/promises";import U from"node:path";import{createInterface as H}from"node:readline";import{fileURLToPath as j}from"node:url";import{Type as i}from"typebox";import{Value as B}from"typebox/value";var V=i.Union([i.Object({kind:i.Literal("ready")}),i.Object({kind:i.Literal("change"),path:i.String(),type:i.Union([i.Literal(1),i.Literal(2),i.Literal(3)])}),i.Object({kind:i.Literal("error"),code:i.Union([i.Literal("WATCH_FAILED"),i.Literal("WATCH_LIMIT"),i.Literal("WATCH_OVERFLOW")])})]);function J(h,s){let c=U.posix.relative(h,s);return c===""||c!==".."&&!c.startsWith("../")&&!U.posix.isAbsolute(c)}u(J,"inside");function I(h,s,c,e){let r=h.resolve(s);if(!r)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");let d=!1,m=new Map,l=new Set,P=u(o=>d||o.closed,"closed"),p=u(o=>(o.closed=!0,o.channel&&(o.stopping??=o.channel.stop().then(()=>{})),o.stopping??Promise.resolve()),"release"),y={async register(o,w){if(d)throw new n("WATCH_DISPOSED",s,"not-applied");let E=w.map(L=>{let f=L.globPattern,S=typeof f=="string"?s:typeof f.baseUri=="string"?f.baseUri:f.baseUri.uri,g=S.startsWith("file://")?W(r.location.target,j(S)).source:S,v=h.resolve(g);if(!v||v.location.target!==r.location.target)throw new n("UNSUPPORTED_SOURCE",g,"not-applied");let O=L.kind??7;if(!Number.isInteger(O)||O<0||O>7)throw new TypeError("Invalid file watcher event mask");return{root:v.location.path,expression:typeof f=="string"?f:f.pattern,kind:O}});if(E.length===0){await y.unregister(o);return}let t={id:o,closed:!1,starting:Promise.resolve()};l.add(t),t.starting=(async()=>{let L=await x(new URL("./file-watch-worker.py",new URL("../src/backend/lsp-file-watchers.ts",import.meta.url).href),"utf8");if(P(t))throw new n("WATCH_DISPOSED",s,"not-applied");let f=await r.backend.startProcess("python3",["-u","-c",L,JSON.stringify([...new Set(E.map(k=>k.root))])],r.location.path);if(t.channel=f,f.stderr.resume(),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let S=H({input:f.stdout}),g=!1,v=!1;if(await new Promise((k,b)=>{let R=u(C=>{if(v||t.closed)return;v=!0;let a=new n(C,s,"not-applied");g?e(a):b(a),p(t).catch(e)},"fail");S.on("line",C=>{if(t.closed)return;let a;try{a=JSON.parse(C)}catch{R("INVALID_RESPONSE");return}if(!B.Check(V,a)){R("INVALID_RESPONSE");return}if(a.kind==="ready"){g=!0,k();return}if(a.kind==="error"){R(a.code);return}if(!g){R("INVALID_RESPONSE");return}if(m.get(o)!==t)return;E.some(T=>{if(!J(T.root,a.path))return!1;let F=U.posix.relative(T.root,a.path);return(T.kind&(a.type===1?1:a.type===2?2:4))!==0&&U.matchesGlob(U.posix.isAbsolute(T.expression)?a.path:F,T.expression)})&&c({uri:W(r.location.target,a.path).source,type:a.type})}),f.completion.then(()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))},()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))})}),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let D=m.get(o);m.set(o,t),D&&await p(D)})();try{await t.starting}catch(L){throw await p(t),L}finally{l.delete(t)}},async unregister(o){let w=m.get(o);m.delete(o);let E=[...l].filter(t=>t.id===o);await Promise.all([...E,...w?[w]:[]].map(p)),await Promise.allSettled(E.map(t=>t.starting))},async dispose(){d=!0;let o=new Set([...m.keys(),...[...l].map(w=>w.id)]);await Promise.all([...o].map(w=>y.unregister(w)))}};return y}u(I,"createSshLspFileWatchers");function he(h,s){let c=h.resolve(s);if(!c)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");return{async start(e){let r=h.resolve(e.rootUri);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e.rootUri,"not-applied");let d=e.command.map(p=>p.replaceAll("{project}",r.location.path));if(!d[0])throw new TypeError("Language server command is empty");let m=Object.entries(await A(r.backend,r.location.path,e.env,e.signal)).map(([p,y])=>`${p}=${y}`),l=await r.backend.startProcess("env",[...m,...d],r.location.path,{signal:e.signal}),P=new M({write:N(async(p,y)=>{await l.write(p)}),final:N(async()=>{await l.end()})});return{stdin:P,stdout:l.stdout,stderr:l.stderr,completion:l.completion,remote:{target:r.location.target,pid:l.pid},async stop(){try{await _(l,h,e.rootUri)}finally{P.destroy()}}}},fileWatchers(e,r,d){let m=h.resolve(e);if(!m||m.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return I(h,e,r,d)},toServerUri(e){if(!e.startsWith("ssh://")){if(e.startsWith("file://"))throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return e}let r=h.resolve(e);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return G(r.location.path).href},fromServerUri(e){return e.startsWith("file://")?W(c.location.target,$(e)).source:e}}}u(he,"createSshLspTransport");export{he as a};
@@ -0,0 +1,11 @@
1
+ import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-PRLIHLCS.js";import{h as w,i as P,j as B}from"./chunk-DXONCYWF.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as D}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as H,parse as W}from"partial-json";function O(o,e=H.ALL){if(!(!o||o.trim().length===0))try{let t=W(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(O,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),s=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),i=e.filterEntries?.(s,t)??s,d=new Set(i.map(c=>c.index));for(let c of s)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of i)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as U}from"@earendil-works/pi-ai";var K=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function $(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((s,i)=>{if(!s)return;let d=i.modelRegistry.getProvider(s.provider);if(!d)return;let u=r.get(s.provider);if(u){if(u.subscribers.add(a),u.api===s.api&&d.streamSimple===u.wrapper)return;u.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:u.wrapper});return}let m=d.streamSimple[K];if(m){if(m.subscribers.add(a),r.set(s.provider,m),m.api===s.api)return;m.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,C,v)=>Q(c,p,C,v,g),"wrapper"),I={api:s.api,delegate:c,wrapper:b,subscribers:g};b[K]=I;let h=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...h,api:s.api,streamSimple:b}),r.set(s.provider,I)},"install");o.on("before_provider_request",(s,i)=>{a.context=i,l(i.model,i)}),o.on("turn_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("agent_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("session_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("model_select",(s,i)=>{a.context=i,l(s.model,i)}),o.on("session_shutdown",()=>{for(let[s,i]of r)i.subscribers.delete(a),i.subscribers.size===0&&o.unregisterProvider(s);r.clear(),a.context=void 0})}y($,"registerStreamingInterceptorProvider");function Q(o,e,t,n,r){let a=U(),l=new AbortController,s=n?.signal,i=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),I=y(()=>{l.abort()},"abortFromParent");return s&&(s.aborted?l.abort():s.addEventListener("abort",I,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(i)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),q(p,u);let C;for(let v of r){let x=v.context;if(x){let T=await v.processStreamEvent(p,x);C??=T}}if(b(p),J(p,m,c,g),a.push(structuredClone(p)),C){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let E of r)E.finalizeStreamInterception(p.contentIndex);i=!0,l.abort();let v=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,x={...d,content:d.content.filter((E,A)=>u.has(A)&&(v===void 0||A<=v||g.has(A))).map(E=>E.type==="toolCall"&&E.id===C.toolCallId?{...E,arguments:structuredClone(C.arguments)}:E)};V(a,b,x,u,m,c,g);let{errorMessage:T,...F}=x;a.push({type:"done",reason:"toolUse",message:{...F,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(i)return;let p=d,C=s?.aborted===!0?"aborted":"error",v={...p,stopReason:C,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:C,error:v}),a.end()}finally{s?.removeEventListener("abort",I)}})(),a}y(Q,"wrapStream");function q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(q,"rememberStartEvent");function J(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(J,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[s,i]of t.content.entries())if(n.has(s)){if(i.type==="text"&&!r.has(s)){let d={type:"text_end",contentIndex:s,content:i.text,partial:t};e(d),o.push(d)}else if(i.type==="thinking"&&!a.has(s)){let d={type:"thinking_end",contentIndex:s,content:i.thinking,partial:t};e(d),o.push(d)}else if(i.type==="toolCall"&&!l.has(s)){let d={type:"toolcall_end",contentIndex:s,toolCall:i,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Y,"emptyAssistantMessage");var X="agentic-ide-partial-tool-recovery",z="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
+ `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",s=r.content.flatMap(i=>i.type==="text"?[i.text]:[]).join(`
3
+ `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(s,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role==="toolResult"){let r=this.toolCallRecords.get(t.message.toolCallId),a=r?.blockExecution?r.guardResult:void 0;if(a){this.toolCallRecords.delete(t.message.toolCallId);let l=a.details;l!==void 0&&w(l);let s=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return s!==void 0&&this.completedBatchEntryIndexes.add(s),{message:{...t.message,content:a.content,...l!==void 0&&{details:l},isError:!0}}}}if(t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=O(a,D.OBJ|D.ARR)??{},s=te(a),i=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:i,toolName:n,args:l,complete:s!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!s&&Object.keys(l).length===0)return;let u=s!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=s??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:i,batchEntries:this.getBatchEntries(i),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let s=!this.completeArgumentContentIndices.has(e.contentIndex),i;s&&(this.completeArgumentContentIndices.add(e.contentIndex),i=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),i}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(z,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=ee(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let s={content:[{type:"text",text:e.message.content}],details:M(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:s,...r&&{blockExecution:!0}}),s}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,i=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(i))for(let d of i)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,s=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],i=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:s,blockedToolCallIds:i,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?oe(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function j(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(j,"toolStreamEventKey");function ee(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(ee,"abortReason");function te(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(te,"parseCompleteArguments");function ne(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(i=>f.IsObjectNotArray(i.data)?i.data:i),a=n===void 0?r:r.filter(i=>i.path===n),s=(a.length>0?a:r).flatMap(i=>{let d=i.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(s)]}y(ne,"freshAnchorsAfterRecovery");function re(o,e){let n=o.indexOf(`
4
+
5
+ Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
+
7
+ Current nearby anchors:
8
+ ${e.map(a=>` ${a}`).join(`
9
+ `)}`}y(re,"replaceCurrentAnchors");function oe(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(u=>`${u.index} (${u.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=ne(e),s=l.length>0&&f.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,i=l.length>0?re(o.message.content,l):o.message.content,d=l.length>0&&f.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:X,content:`${i}
10
+
11
+ [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:s,recovery:d}}}}y(oe,"makeRecoveryResult");var G=new WeakMap;function L(o){let e=G.get(o);if(e)return e;let t=new k(o);return G.set(o,t),$(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(L,"coordinatorFor");function ae(o,e){L(o).register(e)}y(ae,"registerToolCallInterceptor");function se(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on(z,n=>{!f.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(se,"registerToolCallAnnotationSink");function xe(o,e){L(o).registerBlockedCallSink(e)}y(xe,"registerBlockedToolCallSink");export{ae as a,se as b,xe as c};
@@ -1,4 +1,4 @@
1
- import{a as Ae}from"./chunk-IUSLSROY.js";import{a as Ee}from"./chunk-3G54ZL2L.js";import{a as Ie,b as Re}from"./chunk-7HDK3NRQ.js";import{a as xe}from"./chunk-NULNW6GK.js";import"./chunk-KL776TGR.js";import{b as Ce}from"./chunk-OJX3RJ5A.js";import"./chunk-CTJV77FR.js";import{a as X,d as ke}from"./chunk-SBLKPTL3.js";import"./chunk-XZDOVPRC.js";import{a as Pe,b as Se,c as Oe}from"./chunk-HCN5W76B.js";import{a as De}from"./chunk-7TJ6DWW3.js";import{a as K,g as D}from"./chunk-EY65TFHJ.js";import{c as ve}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-R5XJSEOE.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as ue,b as fe,c as ge}from"./chunk-JMVDFOTQ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await Ke(le(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:p}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,p,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:p}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
1
+ import{a as Ae}from"./chunk-N56WAVYA.js";import{a as Ee}from"./chunk-HCK7OIQ3.js";import"./chunk-7LOVUWNI.js";import{a as Ie,b as Re}from"./chunk-GEMDU6XW.js";import{b as Ce}from"./chunk-WPBQ45ZL.js";import{a as xe}from"./chunk-2ITKAXHO.js";import{a as X,d as ke}from"./chunk-JKMXND6V.js";import"./chunk-BQAKA3FU.js";import"./chunk-WXGTU2M6.js";import{a as Pe,b as Se,c as Oe}from"./chunk-LLRUJD62.js";import{a as De}from"./chunk-Q5X6OXNS.js";import{a as K,g as D}from"./chunk-4HWKBCBH.js";import{c as ve}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-DXONCYWF.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as ue,b as fe,c as ge}from"./chunk-57F5GTHO.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await Ke(le(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:p}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,p,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:p}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
2
2
  `;return t===i?!1:(o?await o.writeText(n,i,t,e):await Qe(n,i,{encoding:"utf8",signal:e}),!0)}s(q,"writeJson");function je(n,r){let t=new Set,o;for(let e of n.trim().split(/\s+/u).filter(Boolean))if(["--apply","--no-apply","--agent"].includes(e))t.add(e);else if(e.startsWith("ssh://")&&o===void 0)o=e;else throw new TypeError("Use /pi-agent-ide-doctor [ssh://target/path] [--apply | --no-apply] [--agent]");if(t.has("--apply")&&t.has("--no-apply"))throw new TypeError("Choose --apply or --no-apply, not both");return{cwd:o??r,flags:t}}s(je,"parseDoctorArguments");var z=class{static{s(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(r){let t=this.plugins.get(r.id);if(t!==void 0)return t;let o=this.queue.then(async()=>{let e=!0,i=[],a=[],u=[],f=[],h={addLanguage:s(p=>{V(p,i,r.id,"language",()=>e)},"addLanguage"),addToolRecipe:s(p=>{V(p,a,r.id,"tool recipe",()=>e)},"addToolRecipe"),addSetupCheck:s(p=>{V(p,u,r.id,"setup check",()=>e)},"addSetupCheck"),addCheck:s(p=>{V(p,f,r.id,"check",()=>e)},"addCheck")};try{await r.setup(h)}finally{e=!1}$e(this.languages,i,"language"),$e(this.recipes,a,"tool recipe"),this.languages.push(...i),this.recipes.push(...a),this.setupChecks.push(...u),this.checks.push(...f)});return this.plugins.set(r.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(r.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function Ne(n,r){let t=[],o=[];for(let e of n.setupChecks)try{let i=await e.value.inspect(r);t.push(...(i.selections??[]).map(a=>({...a,pluginId:e.pluginId}))),o.push(...(i.actions??[]).map(a=>({...a,pluginId:e.pluginId})))}catch{}return{selections:t,actions:o}}s(Ne,"runContributedSetupChecks");async function Le(n,r){let t=[];for(let o of n.checks)try{t.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(r)})}catch(e){t.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:e instanceof Error?e.message:String(e)}]})}return t}s(Le,"runContributedChecks");function $e(n,r,t){for(let o of r){let e=n.find(i=>i.value.id===o.value.id)?.pluginId;if(e!==void 0)throw new Error(`${t} ${o.value.id} is already owned by doctor plugin ${e}`)}}s($e,"assertAvailable");function V(n,r,t,o,e){if(!e())throw new Error(`Doctor plugin ${t} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(r.some(i=>i.value.id===n.id))throw new Error(`Doctor plugin ${t} registered ${o} ${n.id} twice`);r.push({pluginId:t,value:n})}s(V,"add");import st from"node:path";import{readFile as Ze}from"node:fs/promises";async function _e(n,r,t,o=process.env,e,i){e?.throwIfAborted();let a=t.filter(({value:g})=>g.languages.some(y=>r.has(y))),u=a.map(g=>g.value),f=i?await i.evidence(u,e):await de(n,u,void 0,e),h=await et(n,e,i),p=[...new Set(u.flatMap(g=>g.executables))],m=i?await i.executableAvailability(p.map(g=>({command:[g]})),e):void 0;if(e?.throwIfAborted(),m&&(m.length!==p.length||m.some(g=>typeof g!="boolean")))throw new TypeError("Invalid Doctor executable availability report");let w=[];for(let g of a){e?.throwIfAborted();let y=g.value,C=[],I=1,b=f.get(y.id),O=b?.config;O!==void 0&&(I+=6,C.push(`project config: ${O}`)),h.has(`${y.kind}:${y.id}`)&&(I+=6,C.push("Pi Agent IDE config"));let c=b?.dependency;c!==void 0&&(I+=4,C.push(`project dependency: ${c}`));let d=m?y.executables.find(l=>m[p.indexOf(l)]===!0):await qe(n,y.executables,o,e);d!==void 0&&(I+=3,C.push(`executable: ${d}`)),w.push({pluginId:g.pluginId,recipe:y,score:I,evidence:C,...d&&{executable:d}})}return w.sort((g,y)=>y.score-g.score||g.recipe.id.localeCompare(y.recipe.id))}s(_e,"discoverRecipeCandidates");function Ue(n,r,t=[]){let o=new Map,e=new Map(t.map(i=>[`${i.kind}:${i.languageId}`,i.toolId]));for(let i of r)for(let a of["formatter","linter","lsp"]){let u=e.get(`${a}:${i}`),f=u===void 0?4:7,h=n.filter(m=>m.recipe.kind===a&&m.recipe.languages.includes(i)&&m.executable!==void 0&&m.recipe.id!==u&&m.score>=f),p=h[0];p!==void 0&&(h.filter(m=>m.score===p.score).length>1||o.set(`${p.recipe.kind}:${p.recipe.id}`,p))}return[...o.values()]}s(Ue,"selectSuggestedRecipes");async function qe(n,r,t,o){for(let e of r)if(await pe(e,n,t,o))return e}s(qe,"firstExecutable");async function et(n,r,t){let o=new Set;for(let[e,i,a]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{r?.throwIfAborted();let u=t?(await t.configPaths(e,r)).project:L(n,e),f=t?await t.readText(u,r):await Ze(u,{encoding:"utf8",signal:r});if(r?.throwIfAborted(),f===void 0)continue;let h=JSON.parse(f);if(typeof h!="object"||h===null||Array.isArray(h))continue;let m=h[i];if(typeof m=="object"&&m!==null&&!Array.isArray(m))for(let w of Object.keys(m))o.add(`${a}:${w}`)}catch(u){if(r?.throwIfAborted(),!(u instanceof SyntaxError)&&!(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT"))throw u}return o}s(et,"managedRecipeIds");import{execFile as tt}from"node:child_process";import{readdir as ot}from"node:fs/promises";import _ from"node:path";import{promisify as nt}from"node:util";var rt=nt(tt),it=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Be(n,r){r?.throwIfAborted();try{let o=(await rt("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:r})).stdout.split("\0").filter(Boolean).map(e=>_.resolve(n,e)).filter(e=>!Me(e));return r?.throwIfAborted(),o.length>0?o:await ee(n,r)}catch{return r?.throwIfAborted(),ee(n,r)}}s(Be,"collectProjectFiles");function Fe(n,r,t=process.platform){let o=new Map,e=t==="win32"?_.win32:_;for(let i of r){let a=new Set(i.extensions.map(p=>p.toLowerCase())),u=s(p=>t==="win32"?p.toLowerCase():p,"normalizeName"),f=new Set(i.fileNames?.map(u)),h=n.filter(p=>!p.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")&&(a.has(e.extname(p).toLowerCase())||f.has(u(e.basename(p)))));h.length>0&&o.set(i.id,h)}return o}s(Fe,"detectProjectLanguages");async function ee(n,r){r?.throwIfAborted();let t=[];for(let o of await ot(n,{withFileTypes:!0})){if(o.isDirectory()&&it.has(o.name))continue;let e=_.join(n,o.name);Me(e)||(o.isDirectory()?t.push(...await ee(e,r)):o.isFile()&&t.push(e))}return t}s(ee,"walk");function Me(n){return n.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")}s(Me,"isManagedIdeConfig");function at(n,r){if(n.includes("://")&&!r||r&&r.source!==n)throw Object.assign(new Error(`Doctor requires the owner of ${n}`),{code:"UNSUPPORTED_SOURCE"})}s(at,"assertWorkspace");async function te(n,r,t=process.env,o,e){o?.throwIfAborted(),at(r,e);let i=e?await e.files(o):await Be(r,o);o?.throwIfAborted();let a=Fe(i,n.languages.map(w=>w.value),e?.platform),u=new Set(a.keys()),f={cwd:r,files:i,detectedLanguageIds:u,detectedLanguages:a,env:e?{...e.toolPaths}:t,signal:o,workspace:e},[h,p]=await Promise.all([_e(r,u,n.recipes,e?{...e.toolPaths}:t,o,e),Ne(n,f)]);o?.throwIfAborted();let m=new Map;for(let w of u)for(let g of["formatter","linter","lsp"]){if(p.selections.some(b=>b.languageId===w&&b.kind===g))continue;let y=h.filter(b=>b.recipe.kind===g&&b.recipe.languages.includes(w)),C=s(b=>b.score-(b.executable===void 0?0:3),"nativeScore"),I=Math.max(1,...y.map(C));for(let b of y){if(b.executable!==void 0||C(b)!==I||I<=1)continue;let O=`${g}-${b.recipe.id}-unavailable`;m.set(O,{id:O,pluginId:b.pluginId,message:`Native project setup selects ${b.recipe.id}, but its executable is unavailable. Install ${b.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:r,files:i,detectedLanguages:a,candidates:h,selections:p.selections,actions:[...p.actions,...m.values()],suggestions:Ue(h,u,p.selections)}}s(te,"inspectDoctorSetup");async function Y(n,r,t=process.env,o,e){let i=await te(n,r,t,o,e),a=new Set(i.detectedLanguages.keys()),u={cwd:r,files:i.files,detectedLanguageIds:a,detectedLanguages:i.detectedLanguages,env:e?{...e.toolPaths}:t,signal:o,workspace:e},f=await Le(n,u);o?.throwIfAborted();let h=[{status:"pass",message:`Project: ${r}`},i.files.length>0?{status:"pass",message:`${i.files.length} project files inspected`}:{status:"warn",message:"No project files found"},a.size>0?{status:"pass",message:`Detected: ${[...a].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...i,sections:[{title:"Project",pluginId:"doctor",findings:h},...f]}}s(Y,"runDoctor");function M(n){let r=["Pi Agent IDE doctor",""];for(let t of n.sections){r.push(`${t.title} (${t.pluginId})`);for(let o of t.findings)r.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&r.push(` \`${o.detail}\``);r.push("")}if(n.actions.length>0){r.push("Setup needs attention");for(let t of n.actions)r.push(` ${t.message} [${t.pluginId}]`);r.push("")}if(n.suggestions.length>0){r.push("Suggested configuration");for(let t of n.suggestions){let o=t.evidence.length>0?` \u2014 ${t.evidence.join(", ")}`:"";r.push(` ${t.recipe.kind.padEnd(9)} ${t.recipe.id} [${t.pluginId}]${o}`)}r.push("")}return r.join(`
3
3
  `).trimEnd()}s(M,"formatDoctorReport");function oe(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(r=>r.findings.some(t=>t.status==="fail"))}s(oe,"doctorNeedsWork");function We(n){let r=n.candidates.map(t=>({owner:t.pluginId,id:t.recipe.id,kind:t.recipe.kind,languages:t.recipe.languages,evidence:t.evidence,documentation:t.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",M(n),"","Relevant registered recipes:",JSON.stringify(r,null,2),"",`Project root: ${n.cwd.includes("://")?n.cwd:st.resolve(n.cwd)}`].join(`
4
4
  `)}s(We,"buildDoctorAgentPrompt");import{createHash as ct}from"node:crypto";var dt="doctor",ne=3;function Je(n,r){let t=ue(n,pt(r));t!==void 0&&t.catch(()=>{})}s(Je,"registerDoctorTipProvider");function pt(n){return{protocol:fe,apiVersion:ge,id:dt,async getTip(r){let t=await n(r),o=lt(t);if(o.length===0)return;let e=o.slice(0,ne).map(i=>`\u2022 ${i.message}`);return o.length>ne&&e.push(`\u2022 ${o.length-ne} more`),{id:`doctor-setup-${ut(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...e,"Run /pi-agent-ide-doctor"].join(`
@@ -1 +1 @@
1
- import{a as d}from"./chunk-XZDOVPRC.js";import{g as n}from"./chunk-EY65TFHJ.js";import{a as p}from"./chunk-EI7MMDWY.js";import{readFile as h}from"node:fs/promises";import{Type as m}from"typebox";import{Value as g}from"typebox/value";async function f(s,a,e,o,t){return d(s,a,e,o,{...t,effect:"not-applied"})}p(f,"readOwnedSshCommand");var S=m.Object({html:m.String(),source:m.String()}),u=new Set(["CAPABILITY_UNAVAILABLE","INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED","BROWSER_FAILED","CANCELLED"]),l;async function B(s,a,e,o){let t=await w(s,a,e,o,"html");if(!g.Check(S,t)||Buffer.byteLength(t.html,"utf8")>16*1024*1024)throw new n("INVALID_RESPONSE",e,"not-applied");let r=new URL(t.source);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw new n("INVALID_RESPONSE",e,"not-applied");return t}p(B,"readSshBrowserPage");async function N(s,a,e,o){let t=await w(s,a,e,{signal:o,timeoutMs:3e4},"image");if(typeof t!="object"||t===null||!("png"in t)||typeof t.png!="string")throw new n("INVALID_RESPONSE",e,"not-applied");let r=Buffer.from(t.png,"base64");if(r.toString("base64")!==t.png||r.length>20*1024*1024||!r.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex")))throw new n("INVALID_RESPONSE",e,"not-applied");return r}p(N,"captureSshBrowserImage");async function R(s,a,e){let o=await w(s,new URL("about:blank"),a,{signal:e,timeoutMs:3e4},"probe");if(!g.Check(m.Object({ready:m.Literal(!0)}),o))throw new n("INVALID_RESPONSE",a,"not-applied")}p(R,"probeSshBrowser");async function w(s,a,e,o,t){o.signal?.throwIfAborted(),l??=h(new URL("./web-browser-worker.mjs",new URL("../src/backend/web-browser.ts",import.meta.url).href),"utf8");try{let r=await f(s,"node",["--input-type=module","-e",await l,JSON.stringify({kind:t,url:a.href,timeoutMs:o.timeoutMs})],e,{signal:o.signal,timeoutMs:o.timeoutMs,maxBytes:33554432});if(r.exitCode!==0)throw new n("BROWSER_FAILED",e,"not-applied");let i;try{i=JSON.parse(r.stdout.toString("utf8"))}catch{throw new n("INVALID_RESPONSE",e,"not-applied")}if(typeof i=="object"&&i!==null&&"error"in i)throw new n(typeof i.error=="string"&&u.has(i.error)?i.error:"INVALID_RESPONSE",e,"not-applied");return i}catch(r){throw r instanceof n?new n(r.code==="ENOENT"?"CAPABILITY_UNAVAILABLE":r.code,e,r.effect):r}}p(w,"runBrowser");export{f as a,B as b,N as c,R as d};
1
+ import{a as d}from"./chunk-WXGTU2M6.js";import{g as n}from"./chunk-4HWKBCBH.js";import{a as p}from"./chunk-EI7MMDWY.js";import{readFile as h}from"node:fs/promises";import{Type as m}from"typebox";import{Value as g}from"typebox/value";async function f(s,a,e,o,t){return d(s,a,e,o,{...t,effect:"not-applied"})}p(f,"readOwnedSshCommand");var S=m.Object({html:m.String(),source:m.String()}),u=new Set(["CAPABILITY_UNAVAILABLE","INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED","BROWSER_FAILED","CANCELLED"]),l;async function B(s,a,e,o){let t=await w(s,a,e,o,"html");if(!g.Check(S,t)||Buffer.byteLength(t.html,"utf8")>16*1024*1024)throw new n("INVALID_RESPONSE",e,"not-applied");let r=new URL(t.source);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw new n("INVALID_RESPONSE",e,"not-applied");return t}p(B,"readSshBrowserPage");async function N(s,a,e,o){let t=await w(s,a,e,{signal:o,timeoutMs:3e4},"image");if(typeof t!="object"||t===null||!("png"in t)||typeof t.png!="string")throw new n("INVALID_RESPONSE",e,"not-applied");let r=Buffer.from(t.png,"base64");if(r.toString("base64")!==t.png||r.length>20*1024*1024||!r.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex")))throw new n("INVALID_RESPONSE",e,"not-applied");return r}p(N,"captureSshBrowserImage");async function R(s,a,e){let o=await w(s,new URL("about:blank"),a,{signal:e,timeoutMs:3e4},"probe");if(!g.Check(m.Object({ready:m.Literal(!0)}),o))throw new n("INVALID_RESPONSE",a,"not-applied")}p(R,"probeSshBrowser");async function w(s,a,e,o,t){o.signal?.throwIfAborted(),l??=h(new URL("./web-browser-worker.mjs",new URL("../src/backend/web-browser.ts",import.meta.url).href),"utf8");try{let r=await f(s,"node",["--input-type=module","-e",await l,JSON.stringify({kind:t,url:a.href,timeoutMs:o.timeoutMs})],e,{signal:o.signal,timeoutMs:o.timeoutMs,maxBytes:33554432});if(r.exitCode!==0)throw new n("BROWSER_FAILED",e,"not-applied");let i;try{i=JSON.parse(r.stdout.toString("utf8"))}catch{throw new n("INVALID_RESPONSE",e,"not-applied")}if(typeof i=="object"&&i!==null&&"error"in i)throw new n(typeof i.error=="string"&&u.has(i.error)?i.error:"INVALID_RESPONSE",e,"not-applied");return i}catch(r){throw r instanceof n?new n(r.code==="ENOENT"?"CAPABILITY_UNAVAILABLE":r.code,e,r.effect):r}}p(w,"runBrowser");export{f as a,B as b,N as c,R as d};
@@ -1,4 +1,4 @@
1
- import{a as re,b as ie,c as oe}from"./chunk-DEP55R35.js";import{a as ee,b as te,c as ne}from"./chunk-R2U5WXYR.js";import{e as B,f as W}from"./chunk-T7I2VX3J.js";import{a as V}from"./chunk-YJ6T3PEP.js";import{b as M,c as _}from"./chunk-S72FVLUX.js";import{a as J}from"./chunk-2K65BSXS.js";import{c as Z,d as Y}from"./chunk-ICDI27GZ.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as R,j as S}from"./chunk-R5XJSEOE.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return H(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return H(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return H(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function H(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(H,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,D=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new D(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=U(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=U(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?$(t,d,`<!-- change: ${a} -->`):($(t,d,`<!-- change-begin: ${a} -->`),$(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function $(n,e,t){if(e.kind==="current"){U(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s($,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function U(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(U,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var L=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(L),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
1
+ import{a as re,b as ie,c as oe}from"./chunk-DEP55R35.js";import{a as ee,b as te,c as ne}from"./chunk-R2U5WXYR.js";import{e as B,f as W}from"./chunk-T7I2VX3J.js";import{a as V}from"./chunk-YJ6T3PEP.js";import{b as M,c as _}from"./chunk-S72FVLUX.js";import{a as J}from"./chunk-M4TVRCMZ.js";import{c as Z,d as Y}from"./chunk-TGC2ZACO.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as R,j as S}from"./chunk-DXONCYWF.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return H(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return H(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return H(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function H(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(H,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,D=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new D(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=U(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=U(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?$(t,d,`<!-- change: ${a} -->`):($(t,d,`<!-- change-begin: ${a} -->`),$(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function $(n,e,t){if(e.kind==="current"){U(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s($,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function U(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(U,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var L=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(L),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
2
2
  `)),0,0)}},async execute(d,c,a,l,f){try{let u=await r(c,a,f);return S(u,L,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=R(u,"INDEX_CHANGE_FAILED",c.file);return S({content:[{type:"text",text:p.message}],details:{action:n,change:c.change,file:N(c.file,f.cwd)}},L,{status:"error",data:{action:n,change:c.change,file:N(c.file,f.cwd),effect:xe(u)},errors:[p]})}}})}s(he,"createIndexChangeTool");function ze(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return async(i,d,c)=>{let a=N(i.file,c.cwd);return _e(a,()=>t.run(async()=>{let l=e.readText?await e.readText(a,d):await Fe(a,"utf8"),f=await h.create(e,m(a,c.cwd),d);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${i.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:c.cwd,...d!==void 0&&{signal:d}},i.change,n);if(u.status==="unavailable"){if("failure"in u&&u.failure!==void 0){if(n==="stage"&&u.reason==="index-write-failed"){let y=R(u.failure,"INDEX_CHANGE_FAILED",i.file);throw Object.assign(new Error(`${y.message}
3
3
  The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`,{cause:u.failure}),{effect:xe(u.failure)})}throw u.failure}throw n==="stage"&&u.reason==="stale-selector"?Object.assign(new Error(`${u.message}. Read ${i.file} with views: ["changes"] and use a current CHANGE# anchor.`),{effect:"not-applied"}):n==="stage"&&u.reason==="index-write-failed"&&!d?.aborted?new Error(`${u.message}
4
4
  The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function N(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(N,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as O}from"typebox";var Ke=O.Object({file:O.Optional({...q,description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."}),change:O.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Ke,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[I],nonAnchorValues:["last"]}],async mutate(r,o){let i=r.sourceFor("file"),d,c;if(o.change==="last")d=e.restore(i,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,m(i,r.cwd),r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:i,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},o.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(d=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;c=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:Xe(r.sourceDocument.content,d),action:"edited"}]]),...c!==void 0&&{afterWrite:c}}}}}s(ye,"createUndoMutationTool");function Xe(n,e){let t=[],r=0,o,i=0,d="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+i,insert:d}),o=void 0,i=0,d="")},"flush");for(let a of Qe(n,e)){if(!a.added&&!a.removed){c(),r+=a.value.length;continue}o??=r,a.removed?(r+=a.value.length,i+=a.value.length):d+=a.value}return c(),t}s(Xe,"createTextChanges");function qe(n){return Ze(n,de(n))}s(qe,"registerGitChanges");async function Ze(n,e){W(n,[await B({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new A,r=new G,o=le(e),i=ue(e),d={protocol:z,apiVersion:Q,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},c={protocol:Z,apiVersion:Y,id:"current-git-changes",setup(a){a.addAnchorResolver({...i,kind:I,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ye(e,t,r)),a.addTextPresenter({presenter:o})}};await Promise.all([V(n,ae),K(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
@@ -1 +1 @@
1
- import{b as d,g,h as c}from"./chunk-EY65TFHJ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readFile as p}from"node:fs/promises";import a from"node:path";import{Type as i}from"typebox";import{Value as f}from"typebox/value";var S=i.Object({targets:i.Array(i.Object({id:i.String(),host:i.String(),workspace:i.String(),configFile:i.Optional(i.String({minLength:1}))},{additionalProperties:!1}))},{additionalProperties:!1});function T(o){return{globalPath:a.join(a.dirname(o.globalPath),"ssh.json"),projectPath:a.join(a.dirname(o.projectPath),"ssh.json")}}s(T,"resolveSshConfigPaths");async function j(o){let r=await h(o.globalPath),t=await h(o.projectPath),e=new Map(r.map(n=>[n.id,n]));for(let n of t)e.set(n.id,n);return[...e.values()]}s(j,"readSshTargets");async function h(o){let r;try{r=await p(o,"utf8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return[];throw new Error(`Cannot read SSH settings at ${o}`,{cause:t})}try{let t=JSON.parse(r);if(!f.Check(S,t))throw new Error("Invalid settings");return u(t,o)}catch{throw new Error(`Invalid SSH settings at ${o}`)}}s(h,"readScope");function u(o,r){let t=new Set;return o.targets.map(e=>{if(t.has(e.id))throw new Error("Duplicate target");t.add(e.id);let n={id:e.id,host:e.host,workspace:e.workspace,...e.configFile===void 0?{}:{configFile:a.resolve(a.dirname(r),e.configFile)}};return new c(n).target})}s(u,"validateScope");var l=class{static{s(this,"SshBackendRegistry")}#t=new Map;constructor(r){for(let t of r){if(this.#t.has(t.id))throw new TypeError(`Duplicate SSH target: ${t.id}`);this.#t.set(t.id,new c(t))}}resolve(r,t){let e=d(r,t);if(!e)return;let n=this.#t.get(e.target);if(!n)throw new g("UNKNOWN_TARGET",e.source,"not-applied");return{location:e,backend:n}}};export{T as a,j as b,l as c};
1
+ import{b as d,g,h as c}from"./chunk-4HWKBCBH.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readFile as p}from"node:fs/promises";import a from"node:path";import{Type as i}from"typebox";import{Value as f}from"typebox/value";var S=i.Object({targets:i.Array(i.Object({id:i.String(),host:i.String(),workspace:i.String(),configFile:i.Optional(i.String({minLength:1}))},{additionalProperties:!1}))},{additionalProperties:!1});function T(o){return{globalPath:a.join(a.dirname(o.globalPath),"ssh.json"),projectPath:a.join(a.dirname(o.projectPath),"ssh.json")}}s(T,"resolveSshConfigPaths");async function j(o){let r=await h(o.globalPath),t=await h(o.projectPath),e=new Map(r.map(n=>[n.id,n]));for(let n of t)e.set(n.id,n);return[...e.values()]}s(j,"readSshTargets");async function h(o){let r;try{r=await p(o,"utf8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return[];throw new Error(`Cannot read SSH settings at ${o}`,{cause:t})}try{let t=JSON.parse(r);if(!f.Check(S,t))throw new Error("Invalid settings");return u(t,o)}catch{throw new Error(`Invalid SSH settings at ${o}`)}}s(h,"readScope");function u(o,r){let t=new Set;return o.targets.map(e=>{if(t.has(e.id))throw new Error("Duplicate target");t.add(e.id);let n={id:e.id,host:e.host,workspace:e.workspace,...e.configFile===void 0?{}:{configFile:a.resolve(a.dirname(r),e.configFile)}};return new c(n).target})}s(u,"validateScope");var l=class{static{s(this,"SshBackendRegistry")}#t=new Map;constructor(r){for(let t of r){if(this.#t.has(t.id))throw new TypeError(`Duplicate SSH target: ${t.id}`);this.#t.set(t.id,new c(t))}}resolve(r,t){let e=d(r,t);if(!e)return;let n=this.#t.get(e.target);if(!n)throw new g("UNKNOWN_TARGET",e.source,"not-applied");return{location:e,backend:n}}};export{T as a,j as b,l as c};
@@ -1 +1 @@
1
- import{g as u,h as E,m as a}from"./chunk-ICDI27GZ.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-TGC2ZACO.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
@@ -1 +1 @@
1
- import{a as f}from"./chunk-OJX3RJ5A.js";import{a as d}from"./chunk-XZDOVPRC.js";import{g as m}from"./chunk-EY65TFHJ.js";import{a as c}from"./chunk-EI7MMDWY.js";import l from"node:path";function k(p){return{async run(t,e){e.signal?.throwIfAborted();let r=p.resolve(e.projectRoot),n=p.resolve(e.filePath);if(!r||!n||r.location.target!==n.location.target)throw new m("UNSUPPORTED_SOURCE",e.filePath,"not-applied");let o=r.location.path,s=n.location.path,u=c(a=>a.replaceAll("{project}",o).replaceAll("{fileDir}",l.posix.dirname(s)).replaceAll("{relativeFile}",l.posix.relative(o,s)).replaceAll("{file}",s),"expand"),h=t.command.map(u),g=await f(r.backend,o,t.env,e.signal);e.signal?.throwIfAborted();let i=await d({...r.backend.target,workspace:t.cwd==="file"?l.posix.dirname(s):o},"env",[...Object.entries(g).map(([a,w])=>`${a}=${w}`),...h],e.filePath,{signal:e.signal,timeoutMs:t.timeoutMs??3e4,maxBytes:20*1024*1024,closeInput:!0,effect:"unknown"});return{ok:(t.successExitCodes??[0]).includes(i.exitCode),exitCode:i.exitCode,stdout:i.stdout.toString("utf8"),stderr:i.stderr.toString("utf8")}}}}c(k,"createSshConfiguredProcessAccess");export{k as a};
1
+ import{a as f}from"./chunk-WPBQ45ZL.js";import{a as d}from"./chunk-WXGTU2M6.js";import{g as m}from"./chunk-4HWKBCBH.js";import{a as c}from"./chunk-EI7MMDWY.js";import l from"node:path";function k(p){return{async run(t,e){e.signal?.throwIfAborted();let r=p.resolve(e.projectRoot),n=p.resolve(e.filePath);if(!r||!n||r.location.target!==n.location.target)throw new m("UNSUPPORTED_SOURCE",e.filePath,"not-applied");let o=r.location.path,s=n.location.path,u=c(a=>a.replaceAll("{project}",o).replaceAll("{fileDir}",l.posix.dirname(s)).replaceAll("{relativeFile}",l.posix.relative(o,s)).replaceAll("{file}",s),"expand"),h=t.command.map(u),g=await f(r.backend,o,t.env,e.signal);e.signal?.throwIfAborted();let i=await d({...r.backend.target,workspace:t.cwd==="file"?l.posix.dirname(s):o},"env",[...Object.entries(g).map(([a,w])=>`${a}=${w}`),...h],e.filePath,{signal:e.signal,timeoutMs:t.timeoutMs??3e4,maxBytes:20*1024*1024,closeInput:!0,effect:"unknown"});return{ok:(t.successExitCodes??[0]).includes(i.exitCode),exitCode:i.exitCode,stdout:i.stdout.toString("utf8"),stderr:i.stderr.toString("utf8")}}}}c(k,"createSshConfiguredProcessAccess");export{k as a};
@@ -0,0 +1,2 @@
1
+ import{b as k,e as f}from"./chunk-YTYLS2UM.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,r,o,i,a=[],l=[]){let c=a.map(t=>({kind:"note",text:t}));c.push(...b(e.flatMap(t=>{let p=h.isAbsolute(t.source),D=p&&i?h.relative(i,t.source)||h.basename(t.source):t.source,z=p?T(t.source).href:/^https?:/iu.test(t.source)?t.source:void 0,x=t.endLineNumber??t.lineNumber;return(x===t.lineNumber?[t.lineText]:[t.lineText,...t.matchedText.split(/\r\n|\n|\r/u).slice(1)]).slice(0,20).map((R,m)=>({source:t.source,label:D,...z===void 0?{}:{link:z},...p?{}:{badge:t.source.startsWith("docs:")?"DOC":/^https?:/iu.test(t.source)?"WEB":"SH"},lineNumber:t.lineNumber+m,text:R,ranges:[{from:m?0:t.startColumn,to:t.lineNumber+m===x?t.endColumn:R.length}]}))}))),e.length||c.push({kind:"note",text:"No matches found"}),e.some(t=>(t.endLineNumber??t.lineNumber)-t.lineNumber>=20)&&c.push({kind:"note",text:"\u2026 source preview shortened"}),c.push(...l.map(t=>({kind:"note",text:t,expandedOnly:!0})));let u=`${e.length}${n?"":"+"}`,y=new Set(e.map(t=>t.source)),F=e.length>0&&e.every(t=>h.isAbsolute(t.source));return new v({summary:`${u} ${e.length===1?"match":"matches"} in ${y.size} ${F?y.size===1?"file":"files":y.size===1?"source":"sources"}`,rows:c},r,o)}s(P,"renderSearchMatches");function $(e,n){return e.targets.some(r=>r.source===n.source&&r.ranges.some(o=>(o.start.lineNumber<n.lineNumber||o.start.lineNumber===n.lineNumber&&o.start.column<=n.startColumn)&&(o.end.lineNumber>(n.endLineNumber??n.lineNumber)||o.end.lineNumber===(n.endLineNumber??n.lineNumber)&&o.end.column>=n.endColumn)))}s($,"containsSearchMatch");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 I(e){return N.Check(k,e)}s(I,"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 r of n.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/gu))if(this.add(r[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((r,o)=>r===n[o])}s(C,"same");function L(e,n){if(e.length<5||n.length<5||Math.abs(e.length-n.length)>1||/\d/u.test(e+n))return!1;let r=0;for(;r<Math.min(e.length,n.length)&&e[r]===n[r];)r++;if(e.length===n.length)return e.slice(r+1)===n.slice(r+1)||e[r]===n[r+1]&&e[r+1]===n[r]&&e.slice(r+2)===n.slice(r+2);let o=e.length<n.length?e:n,i=e.length<n.length?n:e;return o.slice(r)===i.slice(r+1)}s(L,"oneTypo");function M(e,n){if(e.join("")===n.join(""))return{kind:"normalized",reason:"same spelling with different case or separators"};let r=e.length<n.length?e:n,o=e.length<n.length?n:e;if(o.length===r.length+1&&r.length>=2&&r.every(l=>l.length>=3)){let l=C(r,o.slice(1)),c=C(r,o.slice(0,-1));if(l||c)return{kind:"component",reason:`${e.length>n.length?"remove":"add"} ${l?"leading":"trailing"} component '${l?o[0]:o.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||!L(a.word,a.other)))return{kind:"typo",reason:`one character edit: '${a.word}' \u2192 '${a.other}'`}}s(M,"relation");var A={normalized:0,component:1,typo:2};function E(e,n){if(!g(e))return[];let r=w(e);if(r.length===0)return[];let o=[];for(let i of new Set(n)){if(i===e||!g(i))continue;let a=M(r,w(i));a&&o.push({identifier:i,...a})}return o.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(E,"rankFuzzyIdentifiers");function _(e,n,r){return{identifier:e.identifier,kind:e.kind,reason:e.reason,matchCount:e.matches.length,fileCount:new Set(e.matches.map(o=>o.source)).size,selection:{...f(e.matches.slice(0,d.previewMatches),e.complete,n,r),truncated:e.matches.length>d.previewMatches}}}s(_,"fuzzyCandidateData");function O(e){let n=e.selection.complete?"":"+",r=e.selection.all?.line??e.selection.matches[0]?.references?.line,o=e.selection.matches[0],i=r??o?.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}${r||!o?"":` \xB7 line ${o.range.startLine}`}`]:[]].join(`
2
+ `)}s(O,"formatFuzzyCandidate");export{P as a,$ as b,d as c,I as d,g as e,S as f,E as g,_ as h,O as i};
@@ -1 +1 @@
1
- import{f as T,i as m,j as M}from"./chunk-R5XJSEOE.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var E=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),b=o.Object({source:o.String(),effect:E,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),L={effect:E,files:o.Array(b)};function R(n){return o.Object({operation:o.Literal(n),...L,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function v(n){return T(R(n))}p(v,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,h=[]){let r=n.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:c,effect:"pending",...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(t=>t.resourceSource)),s=[],f=[],y=r.results;for(let t of y??[]){let e=t.data,k=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of k)f.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(A=>A.path===i)?"applied":e.rollback?.failedSources.includes(i)?"unknown":e.rollback?.restoredSources.includes(i)?"not-applied":r.effect??"unknown"});for(let i of e.errors??[])s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});e.ok===!1&&(e.errors?.length??0)===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed",...e.path?{source:e.path}:{}})}for(let t of g)f.some(e=>e.source===t)||f.push({source:t,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let t=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",e=typeof a.source=="string"?a.source:void 0;e&&f.push({source:e,...a.kind==="file-operation"&&a.ok===!0?{state:c==="delete"||c==="move"?"absent":"present"}:{},effect:c==="copy"&&typeof a.target=="string"&&a.target!==e?"not-applied":t}),typeof a.target=="string"&&f.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(m(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(m("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(f.map(t=>[t.source,t])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let t of r.metadata.resultFileStates){if(!u(t))continue;let e=d.find(k=>k.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let S=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(y?.length??0)===0&&!a&&g.size===0&&s.length===0&&r.effect!=="not-applied"&&s.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":S?"applied":"not-applied";return{status:s.length===0?"success":!a&&S&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:w,files:d,...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...c!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:s}}p(U,"mutationOutcome");function F(n,c,h=[],r){let l=U(n,c,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(n,R(c),l)}p(F,"structuredMutation");export{R as a,v as b,U as c,F as d};
1
+ import{f as T,i as m,j as M}from"./chunk-DXONCYWF.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var E=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),b=o.Object({source:o.String(),effect:E,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),L={effect:E,files:o.Array(b)};function R(n){return o.Object({operation:o.Literal(n),...L,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function v(n){return T(R(n))}p(v,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,h=[]){let r=n.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:c,effect:"pending",...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(t=>t.resourceSource)),s=[],f=[],y=r.results;for(let t of y??[]){let e=t.data,k=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of k)f.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(A=>A.path===i)?"applied":e.rollback?.failedSources.includes(i)?"unknown":e.rollback?.restoredSources.includes(i)?"not-applied":r.effect??"unknown"});for(let i of e.errors??[])s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});e.ok===!1&&(e.errors?.length??0)===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed",...e.path?{source:e.path}:{}})}for(let t of g)f.some(e=>e.source===t)||f.push({source:t,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let t=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",e=typeof a.source=="string"?a.source:void 0;e&&f.push({source:e,...a.kind==="file-operation"&&a.ok===!0?{state:c==="delete"||c==="move"?"absent":"present"}:{},effect:c==="copy"&&typeof a.target=="string"&&a.target!==e?"not-applied":t}),typeof a.target=="string"&&f.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(m(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(m("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(f.map(t=>[t.source,t])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let t of r.metadata.resultFileStates){if(!u(t))continue;let e=d.find(k=>k.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let S=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(y?.length??0)===0&&!a&&g.size===0&&s.length===0&&r.effect!=="not-applied"&&s.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":S?"applied":"not-applied";return{status:s.length===0?"success":!a&&S&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:w,files:d,...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...c!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:s}}p(U,"mutationOutcome");function F(n,c,h=[],r){let l=U(n,c,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(n,R(c),l)}p(F,"structuredMutation");export{R as a,v as b,U as c,F as d};
@@ -1,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-EY65TFHJ.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-4HWKBCBH.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};