pi-agent-ide 0.8.4 → 0.9.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 (649) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +24 -29
  3. package/dist/{chunk-CM3XGY72.js → chunk-2AY526TN.js} +1 -1
  4. package/dist/{chunk-LEJKDYCK.js → chunk-2TZDG2JH.js} +1 -1
  5. package/dist/{chunk-DUUOCBS3.js → chunk-35LZOKEW.js} +1 -1
  6. package/dist/chunk-3LVBARLW.js +33 -0
  7. package/dist/{chunk-XBQR74IK.js → chunk-4GBFIGH3.js} +1 -1
  8. package/dist/{chunk-PJL3UVMJ.js → chunk-4IWEKRSP.js} +1 -1
  9. package/dist/chunk-52PFWQMU.js +5 -0
  10. package/dist/chunk-5BGWNYQS.js +1 -0
  11. package/dist/chunk-5PC5INOL.js +1 -0
  12. package/dist/{chunk-QUYXINGZ.js → chunk-5S74Z6Y4.js} +3 -3
  13. package/dist/{chunk-XAHU42FP.js → chunk-6A3ORNW3.js} +2 -2
  14. package/dist/{chunk-ANM3Y5FO.js → chunk-6WCHBHFW.js} +5 -5
  15. package/dist/{chunk-IMGIDBCC.js → chunk-7D7PXIVV.js} +1 -1
  16. package/dist/chunk-7PVDTMEM.js +1 -0
  17. package/dist/chunk-AMIIOWFL.js +1 -0
  18. package/dist/{chunk-TOYN4W4F.js → chunk-B25LXXNV.js} +1 -1
  19. package/dist/chunk-BT2CFM7D.js +11 -0
  20. package/dist/chunk-C2JT2G5K.js +1 -0
  21. package/dist/chunk-DDH3FP4G.js +3 -0
  22. package/dist/{chunk-6T7PSDQW.js → chunk-DVNL5NZE.js} +1 -1
  23. package/dist/chunk-FEZLTM4L.js +1 -0
  24. package/dist/{chunk-CPELC6JE.js → chunk-FHRHYY4M.js} +1 -1
  25. package/dist/chunk-FXPY3V4L.js +10 -0
  26. package/dist/chunk-FYOU4RBH.js +2 -0
  27. package/dist/chunk-G4PRFO6G.js +1 -0
  28. package/dist/chunk-GS5ZRTUG.js +1 -0
  29. package/dist/{chunk-XXLLY66B.js → chunk-GXL4NMHR.js} +1 -1
  30. package/dist/{chunk-QT3EAHOG.js → chunk-H3GEEOOL.js} +1 -1
  31. package/dist/chunk-H5Z54BEU.js +25 -0
  32. package/dist/chunk-H7WAM5RH.js +23 -0
  33. package/dist/{chunk-Z2MNHSJ4.js → chunk-HGCJDIRR.js} +1 -1
  34. package/dist/chunk-HISGZD3C.js +81 -0
  35. package/dist/chunk-HKYVP2Q6.js +3 -0
  36. package/dist/chunk-HRBUY2FF.js +4 -0
  37. package/dist/chunk-IG5DXVDJ.js +1 -0
  38. package/dist/chunk-IOGWZNWT.js +1 -0
  39. package/dist/chunk-IUJUECXH.js +9 -0
  40. package/dist/chunk-KN6VPARZ.js +1 -0
  41. package/dist/{chunk-RW2GTYQI.js → chunk-LF325WYO.js} +1 -1
  42. package/dist/chunk-LXDF2NWX.js +1 -0
  43. package/dist/{chunk-YJ6T3PEP.js → chunk-MDD5ORB6.js} +1 -1
  44. package/dist/{chunk-S72FVLUX.js → chunk-MLFJU2US.js} +1 -1
  45. package/dist/chunk-MPNE25CY.js +5 -0
  46. package/dist/chunk-NA2NEU4V.js +1 -0
  47. package/dist/{chunk-ZJQRLVVV.js → chunk-O7V6G3OO.js} +1 -1
  48. package/dist/chunk-OBTT5INC.js +6 -0
  49. package/dist/{chunk-IICJXZBU.js → chunk-OMNKD7WW.js} +3 -3
  50. package/dist/chunk-OUCVZBOR.js +28 -0
  51. package/dist/chunk-PCGBM2D6.js +17 -0
  52. package/dist/{chunk-235QMMVA.js → chunk-PQWANILR.js} +1 -1
  53. package/dist/{chunk-QRJLIV6P.js → chunk-QJ6V5IAY.js} +6 -6
  54. package/dist/{chunk-SMIFCAAX.js → chunk-RIJRPAL2.js} +1 -1
  55. package/dist/chunk-RIOPUTUJ.js +6 -0
  56. package/dist/{chunk-RMI3NMQY.js → chunk-RIZARTUM.js} +2 -2
  57. package/dist/{chunk-NJ7C4KMA.js → chunk-SRFWT562.js} +1 -1
  58. package/dist/{chunk-U22JNO6N.js → chunk-STUZZM5B.js} +1 -1
  59. package/dist/chunk-T3Z4KXOX.js +2 -0
  60. package/dist/chunk-TSQ6FBTB.js +1 -0
  61. package/dist/chunk-U7YDLVFL.js +1 -0
  62. package/dist/{chunk-KZC7TI5M.js → chunk-UD3DMY3Q.js} +1 -1
  63. package/dist/{chunk-VXP5BMW7.js → chunk-USG6WHAT.js} +1 -1
  64. package/dist/{chunk-ZPT5D4VP.js → chunk-VDJSH3DQ.js} +2 -2
  65. package/dist/{chunk-VMTOFEXF.js → chunk-VMLPXSMK.js} +1 -1
  66. package/dist/chunk-VNWGT367.js +1 -0
  67. package/dist/chunk-WAJW4G4F.js +22 -0
  68. package/dist/chunk-WEE3NM6L.js +1 -0
  69. package/dist/{chunk-IM24DB3K.js → chunk-WES2E4VR.js} +1 -1
  70. package/dist/{chunk-RIJMXO43.js → chunk-WQIMM4SU.js} +1 -1
  71. package/dist/chunk-X2WFNMQR.js +9 -0
  72. package/dist/chunk-XCPIIDFS.js +4 -0
  73. package/dist/chunk-XE4W5YTE.js +2 -0
  74. package/dist/chunk-XUYIK4TX.js +1 -0
  75. package/dist/{chunk-AAC77UD4.js → chunk-YPYROPQF.js} +1 -1
  76. package/dist/chunk-ZXO4D5UB.js +1 -0
  77. package/dist/entry-0.js +1 -1
  78. package/dist/entry-1.js +1 -1
  79. package/dist/entry-10.js +1 -1
  80. package/dist/entry-11.js +1 -1
  81. package/dist/entry-12.js +1 -1
  82. package/dist/entry-13.js +1 -1
  83. package/dist/entry-14.js +1 -1
  84. package/dist/entry-15.js +1 -1
  85. package/dist/entry-16.js +1 -1
  86. package/dist/entry-17.js +1 -1
  87. package/dist/entry-18.js +1 -1
  88. package/dist/entry-19.js +1 -1
  89. package/dist/entry-2.js +1 -1
  90. package/dist/entry-20.js +1 -1
  91. package/dist/entry-21.js +1 -0
  92. package/dist/entry-22.js +1 -1
  93. package/dist/entry-24.js +1 -1
  94. package/dist/entry-25.js +1 -1
  95. package/dist/entry-26.js +1 -1
  96. package/dist/entry-27.js +1 -1
  97. package/dist/entry-28.js +1 -1
  98. package/dist/entry-29.js +1 -2
  99. package/dist/entry-3.js +1 -1
  100. package/dist/entry-30.js +1 -1
  101. package/dist/entry-31.js +2 -4
  102. package/dist/entry-32.js +1 -1
  103. package/dist/entry-33.js +1 -1
  104. package/dist/entry-34.js +1 -1
  105. package/dist/entry-35.js +1 -18
  106. package/dist/entry-36.js +1 -1
  107. package/dist/entry-37.js +1 -1
  108. package/dist/entry-38.js +15 -1
  109. package/dist/entry-39.js +1 -1
  110. package/dist/entry-4.js +1 -1
  111. package/dist/entry-40.js +1 -1
  112. package/dist/entry-41.js +1 -1
  113. package/dist/entry-42.js +1 -1
  114. package/dist/entry-43.js +1 -1
  115. package/dist/entry-44.js +1 -1
  116. package/dist/entry-45.js +1 -1
  117. package/dist/entry-46.js +1 -1
  118. package/dist/entry-47.js +1 -1
  119. package/dist/entry-48.js +1 -1
  120. package/dist/entry-49.js +1 -25
  121. package/dist/entry-5.js +1 -1
  122. package/dist/entry-50.js +1 -1
  123. package/dist/entry-51.js +1 -1
  124. package/dist/entry-52.js +1 -1
  125. package/dist/entry-53.js +1 -1
  126. package/dist/entry-54.js +1 -3
  127. package/dist/entry-55.js +1 -13
  128. package/dist/entry-56.js +1 -1
  129. package/dist/entry-57.js +1 -1
  130. package/dist/entry-58.js +1 -1
  131. package/dist/entry-59.js +1 -1
  132. package/dist/entry-6.js +1 -1
  133. package/dist/entry-60.js +1 -1
  134. package/dist/entry-61.js +1 -1
  135. package/dist/entry-62.js +1 -1
  136. package/dist/entry-63.js +1 -1
  137. package/dist/entry-64.js +1 -1
  138. package/dist/entry-65.js +1 -0
  139. package/dist/entry-66.js +1 -1
  140. package/dist/entry-67.js +1 -0
  141. package/dist/entry-68.js +0 -1
  142. package/dist/entry-69.js +1 -1
  143. package/dist/entry-7.js +1 -1
  144. package/dist/entry-70.js +0 -1
  145. package/dist/entry-71.js +1 -1
  146. package/dist/entry-72.js +1 -1
  147. package/dist/entry-73.js +1 -1
  148. package/dist/entry-74.js +1 -1
  149. package/dist/entry-75.js +1 -0
  150. package/dist/entry-76.js +1 -1
  151. package/dist/entry-77.js +1 -0
  152. package/dist/entry-78.js +0 -1
  153. package/dist/entry-79.js +1 -1
  154. package/dist/entry-8.js +1 -1
  155. package/dist/entry-80.js +0 -1
  156. package/dist/entry-81.js +1 -80
  157. package/dist/entry-82.js +1 -22
  158. package/dist/entry-83.js +1 -2
  159. package/dist/entry-84.js +1 -1
  160. package/dist/entry-85.js +1 -1
  161. package/dist/entry-86.js +2 -1
  162. package/dist/entry-87.js +1 -1
  163. package/dist/entry-88.js +1 -3
  164. package/dist/entry-89.js +1 -1
  165. package/dist/entry-9.js +1 -1
  166. package/dist/entry-90.js +1 -1
  167. package/dist/entry-91.js +3 -1
  168. package/dist/entry-92.js +1 -0
  169. package/dist/entry-93.js +1 -0
  170. package/dist/entry-94.js +1 -0
  171. package/dist/pi-agent-ide.js +13 -34
  172. package/docs/agent-guides/ast-search.md +58 -0
  173. package/docs/agent-guides/debugger.md +1 -1
  174. package/docs/agent-guides/editing.md +29 -58
  175. package/docs/agent-guides/git-changes.md +4 -14
  176. package/docs/agent-guides/search.md +38 -0
  177. package/docs/agent-guides/ssh.md +17 -49
  178. package/docs/agent-guides/terminal.md +9 -15
  179. package/docs/configuration.md +9 -13
  180. package/docs/extensions.md +82 -0
  181. package/docs/settings-help.md +2 -2
  182. package/docs/structured-results.md +33 -11
  183. package/docs/tools.md +24 -23
  184. package/node_modules/pi-agent-doctor/package.json +7 -7
  185. package/node_modules/pi-agent-doctor/runtime/entry-29.js +1 -0
  186. package/node_modules/pi-agent-doctor/src/workspace.ts +0 -5
  187. package/node_modules/pi-agent-documentation/package.json +2 -2
  188. package/node_modules/pi-agent-documentation/runtime/entry-30.js +1 -0
  189. package/node_modules/pi-agent-documentation/src/index.ts +26 -10
  190. package/node_modules/pi-agent-filesystem/index.ts +1 -1
  191. package/node_modules/pi-agent-filesystem/package.json +8 -8
  192. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  193. package/node_modules/pi-agent-filesystem-jq/index.ts +9 -63
  194. package/node_modules/pi-agent-filesystem-jq/package.json +12 -6
  195. package/node_modules/pi-agent-filesystem-jq/runtime/entry-33.js +1 -0
  196. package/node_modules/pi-agent-filesystem-jq/runtime/entry-34.js +2 -0
  197. package/node_modules/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  198. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  199. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  200. package/node_modules/pi-agent-filesystem-text/runtime/entry-36.js +2 -0
  201. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  202. package/node_modules/pi-agent-ide-ast/runtime/entry-37.js +1 -0
  203. package/node_modules/pi-agent-ide-ast/src/extension.ts +8 -8
  204. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  205. package/node_modules/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  206. package/node_modules/pi-agent-ide-changes/index.ts +1 -2
  207. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  208. package/node_modules/pi-agent-ide-changes/runtime/entry-39.js +1 -0
  209. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  210. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  211. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  212. package/node_modules/pi-agent-ide-languages/runtime/entry-42.js +2 -0
  213. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  214. package/node_modules/pi-agent-ide-lint/runtime/entry-43.js +2 -0
  215. package/node_modules/pi-agent-ide-lsp/index.ts +22 -28
  216. package/node_modules/pi-agent-ide-lsp/package.json +14 -10
  217. package/node_modules/pi-agent-ide-lsp/runtime/entry-44.js +2 -0
  218. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  219. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  220. package/node_modules/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  221. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  222. package/node_modules/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  223. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  224. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  225. package/node_modules/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  226. package/node_modules/pi-agent-image/package.json +3 -3
  227. package/node_modules/pi-agent-image/src/image-converter.ts +24 -1
  228. package/node_modules/pi-agent-invariant/package.json +2 -2
  229. package/node_modules/pi-agent-pdf/package.json +3 -3
  230. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +23 -1
  231. package/node_modules/pi-agent-read/package.json +12 -12
  232. package/node_modules/pi-agent-read/runtime/entry-49.js +0 -1
  233. package/node_modules/pi-agent-read/runtime/entry-52.js +2 -0
  234. package/node_modules/pi-agent-read/src/api/read-parameters.ts +4 -7
  235. package/node_modules/pi-agent-read/src/api/tools/read.ts +2 -0
  236. package/node_modules/pi-agent-read/src/core/extension.ts +0 -8
  237. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  238. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  239. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  240. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  241. package/node_modules/pi-agent-resource/package.json +2 -2
  242. package/node_modules/pi-agent-resource/src/index.ts +8 -0
  243. package/node_modules/pi-agent-resource/src/resource-error-metadata.ts +89 -0
  244. package/node_modules/pi-agent-resource/src/resource-error.ts +6 -1
  245. package/node_modules/pi-agent-resource/src/result-images.ts +87 -0
  246. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -3
  247. package/node_modules/pi-agent-resource/src/tool-result.ts +17 -0
  248. package/node_modules/pi-agent-search/package.json +9 -9
  249. package/node_modules/pi-agent-search/runtime/entry-54.js +0 -1
  250. package/node_modules/pi-agent-search/runtime/entry-55.js +1 -0
  251. package/node_modules/pi-agent-search/runtime/entry-57.js +2 -0
  252. package/node_modules/pi-agent-search/src/api/glob-list.ts +35 -0
  253. package/node_modules/pi-agent-search/src/api/search-parameters.ts +8 -8
  254. package/node_modules/pi-agent-search/src/api/search.ts +14 -2
  255. package/node_modules/pi-agent-search/src/core/extension.ts +11 -20
  256. package/node_modules/pi-agent-search/src/core/search-core.ts +30 -10
  257. package/node_modules/pi-agent-search-text/index.ts +34 -12
  258. package/node_modules/pi-agent-search-text/package.json +17 -15
  259. package/node_modules/pi-agent-search-text/runtime/entry-58.js +1 -0
  260. package/node_modules/pi-agent-search-text/runtime/entry-60.js +1 -0
  261. package/node_modules/pi-agent-search-text/src/file-search.ts +59 -25
  262. package/node_modules/pi-agent-search-text/src/resolvers.ts +61 -16
  263. package/node_modules/pi-agent-search-text/src/scoped-search.ts +9 -3
  264. package/node_modules/pi-agent-search-text/src/search-backend.ts +44 -48
  265. package/node_modules/pi-agent-search-text/src/search-presentation.ts +19 -15
  266. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -1
  267. package/node_modules/pi-agent-search-text/src/search-result.ts +6 -2
  268. package/node_modules/pi-agent-search-text/src/search-session.ts +1 -0
  269. package/node_modules/pi-agent-search-text/src/tool-file-search.ts +146 -0
  270. package/node_modules/pi-agent-text/package.json +3 -3
  271. package/node_modules/pi-agent-text/runtime/entry-62.js +1 -0
  272. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  273. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  274. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-63.js +2 -0
  275. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  276. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-64.js +1 -0
  277. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-65.js +2 -0
  278. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  279. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +1 -2
  280. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  281. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-67.js +2 -0
  282. package/node_modules/pi-agent-text-editor/package.json +26 -26
  283. package/node_modules/pi-agent-text-editor/runtime/entry-81.js +0 -1
  284. package/node_modules/pi-agent-text-editor/runtime/entry-82.js +1 -0
  285. package/node_modules/pi-agent-text-editor/runtime/entry-83.js +1 -0
  286. package/node_modules/pi-agent-text-editor/runtime/entry-84.js +2 -0
  287. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  288. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  289. package/node_modules/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  290. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  291. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  292. package/node_modules/pi-agent-text-editor/src/core/extension.ts +13 -7
  293. package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  294. package/node_modules/pi-agent-text-editor/src/core/image-write.ts +111 -0
  295. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  296. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +2 -6
  297. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  298. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +17 -36
  299. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  300. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  301. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  302. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  303. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +63 -74
  304. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  305. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +7 -10
  306. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +4 -10
  307. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +8 -8
  308. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +5 -8
  309. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  310. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  311. package/node_modules/pi-agent-text-editor-renderer/index.ts +6 -1
  312. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  313. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-85.js +2 -0
  314. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  315. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -6
  316. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-86.js +2 -0
  317. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  318. package/node_modules/pi-agent-tool-call-interception/runtime/entry-87.js +1 -0
  319. package/node_modules/pi-agent-tool-ui/package.json +3 -3
  320. package/node_modules/pi-agent-tool-ui/runtime/entry-88.js +1 -0
  321. package/node_modules/pi-agent-tool-ui/runtime/entry-89.js +1 -0
  322. package/node_modules/pi-agent-web/index.ts +28 -6
  323. package/node_modules/pi-agent-web/package.json +8 -8
  324. package/node_modules/pi-agent-web-html/package.json +3 -3
  325. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  326. package/node_modules/pi-agent-web-image/package.json +4 -4
  327. package/node_modules/pi-agent-web-image/runtime/entry-92.js +2 -0
  328. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  329. package/node_modules/pi-agent-web-pdf/runtime/entry-93.js +2 -0
  330. package/node_modules/pi-agent-web-text/package.json +4 -4
  331. package/node_modules/pi-agent-web-text/runtime/entry-94.js +2 -0
  332. package/package.json +65 -58
  333. package/src/api/approval.ts +2 -0
  334. package/src/api/capabilities.ts +60 -0
  335. package/src/api/read.ts +2 -0
  336. package/src/api/standalone.ts +7 -0
  337. package/src/backend/doctor-workspace.ts +0 -3
  338. package/src/backend/process-metadata-worker.py +9 -18
  339. package/src/backend/process-metadata.ts +11 -44
  340. package/src/backend/registration.ts +0 -10
  341. package/src/backend/web-browser-worker.mjs +2 -17
  342. package/src/backend/web-browser.ts +1 -26
  343. package/src/composite/builtin-extensions.ts +8 -6
  344. package/src/composite/capabilities.ts +252 -0
  345. package/src/composite/capability-schemas.ts +53 -0
  346. package/src/composite/ide-alias-rendering.ts +18 -2
  347. package/src/composite/module-labels.ts +0 -4
  348. package/src/composite/preferences.ts +0 -36
  349. package/src/composite/responses-tools.ts +27 -9
  350. package/src/composite/settings-documentation.ts +1 -2
  351. package/src/composite/text-results.ts +61 -23
  352. package/src/composite/tool-availability.ts +28 -13
  353. package/src/documentation/extension.ts +39 -15
  354. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +1 -1
  355. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  356. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  357. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +9 -63
  358. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +12 -6
  359. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-33.js +1 -0
  360. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-34.js +2 -0
  361. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  362. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  363. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-35.js +2 -0
  364. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  365. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-36.js +2 -0
  366. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-31.js +2 -0
  367. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -6
  368. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  369. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  370. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  371. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  372. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-92.js +2 -0
  373. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  374. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-93.js +2 -0
  375. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  376. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-94.js +2 -0
  377. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-90.js +2 -0
  378. package/src/extensions/pi-agent-read/package.json +12 -12
  379. package/src/extensions/pi-agent-read/runtime/entry-49.js +0 -1
  380. package/src/extensions/pi-agent-read/runtime/entry-50.js +1 -0
  381. package/src/extensions/pi-agent-read/runtime/entry-52.js +2 -0
  382. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +4 -7
  383. package/src/extensions/pi-agent-read/src/api/tools/read.ts +2 -0
  384. package/src/extensions/pi-agent-read/src/core/extension.ts +0 -8
  385. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  386. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  387. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  388. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  389. package/src/extensions/pi-agent-search/package.json +9 -9
  390. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +34 -12
  391. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +17 -15
  392. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-58.js +1 -0
  393. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-59.js +1 -0
  394. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-60.js +1 -0
  395. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +59 -25
  396. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +61 -16
  397. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +9 -3
  398. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +44 -48
  399. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +19 -15
  400. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -1
  401. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +6 -2
  402. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +1 -0
  403. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/tool-file-search.ts +146 -0
  404. package/src/extensions/pi-agent-search/runtime/entry-54.js +0 -1
  405. package/src/extensions/pi-agent-search/runtime/entry-55.js +1 -0
  406. package/src/extensions/pi-agent-search/runtime/entry-56.js +1 -0
  407. package/src/extensions/pi-agent-search/runtime/entry-57.js +2 -0
  408. package/src/extensions/pi-agent-search/src/api/glob-list.ts +35 -0
  409. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +8 -8
  410. package/src/extensions/pi-agent-search/src/api/search.ts +14 -2
  411. package/src/extensions/pi-agent-search/src/core/extension.ts +11 -20
  412. package/src/extensions/pi-agent-search/src/core/search-core.ts +30 -10
  413. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  414. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  415. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-63.js +2 -0
  416. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  417. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-64.js +1 -0
  418. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-65.js +2 -0
  419. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  420. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +1 -2
  421. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  422. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-66.js +1 -0
  423. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-67.js +2 -0
  424. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +6 -1
  425. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  426. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-85.js +2 -0
  427. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  428. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -6
  429. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-86.js +2 -0
  430. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +0 -1
  431. package/src/extensions/pi-agent-text-editor/runtime/entry-82.js +1 -0
  432. package/src/extensions/pi-agent-text-editor/runtime/entry-83.js +1 -0
  433. package/src/extensions/pi-agent-text-editor/runtime/entry-84.js +2 -0
  434. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  435. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  436. package/src/extensions/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  437. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  438. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  439. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +13 -7
  440. package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  441. package/src/extensions/pi-agent-text-editor/src/core/image-write.ts +111 -0
  442. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  443. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +2 -6
  444. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  445. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +17 -36
  446. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  447. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  448. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  449. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  450. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +63 -74
  451. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  452. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +7 -10
  453. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +4 -10
  454. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +8 -8
  455. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +5 -8
  456. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  457. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  458. package/src/pi-agent-ide.ts +12 -16
  459. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  460. package/src/plugins/pi-agent-ide-ast/runtime/entry-37.js +1 -0
  461. package/src/plugins/pi-agent-ide-ast/src/extension.ts +8 -8
  462. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  463. package/src/plugins/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  464. package/src/plugins/pi-agent-ide-changes/index.ts +1 -2
  465. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  466. package/src/plugins/pi-agent-ide-changes/runtime/entry-39.js +1 -0
  467. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  468. package/src/plugins/pi-agent-ide-debugger/index.ts +31 -13
  469. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +2 -11
  470. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  471. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  472. package/src/plugins/pi-agent-ide-languages/runtime/entry-42.js +2 -0
  473. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  474. package/src/plugins/pi-agent-ide-lint/runtime/entry-43.js +2 -0
  475. package/src/plugins/pi-agent-ide-lsp/index.ts +22 -28
  476. package/src/plugins/pi-agent-ide-lsp/package.json +14 -10
  477. package/src/plugins/pi-agent-ide-lsp/runtime/entry-44.js +2 -0
  478. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  479. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  480. package/src/plugins/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  481. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  482. package/src/plugins/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  483. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  484. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  485. package/src/plugins/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  486. package/src/plugins/pi-agent-ide-processes/src/ui.ts +61 -16
  487. package/src/plugins/pi-agent-ide-terminal/index.ts +43 -1
  488. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +0 -18
  489. package/src/plugins/pi-agent-ide-terminal/src/search.ts +0 -3
  490. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -3
  491. package/src/standalone/resource-host.ts +147 -0
  492. package/src/standalone/scoped-api.ts +457 -0
  493. package/dist/chunk-2RTCSZB3.js +0 -1
  494. package/dist/chunk-4DIUPEDF.js +0 -2
  495. package/dist/chunk-6EDOLYOV.js +0 -1
  496. package/dist/chunk-6FGLAVPJ.js +0 -1
  497. package/dist/chunk-6H32W35W.js +0 -1
  498. package/dist/chunk-6OJ565FL.js +0 -2
  499. package/dist/chunk-6R3Y4AD3.js +0 -1
  500. package/dist/chunk-6TJPMBUQ.js +0 -1
  501. package/dist/chunk-6XFUICD7.js +0 -1
  502. package/dist/chunk-BHSO2MDK.js +0 -6
  503. package/dist/chunk-GBUJOR6V.js +0 -28
  504. package/dist/chunk-GSOYVIQS.js +0 -1
  505. package/dist/chunk-HSRH76JN.js +0 -3
  506. package/dist/chunk-HSZ4AQ6L.js +0 -9
  507. package/dist/chunk-I6NPILT5.js +0 -1
  508. package/dist/chunk-K7SRNBIV.js +0 -1
  509. package/dist/chunk-LCWBVOII.js +0 -3
  510. package/dist/chunk-MKEC3U2M.js +0 -4
  511. package/dist/chunk-NUM3YQGK.js +0 -1
  512. package/dist/chunk-OM4LYD3S.js +0 -1
  513. package/dist/chunk-PLKYHUNT.js +0 -1
  514. package/dist/chunk-PT35ZFLH.js +0 -33
  515. package/dist/chunk-QIJMV2P2.js +0 -2
  516. package/dist/chunk-RVU73VKN.js +0 -2
  517. package/dist/chunk-SDAH3ECM.js +0 -5
  518. package/dist/chunk-SGQWRIRJ.js +0 -10
  519. package/dist/chunk-SWBJS3U4.js +0 -1
  520. package/dist/chunk-T7I2VX3J.js +0 -1
  521. package/dist/chunk-T7MWQQIF.js +0 -3
  522. package/dist/chunk-VDP5CQHM.js +0 -3
  523. package/dist/chunk-XG7QNAKW.js +0 -9
  524. package/dist/chunk-XLWCSJMR.js +0 -1
  525. package/dist/chunk-YFP4P2FV.js +0 -1
  526. package/dist/chunk-YIXP2ALP.js +0 -9
  527. package/dist/entry-23.js +0 -1
  528. package/docs/agent-guides/diagnostics.md +0 -5
  529. package/docs/agent-guides/json-reading.md +0 -57
  530. package/docs/agent-guides/read-resources.md +0 -17
  531. package/docs/agent-guides/search-code.md +0 -76
  532. package/docs/agent-guides/select-code.md +0 -119
  533. package/docs/agent-guides/vision.md +0 -11
  534. package/node_modules/pi-agent-doctor/runtime/entry-22.js +0 -1
  535. package/node_modules/pi-agent-doctor/runtime/entry-23.js +0 -1
  536. package/node_modules/pi-agent-filesystem/runtime/entry-29.js +0 -2
  537. package/node_modules/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  538. package/node_modules/pi-agent-filesystem-text/runtime/entry-33.js +0 -2
  539. package/node_modules/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  540. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  541. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  542. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  543. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  544. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  545. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +0 -387
  546. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +0 -41
  547. package/node_modules/pi-agent-ide-ast/src/source-text.ts +0 -92
  548. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +0 -214
  549. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +0 -277
  550. package/node_modules/pi-agent-ide-changes/runtime/entry-36.js +0 -1
  551. package/node_modules/pi-agent-ide-changes/runtime/entry-37.js +0 -2
  552. package/node_modules/pi-agent-ide-languages/runtime/entry-39.js +0 -2
  553. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  554. package/node_modules/pi-agent-image/runtime/entry-42.js +0 -1
  555. package/node_modules/pi-agent-invariant/runtime/entry-43.js +0 -1
  556. package/node_modules/pi-agent-pdf/runtime/entry-44.js +0 -1
  557. package/node_modules/pi-agent-search/runtime/entry-52.js +0 -1
  558. package/node_modules/pi-agent-search-text/runtime/entry-55.js +0 -2
  559. package/node_modules/pi-agent-search-text/runtime/entry-57.js +0 -1
  560. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  561. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-62.js +0 -2
  562. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-63.js +0 -1
  563. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-64.js +0 -2
  564. package/node_modules/pi-agent-text-editor/runtime/entry-65.js +0 -1
  565. package/node_modules/pi-agent-text-editor/runtime/entry-67.js +0 -1
  566. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  567. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  568. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +0 -1
  569. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +0 -1
  570. package/node_modules/pi-agent-tool-ui/runtime/entry-86.js +0 -1
  571. package/node_modules/pi-agent-web/runtime/entry-87.js +0 -2
  572. package/node_modules/pi-agent-web-html/runtime/entry-88.js +0 -2
  573. package/node_modules/pi-agent-web-image/runtime/entry-89.js +0 -2
  574. package/src/backend/vision-capture-worker.py +0 -319
  575. package/src/backend/vision-capture.ts +0 -165
  576. package/src/backend/vision-registration.ts +0 -104
  577. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  578. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-31.js +0 -2
  579. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-33.js +0 -2
  580. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +0 -2
  581. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-88.js +0 -2
  582. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +0 -2
  583. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-90.js +0 -2
  584. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +0 -2
  585. package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
  586. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  587. package/src/extensions/pi-agent-read/runtime/entry-47.js +0 -1
  588. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +0 -2
  589. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +0 -1
  590. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +0 -1
  591. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  592. package/src/extensions/pi-agent-search/runtime/entry-53.js +0 -1
  593. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  594. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-62.js +0 -2
  595. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-63.js +0 -1
  596. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-64.js +0 -2
  597. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  598. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  599. package/src/extensions/pi-agent-text-editor/runtime/entry-65.js +0 -1
  600. package/src/extensions/pi-agent-text-editor/runtime/entry-66.js +0 -1
  601. package/src/extensions/pi-agent-text-editor/runtime/entry-67.js +0 -1
  602. package/src/plugins/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  603. package/src/plugins/pi-agent-ide-ast/runtime/entry-35.js +0 -2
  604. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  605. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  606. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  607. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  608. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  609. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +0 -387
  610. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +0 -41
  611. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +0 -92
  612. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +0 -214
  613. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +0 -277
  614. package/src/plugins/pi-agent-ide-changes/runtime/entry-36.js +0 -1
  615. package/src/plugins/pi-agent-ide-changes/runtime/entry-37.js +0 -2
  616. package/src/plugins/pi-agent-ide-languages/runtime/entry-39.js +0 -2
  617. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  618. package/src/plugins/pi-agent-ide-vision/index.ts +0 -439
  619. package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +0 -47
  620. package/src/plugins/pi-agent-ide-vision/src/vision.ts +0 -585
  621. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +0 -30
  622. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +0 -33
  623. /package/dist/{chunk-U2JKHKLK.js → chunk-3PMHFEJY.js} +0 -0
  624. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-28.js +0 -0
  625. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem}/runtime/entry-31.js +0 -0
  626. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-32.js +0 -0
  627. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-pdf}/runtime/entry-35.js +0 -0
  628. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-38.js +0 -0
  629. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-40.js +0 -0
  630. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-41.js +0 -0
  631. /package/node_modules/{pi-agent-read → pi-agent-image}/runtime/entry-45.js +0 -0
  632. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-46.js +0 -0
  633. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-47.js +0 -0
  634. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-50.js +0 -0
  635. /package/node_modules/{pi-agent-search → pi-agent-read}/runtime/entry-51.js +0 -0
  636. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-53.js +0 -0
  637. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-56.js +0 -0
  638. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-59.js +0 -0
  639. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-search-text}/runtime/entry-61.js +0 -0
  640. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-66.js +0 -0
  641. /package/node_modules/{pi-agent-web-pdf → pi-agent-web}/runtime/entry-90.js +0 -0
  642. /package/node_modules/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-91.js +0 -0
  643. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-32.js +0 -0
  644. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-91.js +0 -0
  645. /package/src/extensions/{pi-agent-search → pi-agent-read}/runtime/entry-51.js +0 -0
  646. /package/src/extensions/{pi-agent-text-editor/plugins/pi-agent-text-anchor-exact → pi-agent-search/plugins/pi-agent-search-text}/runtime/entry-61.js +0 -0
  647. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-38.js +0 -0
  648. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-40.js +0 -0
  649. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-41.js +0 -0
@@ -1 +1 @@
1
- import{a as d,b as u,c as w}from"./chunk-RIJMXO43.js";import"./chunk-PJL3UVMJ.js";import{b as f}from"./chunk-XAHU42FP.js";import"./chunk-DEP55R35.js";import"./chunk-R2U5WXYR.js";import{c}from"./chunk-W7CASEO3.js";import"./chunk-T7I2VX3J.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-XXLLY66B.js";import"./chunk-235QMMVA.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-LCWBVOII.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import{readFile as x}from"node:fs/promises";async function g(o){let n=new w(await u(d(c())));await f(o,m(o,n))}i(g,"registerOwnedGit");function m(o,n){return{exec:i(async(t,r,e)=>{let a=n.resolve(e.cwd);if(!a){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e.cwd))throw new Error(`Unsupported Git resource: ${e.cwd}`);return o.exec(t,r,e)}let s=await a.backend.execute(t,r,a.location.path,e);return{code:s.exitCode,stdout:s.stdout.toString("utf8"),stderr:s.stderr.toString("utf8")}},"exec"),async writeIndex(t,r){let e=n.resolve(r.cwd);return e?(await e.backend.writeGitIndex(e.location.path,t,r),!0):!1},async readText(t,r){let e=n.resolve(t);if(e)return(await e.backend.read(e.location.path,{signal:r})).bytes.toString("utf8");if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t))throw new Error(`Unsupported Git resource: ${t}`);return x(t,{encoding:"utf8",signal:r})}}}i(m,"createOwnedGitExecutor");export{m as createOwnedGitExecutor,g as default};
1
+ import{a as d,b as u,c as w}from"./chunk-WQIMM4SU.js";import"./chunk-4IWEKRSP.js";import{b as f}from"./chunk-6A3ORNW3.js";import"./chunk-DEP55R35.js";import{c}from"./chunk-W7CASEO3.js";import"./chunk-R2U5WXYR.js";import"./chunk-KN6VPARZ.js";import"./chunk-MDD5ORB6.js";import"./chunk-MLFJU2US.js";import"./chunk-GXL4NMHR.js";import"./chunk-PQWANILR.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DDH3FP4G.js";import"./chunk-756K3LJY.js";import"./chunk-VDJSH3DQ.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import{readFile as x}from"node:fs/promises";async function g(o){let n=new w(await u(d(c())));await f(o,m(o,n))}i(g,"registerOwnedGit");function m(o,n){return{exec:i(async(t,r,e)=>{let a=n.resolve(e.cwd);if(!a){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e.cwd))throw new Error(`Unsupported Git resource: ${e.cwd}`);return o.exec(t,r,e)}let s=await a.backend.execute(t,r,a.location.path,e);return{code:s.exitCode,stdout:s.stdout.toString("utf8"),stderr:s.stderr.toString("utf8")}},"exec"),async writeIndex(t,r){let e=n.resolve(r.cwd);return e?(await e.backend.writeGitIndex(e.location.path,t,r),!0):!1},async readText(t,r){let e=n.resolve(t);if(e)return(await e.backend.read(e.location.path,{signal:r})).bytes.toString("utf8");if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t))throw new Error(`Unsupported Git resource: ${t}`);return x(t,{encoding:"utf8",signal:r})}}}i(m,"createOwnedGitExecutor");export{m as createOwnedGitExecutor,g as default};
@@ -1 +1 @@
1
- import{k as f}from"./chunk-LCWBVOII.js";import{a}from"./chunk-EI7MMDWY.js";import k from"node:path";function p(i,t){if(!/^[a-z0-9][a-z0-9_-]*$/u.test(i))throw new TypeError("SSH target IDs must contain lowercase letters, digits, underscores or hyphens");if(!t.startsWith("/")||t.includes("\0"))throw new TypeError("Remote paths must be absolute and contain no NUL characters");let r=k.posix.normalize(t),e=r.split("/").map(encodeURIComponent).join("/");return{target:i,path:r,source:`ssh://${i}${e}`}}a(p,"remoteLocation");function O(i,t){if(i.startsWith("ssh:")){let e=new URL(i);if(!i.startsWith("ssh://")||!e.hostname||e.username||e.password||e.port||e.search||e.hash||i.includes("?")||i.includes("#"))throw new TypeError("SSH references require a configured target and an absolute path, without credentials or selectors");return p(e.hostname,decodeURIComponent(e.pathname))}if(!t?.startsWith("ssh:")||/^[A-Za-z][A-Za-z\d+.-]*:/u.test(i))return;let r=O(t);if(!r)throw new TypeError("Invalid remote workspace");return p(r.target,k.posix.resolve(r.path,i))}a(O,"resolveRemoteLocation");import{readFile as C}from"node:fs/promises";function S(i){if(p(i.id,i.workspace),!/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9_][A-Za-z0-9_.-]*$/u.test(i.host))throw new TypeError("SSH host must be an OpenSSH host alias, not a command or URI")}a(S,"validateSshTarget");async function y(i){return`exec(__import__("base64").b64decode("${(await C(i)).toString("base64")}"))`}a(y,"sshWorkerProgram");async function F(i){return`python3 -c '${await y(i)}'`}a(F,"sshWorkerCommand");function D(i,t){let r=["-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ForwardAgent=no","-o","PermitLocalCommand=no","-o","ClearAllForwardings=yes"];return i.configFile!==void 0&&r.push("-F",i.configFile),r.push("--",i.host,t),r}a(D,"systemSshArguments");function H(i,t){return/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No .* host key is known/u.test(t)?"HOST_KEY_FAILED":/Permission denied \([^)]*\)/u.test(t)?"AUTH_FAILED":i===127&&/\bpython3:\s*(?:command\s+)?not found\b/u.test(t)?"DEPENDENCY_UNAVAILABLE":"TRANSPORT_FAILED"}a(H,"sshFailureCode");import{createHash as I}from"node:crypto";import{Type as n}from"typebox";import{Value as x}from"typebox/value";var d=class extends f{static{a(this,"SshBackendError")}constructor(t,r,e,o){super(t,r,e,o),this.name=t==="CANCELLED"?"AbortError":"SshBackendError"}},L=n.Object({bytes:n.String(),version:n.String({pattern:"^[a-f0-9]{64}$"})}),v=n.Object({directory:n.String(),path:n.String(),revision:n.String({pattern:"^[a-f0-9]{64}$"}),sourceRevision:n.String({pattern:"^[a-f0-9]{64}$"}),sha256:n.String({pattern:"^[a-f0-9]{64}$"})}),E=n.Object({revision:n.String({pattern:"^[a-f0-9]{64}$"}),bytes:n.String(),offset:n.Integer({minimum:0}),totalBytes:n.Integer({minimum:0})}),T=n.Array(n.Object({name:n.String(),kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")])})),B=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0})}),m=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0}),links:n.Integer({minimum:0}),identity:n.Object({device:n.String({pattern:"^[0-9]+$"}),inode:n.String({pattern:"^[0-9]+$"})}),revision:n.String({pattern:"^[a-f0-9]{64}$"})}),N=n.Object({path:n.String({minLength:1}),entries:n.Array(n.Object({relativePath:n.String(),kind:m.properties.kind,revision:m.properties.revision,identity:m.properties.identity,mode:n.Integer({minimum:0}),link:n.Optional(n.String())}))}),A=n.Union([n.Object({ok:n.Literal(!0),data:n.Unknown()}),n.Object({ok:n.Literal(!1),code:n.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:n.Union([n.Literal("not-applied"),n.Literal("applied"),n.Literal("unknown")])})]),w=class{static{a(this,"SshBackend")}target;constructor(t){S(t),this.target={...t}}async stat(t,r={}){let e=await this.request({operation:"stat",path:t},!1,r);return this.checked(B,e,t,!1),e}async lstat(t,r={}){let e=await this.request({operation:"lstat",path:t},!1,r);return this.checked(m,e,t,!1),e}async temporaryEnvironment(t={}){let r=await this.request({operation:"temporary-environment",path:this.target.workspace},!1,t);return this.checked(n.Object({home:n.String({minLength:1,pattern:"^/"}),temporary:n.String({minLength:1,pattern:"^/"}),agentDirectory:n.Optional(n.String({minLength:1,pattern:"^/"}))}),r,this.target.workspace,!1),r}async objectSnapshot(t,r={}){let e=await this.request({operation:"object-snapshot",path:t},!1,r);return this.checked(N,e,t,!1),e}async ensureObjectDirectory(t,r,e,o={}){let s=await this.request({operation:"mkdir-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async createObjectLink(t,r,e={}){let o=await this.request({operation:"symlink-object",path:t,link:r,revision:null},!0,e);this.checked(n.Null(),o,t,!0)}async setObjectMode(t,r,e,o={}){let s=await this.request({operation:"chmod-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async moveObject(t,r,e={}){let o=await this.request({operation:"move-object",path:t.path,destination:r.path,sourceSnapshot:t,targetSnapshot:r},!0,e);return this.checked(n.Boolean(),o,t.path,!0),o}async captureJournal(t,r={}){let e=await this.request({operation:"journal",path:t},!1,r);return this.checked(v,e,t,!1),e}async releaseJournal(t,r={}){let e=await this.request({operation:"journal-release",path:t},!1,r);this.checked(n.Null(),e,t,!1)}async read(t,r={}){let e=await this.request({operation:"read",path:t},!1,r);return this.checked(L,e,t,!1),{bytes:Buffer.from(e.bytes,"base64"),version:e.version}}async readRange(t,r,e,o={}){if(!Number.isSafeInteger(r)||!Number.isSafeInteger(e)||e<0)throw new TypeError("Byte offset and limit must be safe integers; limit must be nonnegative");let s=await this.request({operation:"range",path:t,offset:r,limit:e},!1,o);return this.checked(E,s,t,!1),{bytes:Buffer.from(s.bytes,"base64"),offset:s.offset,totalBytes:s.totalBytes,revision:s.revision}}async list(t,r={}){let e=await this.request({operation:"list",path:t},!1,r);return this.checked(T,e,t,!1),e}async write(t,r,e,o={}){let s=await this.request({operation:"write",path:t,bytes:Buffer.from(r).toString("base64"),expected:e},!0,o);return this.checked(n.String({pattern:"^[a-f0-9]{64}$"}),s,t,!0),s}async copy(t,r,e,o,s={}){return this.copyEntry("copy",t,r,e,o,s)}async restoreJournal(t,r,e,o,s={}){return this.copyEntry("restore",t,r,e,o,s)}async copyEntry(t,r,e,o,s,c){let u=await this.request({operation:t,path:r,destination:e,sourceRevision:o,targetRevision:s},!0,c);this.checked(n.Null(),u,r,!0)}async move(t,r,e,o,s={}){let c=await this.request({operation:"move",path:t,destination:r,sourceRevision:e,targetRevision:o},!0,s);this.checked(n.Null(),c,t,!0)}async realpath(t,r={}){let e=await this.request({operation:"realpath",path:t},!1,r);if(this.checked(n.String({minLength:1}),e,t,!1),!e.startsWith("/"))throw new d("INVALID_RESPONSE",t,"not-applied");return e}async queryGit(t,r,e={}){let o=await this.request({operation:"git-query",path:t,args:r},!1,{...e,timeoutMs:5e3});return this.checked(n.String(),o,t,!1),o}async removeObject(t,r,e={}){let o=await this.request({operation:"delete-object",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async removeEntry(t,r,e={}){let o=await this.request({operation:"unlink",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async remove(t,r,e={}){let o=await this.request({operation:"remove",path:t,expected:r},!0,e);this.checked(n.Null(),o,t,!0)}async writeGitIndex(t,r,e={}){let o=Buffer.from(r.text,"utf8");if(o.length>32*1024*1024)throw new d("CONTENT_LIMIT",p(this.target.id,t).source,"not-applied");let{text:s,expectedIndexText:c,expectedWorktreeText:u,...g}=r,l=a(b=>I("sha256").update(b,"utf8").digest("hex"),"digest"),h=await this.request({operation:"gitIndex",path:t,...g,bytes:o.toString("base64"),expectedIndexHash:l(c),...u!==void 0&&{expectedWorktreeHash:l(u)}},!0,e);this.checked(n.Null(),h,t,!0)}async execute(t,r,e,o={}){let{runOwnedSshCommand:s}=await import("./chunk-K7SRNBIV.js");return s({...this.target,workspace:e},t,r,p(this.target.id,e).source,{signal:o.signal,timeoutMs:o.timeoutMs??3e4,maxBytes:32*1024*1024,limitCode:"CONTENT_LIMIT",closeInput:!0,effect:"unknown"})}async startProcess(t,r,e,o={}){let{startSshProcess:s}=await import("./chunk-SWBJS3U4.js");return s(this.target,t,r,e,o)}checked(t,r,e,o){if(!x.Check(t,r))throw new d("INVALID_RESPONSE",p(this.target.id,e).source,o?"unknown":"not-applied")}async request(t,r,e){let o=typeof t.path=="string"?t.path:typeof t.cwd=="string"?t.cwd:this.target.workspace,s=p(this.target.id,o).source,c=e.timeoutMs??3e4;if(!Number.isFinite(c)||c<=0)throw new TypeError("SSH operation deadline must be positive");e.signal?.throwIfAborted();let{runOwnedSshCommand:u}=await import("./chunk-K7SRNBIV.js"),g=await y(new URL("./ssh-worker.py",new URL("../src/backend/ssh.ts",import.meta.url).href)),l=await u({...this.target,workspace:t.operation==="gitIndex"?o:"/"},"python3",["-c",g],s,{signal:e.signal,timeoutMs:c,maxBytes:48*1024*1024,limitCode:"CONTENT_LIMIT",effect:r?"unknown":"not-applied",input:Buffer.from(JSON.stringify(t))});if(l.exitCode!==0)throw new d("REMOTE_OPERATION_FAILED",s,r?"unknown":"not-applied");let h;try{h=JSON.parse(l.stdout.toString("utf8"))}catch{throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied")}if(!j(h))throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied");if(!h.ok)throw new d(h.code,s,h.effect);return h.data}};function j(i){return x.Check(A,i)}a(j,"isReply");export{p as a,O as b,S as c,F as d,D as e,H as f,d as g,w as h};
1
+ import{h as f}from"./chunk-DDH3FP4G.js";import{a}from"./chunk-EI7MMDWY.js";import k from"node:path";function p(i,t){if(!/^[a-z0-9][a-z0-9_-]*$/u.test(i))throw new TypeError("SSH target IDs must contain lowercase letters, digits, underscores or hyphens");if(!t.startsWith("/")||t.includes("\0"))throw new TypeError("Remote paths must be absolute and contain no NUL characters");let r=k.posix.normalize(t),e=r.split("/").map(encodeURIComponent).join("/");return{target:i,path:r,source:`ssh://${i}${e}`}}a(p,"remoteLocation");function O(i,t){if(i.startsWith("ssh:")){let e=new URL(i);if(!i.startsWith("ssh://")||!e.hostname||e.username||e.password||e.port||e.search||e.hash||i.includes("?")||i.includes("#"))throw new TypeError("SSH references require a configured target and an absolute path, without credentials or selectors");return p(e.hostname,decodeURIComponent(e.pathname))}if(!t?.startsWith("ssh:")||/^[A-Za-z][A-Za-z\d+.-]*:/u.test(i))return;let r=O(t);if(!r)throw new TypeError("Invalid remote workspace");return p(r.target,k.posix.resolve(r.path,i))}a(O,"resolveRemoteLocation");import{readFile as C}from"node:fs/promises";function S(i){if(p(i.id,i.workspace),!/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9_][A-Za-z0-9_.-]*$/u.test(i.host))throw new TypeError("SSH host must be an OpenSSH host alias, not a command or URI")}a(S,"validateSshTarget");async function y(i){return`exec(__import__("base64").b64decode("${(await C(i)).toString("base64")}"))`}a(y,"sshWorkerProgram");async function F(i){return`python3 -c '${await y(i)}'`}a(F,"sshWorkerCommand");function D(i,t){let r=["-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ForwardAgent=no","-o","PermitLocalCommand=no","-o","ClearAllForwardings=yes"];return i.configFile!==void 0&&r.push("-F",i.configFile),r.push("--",i.host,t),r}a(D,"systemSshArguments");function H(i,t){return/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No .* host key is known/u.test(t)?"HOST_KEY_FAILED":/Permission denied \([^)]*\)/u.test(t)?"AUTH_FAILED":i===127&&/\bpython3:\s*(?:command\s+)?not found\b/u.test(t)?"DEPENDENCY_UNAVAILABLE":"TRANSPORT_FAILED"}a(H,"sshFailureCode");import{createHash as I}from"node:crypto";import{Type as n}from"typebox";import{Value as x}from"typebox/value";var d=class extends f{static{a(this,"SshBackendError")}constructor(t,r,e,o){super(t,r,e,o),this.name=t==="CANCELLED"?"AbortError":"SshBackendError"}},L=n.Object({bytes:n.String(),version:n.String({pattern:"^[a-f0-9]{64}$"})}),v=n.Object({directory:n.String(),path:n.String(),revision:n.String({pattern:"^[a-f0-9]{64}$"}),sourceRevision:n.String({pattern:"^[a-f0-9]{64}$"}),sha256:n.String({pattern:"^[a-f0-9]{64}$"})}),E=n.Object({revision:n.String({pattern:"^[a-f0-9]{64}$"}),bytes:n.String(),offset:n.Integer({minimum:0}),totalBytes:n.Integer({minimum:0})}),T=n.Array(n.Object({name:n.String(),kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")])})),B=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0})}),m=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0}),links:n.Integer({minimum:0}),identity:n.Object({device:n.String({pattern:"^[0-9]+$"}),inode:n.String({pattern:"^[0-9]+$"})}),revision:n.String({pattern:"^[a-f0-9]{64}$"})}),N=n.Object({path:n.String({minLength:1}),entries:n.Array(n.Object({relativePath:n.String(),kind:m.properties.kind,revision:m.properties.revision,identity:m.properties.identity,mode:n.Integer({minimum:0}),link:n.Optional(n.String())}))}),A=n.Union([n.Object({ok:n.Literal(!0),data:n.Unknown()}),n.Object({ok:n.Literal(!1),code:n.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:n.Union([n.Literal("not-applied"),n.Literal("applied"),n.Literal("unknown")])})]),w=class{static{a(this,"SshBackend")}target;constructor(t){S(t),this.target={...t}}async stat(t,r={}){let e=await this.request({operation:"stat",path:t},!1,r);return this.checked(B,e,t,!1),e}async lstat(t,r={}){let e=await this.request({operation:"lstat",path:t},!1,r);return this.checked(m,e,t,!1),e}async temporaryEnvironment(t={}){let r=await this.request({operation:"temporary-environment",path:this.target.workspace},!1,t);return this.checked(n.Object({home:n.String({minLength:1,pattern:"^/"}),temporary:n.String({minLength:1,pattern:"^/"}),agentDirectory:n.Optional(n.String({minLength:1,pattern:"^/"}))}),r,this.target.workspace,!1),r}async objectSnapshot(t,r={}){let e=await this.request({operation:"object-snapshot",path:t},!1,r);return this.checked(N,e,t,!1),e}async ensureObjectDirectory(t,r,e,o={}){let s=await this.request({operation:"mkdir-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async createObjectLink(t,r,e={}){let o=await this.request({operation:"symlink-object",path:t,link:r,revision:null},!0,e);this.checked(n.Null(),o,t,!0)}async setObjectMode(t,r,e,o={}){let s=await this.request({operation:"chmod-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async moveObject(t,r,e={}){let o=await this.request({operation:"move-object",path:t.path,destination:r.path,sourceSnapshot:t,targetSnapshot:r},!0,e);return this.checked(n.Boolean(),o,t.path,!0),o}async captureJournal(t,r={}){let e=await this.request({operation:"journal",path:t},!1,r);return this.checked(v,e,t,!1),e}async releaseJournal(t,r={}){let e=await this.request({operation:"journal-release",path:t},!1,r);this.checked(n.Null(),e,t,!1)}async read(t,r={}){let e=await this.request({operation:"read",path:t},!1,r);return this.checked(L,e,t,!1),{bytes:Buffer.from(e.bytes,"base64"),version:e.version}}async readRange(t,r,e,o={}){if(!Number.isSafeInteger(r)||!Number.isSafeInteger(e)||e<0)throw new TypeError("Byte offset and limit must be safe integers; limit must be nonnegative");let s=await this.request({operation:"range",path:t,offset:r,limit:e},!1,o);return this.checked(E,s,t,!1),{bytes:Buffer.from(s.bytes,"base64"),offset:s.offset,totalBytes:s.totalBytes,revision:s.revision}}async list(t,r={}){let e=await this.request({operation:"list",path:t},!1,r);return this.checked(T,e,t,!1),e}async write(t,r,e,o={}){let s=await this.request({operation:"write",path:t,bytes:Buffer.from(r).toString("base64"),expected:e},!0,o);return this.checked(n.String({pattern:"^[a-f0-9]{64}$"}),s,t,!0),s}async copy(t,r,e,o,s={}){return this.copyEntry("copy",t,r,e,o,s)}async restoreJournal(t,r,e,o,s={}){return this.copyEntry("restore",t,r,e,o,s)}async copyEntry(t,r,e,o,s,c){let u=await this.request({operation:t,path:r,destination:e,sourceRevision:o,targetRevision:s},!0,c);this.checked(n.Null(),u,r,!0)}async move(t,r,e,o,s={}){let c=await this.request({operation:"move",path:t,destination:r,sourceRevision:e,targetRevision:o},!0,s);this.checked(n.Null(),c,t,!0)}async realpath(t,r={}){let e=await this.request({operation:"realpath",path:t},!1,r);if(this.checked(n.String({minLength:1}),e,t,!1),!e.startsWith("/"))throw new d("INVALID_RESPONSE",t,"not-applied");return e}async queryGit(t,r,e={}){let o=await this.request({operation:"git-query",path:t,args:r},!1,{...e,timeoutMs:5e3});return this.checked(n.String(),o,t,!1),o}async removeObject(t,r,e={}){let o=await this.request({operation:"delete-object",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async removeEntry(t,r,e={}){let o=await this.request({operation:"unlink",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async remove(t,r,e={}){let o=await this.request({operation:"remove",path:t,expected:r},!0,e);this.checked(n.Null(),o,t,!0)}async writeGitIndex(t,r,e={}){let o=Buffer.from(r.text,"utf8");if(o.length>32*1024*1024)throw new d("CONTENT_LIMIT",p(this.target.id,t).source,"not-applied");let{text:s,expectedIndexText:c,expectedWorktreeText:u,...g}=r,l=a(b=>I("sha256").update(b,"utf8").digest("hex"),"digest"),h=await this.request({operation:"gitIndex",path:t,...g,bytes:o.toString("base64"),expectedIndexHash:l(c),...u!==void 0&&{expectedWorktreeHash:l(u)}},!0,e);this.checked(n.Null(),h,t,!0)}async execute(t,r,e,o={}){let{runOwnedSshCommand:s}=await import("./chunk-G4PRFO6G.js");return s({...this.target,workspace:e},t,r,p(this.target.id,e).source,{signal:o.signal,timeoutMs:o.timeoutMs??3e4,maxBytes:32*1024*1024,limitCode:"CONTENT_LIMIT",closeInput:!0,effect:"unknown"})}async startProcess(t,r,e,o={}){let{startSshProcess:s}=await import("./chunk-U7YDLVFL.js");return s(this.target,t,r,e,o)}checked(t,r,e,o){if(!x.Check(t,r))throw new d("INVALID_RESPONSE",p(this.target.id,e).source,o?"unknown":"not-applied")}async request(t,r,e){let o=typeof t.path=="string"?t.path:typeof t.cwd=="string"?t.cwd:this.target.workspace,s=p(this.target.id,o).source,c=e.timeoutMs??3e4;if(!Number.isFinite(c)||c<=0)throw new TypeError("SSH operation deadline must be positive");e.signal?.throwIfAborted();let{runOwnedSshCommand:u}=await import("./chunk-G4PRFO6G.js"),g=await y(new URL("./ssh-worker.py",new URL("../src/backend/ssh.ts",import.meta.url).href)),l=await u({...this.target,workspace:t.operation==="gitIndex"?o:"/"},"python3",["-c",g],s,{signal:e.signal,timeoutMs:c,maxBytes:48*1024*1024,limitCode:"CONTENT_LIMIT",effect:r?"unknown":"not-applied",input:Buffer.from(JSON.stringify(t))});if(l.exitCode!==0)throw new d("REMOTE_OPERATION_FAILED",s,r?"unknown":"not-applied");let h;try{h=JSON.parse(l.stdout.toString("utf8"))}catch{throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied")}if(!j(h))throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied");if(!h.ok)throw new d(h.code,s,h.effect);return h.data}};function j(i){return x.Check(A,i)}a(j,"isReply");export{p as a,O as b,S as c,F as d,D as e,H as f,d as g,w as h};
@@ -0,0 +1,5 @@
1
+ import{g as m,h as y,j as T,n as x,r as S}from"./chunk-DDH3FP4G.js";import{m as O,o as E}from"./chunk-VDJSH3DQ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as a}from"typebox";import{Value as f}from"typebox/value";import{Type as l}from"typebox";var R=l.Object({path:l.Optional(l.String({description:"What to read: a supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# or RESULT# reference, or registered protocol source. Supply a path; an empty call cannot select a source."})),offset:l.Optional(l.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor, SEARCH or RESULT# selections, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:l.Optional(l.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:l.Optional(l.Array(l.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))}),B={path:"What to read: a path, URL, unchanged Read/Search result or its UUID, or one of the forms below. temp:<id> \u2014 saved output; raw:<file> \u2014 original bytes.",offset:"First line, from 1; negative counts from the end. For raw:, a byte offset.",limit:"Maximum lines. For raw:, bytes.",views:"Extra presentations; combine them unless a view says otherwise."};function ie(e){let t=s((o,r)=>({...o,description:[B[r],e[r]].filter(d=>d!==void 0).join(`
2
+ `)}),"describe");return{...R,properties:{path:t(R.properties.path,"path"),offset:t(R.properties.offset,"offset"),limit:t(R.properties.limit,"limit"),views:t(R.properties.views,"views")}}}s(ie,"describeReadParameters");import{Type as n}from"typebox";function ue(e,t,o,r){if(!$(e))return{content:e,source:t,resolvedBy:o,preserveTruncatedOutput:r.preserveTruncatedOutput,textMode:r.textMode,contentKind:"other"};let d=e[0].text;return{content:e,source:t,resolvedBy:o,preserveTruncatedOutput:r.preserveTruncatedOutput,textMode:r.textMode,contentKind:"text",text:O(t,d)}}s(ue,"createReadState");function pe(e,t,o){if(e.contentKind!=="text"){if(t.offset!==void 0||t.limit!==void 0)return M({code:"UNSUPPORTED_RANGE",source:e.source,resolverId:e.resolvedBy,message:"Line ranges require textual content. Omit offset and limit to read this content without a line range."});let u=V(e.content);return{script:{kind:"native",source:e.source,blocks:e.content},content:u.content,details:{...C(e),...u.unsupportedContentBlocks!==void 0&&{unsupportedContentBlocks:u.unsupportedContentBlocks}}}}let r=e.text.lines.length,d=H(t,r,o?.originLine),i=e.text.lines.slice(d.startIndex,d.endIndex),c=e.textMode==="final"?j(i,d.endIndex<r):E({...e.text,lines:i.map((u,U)=>({...u,lineEnding:U===i.length-1&&d.endIndex<r?"":u.lineEnding}))}),b=e.content[0],F=[{type:"text",text:c,...b.textSignature!==void 0&&{textSignature:b.textSignature}}];return{script:{kind:"text",...e.text.references===void 0?{}:{references:e.text.references},source:e.source,content:i.map(u=>u.content+u.lineEnding).join(""),lines:i,startLine:i[0]?.lineNumber??0,endLine:i.at(-1)?.lineNumber??0,totalLines:r},content:F,details:{...C(e),startLine:i[0]?.lineNumber??0,endLine:i.at(-1)?.lineNumber??0,totalLines:r,lines:i}}}s(pe,"projectReadState");function j(e,t){return e.map((o,r)=>`${o.content}${r===e.length-1&&t?"":o.lineEnding}`).join("")}s(j,"renderFinalTextLines");function L(e){let t=e.cause,o,r=new Set;for(;t instanceof Error&&!r.has(t);)r.add(t),o=t,t=t.cause;return o}s(L,"deepestCause");var k="Supply path with a source or an unchanged result reference.",v=s(e=>`Read ${JSON.stringify(e)} with views=["anchors"] and choose a current anchor.`,"fragmentRecovery");function w(e){return e.candidates?.length?["Possible matches:",...e.candidates.map(t=>`- ${JSON.stringify(t.path)}`),"","Retry read with an exact candidate path."]:[]}s(w,"candidateLines");function P(e){let t=L(e),o=t!==void 0&&"code"in t?t.code:void 0,r=[];return o==="ENOENT"&&!e.candidates?.length&&r.push("Search for the correct path."),e.code==="INVALID_REQUEST"?r.push(k):e.code==="FRAGMENT_FAILED"&&e.source!==void 0?r.push(v(e.source)):e.code==="NO_RESOLVER"?r.push("Choose a supported source from the path parameter."):e.code==="NO_FRAGMENT_RESOLVER"&&r.push("Read the source without the anchor."),[...r,...w(e)]}s(P,"readFailureRecovery");function _(e){let t=L(e),o=t!==void 0&&"code"in t?t.code:void 0,r=t?.message||e.message;return o==="ENOENT"?r=e.candidates?.length?"Source not found.":"Source not found. Search for the correct path.":o==="EACCES"||o==="EPERM"?r="Access denied.":e.code==="INVALID_RESOLVER_RESULT"?r="The source provider returned an invalid result.":e.code==="INVALID_RESOURCE_CONTENT"?r="The source provider returned invalid content.":e.code==="UNSUPPORTED_CAPABILITY"?r="This source does not support reading.":e.code==="NO_RESOLVER"?r="This source is not supported. Choose a supported source from the path parameter.":e.code==="NO_FRAGMENT_RESOLVER"&&(r="This anchor is not supported. Read the source without the anchor."),e.code==="INVALID_REQUEST"?r+=`. ${k}`:e.code==="FRAGMENT_FAILED"&&e.source!==void 0&&(r+=`
3
+ ${v(e.source)}`),`Read failed${e.source===void 0?"":` for ${JSON.stringify(e.source)}`}: ${r}`}s(_,"readFailureMessage");function Re(e,t,o){if(!o?.aborted||!e.isError)return e;let r=e.details.source??e.details.failure?.source??t;return{...e,content:[{type:"text",text:`Read cancelled${r===void 0?"":` for ${JSON.stringify(r)}`}. No completed result was returned.`}]}}s(Re,"withReadCancellation");function M(e){let t=e.cause instanceof y?e.cause:void 0;return t!==void 0?e={...e,source:e.source??t.source,message:`${t.code}: ${e.source??t.source}`,cause:new y(t.code,t.source,t.effect,{metadata:m(t)})}:e.cause instanceof Error&&"code"in e.cause&&!["ENOENT","EACCES","EPERM"].includes(String(e.cause.code))&&(e={...e,message:`${e.code}: ${e.source??"source"}`,cause:void 0}),{content:[{type:"text",text:[_(e),...e.candidates?.length?["",...w(e)]:[]].join(`
4
+ `)}],details:{failure:e},isError:!0}}s(M,"failureResult");function C(e){return{source:e.source,resolvedBy:e.resolvedBy}}s(C,"readDetails");function V(e){let t=[],o=[];for(let[d,i]of e.entries()){if(i.type!=="custom"){t.push(i);continue}o.push({index:d,kind:i.kind}),t.push({type:"text",text:`[unsupported_content_block kind=${i.kind} index=${d}]`})}let r=o[0];return{content:t,...r!==void 0&&{unsupportedContentBlocks:[r,...o.slice(1)]}}}s(V,"projectAgentContent");function H(e,t,o){let r=e.offset===void 0?1:Math.trunc(e.offset),d=q(r,t,o),i=e.limit===void 0?t:Math.max(0,Math.trunc(e.limit));return{startIndex:Math.min(t,d-1),endIndex:Math.min(t,d-1+i)}}s(H,"resolveTextRange");function q(e,t,o){if(o===void 0)return e<0?Math.max(1,t+e+1):Math.max(1,e);let r=e<0?o+e:o+Math.max(1,e)-1;return Math.max(1,r)}s(q,"anchoredStartLine");function $(e){return e.length===1&&e[0].type==="text"}s($,"isSingleTextContent");var G=n.Object({value:n.String(),kind:n.String(),state:n.Optional(n.String())},{additionalProperties:!1}),K=n.Object({lineNumber:n.Integer(),content:n.String(),lineEnding:n.String(),anchors:n.Optional(n.Array(n.String()))},{additionalProperties:!1}),W=n.Object({path:n.String(),offset:n.Integer()},{additionalProperties:!1}),h={source:n.String(),truncated:n.Boolean(),continuation:n.Optional(W),fullResult:n.Optional(n.String())},N=n.Object({...h,kind:n.Literal("text"),target:n.Optional(n.String()),lines:n.Array(K),startLine:n.Integer(),endLine:n.Integer(),totalLines:n.Integer(),references:n.Optional(n.Array(G))},{additionalProperties:!1}),D=n.Object({...h,kind:n.Literal("bytes"),bytes:n.Array(n.Integer({minimum:0,maximum:255})),byteOffset:n.Integer(),byteLength:n.Integer(),totalBytes:n.Integer()},{additionalProperties:!1}),J=n.Union([n.Object({type:n.Literal("text"),text:n.String()},{additionalProperties:!1}),n.Object({type:n.Literal("image"),mimeType:n.String()},{additionalProperties:!1})]),A=n.Object({...h,kind:n.Literal("native"),blocks:n.Array(J)},{additionalProperties:!1}),g=n.Union([n.Object({kind:n.Literal("recovery"),source:n.String(),candidates:n.Array(n.Object({path:n.String()},{additionalProperties:!1}))},{additionalProperties:!1}),N,D,A,n.Object({kind:n.Literal("resources"),source:n.Optional(n.String()),resources:n.Array(n.Union([N,D,A])),truncated:n.Boolean(),fullResult:n.Optional(n.String())},{additionalProperties:!1})]),z=T(g);function Q(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}s(Q,"publicLine");function I(e){if(e.kind==="resources"){let i=e.resources.map(c=>I(c));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:i,truncated:i.some(c=>typeof c=="object"&&c!==null&&"truncated"in c&&c.truncated===!0)}}if(e.kind==="bytes"){let i=e.bytes.slice(0,32768),c=e.truncated===!0||i.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:i,byteOffset:e.byteOffset,byteLength:i.length,totalBytes:e.totalBytes,truncated:c,...e.byteOffset+i.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+i.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(i=>{if(i.type==="text")return{type:i.type,text:i.text};if(i.type==="image")return{type:i.type,mimeType:i.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let t=[],o=0;for(let i of e.lines){let c=Q(i);if(o+=Buffer.byteLength(JSON.stringify(c)),t.length>=2e3||o>512*1024)break;t.push(c)}if(t.length===0&&e.lines.length>0)throw new RangeError("Selected line exceeds the structured window; use a raw byte range or a source-specific view");let r=t.length<e.lines.length,d=t.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,...e.target===void 0?{}:{target:e.target},lines:t,startLine:t[0]?.lineNumber??0,endLine:t.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:r,...e.target===void 0?{}:{target:e.target},...e.references===void 0?{}:{references:e.references},...r||d<e.totalLines?{continuation:{path:e.source,offset:d+1}}:{}}}s(I,"publicData");function Y(e){let t=e.details.failure,o=t?.cause instanceof y?t.cause:void 0,r=o===void 0?void 0:m(o);if(e.isError||t!==void 0)return x(e,g,{status:"error",...t?.candidates?.length&&t.source!==void 0?{data:{kind:"recovery",source:t.source,candidates:t.candidates}}:{},errors:[{code:o?.code??t?.code??"READ_FAILED",message:o===void 0?[t?.message??"Read failed",...t===void 0?[]:P(t)].join(`
5
+ `):`${o.code}: ${t?.source??o.source}`,...t?.source===void 0?{}:{source:t.source},...r===void 0?{}:{metadata:r}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let d=I(e.script);return x(e,g,{status:"success",data:e.details.temporarySource!==void 0&&typeof d=="object"&&d!==null?{...d,fullResult:e.details.temporarySource}:d,errors:[]})}catch(d){return x(e,g,{status:"error",errors:[{code:d instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:d instanceof Error?d.message:String(d)}]})}}s(Y,"structuredRead");var p=a.Function([],a.Unknown()),X=a.Object({resolver:a.Unknown(),matchesCall:a.Optional(p),renderCall:a.Optional(p),priority:a.Optional(a.Number()),renderResult:a.Optional(p),preserveTruncatedOutput:a.Optional(a.Boolean())}),Z=a.Object({resolver:a.Unknown(),priority:a.Optional(a.Number())}),ee=a.Object({id:a.String({pattern:"\\S"}),priority:a.Optional(a.Number()),resolve:p}),te=a.Object({view:a.String({pattern:"\\S"}),contentKind:a.Optional(a.Union([a.Literal("text"),a.Literal("any")])),includes:a.Optional(a.Array(a.String({pattern:"\\S"}))),presenter:a.Object({id:a.String(),present:p}),priority:a.Optional(a.Number())}),ne=a.Object({resolvedBy:a.String({pattern:"\\S"}),contentKind:a.Union([a.Literal("text"),a.Literal("any")])}),re=a.Union([a.Object({stage:a.Literal("pre-read"),handler:p}),a.Object({stage:a.Literal("read"),when:ne,handler:p}),a.Object({stage:a.Literal("post-read"),handler:p})]);function Ee(e){if(!f.Check(Z,e))return!1;let t=e,o=t.resolver;return typeof o.id=="string"&&o.id.length>0&&typeof o.tryResolve=="function"&&(!("priority"in t)||typeof t.priority=="number")}s(Ee,"isTextTargetResolverRegistration");function Ce(e){if(!f.Check(X,e))return!1;let t=e;return S(t.resolver)?t.resolver.id!=="any"&&(!("priority"in t)||typeof t.priority=="number")&&(!("matchesCall"in t)||typeof t.matchesCall=="function")&&(!("renderCall"in t)||typeof t.renderCall=="function")&&"matchesCall"in t=="renderCall"in t&&(!("renderResult"in t)||typeof t.renderResult=="function"):!1}s(Ce,"isResourceResolverRegistration");function Le(e){return f.Check(re,e)}s(Le,"isReadHandlerRegistration");function ke(e){return f.Check(te,e)}s(ke,"isReadViewRegistration");function ve(e){return f.Check(ee,e)}s(ve,"isFragmentResolverRegistration");function we(e){return oe(e)?e.kind==="not-handled"?!0:e.kind==="failed"?typeof e.message=="string"&&e.message.length>0:e.kind==="resolved"&&typeof e.originLine=="number":!1}s(we,"isReadFragmentResolution");function oe(e){return typeof e=="object"&&e!==null}s(oe,"isRecord");export{R as a,ie as b,ue as c,pe as d,Re as e,M as f,q as g,g as h,z as i,Y as j,Ee as k,Ce as l,Le as m,ke as n,ve as o,we as p};
@@ -0,0 +1 @@
1
+ import{a as u}from"./chunk-VDJSH3DQ.js";import{a as d}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";var y=Symbol.for("pi-agent-text-editor/TextSelectionAnchor"),x=class extends u{constructor(t,o,i,p){let c=i.map(r=>({start:{...r.start},end:{...r.end},...r.linewise===!0&&{linewise:!0}}));m(c);super(t,d(c[0]).start.lineNumber);this.source=o;if(o.length===0)throw new TypeError("Text selection anchor source must be non-empty");if(this.ranges=c,p!==void 0){let r=p.map(s=>({start:{...s.start},end:{...s.end},...s.linewise===!0&&{linewise:!0}}));if(m(r),r.length!==c.length||r.some((s,h)=>{let f=d(c[h]);return l(s.start,f.start)<0||l(s.end,f.end)>0}))throw new RangeError("Endpoint ranges must stay within their corresponding selection ranges");this.endpointRanges=r}}static{a(this,"TextSelectionAnchor")}[y]=!0;ranges;endpointRanges;static is(t){if(!u.is(t))return!1;try{let o=t,i=o.ranges;return o[y]===!0&&typeof o.source=="string"&&o.source.length>0&&Array.isArray(i)&&i.length>0&&i.every(g)&&(o.endpointRanges===void 0||Array.isArray(o.endpointRanges)&&o.endpointRanges.length===i.length&&o.endpointRanges.every(g))}catch{return!1}}};function m(n){if(n.length===0)throw new TypeError("Text selection anchor must contain at least one range");let e;for(let t of n){if(!g(t)||l(t.start,t.end)>0)throw new RangeError("Text selection anchor contains an invalid range");if(e!==void 0&&l(t.start,e.end)<0)throw new Error("Text selection anchor ranges must be ordered and must not overlap");e=t}}a(m,"assertSelectionRanges");function g(n){if(typeof n!="object"||n===null)return!1;let e=n;return T(e.start)&&T(e.end)&&(e.linewise===void 0||typeof e.linewise=="boolean")}a(g,"isTextSelectionRange");function T(n){if(typeof n!="object"||n===null)return!1;let e=n;return Number.isSafeInteger(e.lineNumber)&&(e.lineNumber??0)>=1&&Number.isSafeInteger(e.column)&&(e.column??-1)>=0}a(T,"isTextSelectionPosition");function l(n,e){return n.lineNumber-e.lineNumber||n.column-e.column}a(l,"comparePositions");export{x as a};
@@ -0,0 +1 @@
1
+ import{a as g,c as P,d as T}from"./chunk-B25LXXNV.js";import{b as C,c as k,g as R,i as E,k as F,m as d,n as x}from"./chunk-7D7PXIVV.js";import{a as w}from"./chunk-MDD5ORB6.js";import{b as y,c as h}from"./chunk-MLFJU2US.js";import{a as v}from"./chunk-ZAWRSA7N.js";import{a as b,b as j}from"./chunk-OFILFO6D.js";import{a as f}from"./chunk-EI7MMDWY.js";var A=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".html",".md",".yaml",".yml",".vue",".svelte"],z=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css",".scss",".less",".html",".htm",".md",".markdown",".mdx",".yaml",".yml",".toml"],p=[e("dart-format",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],[".dart"],["dart","format","{file}"],"https://dart.dev/tools/dart-format"),e("zig-format",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","fmt","{file}"],"https://ziglang.org/documentation/master/"),e("styler",["r"],["Rscript"],[".Rprofile","DESCRIPTION"],[".r"],["Rscript","-e","styler::style_file(commandArgs(TRUE)[1])","{file}"],"https://styler.r-lib.org/"),e("clang-format",["c","cpp"],["clang-format"],[".clang-format","_clang-format"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-format","-i","{file}"],"https://clang.llvm.org/docs/ClangFormat.html"),e("prettier",["javascript","typescript","html","css","json","yaml","markdown","vue","svelte"],["prettier"],[".prettierrc",".prettierrc.json",".prettierrc.json5",".prettierrc.yaml",".prettierrc.yml",".prettierrc.toml",".prettierrc.js",".prettierrc.cjs",".prettierrc.mjs","prettier.config.js","prettier.config.cjs","prettier.config.mjs","prettier.config.ts","prettier.config.mts","prettier.config.cts"],A,["prettier","--write","{file}"],"https://prettier.io/docs/",["prettier"],{"package.json":["prettier"]}),e("biome",["javascript","typescript","json","css"],["biome"],["biome.json","biome.jsonc"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".json",".jsonc",".css"],["biome","format","--write","{file}"],"https://biomejs.dev/",["@biomejs/biome"]),e("oxfmt",["javascript","typescript","json","css","html","markdown","yaml","toml"],["oxfmt"],[".oxfmtrc.json",".oxfmtrc.jsonc","oxfmt.config.ts","oxfmt.config.mts"],z,["oxfmt","--write","{file}"],"https://oxc.rs/docs/guide/usage/formatter.html",["oxfmt"]),e("ruff-format",["python"],["ruff"],["ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","format","{file}"],"https://docs.astral.sh/ruff/formatter/",["ruff"],{"pyproject.toml":["tool.ruff"]}),e("black",["python"],["black"],[],[".py",".pyi"],["black","--quiet","{file}"],"https://black.readthedocs.io/",["black"],{"pyproject.toml":["tool.black"]}),e("gofmt",["go"],["gofmt"],["go.mod"],[".go"],["gofmt","-w","{file}"],"https://pkg.go.dev/cmd/gofmt"),e("goimports",["go"],["goimports"],["go.mod"],[".go"],["goimports","-w","{file}"],"https://pkg.go.dev/golang.org/x/tools/cmd/goimports"),e("rustfmt",["rust"],["rustfmt"],["rustfmt.toml",".rustfmt.toml","Cargo.toml"],[".rs"],["rustfmt","{file}"],"https://github.com/rust-lang/rustfmt"),e("csharpier",["csharp"],["csharpier"],[".csharpierrc",".csharpierrc.json",".csharpierrc.yaml",".csharpierrc.yml"],[".cs"],["csharpier","format","{file}"],"https://csharpier.com/"),e("google-java-format",["java"],["google-java-format"],["pom.xml","build.gradle"],[".java"],["google-java-format","--replace","{file}"],"https://github.com/google/google-java-format"),e("ktlint-format",["kotlin"],["ktlint"],[".editorconfig","build.gradle.kts"],[".kt",".kts"],["ktlint","-F","{file}"],"https://pinterest.github.io/ktlint/"),e("rubocop-format",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--fix-layout","{file}"],"https://docs.rubocop.org/"),e("pint",["php"],["pint"],["pint.json","composer.json"],[".php"],["pint","{file}"],"https://laravel.com/docs/pint"),e("swift-format",["swift"],["swift-format"],[".swift-format","Package.swift"],[".swift"],["swift-format","format","--in-place","{file}"],"https://github.com/swiftlang/swift-format"),e("stylua",["lua"],["stylua"],["stylua.toml",".stylua.toml"],[".lua"],["stylua","{file}"],"https://github.com/JohnnyMorganz/StyLua"),e("shfmt",["shell"],["shfmt"],[".editorconfig"],[".sh",".bash",".zsh"],["shfmt","-w","{file}"],"https://github.com/mvdan/sh"),e("taplo",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","format","{file}"],"https://taplo.tamasfe.dev/"),e("sqlfluff-format",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","format","{file}"],"https://docs.sqlfluff.com/"),e("terraform-fmt",["terraform"],["terraform"],[".terraform.lock.hcl"],[".tf",".tfvars"],["terraform","fmt","{file}"],"https://developer.hashicorp.com/terraform/cli/commands/fmt"),e("cmake-format",["cmake"],["cmake-format"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-format","-i","{file}"],"https://cmake-format.readthedocs.io/",void 0,void 0,["CMakeLists.txt"]),e("xmlformat",["xml"],["xmlformat"],[".xmlformat.conf"],[".xml",".xsd",".xsl"],["xmlformat","--overwrite","{file}"],"https://github.com/pamoller/xmlformatter"),e("mix-format",["elixir"],["mix"],["mix.exs",".formatter.exs"],[".ex",".exs"],["mix","format","{file}"],"https://hexdocs.pm/mix/Mix.Tasks.Format.html"),e("scalafmt",["scala"],["scalafmt"],[".scalafmt.conf"],[".scala",".sc",".sbt"],["scalafmt","{file}"],"https://scalameta.org/scalafmt/"),e("julia-format",["julia"],["julia"],[".JuliaFormatter.toml","Project.toml"],[".jl"],["julia","--startup-file=no","--history-file=no","-e","using JuliaFormatter; format_file(ARGS[1])","{file}"],"https://github.com/domluna/JuliaFormatter.jl"),e("powershell-format",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$p=$args[0];$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};[IO.File]::WriteAllText($p,(Invoke-Formatter -ScriptDefinition ([IO.File]::ReadAllText($p)) @options))',"{file}"],"https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-formatter"),e("dockfmt",["dockerfile"],["dockfmt"],["Dockerfile","Containerfile"],[".dockerfile"],["dockfmt","fmt","--write","{file}"],"https://github.com/jessfraz/dockfmt",void 0,void 0,["Dockerfile","Containerfile"])];function e(r,t,o,i,a,l,n,s,m,u){return{id:r,name:r,kind:"formatter",languages:t,executables:o,configFiles:i,documentation:n,...s&&{dependencies:s},...m&&{configSections:m},formatter:{extensions:a,...u&&{fileNames:u},run:{command:l},output:"in-place"}}}f(e,"recipe");var c=class r{constructor(t,o,i=new Map){this.formatters=t;this.availableBuiltIns=o;this.evidence=i}static{f(this,"FormatterCommandRegistry")}static async fromDirectory(t,o={}){let i=await R(t,"formatters",s=>x(s).formatters,o),{available:a,evidence:l}=await F(t,i.entries.filter(s=>s.layer==="built-in").map(s=>({id:s.id,config:s.config.run})),p,o),n=[...i.entries].sort((s,m)=>s.layer==="built-in"&&m.layer==="built-in"?(l.get(m.id)?.score??0)-(l.get(s.id)?.score??0):0);return new r(n,a,l)}static fromConfig(t){return new r(Object.entries(t.formatters).map(([o,i])=>({id:o,config:i,layer:"project",sourcePath:"<memory>"})),new Set)}resolve(t,o){return this.resolveEntry(t,o)?.config}resolveEntry(t,o){return E(this.formatters,this.availableBuiltIns,this.evidence,t,o)}get entries(){return this.formatters}};var I={protocol:y,apiVersion:h,id:"formatter",setup(r){for(let t of p)r.addToolRecipe(t);r.addSetupCheck({id:"effective-config",inspect:$}),r.addCheck({id:"config",title:"Formatter",async run(t){try{let o=await c.fromDirectory(t.cwd,g(t)),i=M(o,t.files,t.cwd);return i.length===0?[{status:"skip",message:"No formatter matches the inspected project files"}]:await Promise.all(i.map(async({entry:a,source:l})=>{let n=`${a.id} [${a.layer}] command ${JSON.stringify(a.config.run.command)}`;return T(t,l,async s=>{try{let m=t.workspace?await t.workspace.run(a.config.run,s,t.signal):await d(a.config,{projectRoot:t.cwd,filePath:s,env:t.env});return t.signal?.throwIfAborted(),m.ok?{status:"pass",message:`${n}: probe passed`,detail:a.sourcePath}:{status:"fail",message:`${n}: probe failed`,detail:a.sourcePath}}catch(m){return t.signal?.throwIfAborted(),{status:"fail",message:`${n}: ${m instanceof Error?m.message:String(m)}`,detail:a.sourcePath}}})}))}catch(o){return t.signal?.throwIfAborted(),[{status:"fail",message:o instanceof Error?o.message:String(o)}]}}})}};async function $(r){try{let t=await c.fromDirectory(r.cwd,g(r)),o=[],i=new Map;for(let[a,l]of r.detectedLanguages){let n=l.map(s=>t.resolveEntry(s,r.cwd)).find(s=>s!==void 0);n!==void 0&&(o.push({kind:"formatter",languageId:a,toolId:n.id}),await P(r,n.config.run)||i.set(n.id,{id:`formatter-${n.id}-unavailable`,message:`Configured formatter ${n.id} cannot run ${JSON.stringify(n.config.run.command)}`}))}return{selections:o,actions:[...i.values()]}}catch(t){return r.signal?.throwIfAborted(),{actions:[{id:"formatter-config-invalid",message:`Formatter configuration cannot load: ${t instanceof Error?t.message:String(t)}`}]}}}f($,"inspectFormatterSetup");function M(r,t,o){let i=new Map;for(let a of t){let l=r.resolveEntry(a,o);l!==void 0&&!i.has(l.id)&&i.set(l.id,{entry:l,source:a})}return[...i.values()]}f(M,"applicableFormatters");import _ from"node:path";var S=new Map;function D(r){return{kind:"formatter",name:"formatter",priority:100,extensions:["*"],detect:f(async t=>(r?await r.loadRegistry(t.cwd,!1):await O(t.cwd),!0),"detect"),async format({filePath:t},o){if(!r&&(t.includes("://")||o.cwd.includes("://")))throw Object.assign(new Error("Formatter requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r?await r.resolveProject(t,o.cwd):await k(o.cwd,t,"formatters",p).then(m=>m===void 0?void 0:{cwd:m,external:m!==_.resolve(o.cwd)});if(i===void 0)return{ok:!0,edits:0,formatter:null};let a=i.cwd,n=(r?await r.loadRegistry(a,i.external):await O(a,i.external)).resolve(t,a);if(n===void 0)return{ok:!0,edits:0,formatter:null};let s=C(n.run.command);if(r){let m=await r.run(n,a,t);return{ok:m.ok,edits:m.changed?1:0,formatter:s}}try{let m=await d(n,{projectRoot:a,filePath:t});return{ok:m.ok,edits:m.changed?1:0,formatter:s}}catch{return{ok:!1,edits:0,formatter:s}}}}}f(D,"createFormatter");async function O(r,t=!1){let o=JSON.stringify([r,t]),i=S.get(o);return i===void 0&&(i=c.fromDirectory(r,{includeGlobal:!t,requireBuiltInEvidence:!0}),S.set(o,i)),i}f(O,"loadRegistry");async function q(r){await N(r)}f(q,"registerFormatter");async function N(r,t){let o=D(t),i={kind:"formatter",name:"pi-agent-ide-formatter",priority:200,extensions:["*"],detect:f(()=>Promise.resolve(!0),"detect"),async format(l,n){return o.format(l,n)}},a={protocol:b,apiVersion:5,id:"formatter",setup(l){l.addTool(i)}};await Promise.all([v(r,a),w(r,I)])}f(N,"registerFormatterWithOwner");export{p as a,c as b,q as c,N as d};
@@ -1,7 +1,7 @@
1
- import{a as o}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";var f=class i{static{s(this,"FileRange")}start;end;constructor(e,t=e){t.lineNumber<e.lineNumber&&([e,t]=[t,e]),this.start=e,this.end=t}static fromLines(e,t){let n=t??e;return new i({lineNumber:e},{lineNumber:n})}},l=class i{static{s(this,"FileMutationResult")}data;constructor(e){let t=e?.formatting;this.data=t===void 0||e?.diffStatuses===void 0?e??{}:{...e,diffStatuses:e.diffStatuses.map(n=>n.formattingStatus!==void 0||t.formatter===void 0||n.formatter!==t.formatter||n.tone!=="success"&&n.tone!=="error"?n:{...n,formattingStatus:t.status})}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,t=e?.[0];if(t?.range){let n=t.range.start,a=o(e).at(-1)?.range?.end??n;return new f(n,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let t of this.files)e.add(t.path);for(let t of this.errors)t.path&&e.add(t.path);for(let t of this.warnings)t.file&&e.add(t.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let r=this.errors[0];return r?`Failed: ${r.code??"ERROR"}${r.reason?` \u2014 ${r.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let r=this.appliedPaths;return r&&r.length>0?`${r.length} path${r.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,t=this.overwrittenFiles.length,n=[];if(e>0&&n.push(`Created ${e} ${e===1?"file":"files"}`),t>0&&n.push(`Edited ${t} ${t===1?"file":"files"}`),this.diffs.length>0){let r=0,a=0;for(let d of this.diffs)for(let u of d.split(`
2
- `))u.startsWith("+")&&!u.startsWith("+++")?r++:u.startsWith("-")&&!u.startsWith("---")&&a++;(r>0||a>0)&&n.push(`+${r}/-${a} lines`)}return n.join(", ")}getFileChange(e){return this.files.find(t=>t.path===e)}getDiffFor(e){let t=g(e);for(let n of this.diffs){let r=n.match(/^---\s+(.+)$/m);if(r&&(g(o(r[1]))===t||r[1]===e))return n}}getErrorsFor(e){return this.errors.filter(t=>t.path===e)}getWarningsFor(e){return this.warnings.filter(t=>t.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let t=e;return t.data&&typeof t.data=="object"?(Object.setPrototypeOf(t,i.prototype),t):new i(t)}return new i}};function g(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(g,"normalisePath");import{createTwoFilesPatch as p,diffLines as c}from"diff";function D(i,e,t,n=i){return{diff:p(i,n,e,t,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:m(e,t)}}s(D,"createUnifiedDiff");function m(i,e){let t=0,n=0;for(let r of c(i,e)){let a=h(r.value);r.removed&&(t+=a),r.added&&(n+=a)}return{removed:t,added:n}}s(m,"computeStats");function h(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
1
+ import{a as s}from"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";var f=class i{static{o(this,"FileRange")}start;end;constructor(e,t=e){t.lineNumber<e.lineNumber&&([e,t]=[t,e]),this.start=e,this.end=t}static fromLines(e,t){let n=t??e;return new i({lineNumber:e},{lineNumber:n})}},l=class i{static{o(this,"FileMutationResult")}data;constructor(e){let t=e?.formatting;this.data=t===void 0||e?.diffStatuses===void 0?e??{}:{...e,diffStatuses:e.diffStatuses.map(n=>n.formattingStatus!==void 0||t.formatter===void 0||n.formatter!==t.formatter||n.tone!=="success"&&n.tone!=="error"?n:{...n,formattingStatus:t.status})}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,t=e?.[0];if(t?.range){let n=t.range.start,a=s(e).at(-1)?.range?.end??n;return new f(n,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let t of this.files)e.add(t.path);for(let t of this.errors)t.path&&e.add(t.path);for(let t of this.warnings)t.file&&e.add(t.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let r=this.errors[0];return r?`Failed: ${r.code??"ERROR"}${r.reason?` \u2014 ${r.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let r=this.appliedPaths;return r&&r.length>0?`${r.length} path${r.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,t=this.overwrittenFiles.length,n=[];if(e>0&&n.push(`Created ${e} ${e===1?"file":"files"}`),t>0&&n.push(`Edited ${t} ${t===1?"file":"files"}`),this.diffs.length>0){let r=0,a=0;for(let d of this.diffs)for(let u of d.split(`
2
+ `))u.startsWith("+")&&!u.startsWith("+++")?r++:u.startsWith("-")&&!u.startsWith("---")&&a++;(r>0||a>0)&&n.push(`+${r}/-${a} lines`)}return n.join(", ")}getFileChange(e){return this.files.find(t=>t.path===e)}getDiffFor(e){let t=g(e);for(let n of this.diffs){let r=n.match(/^---\s+(.+)$/m);if(r&&(g(s(r[1]))===t||r[1]===e))return n}}getErrorsFor(e){return this.errors.filter(t=>t.path===e)}getWarningsFor(e){return this.warnings.filter(t=>t.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let t=e;return t.data&&typeof t.data=="object"?(Object.setPrototypeOf(t,i.prototype),t):new i(t)}return new i}};function g(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}o(g,"normalisePath");import{createTwoFilesPatch as p,diffLines as c}from"diff";function D(i,e,t,n=i){return{diff:p(i,n,e,t,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:m(e,t)}}o(D,"createUnifiedDiff");function m(i,e){let t=0,n=0;for(let r of c(i,e)){let a=h(r.value);r.removed&&(t+=a),r.added&&(n+=a)}return{removed:t,added:n}}o(m,"computeStats");function h(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
3
3
  `,`
4
4
  `);return e.endsWith(`
5
5
  `)?e.slice(0,-1).split(`
6
6
  `).length:e.split(`
7
- `).length}s(h,"countDiffLines");function y(i,e){let t=c(i,e),n=[],r=0;for(let a of t){let d=h(a.value);d!==0&&(a.removed||(a.added&&n.push({start:r+1,end:r+d}),r+=d))}return E(n)}s(y,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((n,r)=>n.start-r.start),t=[o(e[0])];for(let n=1;n<e.length;n++){let r=o(t.at(-1)),a=o(e[n]);a.start<=r.end+1?r.end=Math.max(r.end,a.end):t.push(a)}return t}s(E,"mergeAdjacentRanges");export{f as a,l as b,D as c,y as d};
7
+ `).length}o(h,"countDiffLines");function y(i,e){let t=c(i,e),n=[],r=0;for(let a of t){let d=h(a.value);d!==0&&(a.removed||(a.added&&n.push({start:r+1,end:r+d}),r+=d))}return E(n)}o(y,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((n,r)=>n.start-r.start),t=[s(e[0])];for(let n=1;n<e.length;n++){let r=s(t.at(-1)),a=s(e[n]);a.start<=r.end+1?r.end=Math.max(r.end,a.end):t.push(a)}return t}o(E,"mergeAdjacentRanges");export{f as a,l as b,D as c,y 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-XXLLY66B.js";import{c as Z,d as Y}from"./chunk-235QMMVA.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as S,j as H}from"./chunk-LCWBVOII.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return D(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return D(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return D(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function D(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(D,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,$=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new $(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=L(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=L(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?U(t,d,`<!-- change: ${a} -->`):(U(t,d,`<!-- change-begin: ${a} -->`),U(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function U(n,e,t){if(e.kind==="current"){L(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s(U,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function L(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(L,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var N=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(N),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
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{f as K,g as X}from"./chunk-KN6VPARZ.js";import{a as Y}from"./chunk-MDD5ORB6.js";import{b as q,c as Z}from"./chunk-MLFJU2US.js";import{a as J}from"./chunk-GXL4NMHR.js";import{c as z,d as Q}from"./chunk-PQWANILR.js";import{a as W}from"./chunk-BU7IZLKB.js";import{a as _,b as B}from"./chunk-S5PL5DFQ.js";import{K as M,j as F,m as S,n as H}from"./chunk-DDH3FP4G.js";import{a as V}from"./chunk-VDJSH3DQ.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:q,apiVersion:Z,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 k=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=ve(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=ke(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 ve(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(ve,"parseTreeEntry");function ke(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(ke,"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 k.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return D(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return D(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return D(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function D(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(D,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,$=class extends V{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Ae(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 Ae(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new $(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Ae,"createChangeAnchorResolver");import{diffLines as Pe}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=Pe(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Ue(a.value);if(a.removed){let f=Le(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)?L(t,d,`<!-- change: ${a} -->`):(L(t,d,`<!-- change-begin: ${a} -->`),L(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 L(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(L,"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 Le(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Le,"placementFor");function Ue(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Ue,"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 P=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===A(o.content)?this.#e.set(t,{...r,afterDigest:A(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:A(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!==A(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 A(n){return Ne("sha256").update(n).digest("hex")}s(A,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var N=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=F(N),v=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:{...v.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...v.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"?{...v,properties:{file:{...v.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...v.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 H(u,N,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=S(u,"INDEX_CHANGE_FAILED",c.file);return H({content:[{type:"text",text:p.message}],details:{action:n,change:c.change,file:O(c.file,f.cwd)}},N,{status:"error",data:{action:n,change:c.change,file:O(c.file,f.cwd),effect:xe(u)},errors:[p]})}}})}s(he,"createIndexChangeTool");function ze(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return async(i,d,c)=>{let a=O(i.file,c.cwd);return _e(a,()=>t.run(async()=>{let l=e.readText?await e.readText(a,d):await Fe(a,"utf8"),f=await h.create(e,m(a,c.cwd),d);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${i.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:c.cwd,...d!==void 0&&{signal:d}},i.change,n);if(u.status==="unavailable"){if("failure"in u&&u.failure!==void 0){if(n==="stage"&&u.reason==="index-write-failed"){let y=S(u.failure,"INDEX_CHANGE_FAILED",i.file);throw Object.assign(new Error(`${y.message}
3
3
  The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`,{cause:u.failure}),{effect:xe(u.failure)})}throw u.failure}throw n==="stage"&&u.reason==="stale-selector"?Object.assign(new Error(`${u.message}. Read ${i.file} with views: ["changes"] and use a current CHANGE# anchor.`),{effect:"not-applied"}):n==="stage"&&u.reason==="index-write-failed"&&!d?.aborted?new Error(`${u.message}
4
- The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function O(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(O,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as R}from"typebox";var Ke=R.Object({file:R.Optional(R.Union(q.anyOf,{description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."})),change:R.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Ke,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[I],nonAnchorValues:["last"]}],async mutate(r,o){let i=r.sourceFor("file"),d,c;if(o.change==="last")d=e.restore(i,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,m(i,r.cwd),r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:i,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},o.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(d=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;c=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:Xe(r.sourceDocument.content,d),action:"edited"}]]),...c!==void 0&&{afterWrite:c}}}}}s(ye,"createUndoMutationTool");function Xe(n,e){let t=[],r=0,o,i=0,d="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+i,insert:d}),o=void 0,i=0,d="")},"flush");for(let a of Qe(n,e)){if(!a.added&&!a.removed){c(),r+=a.value.length;continue}o??=r,a.removed?(r+=a.value.length,i+=a.value.length):d+=a.value}return c(),t}s(Xe,"createTextChanges");function qe(n){return Ze(n,de(n))}s(qe,"registerGitChanges");async function Ze(n,e){W(n,[await B({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new A,r=new G,o=le(e),i=ue(e),d={protocol:z,apiVersion:Q,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},c={protocol:Z,apiVersion:Y,id:"current-git-changes",setup(a){a.addAnchorResolver({...i,kind:I,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ye(e,t,r)),a.addTextPresenter({presenter:o})}};await Promise.all([V(n,ae),K(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
4
+ The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function O(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(O,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as R}from"typebox";var Ke=R.Object({file:R.Optional(R.Union(M.anyOf,{description:"File path or an unchanged whole-file result. Omit to use the file of the CHANGE# anchor or the last file read."})),change:R.String({description:`A CHANGE#HASH anchor from read with views: ["changes"] reverts that change to HEAD in the worktree and index; last reverts the file's last tool edit.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to revert one uncommitted Git change or the last edit a tool made to a file.",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){X(n,[await K({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new P,r=new G,o=le(e),i=ue(e),d={protocol:_,apiVersion:B,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted Git edits with CHANGE# anchors."})}},c={protocol:z,apiVersion:Q,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([Y(n,ae),W(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
@@ -1,11 +1,11 @@
1
- import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-XLWCSJMR.js";import{h as w,i as P,j as B}from"./chunk-LCWBVOII.js";import{a as u}from"./chunk-EI7MMDWY.js";import{Allow as D}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as W,parse as U}from"partial-json";function O(o,e=W.ALL){if(!(!o||o.trim().length===0))try{let t=U(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}u(O,"resolvePartial");var R=class{static{u(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),i=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 y=e.isCompleteEntry?.(c,t)??c.complete;return y||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:y}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let m=[];for(let c of s)try{e.validateEntry?.(c,t),m.push(c)}catch(y){n.push({index:c.index,reason:y instanceof Error?y.message:String(y)})}let g={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(m.length===0)return{...g,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(m,t),y=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...g,status:"recovered",appliedEntries:e.getAppliedEntries?.(y,m,t)??m.map(C=>C.index),skippedEntries:n,normalResult:y}}catch(c){return{...g,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as Q}from"@earendil-works/pi-ai";var j=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=u((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let m=u(p=>{let f=s.modelRegistry.getRegisteredNativeProvider(i.provider);if(f)o.registerProvider(K(f,p));else{let v=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...v,api:i.api,streamSimple:p})}},"register"),g=r.get(i.provider);if(g){if(g.subscribers.add(a),g.api===i.api&&d.streamSimple===g.wrapper)return;g.api=i.api,m(g.wrapper);return}let c=d.streamSimple[j];if(c){if(c.subscribers.add(a),r.set(i.provider,c),c.api===i.api)return;c.api=i.api,m(c.wrapper);return}let y=d.streamSimple.bind(d),C=new Set([a]),E=u((p,f,v)=>q(y,p,f,v,C),"wrapper"),b={api:i.api,originalStreamSimple:d.streamSimple,wrapper:E,subscribers:C};E[j]=b,m(E),r.set(i.provider,b)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r){if(s.subscribers.delete(a),s.subscribers.size!==0)continue;let d=a.context?.modelRegistry;if(d?.getProvider(i)?.streamSimple!==s.wrapper)continue;let g=d?.getRegisteredNativeProvider(i);g?o.registerProvider(K(g,s.originalStreamSimple)):o.unregisterProvider(i)}r.clear(),a.context=void 0})}u($,"registerStreamingInterceptorProvider");function K(o,e){return Object.create(Object.getPrototypeOf(o),{...Object.getOwnPropertyDescriptors(o),streamSimple:{value:e,writable:!0,enumerable:!0,configurable:!0}})}u(K,"withStreamSimple");function q(o,e,t,n,r){let a=Q(),l=new AbortController,i=n?.signal,s=!1,d=Z(e),m=new Set,g=new Set,c=new Set,y=new Set,C=u(b=>{for(let p of r)p.markStreamEventProcessed(b)},"markStreamEventProcessed"),E=u(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let b=o(e,t,{...n,signal:l.signal});for await(let p of b){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),J(p,m);let f;for(let v of r){let I=v.context;if(I){let T=await v.processStreamEvent(p,I);f??=T}}if(C(p),V(p,g,c,y),a.push(structuredClone(p)),f){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);s=!0,l.abort();let v=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,S)=>m.has(S)&&(v===void 0||S<=v||y.has(S))).map(x=>x.type==="toolCall"&&x.id===f.toolCallId?{...x,arguments:structuredClone(f.arguments)}:x)};Y(a,C,I,m,g,c,y);let{errorMessage:T,...H}=I;a.push({type:"done",reason:"toolUse",message:{...H,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(b){if(s)return;let p=d,f=i?.aborted===!0?"aborted":"error",v={...p,stopReason:f,errorMessage:b instanceof Error?b.message:String(b)};a.push({type:"error",reason:f,error:v}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}u(q,"wrapStream");function J(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}u(J,"rememberStartEvent");function V(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}}}u(V,"rememberEndEvent");function Y(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}u(Y,"emitMissingEndEvents");function Z(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()}}u(Z,"emptyAssistantMessage");var ee="agentic-ide-partial-tool-recovery",L="pi-agent-text-editor/tool-call-annotation",A=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",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
3
- `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(i,"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 i=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return i!==void 0&&this.completedBatchEntryIndexes.add(i),{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{u(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)??{},i=ne(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let m=i!==void 0;if(m&&this.completeArgumentContentIndices.has(e.contentIndex))return;m&&this.completeArgumentContentIndices.add(e.contentIndex);let g=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:g},args:g,...!m&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),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 i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=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),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=G(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=G(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(L,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=te(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 i={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:i,...r&&{blockExecution:!0}}),i}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,s=(h.IsObjectNotArray(l)&&h.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)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=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(y=>y.ctx.batchEntryIndex).filter(y=>y!==void 0))],s=[...new Set(r.map(y=>y.ctx.toolCall.id))],d=r.map(y=>y.blocked.message.details),m=r[0],g=m?this.recoveryRegistry.recoveryKeyFor(m.ctx.toolCall.name):void 0;if(!g)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:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:g,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?ae(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=u(()=>{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 G(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}`}u(G,"toolStreamEventKey");function te(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"}u(te,"abortReason");function ne(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}u(ne,"parseCompleteArguments");function re(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(s=>h.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(m=>typeof m=="string"):[]});return[...new Set(i)]}u(re,"freshAnchorsAfterRecovery");function oe(o,e){let n=o.indexOf(`
1
+ import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-GS5ZRTUG.js";import{l as w,m as P,n as B}from"./chunk-DDH3FP4G.js";import{a as m}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as W,parse as U}from"partial-json";function O(o,e=W.ALL){if(!(!o||o.trim().length===0))try{let t=U(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}m(O,"resolvePartial");var S=class{static{m(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),d=e.extractEntries(t).filter(u=>{if(r.has(u.index))return n.push({index:u.index,reason:"entry already completed before recovery"}),!1;if(a.has(u.index))return n.push({index:u.index,reason:"entry was blocked by a guard"}),!1;let p=e.isCompleteEntry?.(u,t)??u.complete;return p||n.push({index:u.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&u.index>=t.staleEntryIndex?!1:p}),l=e.filterEntries?.(d,t)??d,s=new Set(l.map(u=>u.index));for(let u of d)s.has(u.index)||n.push({index:u.index,reason:"entry was excluded by recovery filtering"});let c=[];for(let u of l)try{e.validateEntry?.(u,t),c.push(u)}catch(p){n.push({index:u.index,reason:p instanceof Error?p.message:String(p)})}let g={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(c.length===0)return{...g,status:"skipped",appliedEntries:[],skippedEntries:n};try{let u=e.buildParams(c,t),p=await e.execute(u,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...g,status:"recovered",appliedEntries:e.getAppliedEntries?.(p,c,t)??c.map(v=>v.index),skippedEntries:n,normalResult:p}}catch(u){return{...g,status:"failed",appliedEntries:[],skippedEntries:n,error:u instanceof Error?u.message:String(u)}}}};import{createAssistantMessageEventStream as Q}from"@earendil-works/pi-ai";var j=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},i=m((s,c)=>{if(!s)return;let g=c.modelRegistry.getProvider(s.provider);if(!g)return;let u=m(f=>{let x=c.modelRegistry.getRegisteredNativeProvider(s.provider);if(x)o.registerProvider(D(x,f));else{let I=c.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...I,api:s.api,streamSimple:f})}},"register"),p=r.get(s.provider);if(p){if(p.subscribers.add(a),p.api===s.api&&g.streamSimple===p.wrapper)return;p.api=s.api,u(p.wrapper);return}let v=g.streamSimple[j];if(v){if(v.subscribers.add(a),r.set(s.provider,v),v.api===s.api)return;v.api=s.api,u(v.wrapper);return}let R=g.streamSimple.bind(g),C=new Set([a]),y=m((f,x,I)=>q(R,f,x,I,C),"wrapper"),b={api:s.api,originalStreamSimple:g.streamSimple,wrapper:y,subscribers:C};y[j]=b,u(y),r.set(s.provider,b)},"install"),d=!1,l=m((s,c)=>{d||(a.context=s,i(c??s.model,s))},"attach");o.on("before_provider_request",(s,c)=>l(c)),o.on("turn_start",(s,c)=>l(c)),o.on("agent_start",(s,c)=>l(c)),o.on("session_start",(s,c)=>{d=!1,l(c)}),o.on("model_select",(s,c)=>l(c,s.model)),o.on("session_shutdown",()=>{d=!0;for(let[s,c]of r){if(c.subscribers.delete(a),c.subscribers.size!==0)continue;let g=a.context?.modelRegistry;if(g?.getProvider(s)?.streamSimple!==c.wrapper)continue;let p=g?.getRegisteredNativeProvider(s);p?o.registerProvider(D(p,c.originalStreamSimple)):o.unregisterProvider(s)}r.clear(),a.context=void 0})}m(K,"registerStreamingInterceptorProvider");function D(o,e){return Object.create(Object.getPrototypeOf(o),{...Object.getOwnPropertyDescriptors(o),streamSimple:{value:e,writable:!0,enumerable:!0,configurable:!0}})}m(D,"withStreamSimple");function q(o,e,t,n,r){let a=Q(),i=new AbortController,d=n?.signal,l=!1,s=Z(e),c=new Set,g=new Set,u=new Set,p=new Set,v=m(C=>{for(let y of r)y.markStreamEventProcessed(C)},"markStreamEventProcessed"),R=m(()=>{i.abort()},"abortFromParent");return d&&(d.aborted?i.abort():d.addEventListener("abort",R,{once:!0})),(async()=>{try{let C=o(e,t,{...n,signal:i.signal});for await(let y of C){if(l)continue;y.type==="done"?s=structuredClone(y.message):y.type==="error"?s=structuredClone(y.error):s=structuredClone(y.partial),J(y,c);let b;for(let f of r){let x=f.context;if(x){let I=await f.processStreamEvent(y,x);b??=I}}if(v(y),V(y,g,u,p),a.push(structuredClone(y)),b){if(y.type==="toolcall_delta"||y.type==="toolcall_end")for(let E of r)E.finalizeStreamInterception(y.contentIndex);l=!0,i.abort();let f=y.type==="toolcall_delta"||y.type==="toolcall_end"?y.contentIndex:void 0,x={...s,content:s.content.filter((E,A)=>c.has(A)&&(f===void 0||A<=f||p.has(A))).map(E=>E.type==="toolCall"&&E.id===b.toolCallId?{...E,arguments:structuredClone(b.arguments)}:E)};Y(a,v,x,c,g,u,p);let{errorMessage:I,...H}=x;a.push({type:"done",reason:"toolUse",message:{...H,stopReason:"toolUse"}}),a.end();continue}if(y.type==="done"||y.type==="error"){a.end();return}}}catch(C){if(l)return;let y=s,b=d?.aborted===!0?"aborted":"error",f={...y,stopReason:b,errorMessage:C instanceof Error?C.message:String(C)};a.push({type:"error",reason:b,error:f}),a.end()}finally{d?.removeEventListener("abort",R)}})(),a}m(q,"wrapStream");function J(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}m(J,"rememberStartEvent");function V(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}}}m(V,"rememberEndEvent");function Y(o,e,t,n,r,a,i){for(let[d,l]of t.content.entries())if(n.has(d)){if(l.type==="text"&&!r.has(d)){let s={type:"text_end",contentIndex:d,content:l.text,partial:t};e(s),o.push(s)}else if(l.type==="thinking"&&!a.has(d)){let s={type:"thinking_end",contentIndex:d,content:l.thinking,partial:t};e(s),o.push(s)}else if(l.type==="toolCall"&&!i.has(d)){let s={type:"toolcall_end",contentIndex:d,toolCall:l,partial:t};e(s),o.push(s)}}}m(Y,"emitMissingEndEvents");function Z(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()}}m(Z,"emptyAssistantMessage");var ee="agentic-ide-partial-tool-recovery",L="pi-agent-text-editor/tool-call-annotation",k=new WeakMap,T=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(i=>i.type==="text").map(i=>i.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,i=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",d=r.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
3
+ `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(d,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:i,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 i=a.details;i!==void 0&&w(i);let d=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return d!==void 0&&this.completedBatchEntryIndexes.add(d),{message:{...t.message,content:a.content,...i!==void 0&&{details:i},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{m(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new S;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 i=O(a,$.OBJ|$.ARR)??{},d=ne(a),l=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:l,toolName:n,args:i,complete:d!==void 0});let s=this.handlers.get(n);if(!r||!s||s.length===0||!d&&Object.keys(i).length===0)return;let c=d!==void 0;if(c&&this.completeArgumentContentIndices.has(e.contentIndex))return;c&&this.completeArgumentContentIndices.add(e.contentIndex);let g=d??i,u=await this.dispatchHandlers(s,{toolCall:{id:r,name:n,arguments:g},args:g,...!c&&{partialArgs:i},batchEntryIndex:l,batchEntries:this.getBatchEntries(l),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return u&&this.rememberOriginalArguments(u.toolCallId,u.arguments),u}):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 i=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...i?.guardResult&&{guardResult:i.guardResult},...i?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let d=!this.completeArgumentContentIndices.has(e.contentIndex),l;d&&(this.completeArgumentContentIndices.add(e.contentIndex),l=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 s=this.streamedBatchEntries.get(e.contentIndex);return s&&this.streamedBatchEntries.set(e.contentIndex,{...s,complete:!0}),this.cleanupContent(e.contentIndex,n),l}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=G(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=G(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(L,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=te(e,n),i=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,i));let d={content:[{type:"text",text:e.message.content}],details:M(e.message.details,i,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:d,...r&&{blockExecution:!0}}),d}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 i=a.message.details,l=(h.IsObjectNotArray(i)&&h.IsObjectNotArray(i.recovery)?i.recovery:void 0)?.appliedEntries;if(Array.isArray(l))for(let s of l)typeof s=="number"&&this.recoveryAppliedBatchIndexes.add(s)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,i=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,d=[...new Set(r.map(p=>p.ctx.batchEntryIndex).filter(p=>p!==void 0))],l=[...new Set(r.map(p=>p.ctx.toolCall.id))],s=r.map(p=>p.blocked.message.details),c=r[0],g=c?this.recoveryRegistry.recoveryKeyFor(c.ctx.toolCall.name):void 0;if(!g)return e;let u=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...i!==void 0&&{staleEntryIndex:i},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:d,blockedToolCallIds:l,blockedDetails:s,recoveryKey:g,cwd:t.cwd,ctx:t.ctx});return u&&(u.appliedEntries.length>0||u.skippedEntries.length>0)?ae(e,u):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=m(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let i of a??[])i.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 i of a??[])n&&i.onAbort?.(e),i.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(i=>i.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 G(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}`}m(G,"toolStreamEventKey");function te(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"}m(te,"abortReason");function ne(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}m(ne,"parseCompleteArguments");function re(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(l=>h.IsObjectNotArray(l.data)?l.data:l),a=n===void 0?r:r.filter(l=>l.path===n),d=(a.length>0?a:r).flatMap(l=>{let s=l.freshAnchors;return Array.isArray(s)?s.filter(c=>typeof c=="string"):[]});return[...new Set(d)]}m(re,"freshAnchorsAfterRecovery");function oe(o,e){let n=o.indexOf(`
4
4
 
5
5
  Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
6
 
7
7
  Current nearby anchors:
8
8
  ${e.map(a=>` ${a}`).join(`
9
- `)}`}u(oe,"replaceCurrentAnchors");function ae(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(m=>`${m.index} (${m.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=re(e),i=l.length>0&&h.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,s=l.length>0?oe(o.message.content,l):o.message.content,d=l.length>0&&h.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:ee,content:`${s}
9
+ `)}`}m(oe,"replaceCurrentAnchors");function ae(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(c=>`${c.index} (${c.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",i=re(e),d=i.length>0&&h.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:i}:o.message.details,l=i.length>0?oe(o.message.content,i):o.message.content,s=i.length>0&&h.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:i}}:e;return{message:{customType:ee,content:`${l}
10
10
 
11
- [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:i,recovery:d}}}}u(ae,"makeRecoveryResult");var z=new WeakMap;function F(o){let e=z.get(o);if(e)return e;let t=new k(o);return z.set(o,t),$(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}u(F,"coordinatorFor");function se(o,e){F(o).register(e)}u(se,"registerToolCallInterceptor");function ie(o,e){if(A.get(o)?.(),A.delete(o),e===void 0)return;let t=o.events.on(L,n=>{!h.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});A.set(o,t)}u(ie,"registerToolCallAnnotationSink");function Re(o,e){F(o).registerBlockedCallSink(e)}u(Re,"registerBlockedToolCallSink");export{se as a,ie as b,Re as c};
11
+ [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:d,recovery:s}}}}m(ae,"makeRecoveryResult");var z=new WeakMap;function F(o){let e=z.get(o);if(e)return e;let t=new T(o);return z.set(o,t),K(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}m(F,"coordinatorFor");function se(o,e){F(o).register(e)}m(se,"registerToolCallInterceptor");function ie(o,e){if(k.get(o)?.(),k.delete(o),e===void 0)return;let t=o.events.on(L,n=>{!h.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});k.set(o,t)}m(ie,"registerToolCallAnnotationSink");function Re(o,e){F(o).registerBlockedCallSink(e)}m(Re,"registerBlockedToolCallSink");export{se as a,ie as b,Re as c};
@@ -1 +1 @@
1
- import{a as v}from"./chunk-BXGMMZT3.js";import{b as E,c as A,d as j}from"./chunk-756K3LJY.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import F from"cross-spawn";import{access as M,readFile as P,writeFile as D}from"node:fs/promises";import _ from"node:os";import l from"node:path";import{fileURLToPath as U}from"node:url";var N=1;function se(e){return l.win32.basename(h(e[0]))}a(se,"configuredExecutableName");async function ae(e,o,n,r,i){i?.throwIfAborted();let s=l.resolve(e),t=l.resolve(s,o),c=r.filter(d=>H(d,t));if(X(s,t))return s;let f=l.dirname(t);for(;;){if(i?.throwIfAborted(),await Q(S(f,n),i)||[...(await v(f,c,void 0,i)).values()].some(p=>p.score>0))return f;let u=l.dirname(f);if(u===f)return;f=u}}a(ae,"resolveExternalToolProjectRoot");function G(e){return l.join(e,".pi","pi-agent-ide")}a(G,"projectIdeConfigDirectory");function S(e,o){return l.join(G(e),`${o}.json`)}a(S,"projectIdeConfigPath");function B(e,o,n={}){let i=(n.environment??process.env).PI_CODING_AGENT_DIR?.trim(),s=i===void 0||i.length===0?l.join(n.homeDirectory??_.homedir(),".pi","agent"):l.resolve(i);return{project:S(e,o),global:l.join(s,"extensions","pi-agent-ide",`${o}.json`),builtIn:U(new URL(`tool-config/${o}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}a(B,"resolveToolConfigPaths");async function le(e,o,n,r={}){let i=r.signal;i?.throwIfAborted();let s=r.layerAccess;if(e.includes("://")&&!s)throw Object.assign(new Error("No config owner for this project"),{code:"UNSUPPORTED_SOURCE"});let t={...B(e,o,r),...s?await s.paths(e,o,i):{}},c=[{layer:"project",sourcePath:t.project,optional:!0},...r.includeGlobal===!1?[]:[{layer:"global",sourcePath:t.global,optional:!0}],{layer:"built-in",sourcePath:t.builtIn,optional:!1}],f=[],d=new Set;for(let u of c){i?.throwIfAborted();let p=await z(u,o,n,u.layer!=="built-in"&&s?m=>s.readText(m,i):void 0,i);for(let[m,C]of Object.entries(p))d.has(m)||(d.add(m),f.push({id:m,config:C,layer:u.layer,sourcePath:u.sourcePath}))}return{entries:f,paths:t}}a(le,"loadLayeredToolConfig");function J(e,o,n){let r=l.extname(o).toLowerCase();if(e.extensions.every(t=>!(L(t)===r||t==="*"))&&!e.fileNames?.some(t=>process.platform==="win32"?t.toLowerCase()===l.basename(o).toLowerCase():t===l.basename(o)))return!1;let i=l.relative(n,o).split(l.sep).join("/"),s=a(t=>t?.some(c=>l.matchesGlob(i,c))??!1,"matches");return(e.include===void 0||s(e.include))&&!s(e.exclude)}a(J,"matchesConfiguredFile");function ce(e,o,n,r,i){let s=l.resolve(i,r),t=e.filter(d=>J(d.config,s,i)),c=t.find(d=>d.layer!=="built-in");if(c!==void 0)return c;let f=Math.max(0,...t.map(d=>n.get(d.id)?.score??0));return t.find(d=>o.has(d.id)&&(n.get(d.id)?.score??0)===f)}a(ce,"selectConfiguredEntry");async function q(e,o,n=process.env,r){r?.throwIfAborted(),w(e,"process");let i=h(e.command[0]).replaceAll("{project}",o),s=k(e,o,n);return j(i,o,s,r)}a(q,"hasConfiguredExecutable");async function fe(e,o,n,r){if(r.signal?.throwIfAborted(),e.includes("://")&&!r.executableAvailability)throw Object.assign(new Error("Tool probes require their resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r.executableAvailability?await r.executableAvailability(o.map(t=>t.config),r.signal):await Promise.all(o.map(t=>q(t.config,e,r.environment??process.env,r.signal)));if(r.signal?.throwIfAborted(),i.length!==o.length||i.some(t=>typeof t!="boolean"))throw new TypeError("Invalid tool executable availability report");let s=r.recipeEvidence?await r.recipeEvidence(n,r.signal):await v(e,n,void 0,r.signal);return r.signal?.throwIfAborted(),{available:new Set(o.filter((t,c)=>i[c]===!0&&(!r.requireBuiltInEvidence||(s.get(t.id)?.score??0)>0)).map(t=>t.id)),evidence:s}}a(fe,"toolRuntimeEvidence");async function V(e,o){if(w(e,"process"),o.processAccess)return o.processAccess.run(e,o);if(o.projectRoot.includes("://")||o.filePath.includes("://"))throw Object.assign(new Error("No process owner for this resource"),{code:"UNSUPPORTED_SOURCE"});let n=e.command.map(f=>W(f,o)),r=h(n[0]),i=n.slice(1),s=e.cwd==="file"?l.dirname(o.filePath):o.projectRoot,t=e.successExitCodes??[0],c=k(e,o.projectRoot,o.env??process.env);return new Promise((f,d)=>{let u=F(r,i,{cwd:s,env:c,signal:o.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),p="",m="",C=h(u.stdout),x=h(u.stderr),T=!1,R=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);C.setEncoding("utf8"),x.setEncoding("utf8"),C.on("data",g=>{p+=g}),x.on("data",g=>{m+=g}),u.on("error",g=>{clearTimeout(R),d(g)}),u.on("close",g=>{clearTimeout(R),f({ok:!T&&g!==null&&t.includes(g),exitCode:g,stdout:p,stderr:m})})})}a(V,"runConfiguredProcess");async function de(e,o){let n=await P(o.filePath,"utf8"),r=await V(e.run,o);if(!r.ok)return{ok:!1,changed:await P(o.filePath,"utf8")!==n};e.output==="stdout"&&r.stdout!==n&&await D(o.filePath,r.stdout,"utf8");let i=await P(o.filePath,"utf8");return{ok:!0,changed:n!==i}}a(de,"runConfiguredFormatter");function ue(e){let o=$(e,"formatters");for(let[n,r]of Object.entries(o.entries)){let i=y(r,`formatter ${n}`);if(O(i,`formatter ${n}`),w(i.run,`formatter ${n}.run`),i.output!=="in-place"&&i.output!=="stdout")throw new Error(`formatter ${n}.output must be in-place or stdout`)}return e}a(ue,"parseFormattersConfig");function ge(e){let o=$(e,"linters"),n=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,i]of Object.entries(o.entries)){let s=y(i,`linter ${r}`);O(s,`linter ${r}`),w(s.check,`linter ${r}.check`),s.fix!==void 0&&w(s.fix,`linter ${r}.fix`);let t=y(s.diagnostics,`linter ${r}.diagnostics`);if(!n.has(String(t.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(t.columnBase!==void 0&&(t.format!=="regex"||t.columnBase!==0&&t.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(t.format==="regex"&&typeof t.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}a(ge,"parseLintersConfig");function $(e,o){let n=y(e,"tool config");if(n.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:y(n[o],o)}}a($,"configRoot");function O(e,o){b(e.extensions,`${o}.extensions`,!1),e.fileNames!==void 0&&b(e.fileNames,`${o}.fileNames`,!1),e.include!==void 0&&b(e.include,`${o}.include`,!1),e.exclude!==void 0&&b(e.exclude,`${o}.exclude`,!0)}a(O,"assertMatcher");function w(e,o){let n=y(e,o);if(b(n.command,`${o}.command`,!1),n.cwd!==void 0&&n.cwd!=="project"&&n.cwd!=="file")throw new Error(`${o}.cwd must be project or file`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||Number(n.timeoutMs)<=0))throw new Error(`${o}.timeoutMs must be positive`);if(n.successExitCodes!==void 0&&(!Array.isArray(n.successExitCodes)||n.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${o}.successExitCodes must contain integers`);if(n.env!==void 0){let r=y(n.env,`${o}.env`);if(Object.values(r).some(i=>typeof i!="string"))throw new Error(`${o}.env values must be strings`)}}a(w,"assertProcessConfig");function b(e,o,n){if(!Array.isArray(e)||!n&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${o} must be ${n?"an":"a non-empty"} array of strings`)}a(b,"assertStringArray");function y(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${o} must be an object`);return e}a(y,"configRecord");function L(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}a(L,"normalizeExtension");async function z(e,o,n,r,i){i?.throwIfAborted();let s;try{s=r?await r(e.sourcePath):await P(e.sourcePath,{encoding:"utf8",signal:i})}catch(t){if(i?.throwIfAborted(),e.optional&&K(t))return{};throw new Error(`Cannot read ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}i?.throwIfAborted();try{return n(JSON.parse(s))}catch(t){throw new Error(`Invalid ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}}a(z,"readToolConfigLayer");function K(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}a(K,"isMissingFile");function I(e){return e instanceof Error?e.message:String(e)}a(I,"errorMessage");function k(e,o,n){return A(o,{...E(n),...E(e.env??{})})}a(k,"createConfiguredProcessEnvironment");function W(e,o){let n=l.relative(o.projectRoot,o.filePath);return e.replaceAll("{project}",o.projectRoot).replaceAll("{fileDir}",l.dirname(o.filePath)).replaceAll("{relativeFile}",n).replaceAll("{file}",o.filePath)}a(W,"expandPlaceholders");function H(e,o){let n=l.extname(o).toLowerCase(),r=l.basename(o),i=a((s,t=[])=>s.some(c=>L(c)===n)||t.some(c=>c===r),"matches");return e.formatter?i(e.formatter.extensions,e.formatter.fileNames):e.linter?i(e.linter.extensions,e.linter.fileNames):e.lsp?i(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}a(H,"recipeMatchesFile");async function Q(e,o){o?.throwIfAborted();try{return await M(e),o?.throwIfAborted(),!0}catch{return o?.throwIfAborted(),!1}}a(Q,"fileExists");function X(e,o){let n=l.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}a(X,"isPathInside");export{N as a,se as b,ae as c,G as d,S as e,B as f,le as g,J as h,ce as i,q as j,fe as k,V as l,de as m,ue as n,ge as o,k as p,H as q};
1
+ import{a as E}from"./chunk-BXGMMZT3.js";import{b as v,c as A,d as j}from"./chunk-756K3LJY.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import F from"cross-spawn";import{access as M,readFile as P,writeFile as D}from"node:fs/promises";import _ from"node:os";import l from"node:path";import{fileURLToPath as U}from"node:url";var N=1;function se(e){return l.win32.basename(h(e[0]))}a(se,"configuredExecutableName");async function ae(e,o,n,r,i){i?.throwIfAborted();let s=l.resolve(e),t=l.resolve(s,o),c=r.filter(d=>H(d,t));if(X(s,t))return s;let f=l.dirname(t);for(;;){if(i?.throwIfAborted(),await Q(S(f,n),i)||[...(await E(f,c,void 0,i)).values()].some(p=>p.score>0))return f;let u=l.dirname(f);if(u===f)return;f=u}}a(ae,"resolveExternalToolProjectRoot");function G(e){return l.join(e,".pi","pi-agent-ide")}a(G,"projectIdeConfigDirectory");function S(e,o){return l.join(G(e),`${o}.json`)}a(S,"projectIdeConfigPath");function B(e,o,n={}){let i=(n.environment??process.env).PI_CODING_AGENT_DIR?.trim(),s=i===void 0||i.length===0?l.join(n.homeDirectory??_.homedir(),".pi","agent"):l.resolve(i);return{project:S(e,o),global:l.join(s,"extensions","pi-agent-ide",`${o}.json`),builtIn:U(new URL(`tool-config/${o}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}a(B,"resolveToolConfigPaths");async function le(e,o,n,r={}){let i=r.signal;i?.throwIfAborted();let s=r.layerAccess;if(e.includes("://")&&!s)throw Object.assign(new Error("No config owner for this project"),{code:"UNSUPPORTED_SOURCE"});let t={...B(e,o,r),...s?await s.paths(e,o,i):{}},c=[{layer:"project",sourcePath:t.project,optional:!0},...r.includeGlobal===!1?[]:[{layer:"global",sourcePath:t.global,optional:!0}],{layer:"built-in",sourcePath:t.builtIn,optional:!1}],f=[],d=new Set;for(let u of c){i?.throwIfAborted();let p=await z(u,o,n,u.layer!=="built-in"&&s?m=>s.readText(m,i):void 0,i);for(let[m,C]of Object.entries(p))d.has(m)||(d.add(m),f.push({id:m,config:C,layer:u.layer,sourcePath:u.sourcePath}))}return{entries:f,paths:t}}a(le,"loadLayeredToolConfig");function J(e,o,n){let r=l.extname(o).toLowerCase();if(e.extensions.every(t=>!(L(t)===r||t==="*"))&&!e.fileNames?.some(t=>process.platform==="win32"?t.toLowerCase()===l.basename(o).toLowerCase():t===l.basename(o)))return!1;let i=l.relative(n,o).split(l.sep).join("/"),s=a(t=>t?.some(c=>l.matchesGlob(i,c))??!1,"matches");return(e.include===void 0||s(e.include))&&!s(e.exclude)}a(J,"matchesConfiguredFile");function ce(e,o,n,r,i){let s=l.resolve(i,r),t=e.filter(d=>J(d.config,s,i)),c=t.find(d=>d.layer!=="built-in");if(c!==void 0)return c;let f=Math.max(0,...t.map(d=>n.get(d.id)?.score??0));return t.find(d=>o.has(d.id)&&(n.get(d.id)?.score??0)===f)}a(ce,"selectConfiguredEntry");async function q(e,o,n=process.env,r){r?.throwIfAborted(),w(e,"process");let i=h(e.command[0]).replaceAll("{project}",o),s=k(e,o,n);return j(i,o,s,r)}a(q,"hasConfiguredExecutable");async function fe(e,o,n,r){if(r.signal?.throwIfAborted(),e.includes("://")&&!r.executableAvailability)throw Object.assign(new Error("Tool probes require their resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r.executableAvailability?await r.executableAvailability(o.map(t=>t.config),r.signal):await Promise.all(o.map(t=>q(t.config,e,r.environment??process.env,r.signal)));if(r.signal?.throwIfAborted(),i.length!==o.length||i.some(t=>typeof t!="boolean"))throw new TypeError("Invalid tool executable availability report");let s=r.recipeEvidence?await r.recipeEvidence(n,r.signal):await E(e,n,void 0,r.signal);return r.signal?.throwIfAborted(),{available:new Set(o.filter((t,c)=>i[c]===!0&&(!r.requireBuiltInEvidence||(s.get(t.id)?.score??0)>0)).map(t=>t.id)),evidence:s}}a(fe,"toolRuntimeEvidence");async function V(e,o){if(w(e,"process"),o.processAccess)return o.processAccess.run(e,o);if(o.projectRoot.includes("://")||o.filePath.includes("://"))throw Object.assign(new Error("No process owner for this resource"),{code:"UNSUPPORTED_SOURCE"});let n=e.command.map(f=>W(f,o)),r=h(n[0]),i=n.slice(1),s=e.cwd==="file"?l.dirname(o.filePath):o.projectRoot,t=e.successExitCodes??[0],c=k(e,o.projectRoot,o.env??process.env);return new Promise((f,d)=>{let u=F(r,i,{cwd:s,env:c,signal:o.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),p="",m="",C=h(u.stdout),x=h(u.stderr),T=!1,R=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);C.setEncoding("utf8"),x.setEncoding("utf8"),C.on("data",g=>{p+=g}),x.on("data",g=>{m+=g}),u.on("error",g=>{clearTimeout(R),d(g)}),u.on("close",g=>{clearTimeout(R),f({ok:!T&&g!==null&&t.includes(g),exitCode:g,stdout:p,stderr:m})})})}a(V,"runConfiguredProcess");async function de(e,o){let n=await P(o.filePath,"utf8"),r=await V(e.run,o);if(!r.ok)return{ok:!1,changed:await P(o.filePath,"utf8")!==n};e.output==="stdout"&&r.stdout!==n&&await D(o.filePath,r.stdout,"utf8");let i=await P(o.filePath,"utf8");return{ok:!0,changed:n!==i}}a(de,"runConfiguredFormatter");function ue(e){let o=$(e,"formatters");for(let[n,r]of Object.entries(o.entries)){let i=y(r,`formatter ${n}`);if(O(i,`formatter ${n}`),w(i.run,`formatter ${n}.run`),i.output!=="in-place"&&i.output!=="stdout")throw new Error(`formatter ${n}.output must be in-place or stdout`)}return e}a(ue,"parseFormattersConfig");function ge(e){let o=$(e,"linters"),n=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,i]of Object.entries(o.entries)){let s=y(i,`linter ${r}`);O(s,`linter ${r}`),w(s.check,`linter ${r}.check`),s.fix!==void 0&&w(s.fix,`linter ${r}.fix`);let t=y(s.diagnostics,`linter ${r}.diagnostics`);if(!n.has(String(t.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(t.columnBase!==void 0&&(t.format!=="regex"||t.columnBase!==0&&t.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(t.format==="regex"&&typeof t.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}a(ge,"parseLintersConfig");function $(e,o){let n=y(e,"tool config");if(n.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:y(n[o],o)}}a($,"configRoot");function O(e,o){b(e.extensions,`${o}.extensions`,!1),e.fileNames!==void 0&&b(e.fileNames,`${o}.fileNames`,!1),e.include!==void 0&&b(e.include,`${o}.include`,!1),e.exclude!==void 0&&b(e.exclude,`${o}.exclude`,!0)}a(O,"assertMatcher");function w(e,o){let n=y(e,o);if(b(n.command,`${o}.command`,!1),n.cwd!==void 0&&n.cwd!=="project"&&n.cwd!=="file")throw new Error(`${o}.cwd must be project or file`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||Number(n.timeoutMs)<=0))throw new Error(`${o}.timeoutMs must be positive`);if(n.successExitCodes!==void 0&&(!Array.isArray(n.successExitCodes)||n.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${o}.successExitCodes must contain integers`);if(n.env!==void 0){let r=y(n.env,`${o}.env`);if(Object.values(r).some(i=>typeof i!="string"))throw new Error(`${o}.env values must be strings`)}}a(w,"assertProcessConfig");function b(e,o,n){if(!Array.isArray(e)||!n&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${o} must be ${n?"an":"a non-empty"} array of strings`)}a(b,"assertStringArray");function y(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${o} must be an object`);return e}a(y,"configRecord");function L(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}a(L,"normalizeExtension");async function z(e,o,n,r,i){i?.throwIfAborted();let s;try{s=r?await r(e.sourcePath):await P(e.sourcePath,{encoding:"utf8",signal:i})}catch(t){if(i?.throwIfAborted(),e.optional&&K(t))return{};throw new Error(`Cannot read ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}i?.throwIfAborted();try{return n(JSON.parse(s))}catch(t){throw new Error(`Invalid ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}}a(z,"readToolConfigLayer");function K(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}a(K,"isMissingFile");function I(e){return e instanceof Error?e.message:String(e)}a(I,"errorMessage");function k(e,o,n){return A(o,{...v(n),...v(e.env??{})})}a(k,"createConfiguredProcessEnvironment");function W(e,o){let n=l.relative(o.projectRoot,o.filePath);return e.replaceAll("{project}",o.projectRoot).replaceAll("{fileDir}",l.dirname(o.filePath)).replaceAll("{relativeFile}",n).replaceAll("{file}",o.filePath)}a(W,"expandPlaceholders");function H(e,o){let n=l.extname(o).toLowerCase(),r=l.basename(o),i=a((s,t=[])=>s.some(c=>L(c)===n)||t.some(c=>c===r),"matches");return e.formatter?i(e.formatter.extensions,e.formatter.fileNames):e.linter?i(e.linter.extensions,e.linter.fileNames):e.lsp?i(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}a(H,"recipeMatchesFile");async function Q(e,o){o?.throwIfAborted();try{return await M(e),o?.throwIfAborted(),!0}catch{return o?.throwIfAborted(),!1}}a(Q,"fileExists");function X(e,o){let n=l.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}a(X,"isPathInside");export{N as a,se as b,ae as c,G as d,S as e,B as f,le as g,J as h,ce as i,q as j,fe as k,V as l,de as m,ue as n,ge as o,k as p,H as q};
@@ -0,0 +1 @@
1
+ import{K as d,j as c}from"./chunk-DDH3FP4G.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},O=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),S=e.Union([e.Object({...g,fuzzy:e.Optional(O)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),y=c(S);function x(o,l,r,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((n,a)=>({source:n.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:n.lineNumber,startColumn:n.startColumn,endLine:n.endLineNumber??n.lineNumber,endColumn:n.endColumn},...Buffer.byteLength(n.matchedText)<=4096?{matchedText:n.matchedText}:{textTruncated:!0},...r===void 0?{}:{references:{line:`SEARCH#${r}:${a+1}:line`,match:`SEARCH#${r}:${a+1}:match`}}})),...l&&r!==void 0?{all:{line:`SEARCH#${r}:all:line`,match:`SEARCH#${r}:all:match`}}:{}}}s(x,"selectionData");import{Type as t}from"typebox";var j=t.Object({query:t.String({minLength:1,description:"Text to find or a Boolean expression. Quote text to keep it literal. Use regex:<pattern> for regular expressions."}),path:t.Optional(t.Union(d.anyOf,{description:"File, directory, URL (no read needed first), docs:all for all packaged guide bodies, docs:<id> for one guide, unchanged Read/Search/edit result, its UUID, or an array of such results. Use literal text or regex: for docs: sources. Results select only their registered ranges."})),include:t.Optional(t.String({description:"Optional include glob for local or SSH files"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local or SSH files"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),multiline:t.Optional(t.Boolean({description:"Let text or regex:<pattern> match across lines; . also matches line breaks. Local or SSH files and result scopes only."})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum displayed items, including compact file summaries (default 50)."}))},{additionalProperties:!1});export{O as a,S as b,y as c,x as d,j as e};
@@ -0,0 +1 @@
1
+ import{g as n}from"./chunk-4IWEKRSP.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as h}from"node:fs/promises";import{Type as t}from"typebox";import{Value as f}from"typebox/value";var w=t.Object({pid:t.Integer({minimum:1}),parentPid:t.Integer({minimum:0}),command:t.String(),started:t.String(),identity:t.String({pattern:"^[a-f0-9-]+:[0-9]+$"}),executable:t.Union([t.String(),t.Null()])}),u=t.Object({processes:t.Array(w)}),p;async function S(s,o,a,r){if(r?.throwIfAborted(),!Number.isSafeInteger(a)||a<1)throw new Error("Invalid process PID");let i=s.resolve(o);if(!i)throw new n("UNSUPPORTED_SOURCE",o,"not-applied");p??=h(new URL("./process-metadata-worker.py",new URL("../src/backend/process-metadata.ts",import.meta.url).href),"utf8");let c=await i.backend.execute("python3",["-c",await p,String(a)],i.location.path,{signal:r});if(r?.throwIfAborted(),c.exitCode!==0)throw new n("CAPABILITY_UNAVAILABLE",o,"not-applied");let e;try{e=JSON.parse(c.stdout.toString("utf8"))}catch{throw new n("INVALID_RESPONSE",o,"not-applied")}if(typeof e=="object"&&e!==null&&"error"in e){if(e.error==="ENOENT")return;let m=new Set(["CAPABILITY_UNAVAILABLE","EACCES","BYTE_LIMIT"]);throw new n(typeof e.error=="string"&&m.has(e.error)?e.error:"INVALID_RESPONSE",o,"not-applied")}if(!f.Check(u,e)||e.processes.length!==1||e.processes[0]?.pid!==a)throw new n("INVALID_RESPONSE",o,"not-applied");return e.processes[0]}d(S,"findSshProcessMetadata");async function k(s,o,a){try{await s.stop()}catch(r){if(!(r instanceof n)||r.code!=="TRANSPORT_FAILED"||!s.identity)throw r;let i;try{i=await S(o,a,s.pid)}catch(c){throw new AggregateError([r,c],"Owned SSH cleanup could not be reconciled",{cause:c})}if(i===void 0||i.identity!==s.identity)return;throw r}}d(k,"stopOwnedSshProcess");export{k as a};
@@ -1 +1 @@
1
- import{j as s}from"./chunk-IMGIDBCC.js";import{a as i}from"./chunk-EI7MMDWY.js";import{copyFile as c,mkdtemp as l,rm as p}from"node:fs/promises";import a from"node:path";function d(o){let e=o.workspace;return{environment:o.env,signal:o.signal,...e?{layerAccess:{paths:i((r,t,n)=>e.configPaths(t,n),"paths"),async readText(r,t){let n=await e.readText(r,t);if(n===void 0)throw Object.assign(new Error(`ENOENT: ${r}`),{code:"ENOENT"});return n}},executableAvailability:i((r,t)=>e.executableAvailability(r,t),"executableAvailability"),recipeEvidence:i((r,t)=>e.evidence(r,t),"recipeEvidence")}:{}}}i(d,"doctorRuntimeOptions");function f(o){let e=o.workspace;return e?{run:i((r,t)=>e.run(r,t.filePath,t.signal),"run")}:void 0}i(f,"doctorProcessAccess");async function u(o,e){if(o.signal?.throwIfAborted(),!o.workspace)return s(e,o.cwd,o.env,o.signal);let r=await o.workspace.executableAvailability([e],o.signal);if(o.signal?.throwIfAborted(),r.length!==1||typeof r[0]!="boolean")throw new TypeError("Invalid Doctor executable availability report");return r[0]}i(u,"doctorExecutableAvailable");async function w(o,e,r){if(o.signal?.throwIfAborted(),o.workspace)return o.workspace.withProbeCopy(e,r,o.signal);if(e.includes("://"))throw Object.assign(new Error(`Doctor requires the owner of ${e}`),{code:"UNSUPPORTED_SOURCE"});let t=await l(a.join(a.dirname(e),".pi-agent-ide-doctor-")),n=a.join(t,a.basename(e));try{return await c(e,n),o.signal?.throwIfAborted(),await r(n)}finally{await p(t,{recursive:!0,force:!0})}}i(w,"withDoctorProbeCopy");export{d as a,f as b,u as c,w as d};
1
+ import{j as s}from"./chunk-7D7PXIVV.js";import{a as i}from"./chunk-EI7MMDWY.js";import{copyFile as c,mkdtemp as l,rm as p}from"node:fs/promises";import a from"node:path";function d(o){let e=o.workspace;return{environment:o.env,signal:o.signal,...e?{layerAccess:{paths:i((r,t,n)=>e.configPaths(t,n),"paths"),async readText(r,t){let n=await e.readText(r,t);if(n===void 0)throw Object.assign(new Error(`ENOENT: ${r}`),{code:"ENOENT"});return n}},executableAvailability:i((r,t)=>e.executableAvailability(r,t),"executableAvailability"),recipeEvidence:i((r,t)=>e.evidence(r,t),"recipeEvidence")}:{}}}i(d,"doctorRuntimeOptions");function f(o){let e=o.workspace;return e?{run:i((r,t)=>e.run(r,t.filePath,t.signal),"run")}:void 0}i(f,"doctorProcessAccess");async function u(o,e){if(o.signal?.throwIfAborted(),!o.workspace)return s(e,o.cwd,o.env,o.signal);let r=await o.workspace.executableAvailability([e],o.signal);if(o.signal?.throwIfAborted(),r.length!==1||typeof r[0]!="boolean")throw new TypeError("Invalid Doctor executable availability report");return r[0]}i(u,"doctorExecutableAvailable");async function w(o,e,r){if(o.signal?.throwIfAborted(),o.workspace)return o.workspace.withProbeCopy(e,r,o.signal);if(e.includes("://"))throw Object.assign(new Error(`Doctor requires the owner of ${e}`),{code:"UNSUPPORTED_SOURCE"});let t=await l(a.join(a.dirname(e),".pi-agent-ide-doctor-")),n=a.join(t,a.basename(e));try{return await c(e,n),o.signal?.throwIfAborted(),await r(n)}finally{await p(t,{recursive:!0,force:!0})}}i(w,"withDoctorProbeCopy");export{d as a,f as b,u as c,w as d};