pi-agent-ide 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/{chunk-XNXQYPVT.js → chunk-4LUW26BX.js} +1 -1
  3. package/dist/{chunk-2ZMYT6ZC.js → chunk-4U6KGABH.js} +1 -1
  4. package/dist/chunk-4ZTEPMJO.js +14 -0
  5. package/dist/{chunk-KNMWCDDK.js → chunk-6ACQQBUY.js} +1 -1
  6. package/dist/chunk-76WHES5H.js +7 -0
  7. package/dist/chunk-BHSO2MDK.js +6 -0
  8. package/dist/chunk-BMOJTJJJ.js +3 -0
  9. package/dist/chunk-GFWDXTOB.js +4 -0
  10. package/dist/{chunk-VSP2QQPQ.js → chunk-GIRAEVUJ.js} +1 -1
  11. package/dist/chunk-JJVXUL5U.js +2 -0
  12. package/dist/chunk-KCEOTU5Z.js +3 -0
  13. package/dist/chunk-KVGQG43U.js +1 -0
  14. package/dist/{chunk-MTTKFJV6.js → chunk-LQYZG62K.js} +1 -1
  15. package/dist/{chunk-PETQCA7G.js → chunk-P6T3Q7LB.js} +1 -1
  16. package/dist/chunk-QIJMV2P2.js +2 -0
  17. package/dist/chunk-QJFRAMK7.js +2 -0
  18. package/dist/{chunk-2SKAED2I.js → chunk-RAZOACDD.js} +2 -2
  19. package/dist/chunk-RIGRP3FD.js +1 -0
  20. package/dist/chunk-S3ZPXWX7.js +2 -0
  21. package/dist/{chunk-266RH77Z.js → chunk-THSCUT2L.js} +1 -1
  22. package/dist/{chunk-EEH4WYI7.js → chunk-WNMGUALD.js} +1 -1
  23. package/dist/{chunk-ZIHEF6K3.js → chunk-X6MPU7UO.js} +1 -1
  24. package/dist/{chunk-SMSIT3CE.js → chunk-XF5PVZOS.js} +1 -1
  25. package/dist/{chunk-SJYDLHEF.js → chunk-ZXN3TWWW.js} +1 -1
  26. package/dist/entry-0.js +1 -1
  27. package/dist/entry-10.js +1 -1
  28. package/dist/entry-11.js +1 -1
  29. package/dist/entry-13.js +1 -1
  30. package/dist/entry-14.js +1 -1
  31. package/dist/entry-21.js +2 -1
  32. package/dist/entry-22.js +1 -1
  33. package/dist/entry-23.js +1 -1
  34. package/dist/entry-24.js +1 -1
  35. package/dist/entry-25.js +1 -1
  36. package/dist/entry-26.js +7 -1
  37. package/dist/entry-28.js +1 -1
  38. package/dist/entry-29.js +1 -1
  39. package/dist/entry-30.js +1 -1
  40. package/dist/entry-31.js +4 -1
  41. package/dist/entry-32.js +8 -1
  42. package/dist/entry-33.js +1 -1
  43. package/dist/entry-35.js +1 -1
  44. package/dist/entry-37.js +1 -1
  45. package/dist/entry-39.js +1 -1
  46. package/dist/entry-4.js +1 -1
  47. package/dist/entry-40.js +14 -1
  48. package/dist/entry-41.js +1 -1
  49. package/dist/entry-45.js +7 -1
  50. package/dist/entry-46.js +11 -1
  51. package/dist/entry-47.js +1 -1
  52. package/dist/entry-48.js +1 -1
  53. package/dist/entry-49.js +1 -1
  54. package/dist/entry-50.js +1 -1
  55. package/dist/entry-51.js +1 -1
  56. package/dist/entry-52.js +1 -1
  57. package/dist/entry-53.js +1 -1
  58. package/dist/entry-55.js +1 -1
  59. package/dist/entry-58.js +1 -1
  60. package/dist/entry-60.js +1 -1
  61. package/dist/entry-61.js +1 -1
  62. package/dist/entry-62.js +1 -1
  63. package/dist/entry-67.js +1 -1
  64. package/dist/entry-69.js +59 -1
  65. package/dist/entry-70.js +4 -1
  66. package/dist/entry-71.js +1 -1
  67. package/dist/entry-72.js +29 -1
  68. package/dist/entry-73.js +2 -1
  69. package/dist/entry-74.js +1 -1
  70. package/dist/entry-76.js +1 -1
  71. package/dist/entry-77.js +3 -1
  72. package/dist/entry-78.js +1 -1
  73. package/dist/entry-79.js +1 -1
  74. package/dist/entry-80.js +1 -1
  75. package/dist/pi-agent-ide.js +2 -13
  76. package/docs/configuration.md +25 -0
  77. package/docs/extensions.md +4 -2
  78. package/docs/tools.md +1 -1
  79. package/node_modules/pi-agent-doctor/package.json +1 -1
  80. package/node_modules/pi-agent-filesystem/index.ts +2 -2
  81. package/node_modules/pi-agent-filesystem/package.json +6 -6
  82. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  83. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  84. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  85. package/node_modules/pi-agent-ide-ast/package.json +9 -9
  86. package/node_modules/pi-agent-ide-ast/src/ast/outline.ts +89 -19
  87. package/node_modules/pi-agent-ide-ast/src/extension.ts +9 -14
  88. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +60 -0
  89. package/node_modules/pi-agent-ide-ast/src/scope-resolver.ts +1 -1
  90. package/node_modules/pi-agent-ide-changes/index.ts +1 -5
  91. package/node_modules/pi-agent-ide-changes/package.json +6 -6
  92. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +1 -7
  93. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +1 -5
  94. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  95. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +12 -7
  96. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  97. package/node_modules/pi-agent-ide-lint/index.ts +4 -1
  98. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  99. package/node_modules/pi-agent-ide-lsp/index.ts +1 -12
  100. package/node_modules/pi-agent-ide-lsp/package.json +8 -8
  101. package/node_modules/pi-agent-ide-lsp/src/diagnostic-source.ts +7 -4
  102. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +8 -1
  103. package/node_modules/pi-agent-image/package.json +2 -2
  104. package/node_modules/pi-agent-image/src/image-converter.ts +1 -1
  105. package/node_modules/pi-agent-invariant/package.json +1 -1
  106. package/node_modules/pi-agent-pdf/package.json +2 -2
  107. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +1 -1
  108. package/node_modules/pi-agent-read/package.json +6 -6
  109. package/node_modules/pi-agent-read/src/api/rendering.ts +3 -0
  110. package/node_modules/pi-agent-read/src/core/read-core.ts +6 -26
  111. package/node_modules/pi-agent-read/src/core/tools/read/native-resource-renderer.ts +74 -0
  112. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +28 -7
  113. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +35 -30
  114. package/node_modules/pi-agent-resource/package.json +1 -1
  115. package/node_modules/pi-agent-resource/src/content-conversion/content-description.ts +1 -8
  116. package/node_modules/pi-agent-search/package.json +3 -3
  117. package/node_modules/pi-agent-search/src/core/extension.ts +7 -5
  118. package/node_modules/pi-agent-search/src/core/search-core.ts +10 -0
  119. package/node_modules/pi-agent-search-text/index.ts +42 -33
  120. package/node_modules/pi-agent-search-text/package.json +6 -6
  121. package/node_modules/pi-agent-search-text/src/file-search.ts +9 -1
  122. package/node_modules/pi-agent-search-text/src/resolvers.ts +1 -1
  123. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -0
  124. package/node_modules/pi-agent-search-text/src/search-session.ts +48 -0
  125. package/node_modules/pi-agent-text/package.json +2 -2
  126. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  127. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  128. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  129. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +2 -6
  130. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  131. package/node_modules/pi-agent-text-editor/package.json +6 -6
  132. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +3 -0
  133. package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +71 -1
  134. package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +4 -12
  135. package/node_modules/pi-agent-text-editor/src/core/extension.ts +7 -9
  136. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +27 -2
  137. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +38 -0
  138. package/node_modules/pi-agent-text-editor/src/core/mutation-result/final-state-fragment.ts +2 -0
  139. package/node_modules/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +81 -0
  140. package/node_modules/pi-agent-text-editor/src/core/text-anchor-registry.ts +5 -2
  141. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +23 -0
  142. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +5 -9
  143. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +54 -14
  144. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +45 -43
  145. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +18 -8
  146. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +7 -4
  147. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +13 -5
  148. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +18 -8
  149. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -5
  150. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +2 -1
  151. package/node_modules/pi-agent-text-editor-argument-order/package.json +2 -2
  152. package/node_modules/pi-agent-text-editor-overwrite/package.json +3 -3
  153. package/node_modules/pi-agent-text-editor-renderer/index.ts +5 -1
  154. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  155. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +7 -0
  156. package/node_modules/pi-agent-text-editor-renderer/src/diff-renderer.ts +1 -1
  157. package/node_modules/pi-agent-text-editor-renderer/src/diff-viewport.ts +11 -2
  158. package/node_modules/pi-agent-text-editor-renderer/src/frozen-viewport.ts +140 -52
  159. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +52 -4
  160. package/node_modules/pi-agent-text-editor-renderer/src/mutation-result.ts +53 -1
  161. package/node_modules/pi-agent-text-editor-renderer/src/persisted-result.ts +8 -2
  162. package/node_modules/pi-agent-text-editor-renderer/src/render-resource.ts +10 -0
  163. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +5 -3
  164. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  165. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  166. package/node_modules/pi-agent-tool-call-interception/src/index.ts +3 -0
  167. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  168. package/node_modules/pi-agent-web/index.ts +1 -6
  169. package/node_modules/pi-agent-web/package.json +6 -6
  170. package/node_modules/pi-agent-web-html/package.json +2 -2
  171. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  172. package/node_modules/pi-agent-web-image/package.json +3 -3
  173. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  174. package/node_modules/pi-agent-web-text/package.json +3 -3
  175. package/package.json +35 -35
  176. package/src/api/plugin-protocol.ts +2 -0
  177. package/src/api/text-editor.ts +7 -0
  178. package/src/api/tool-config.ts +4 -0
  179. package/src/composite/builtin-extensions.ts +148 -66
  180. package/src/composite/extensions-config.ts +18 -0
  181. package/src/core/diagnostic-entry.ts +94 -0
  182. package/src/core/diagnostic-store.ts +43 -21
  183. package/src/core/extension.ts +39 -17
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +2 -2
  185. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  186. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  187. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  188. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  189. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +1 -6
  190. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +6 -6
  191. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  192. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  193. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  194. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  195. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  196. package/src/extensions/pi-agent-read/package.json +6 -6
  197. package/src/extensions/pi-agent-read/src/api/rendering.ts +3 -0
  198. package/src/extensions/pi-agent-read/src/core/read-core.ts +6 -26
  199. package/src/extensions/pi-agent-read/src/core/tools/read/native-resource-renderer.ts +74 -0
  200. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +28 -7
  201. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +35 -30
  202. package/src/extensions/pi-agent-search/package.json +3 -3
  203. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +42 -33
  204. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
  205. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +9 -1
  206. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +1 -1
  207. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -0
  208. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +48 -0
  209. package/src/extensions/pi-agent-search/src/core/extension.ts +7 -5
  210. package/src/extensions/pi-agent-search/src/core/search-core.ts +10 -0
  211. package/src/extensions/pi-agent-text-editor/package.json +6 -6
  212. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  213. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  214. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +2 -6
  215. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  216. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/package.json +2 -2
  217. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/package.json +3 -3
  218. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +5 -1
  219. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  220. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +7 -0
  221. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-renderer.ts +1 -1
  222. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-viewport.ts +11 -2
  223. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/frozen-viewport.ts +140 -52
  224. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +52 -4
  225. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-result.ts +53 -1
  226. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/persisted-result.ts +8 -2
  227. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/render-resource.ts +10 -0
  228. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +5 -3
  229. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  230. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +3 -0
  231. package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +71 -1
  232. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +4 -12
  233. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +7 -9
  234. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +27 -2
  235. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +38 -0
  236. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/final-state-fragment.ts +2 -0
  237. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +81 -0
  238. package/src/extensions/pi-agent-text-editor/src/core/text-anchor-registry.ts +5 -2
  239. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +23 -0
  240. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +5 -9
  241. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +54 -14
  242. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +45 -43
  243. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +18 -8
  244. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +7 -4
  245. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +13 -5
  246. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +18 -8
  247. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -5
  248. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +2 -1
  249. package/src/pi-agent-ide.ts +11 -0
  250. package/src/plugins/pi-agent-ide-ast/package.json +9 -9
  251. package/src/plugins/pi-agent-ide-ast/src/ast/outline.ts +89 -19
  252. package/src/plugins/pi-agent-ide-ast/src/extension.ts +9 -14
  253. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +60 -0
  254. package/src/plugins/pi-agent-ide-ast/src/scope-resolver.ts +1 -1
  255. package/src/plugins/pi-agent-ide-changes/index.ts +1 -5
  256. package/src/plugins/pi-agent-ide-changes/package.json +6 -6
  257. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +1 -7
  258. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +1 -5
  259. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +1 -16
  260. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  261. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +12 -7
  262. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  263. package/src/plugins/pi-agent-ide-lint/index.ts +4 -1
  264. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  265. package/src/plugins/pi-agent-ide-lsp/index.ts +1 -12
  266. package/src/plugins/pi-agent-ide-lsp/package.json +8 -8
  267. package/src/plugins/pi-agent-ide-lsp/src/diagnostic-source.ts +7 -4
  268. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +8 -1
  269. package/src/post-edit/gate.ts +44 -15
  270. package/src/toolchain/types.ts +2 -0
  271. package/dist/chunk-2XYXV5HS.js +0 -4
  272. package/dist/chunk-34ZQTTU2.js +0 -2
  273. package/dist/chunk-4SQQKEVD.js +0 -16
  274. package/dist/chunk-5BWUVAR4.js +0 -1
  275. package/dist/chunk-6DN7NO7L.js +0 -1
  276. package/dist/chunk-6SMFVLTY.js +0 -1
  277. package/dist/chunk-6XQQBKPE.js +0 -58
  278. package/dist/chunk-BYWAG6X3.js +0 -6
  279. package/dist/chunk-EW2KVKCN.js +0 -2
  280. package/dist/chunk-F6SESI3P.js +0 -4
  281. package/dist/chunk-GTK5AREE.js +0 -2
  282. package/dist/chunk-HOBTFFQR.js +0 -1
  283. package/dist/chunk-IMVCVPMP.js +0 -3
  284. package/dist/chunk-IOCABSRL.js +0 -1
  285. package/dist/chunk-KH5KPBCR.js +0 -10
  286. package/dist/chunk-KYVOMBO5.js +0 -1
  287. package/dist/chunk-L4FA6OD4.js +0 -1
  288. package/dist/chunk-LFV6G5Z3.js +0 -1
  289. package/dist/chunk-LGN7EJYR.js +0 -13
  290. package/dist/chunk-MB6VVVAF.js +0 -2
  291. package/dist/chunk-MTQSGWZJ.js +0 -1
  292. package/dist/chunk-NI2NK4JU.js +0 -1
  293. package/dist/chunk-NXHPO7ER.js +0 -6
  294. package/dist/chunk-OFHVDY4Q.js +0 -2
  295. package/dist/chunk-OIL6BB2S.js +0 -33
  296. package/dist/chunk-ONWUJXUR.js +0 -1
  297. package/dist/chunk-PODWLGNO.js +0 -6
  298. package/dist/chunk-QZANC2IG.js +0 -1
  299. package/dist/chunk-SSZB66C3.js +0 -3
  300. package/dist/chunk-TG6H6EOI.js +0 -1
  301. package/dist/chunk-UTTW55S2.js +0 -1
  302. package/dist/chunk-VEJGSURY.js +0 -8
  303. package/dist/chunk-W3XYKJ5H.js +0 -1
  304. package/dist/chunk-XGUAL3CA.js +0 -1
  305. package/node_modules/pi-agent-read/src/core/tools/read/views.ts +0 -29
  306. package/src/extensions/pi-agent-read/src/core/tools/read/views.ts +0 -29
package/dist/entry-40.js CHANGED
@@ -1 +1,14 @@
1
- import{a}from"./chunk-4SQQKEVD.js";import"./chunk-VSP2QQPQ.js";import"./chunk-2ZMYT6ZC.js";import"./chunk-SSZB66C3.js";import"./chunk-YHUTTZC6.js";import"./chunk-JASLOB2X.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{e as le,f as ce,g as fe}from"./chunk-GIRAEVUJ.js";import{a as N,b as U,c as M,d as V,e as B,f as ue}from"./chunk-4U6KGABH.js";import{a as oe,b as ie,c as se}from"./chunk-KCEOTU5Z.js";import"./chunk-YHUTTZC6.js";import{a as I,b as F,c as te,d as re,g as ne}from"./chunk-JASLOB2X.js";import{b as ae,e as de}from"./chunk-S3ZPXWX7.js";import{m as J,o as Z,s as ee}from"./chunk-RAZOACDD.js";import{a as L}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as S}from"typebox";import{DEFAULT_MAX_BYTES as _e,DEFAULT_MAX_LINES as Ie,formatSize as j,truncateHead as Fe}from"@earendil-works/pi-coding-agent";var H=_e,K=Ie;async function O(e,t,r,o){let n=o?.originLine,i=e.content.length===1?e.content[0]:void 0;if(i?.type!=="text")return e;let d=Fe(i.text,{maxBytes:H,maxLines:K});if(d.truncated){let m=r===void 0?void 0:await r(i.text),u=d.firstLineExceedsLimit?Ue(i.text,e.details,t):Me(d,e.details,t,n),l=m===void 0?u:Ne(u,m);return{...e,content:[{...i,text:pe(d.content,l)}],details:{...je(e.details,d),...m!==void 0&&{temporarySource:m}}}}let a=Be(e.details,t,n);return a===void 0?e:{...e,content:[{...i,text:pe(i.text,a)}]}}s(O,"limitReadOutput");function Ne(e,t){return`${e.slice(0,-1)} Full output: ${t}. Expires after 5 minutes of inactivity.]`}s(Ne,"appendTemporarySource");function Ue(e,t,r){let o=e.split(/\r\n|\r|\n/u,1)[0]??"",n=j(Buffer.byteLength(o,"utf8")),i=W(t,r);return`[${i===void 0?"First output line":`Line ${i}`} is ${n}, exceeds ${j(H)} limit. Use a source-specific tool to read this line in smaller byte ranges.]`}s(Ue,"oversizedFirstLineNotice");function Me(e,t,r,o){let n=Ve(e,t,r);if(n!==void 0&&n.endLine<n.totalLines){let d=e.truncatedBy==="bytes"?` (${j(e.maxBytes)} limit)`:"",a=Re(n.endLine+1,o);return`[Showing lines ${n.startLine}-${n.endLine} of ${n.totalLines}${d}. Use offset=${a} to continue.]`}let i=e.truncatedBy==="lines"?`${e.maxLines} line limit`:`${j(e.maxBytes)} limit`;return`[Output truncated: showing ${e.outputLines} of ${e.totalLines} rendered lines (${i}). Use a smaller line range to read this source.]`}s(Me,"truncatedOutputNotice");function Ve(e,t,r){let o=t.totalLines,n=W(t,r);if(o===void 0||o===0||n===void 0||e.outputLines===0)return;let d=(t.endLine===void 0||t.endLine<n?o:t.endLine)-n+1,a=Math.min(e.outputLines,d);return{startLine:n,endLine:n+a-1,totalLines:o}}s(Ve,"shownSourceRange");function Be(e,t,r){if(t.limit===void 0||e.totalLines===void 0||e.totalLines===0)return;let o=W(e,t);if(o===void 0)return;let n=e.endLine===void 0||e.endLine<o?o:e.endLine+1;return n>e.totalLines?void 0:`[${e.totalLines-n+1} more lines in source. Use offset=${Re(n,r)} to continue.]`}s(Be,"explicitLimitNotice");function Re(e,t){return t===void 0?e:e-t+1}s(Re,"continuationOffset");function W(e,t){if(e.startLine!==void 0&&e.startLine>0)return e.startLine;if(e.totalLines===void 0||e.totalLines===0)return;let r=t.offset===void 0?1:Math.trunc(t.offset);return r<0?Math.max(1,e.totalLines+r+1):Math.max(1,r)}s(W,"sourceStartLine");function je(e,t){return{...e,...e.lines!==void 0&&{lines:e.lines.slice(0,t.outputLines)},truncation:t}}s(je,"truncatedDetails");function pe(e,t){return e.length===0?t:`${e}
2
+
3
+ ${t}`}s(pe,"appendNotice");function me(e,t,r,o){if(!We(e))return{content:e,source:t,resolvedBy:r,preserveTruncatedOutput:o.preserveTruncatedOutput,textMode:o.textMode,contentKind:"other"};let n=e[0].text;return{content:e,source:t,resolvedBy:r,preserveTruncatedOutput:o.preserveTruncatedOutput,textMode:o.textMode,contentKind:"text",text:J(t,n)}}s(me,"createReadState");function G(e,t,r){if(e.contentKind!=="text"){if(t.offset!==void 0||t.limit!==void 0)return h({code:"UNSUPPORTED_RANGE",source:e.source,resolverId:e.resolvedBy,message:"Line ranges require textual content"});let u=Ge(e.content);return{content:u.content,details:{...ge(e),...u.unsupportedContentBlocks!==void 0&&{unsupportedContentBlocks:u.unsupportedContentBlocks}}}}let o=e.text.lines.length,n=qe(t,o,r?.originLine),i=e.text.lines.slice(n.startIndex,n.endIndex),d=e.textMode==="final"?He(i,n.endIndex<o):Z({...e.text,lines:i.map((u,l)=>({...u,lineEnding:l===i.length-1&&n.endIndex<o?"":u.lineEnding}))}),a=e.content[0];return{content:[{type:"text",text:d,...a.textSignature!==void 0&&{textSignature:a.textSignature}}],details:{...ge(e),startLine:i[0]?.lineNumber??0,endLine:i.at(-1)?.lineNumber??0,totalLines:o,lines:i}}}s(G,"projectReadState");function He(e,t){return e.map((r,o)=>`${r.content}${o===e.length-1&&t?"":r.lineEnding}`).join("")}s(He,"renderFinalTextLines");function h(e){return{content:[{type:"text",text:`${e.code}: ${e.message}`}],details:{failure:e},isError:!0}}s(h,"failureResult");function ge(e){return{source:e.source,resolvedBy:e.resolvedBy}}s(ge,"readDetails");function Ge(e){let t=[],r=[];for(let[n,i]of e.entries()){if(i.type!=="custom"){t.push(i);continue}r.push({index:n,kind:i.kind}),t.push({type:"text",text:`[unsupported_content_block kind=${i.kind} index=${n}]`})}let o=r[0];return{content:t,...o!==void 0&&{unsupportedContentBlocks:[o,...r.slice(1)]}}}s(Ge,"projectAgentContent");function qe(e,t,r){let o=e.offset===void 0?1:Math.trunc(e.offset),n=Ke(o,t,r),i=e.limit===void 0?t:Math.max(0,Math.trunc(e.limit));return{startIndex:Math.min(t,n-1),endIndex:Math.min(t,n-1+i)}}s(qe,"resolveTextRange");function Ke(e,t,r){if(r===void 0)return e<0?Math.max(1,t+e+1):Math.max(1,e);let o=e<0?r+e:r+Math.max(1,e)-1;return Math.max(1,o)}s(Ke,"anchoredStartLine");function We(e){return e.length===1&&e[0].type==="text"}s(We,"isSingleTextContent");import{randomUUID as ze}from"node:crypto";import{mkdir as Xe,mkdtemp as Ye,readFile as Qe,rm as Je,unlink as ye,writeFile as Ze}from"node:fs/promises";import{tmpdir as et}from"node:os";import he from"node:path";var tt=5*6e4,q=class{static{s(this,"TempResourceStore")}resolver;#e=new Map;#i;#t;#s;#o=!1;#r;constructor(t={}){if(this.#i=t.parentDirectory??et(),this.#t=t.ttlMs??tt,!Number.isFinite(this.#t)||this.#t<=0)throw new TypeError("Temporary resource TTL must be a positive finite number");this.resolver={id:"temp",tryResolve:s(r=>Promise.resolve(this.#d(r)),"tryResolve")}}async save(t){if(this.#o)throw new Error("Temporary resource store is closed");let r=await this.#l(),o=ze(),n=`temp:${o}`,i=he.join(r,`${o}.txt`);return await Ze(i,t,{encoding:"utf8",flag:"wx"}),this.#e.set(n,{activeReads:0,filePath:i,lastUsedAt:Date.now()}),this.#n(),n}async dispose(){if(this.#o)return;this.#o=!0,this.#a(),this.#e.clear();let t=this.#s;t!==void 0&&await Je(await t,{recursive:!0,force:!0})}#d(t){if(!t.startsWith("temp:"))return{kind:"not-handled"};let r=this.#e.get(t);return r===void 0?{kind:"failed",error:new Error(`Temporary resource ${t} expired or does not exist`)}:r.activeReads===0&&r.lastUsedAt+this.#t<=Date.now()?(this.#e.delete(t),ye(r.filePath).catch(()=>{}),this.#n(),{kind:"failed",error:new Error(`Temporary resource ${t} expired or does not exist`)}):{kind:"resolved",resource:{source:t,read:s(()=>this.#u(t),"read")}}}async#u(t){let r=this.#e.get(t);if(r===void 0)throw new Error(`Temporary resource ${t} expired or does not exist`);r.activeReads+=1,this.#n();try{return[{type:"text",text:await Qe(r.filePath,"utf8")}]}finally{r.activeReads-=1,r.lastUsedAt=Date.now(),this.#n()}}async#l(){return this.#s??=(async()=>(await Xe(this.#i,{recursive:!0}),Ye(he.join(this.#i,"pi-agent-read-"))))(),this.#s}#n(){if(this.#a(),this.#o)return;let t=Date.now(),r;for(let o of this.#e.values()){if(o.activeReads>0)continue;let n=o.lastUsedAt+this.#t;r=r===void 0?n:Math.min(r,n)}r!==void 0&&(this.#r=setTimeout(()=>{this.#r=void 0,this.#c().catch(()=>{this.#n()})},Math.max(0,r-t)),this.#r.unref())}async#c(){let t=Date.now(),r=[...this.#e].filter(([,o])=>o.activeReads===0&&o.lastUsedAt+this.#t<=t);await Promise.all(r.map(async([o,n])=>{await ye(n.filePath).catch(i=>{if(!(i instanceof Error)||!("code"in i)||i.code!=="ENOENT")throw i}),this.#e.delete(o)})),this.#n()}#a(){this.#r!==void 0&&(clearTimeout(this.#r),this.#r=void 0)}};var rt=S.Object({path:S.Optional(S.String({description:"What to read: a file or directory path, URL, returned temp: or SEARCH# reference, or one of the source forms listed in the description. Supply a path; an empty call cannot select a source."})),offset:S.Optional(S.Number({description:"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 or a SEARCH selection, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier."})),limit:S.Optional(S.Number({description:"Maximum lines to read from the selected starting position, subject to the output budget. Omit for the default bounded read."})),views:S.Optional(S.Array(S.String(),{description:`Optional additions to the returned text. Use the views listed in the tool description. Combine views when needed, for example ["anchors", "ast"] for source text with editable line references and scope boundaries. Omit for the source's default presentation.`}))}),nt=se({kind:"source"});function Pe(e,t){let r=new q,o=[{resolver:r.resolver,preserveTruncatedOutput:!1,priority:Number.MIN_SAFE_INTEGER,order:0}],n=[],i=[],d=[],a=[],m="read";return{tool:{name:m,label:m,promptSnippet:"Read files, URLs, temporary resources, search selections, and protocol sources, with optional views projected onto text content",get description(){return[`Use read to inspect files, directories, URLs and supported sources without changing them. path selects the source; offset/limit select a text window; views add annotations. Text limit: ${K} lines or ${H/1024}KB. Continuation: returned offset, or returned temp: reference as path.`,t?.()??""].filter(Boolean).join(`
4
+ `)},get promptGuidelines(){return["Use read to examine supported sources instead of cat, sed, head or tail. Use search to locate workspace text and paths instead of grep, rg or find.",...e?.()??[]]},parameters:rt,renderCall:ie,renderResult(u,l,c,y){let x=u.details.resolvedBy;return((x===void 0?void 0:o.find(({resolver:v})=>v.id===x)?.renderResult)??nt)(u,l,c,y)},async execute(u,l,c,y,x){let p={cwd:x.cwd,...c!==void 0&&{signal:c}};return ve(l,p,o,n,i,r,d,a)}},execute(u,l){return ve(u,l,o,n,i,r,d,a)},registerContributions(u,l){let c=[...l.resolvers??[]],y=[...l.targetResolvers??[]],x=[...l.handlers??[]],p=[...l.views??[]],v=[...l.fragments??[]];yt(u,c,x,o,n),ht(u,v,d);let R=new Set(a.map(({resolver:f})=>f.id));for(let f of y){if(!N(f))throw new TypeError(`Plugin ${u} provided an invalid text target resolver`);if(R.has(f.resolver.id))throw new Error(`Text target resolver ${f.resolver.id} is already registered`);R.add(f.resolver.id)}let C=new Set(i.map(({registration:f})=>f.view)),w=new Set(i.map(({registration:f})=>`${f.view}/${f.presenter.id}`));for(let f of p){if(!V(f))throw new TypeError(`Plugin ${u} provided an invalid view registration`);let T=`${f.view}/${f.presenter.id}`;if(w.has(T))throw new Error(`View ${f.view} already has a presenter ${f.presenter.id}`);C.add(f.view),w.add(T)}for(let f of c)o.push({resolver:f.resolver,...f.renderResult!==void 0&&{renderResult:f.renderResult},priority:f.priority??0,preserveTruncatedOutput:f.preserveTruncatedOutput??!1,order:o.length});for(let f of y)a.push({resolver:f.resolver,priority:f.priority??0,order:a.length});for(let f of x)n.push({pluginId:u,registration:f});for(let f of p)i.push({pluginId:u,registration:f,order:i.length});for(let f of v)d.push({registration:f,priority:f.priority??0,order:d.length})},dispose(){return r.dispose()}}}s(Pe,"createReadTool");async function ve(e,t,r,o,n,i,d,a){let m=[...r].sort((g,E)=>g.priority-E.priority||g.order-E.order),u=[...o],l=[...n].sort((g,E)=>(g.registration.priority??0)-(E.registration.priority??0)||g.order-E.order),c=[...d].sort((g,E)=>g.priority-E.priority||g.order-E.order),y=[...a].sort((g,E)=>g.priority-E.priority||g.order-E.order),x=new Set(e.views??[]),p=new Set([...l.map(({registration:g})=>g.view)]),v=[...x].filter(g=>!p.has(g));if(e.path!==void 0&&y.length>0){let g=await st(e,t,y,m,u,l,x,v);if(g!==void 0)return g}let R={request:{...e},resolverContext:t};if(!R.request.path?.startsWith("temp:")){let g=await Ee(R,u);if(g.kind==="return")return b(await O(g.result,R.request),v);R=g.context}let C=R.request.path;if(C===void 0||C.length===0)return h({code:"INVALID_REQUEST",message:"No source was provided"});let w=await z(R,m),f;if(w.kind==="return"&&w.result.isError===!0&&it(w.result)&&!C.startsWith("temp:")){let g=at(C);if(g!==void 0){let E={result:w,pipeline:R},Y={...R,request:{...R.request,path:g.source}},Q=await z(Y,m);Q.kind==="continue"?(w=Q,R=Y,f=g.fragment):w=E.result}}if(w.kind==="return")return O(w.result,R.request);R=w.context;let T;if(f!==void 0){let g=await dt(R,c,f);if(typeof g!="number")return g;T=g}if(R.state?.textMode==="final")return b(await O(G(R.state,R.request,{originLine:T}),R.request,void 0,{originLine:T}),v);let A=await Le(R,u);if(A.kind==="return")return b(await O(A.result,R.request,void 0,{originLine:T}),v);R=A.context,R=await Se(R,l,x);let k=G(L(R.state),R.request,{originLine:T});R={...R,result:k};let D=await be(R,u),$=D.kind==="return"?D.result:L(D.context.result),P=R.request.limit===void 0&&R.state?.preserveTruncatedOutput===!0?g=>i.save(g):void 0;return b(await O($,R.request,P,{originLine:T}),v)}s(ve,"executeRead");var ot=new Set(["INVALID_RESOLVER_RESULT","NO_RESOLVER","READ_FAILED","RESOLVE_FAILED"]);function it(e){let t=e.details.failure?.code;return t!==void 0&&ot.has(t)}s(it,"isRetryableFailure");async function st(e,t,r,o,n,i,d,a){for(let{resolver:m}of r){let u;try{u=await m.tryResolve(e.path??"",t)}catch(p){return h({code:"RESOLVE_FAILED",source:e.path,message:_(`Text target resolver ${m.id} failed`,p),cause:p})}if(!ee(u))return h({code:"INVALID_RESOLVER_RESULT",source:e.path,message:`Text target resolver ${m.id} returned an invalid result`,cause:u});let l=u;if(l.kind==="not-handled")continue;if(l.kind==="rejected")return h({code:"RESOLVE_FAILED",source:e.path,message:l.rejection.reason});if(l.kind==="failed")return h({code:"RESOLVE_FAILED",source:e.path,message:l.error instanceof Error?l.error.message:String(l.error)});if(l.targets.length===0)return h({code:"RESOLVE_FAILED",source:e.path,message:"Text target resolver returned no targets"});let c=[],y;for(let p of l.targets){let v=p.ranges??[{start:{lineNumber:1,column:0},end:{lineNumber:1,column:1}}];for(let R of v){let C=Math.max(1,R.end.lineNumber-R.start.lineNumber),w={request:{...e,path:p.source,limit:e.limit??C},resolverContext:t};if(!p.source.startsWith("temp:")){let P=await Ee(w,n);if(P.kind==="return"){if(P.result.isError===!0)return b(P.result,a);for(let g of P.result.content)g.type==="text"&&c.push(g.text);y??=P.result.details;continue}w=P.context}let f=await z(w,o);if(f.kind==="return")return b(f.result,a);let T=await Le(f.context,n);if(T.kind==="return"){if(T.result.isError===!0)return b(T.result,a);for(let P of T.result.content)P.type==="text"&&c.push(P.text);y??=T.result.details;continue}let A=await Se(T.context,i,d),k=G(L(A.state),A.request,{originLine:R.start.lineNumber}),D=await be({...A,result:k},n);if(k.isError===!0)return b(k,a);let $=D.kind==="return"?D.result:L(D.context.result);if($.isError===!0)return b($,a);for(let P of $.content)P.type==="text"&&c.push(P.text);y??=$.details}}let x={content:[{type:"text",text:c.join(`
5
+ `)}],details:y??{source:e.path}};return b(await O(x,{path:e.path,views:e.views}),a)}}s(st,"resolveTextTargets");var xe="#";function at(e){let t=e.indexOf(xe);if(!(t<=0||t===e.length-1))return{source:e.slice(0,t),fragment:e.slice(t+xe.length)}}s(at,"splitAnchoredSource");async function dt(e,t,r){let o=L(e.state);if(o.contentKind!=="text")return h({code:"UNSUPPORTED_RANGE",source:o.source,resolverId:o.resolvedBy,message:"Anchored reads require textual content"});if(t.length===0)return h({code:"NO_FRAGMENT_RESOLVER",source:o.source,message:`No fragment resolver is registered for anchor "${r}"`});for(let{registration:n}of t){let i;try{i=await n.resolve({source:o.source,fragment:r,text:o.text,cwd:e.resolverContext.cwd,...e.resolverContext.signal!==void 0&&{signal:e.resolverContext.signal}})}catch(d){return h({code:"FRAGMENT_FAILED",source:o.source,resolverId:n.id,message:_(`Fragment resolver ${n.id} failed`,d),cause:d})}if(!ue(i))return h({code:"INVALID_RESOLVER_RESULT",source:o.source,resolverId:n.id,message:`Fragment resolver ${n.id} returned an invalid result`,cause:i});if(i.kind!=="not-handled")return i.kind==="failed"?h({code:"FRAGMENT_FAILED",source:o.source,resolverId:n.id,message:i.message}):!Number.isInteger(i.originLine)||i.originLine<1||i.originLine>o.text.lines.length?h({code:"INVALID_RESOLVER_RESULT",source:o.source,resolverId:n.id,message:`Fragment resolver ${n.id} returned out-of-range origin line ${i.originLine}`}):i.originLine}return h({code:"NO_FRAGMENT_RESOLVER",source:o.source,message:`No fragment resolver handled anchor "${r}"`})}s(dt,"resolveAnchoredOrigin");async function z(e,t){let r=L(e.request.path),o=e.resolverContext;for(let i of t){let{resolver:d}=i,a;try{a=await d.tryResolve(r,o)}catch(l){return{kind:"return",result:h({code:"RESOLVE_FAILED",source:r,resolverId:d.id,message:_(`Resolver ${d.id} failed`,l),cause:l})}}if(!de(a))return{kind:"return",result:h({code:"INVALID_RESOLVER_RESULT",source:r,resolverId:d.id,message:`Resolver ${d.id} returned an invalid result`,cause:a})};if(a.kind==="not-handled")continue;if(a.kind==="failed")return{kind:"return",result:h({code:"RESOLVE_FAILED",source:r,resolverId:d.id,message:_(`Resolver ${d.id} failed`,a.error),cause:a.error})};let m=a.resource;if(m.read===void 0)return{kind:"return",result:h({code:"UNSUPPORTED_CAPABILITY",source:m.source,resolverId:d.id,message:`Resource ${m.source} does not support reading`})};let u;try{u=await m.read({...o.signal!==void 0&&{signal:o.signal}})}catch(l){return{kind:"return",result:h({code:"READ_FAILED",source:m.source,resolverId:d.id,message:_(`Unable to read ${m.source}`,l),cause:l})}}return ae(u)?{kind:"continue",context:{...e,state:me(u,m.source,d.id,{preserveTruncatedOutput:i.preserveTruncatedOutput,textMode:d.id==="temp"?"final":"normal"})}}:{kind:"return",result:h({code:"INVALID_RESOURCE_CONTENT",source:m.source,resolverId:d.id,message:`Resource ${m.source} returned invalid content`,cause:u})}}let n=`No resolver handled ${r}`;return{kind:"return",result:le(h({code:"NO_RESOLVER",source:r,message:n}),n)}}s(z,"resolveSource");async function Ee(e,t){let r=e;for(let o of t){if(o.registration.stage!=="pre-read")continue;let n=await X(o.registration.handler,r,o.pluginId,"pre-read");if(n.kind==="return")return n;r=n.context}return{kind:"continue",context:r}}s(Ee,"runPreReadHandlers");async function Le(e,t){let r=e.state,o=r===void 0?[]:t.filter(i=>i.registration.stage==="read"&&mt(i.registration,r)),n=e;for(let i of o){let d=i.registration;if(d.stage!=="read")continue;let a=await X(d.handler,n,i.pluginId,"read");if(a.kind==="return")return a;n=a.context}return{kind:"continue",context:n}}s(Le,"runReadHandlers");async function Se(e,t,r){let o=e.state;if(o?.contentKind!=="text"||r.size===0)return e;let n=o.text,i={purpose:"read",source:o.source,cwd:e.resolverContext.cwd,resolvedBy:o.resolvedBy,...e.resolverContext.signal!==void 0&&{signal:e.resolverContext.signal}},d=t.filter(({registration:c})=>r.has(c.view)),a=new Set(d.flatMap(({registration:c})=>c.includes??[])),m=d.filter(({registration:c})=>!a.has(c.view)),u=await Promise.all(m.map(async({registration:c})=>({presenterId:c.presenter.id,document:await c.presenter.present(n,i)}))),l=ut(n,u);return{...e,state:{...o,text:l}}}s(Se,"runTextPresenters");function b(e,t){if(t.length===0)return e;let r=`note: ignored unknown views: ${t.join(", ")}`,o=e.content[0],n=o?.type==="text"?[{...o,text:`${r}
6
+ ${o.text}`}]:[...e.content];return{...e,content:n,details:{...e.details,ignoredViews:t}}}s(b,"withIgnoredViews");function ut(e,t){let r=e.lines;for(let o of t)lt(e,o),r=r.map((n,i)=>ct(L(e.lines[i]),n,L(o.document.lines[i])));return r===e.lines?e:{...e,lines:r}}s(ut,"mergeViewContributions");function lt(e,t){let r=t.document;if(r.source!==e.source||r.content!==e.content||r.lines.length!==e.lines.length)throw new Error(`Text presenter ${t.presenterId} changed canonical text`);for(let[o,n]of r.lines.entries()){let i=L(e.lines[o]);if(n.lineNumber!==i.lineNumber||n.content!==i.content||n.lineEnding!==i.lineEnding)throw new Error(`Text presenter ${t.presenterId} changed canonical text`)}}s(lt,"assertPresentationOnly");function ct(e,t,r){let o=ft(e.presentation,t.presentation,r.presentation),n=gt(e.metadata,t.metadata,r.metadata);return o===t.presentation&&n===t.metadata?t:{...t,...o!==void 0&&{presentation:o},...n!==void 0&&{metadata:n}}}s(ct,"mergePresentedLine");function ft(e,t,r){if(r===e)return t;let o=we(e?.prefix,t?.prefix,r?.prefix),n=we(e?.suffix,t?.suffix,r?.suffix),i=Te(e?.before,t?.before,r?.before),d=Te(e?.after,t?.after,r?.after),a=r?.marker===e?.marker?t?.marker:r?.marker;return o===t?.prefix&&n===t?.suffix&&i===t?.before&&d===t?.after&&a===t?.marker?t:{...t,...o!==void 0&&{prefix:o},...n!==void 0&&{suffix:n},...i!==void 0&&{before:i},...d!==void 0&&{after:d},...a!==void 0&&{marker:a}}}s(ft,"mergeLinePresentation");function we(e,t,r){if(r===e)return t;let o=e??"",n=t??"",i=r??"";return o.length>0&&i.startsWith(o)?`${n}${i.slice(o.length)}`:o.length>0&&i.endsWith(o)?`${i.slice(0,-o.length)}${n}`:`${n}${i}`}s(we,"mergePresentedText");function Te(e,t,r){if(r===e)return t;let o=e??[],n=t??[],i=r??[];return pt(i,o)?[...n,...i.slice(o.length)]:Rt(i,o)?[...i.slice(0,i.length-o.length),...n]:[...n,...i]}s(Te,"mergePresentedRows");function pt(e,t){return t.length>0&&t.length<=e.length&&t.every((r,o)=>e[o]===r)}s(pt,"startsWithRows");function Rt(e,t){let r=e.length-t.length;return t.length>0&&r>=0&&t.every((o,n)=>e[r+n]===o)}s(Rt,"endsWithRows");function gt(e,t,r){if(r===e||r===void 0)return t;let o=Object.fromEntries(Object.entries(r).filter(([n,i])=>e?.[n]!==i));return Object.keys(o).length===0?t:{...t,...o}}s(gt,"mergeLineMetadata");async function be(e,t){let r=e;for(let o of t){if(o.registration.stage!=="post-read")continue;let n=await X(o.registration.handler,r,o.pluginId,"post-read");if(n.kind==="return")return n;r=n.context}return{kind:"continue",context:r}}s(be,"runPostReadHandlers");async function X(e,t,r,o){try{return await e(t)}catch(n){return{kind:"return",result:h({code:"PIPELINE_FAILED",...t.state?.source===void 0?t.result?.details.source===void 0?{}:{source:t.result.details.source}:{source:t.state.source},pluginId:r,stage:o,message:`Plugin ${r} failed during ${o}`,cause:n})}}}s(X,"invokeHandler");function mt(e,t){return(e.when.resolvedBy==="any"||e.when.resolvedBy===t.resolvedBy)&&(e.when.contentKind==="any"||e.when.contentKind===t.contentKind)}s(mt,"matchesReadState");function yt(e,t,r,o,n){let i=new Set(o.map(({resolver:a})=>a.id));for(let a of t){if(!U(a))throw new TypeError(`Plugin ${e} provided an invalid resource resolver`);if(i.has(a.resolver.id))throw new Error(`Resource resolver ${a.resolver.id} is already registered`);i.add(a.resolver.id)}let d=new Set(n.filter(a=>a.pluginId===e).map(a=>a.registration.stage));for(let a of r){if(!M(a))throw new TypeError(`Plugin ${e} provided an invalid read handler`);if(d.has(a.stage))throw new Error(`Plugin ${e} already handles ${a.stage}`);d.add(a.stage)}}s(yt,"validateContributions");function ht(e,t,r){let o=new Set(r.map(({registration:n})=>n.id));for(let n of t){if(!B(n))throw new TypeError(`Plugin ${e} provided an invalid fragment resolver`);if(o.has(n.id))throw new Error(`Fragment resolver ${n.id} is already registered`);o.add(n.id)}}s(ht,"validateFragmentRegistrations");function _(e,t){return!(t instanceof Error)||t.message.length===0?e:`${e}: ${t.message}`}s(_,"appendErrorMessage");function De(){let e=new Set,t=new Map,r=Pe(()=>wt(t),()=>Ce(t)),o=Promise.resolve();return{read:r,registerPlugin(n){let i=vt(n);if(i!==void 0)return Promise.reject(i);let d=t.get(n.id);if(d?.plugin===n)return d.ready;if(d!==void 0)return Promise.reject(new Error(`Plugin ${n.id} is already registered`));let a={status:"pending"},m=[],u=[],l=xt(n.id,r,u,m),c=o.then(async()=>{try{await n.setup(l.api),l.commit(),a.status="active";return}catch(x){throw l.close(),x}}),y={lifecycle:a,plugin:n,promptGuidelines:u,promptContributions:m,ready:c};return t.set(n.id,y),e.add(c),o=c.catch(()=>{}),c.then(()=>{e.delete(c)},()=>{e.delete(c),t.get(n.id)===y&&t.delete(n.id)}),c},renderPluginPromptGuideline:s(()=>Ce(t),"renderPluginPromptGuideline"),async waitForPendingPlugins(){await Promise.all(e)}}}s(De,"createReadCore");function vt(e){if(e.protocol!==I)return new Error(`Plugin ${e.id} uses an unsupported protocol`);if(e.apiVersion!==F)return new Error(`Plugin ${e.id} uses an unsupported API version`);if(e.id.trim().length===0)return new Error("Plugin ID must not be empty")}s(vt,"getPluginValidationError");function xt(e,t,r,o){let n=[],i=[],d=[],a=[],m=[],u=[],l=[],c="setup",y=s(()=>{if(c==="closed")throw new Error(`Plugin ${e} API is closed`)},"assertAvailable");return{api:{read(p,v){return y(),t.execute(p,v)},addResolver(p){if(y(),!U(p))throw new TypeError(`Plugin ${e} provided an invalid resource resolver`);if(c==="setup"){d.push(p);return}t.registerContributions(e,{resolvers:[p]})},addTargetResolver(p){if(y(),!N(p))throw new TypeError(`Plugin ${e} provided an invalid text target resolver`);if(c==="setup"){a.push(p);return}t.registerContributions(e,{targetResolvers:[p]})},addHandler(p){if(y(),!M(p))throw new TypeError(`Plugin ${e} provided an invalid read handler`);if(c==="setup"){m.push(p);return}t.registerContributions(e,{handlers:[p]})},addView(p){if(y(),!V(p))throw new TypeError(`Plugin ${e} provided an invalid view registration`);if(c==="setup"){u.push(p);return}t.registerContributions(e,{views:[p]})},addFragmentResolver(p){if(y(),!B(p))throw new TypeError(`Plugin ${e} provided an invalid fragment resolver`);if(c==="setup"){l.push(p);return}t.registerContributions(e,{fragments:[p]})},describe(p){if(y(),n.length>0||o.length>0)throw new Error(`Plugin ${e} provides more than one description`);let v=Ae(p);if(c==="setup"){n.push(v);return}o.push(v)},addPromptGuideline(p){y();let v=Ae(p);if(c==="setup"){i.push(v);return}r.push(v)}},close(){c="closed"},commit(){if(c!=="setup")throw new Error(`Plugin ${e} setup contributions cannot be committed`);t.registerContributions(e,{resolvers:d,targetResolvers:a,handlers:m,views:u,fragments:l}),o.push(...n),r.push(...i),c="active"}}}s(xt,"createPluginContributionController");function wt(e){let t=[];for(let r of e.values())if(r.lifecycle.status==="active")for(let o of r.promptGuidelines){let n=Oe(o);n!==void 0&&t.push(n)}return t}s(wt,"renderPromptGuidelines");function Ce(e){let t=[];for(let r of e.values()){if(r.lifecycle.status!=="active")continue;let o=r.promptContributions[0];if(o===void 0)continue;let n=Oe(o);n!==void 0&&t.push(n)}return t.length===0?void 0:[...new Set(t.flatMap(r=>r.split(`
7
+ `)))].join(`
8
+ `)}s(Ce,"renderPluginPromptGuideline");function Ae(e){if(typeof e=="string")return $e(e);if(typeof e=="function")return e;throw new TypeError("Read plugin prompt description must be a string or callback")}s(Ae,"normalizeDescriptionSource");function Oe(e){if(typeof e=="string")return e;let t=e();return t===void 0?void 0:$e(t)}s(Oe,"renderDescriptionSource");function $e(e){if(typeof e!="string")throw new TypeError("Read plugin prompt description must be a string");let t=e.replaceAll(`\r
9
+ `,`
10
+ `).replaceAll("\r",`
11
+ `).split(`
12
+ `).map(o=>o.trimEnd());for(;t[0]?.trim().length===0;)t.shift();for(;t.at(-1)?.trim().length===0;)t.pop();let r=t.join(`
13
+ `);if(r.trim().length===0)throw new Error("Read plugin prompt description is empty");return r}s($e,"normalizeDescription");function Tt(e){return typeof e=="object"&&e!==null}s(Tt,"isRecord");async function ke(e){let t=De(),r=e.events.on(re,n=>{if(!ne(n))throw new Error("Invalid pi-agent-read plugin registration request");n.accept(t.registerPlugin(n.plugin))});e.on("session_shutdown",async()=>{r(),await t.read.dispose()});let o=new ce;e.registerTool(fe(t.read.tool,o)),e.on("tool_result",n=>{if(!(n.toolName!=="read"||!Tt(n.details)))return{details:oe(n.details,n.content.flatMap(i=>i.type==="text"?[i.text]:[]).join(`
14
+ `)),...n.details.failure!==void 0&&{isError:!0}}}),e.events.emit(te,{protocol:I,apiVersion:F}),await t.waitForPendingPlugins()}s(ke,"registerReadCore");export{ke as default};
package/dist/entry-41.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v}from"./chunk-EW2KVKCN.js";import"./chunk-EI7MMDWY.js";export{p as CONTENT_API_VERSION,r as CONTENT_CONVERTER_REGISTER_EVENT,q as CONTENT_HOST_READY_EVENT,o as CONTENT_PROTOCOL,l as UnsupportedContentError,v as connectContentConverter,u as createContentHost,m as createContentRunner,b as isAgentContent,j as isContentConversionAttempt,h as isContentConversionContext,i as isContentConverter,k as isContentConverterRegistration,t as isContentConverterRegistrationRequest,s as isContentHostReady,g as isContentInput,f as isContentTarget,c as isResource,e as isResourceResolutionAttempt,d as isResourceResolver,a as renderContentDescription,n as targetsEqual};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v}from"./chunk-S3ZPXWX7.js";import"./chunk-EI7MMDWY.js";export{p as CONTENT_API_VERSION,r as CONTENT_CONVERTER_REGISTER_EVENT,q as CONTENT_HOST_READY_EVENT,o as CONTENT_PROTOCOL,l as UnsupportedContentError,v as connectContentConverter,u as createContentHost,m as createContentRunner,b as isAgentContent,j as isContentConversionAttempt,h as isContentConversionContext,i as isContentConverter,k as isContentConverterRegistration,t as isContentConverterRegistrationRequest,s as isContentHostReady,g as isContentInput,f as isContentTarget,c as isResource,e as isResourceResolutionAttempt,d as isResourceResolver,a as renderContentDescription,n as targetsEqual};
package/dist/entry-45.js CHANGED
@@ -1 +1,7 @@
1
- import{a}from"./chunk-BYWAG6X3.js";import"./chunk-VSP2QQPQ.js";import"./chunk-YHUTTZC6.js";import"./chunk-T2RPMEM2.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{e as M,f as N,g as j}from"./chunk-GIRAEVUJ.js";import{c as k}from"./chunk-YHUTTZC6.js";import{a as I,b as C,c as D,d as $,g as O}from"./chunk-T2RPMEM2.js";import{a as o}from"./chunk-EI7MMDWY.js";import{keyText as te}from"@earendil-works/pi-coding-agent";import{Text as ne}from"@earendil-works/pi-tui";import oe from"node:os";import{Type as p}from"typebox";function q(){let e=[],r=new Map,s=new Map,a=new Map,i=new Map,l=Promise.resolve(),u={registerPlugin(n){if(n.id.trim().length===0)return Promise.reject(new Error("Plugin ID must not be empty"));let c=i.get(n.id);if(c!==void 0)return c;let f=l.then(async()=>{let h=[],m=[],y,g=[],d={addResolver(t){z(t),h.push(t)},addAction(t){_(t),m.push(t)},describe(t){if(y!==void 0)throw new Error(`Plugin ${n.id} provides more than one description`);y=L(t)},addPromptGuideline(t){g.push(L(t))},search:o((t,w)=>u.execute(t,w),"search"),runAction(t,w){return u.runAction(t.reference,t.capability,t.resolverId,t.input,w)}};await n.setup(d);let S=new Set(e.map(({registration:t})=>t.resolver.id));for(let t of h){if(S.has(t.resolver.id))throw new Error(`Search resolver ${t.resolver.id} is already registered`);S.add(t.resolver.id)}for(let t of m){let w=P(t.resolverId,t.capability);if(r.has(w)||m.some(x=>x!==t&&P(x.resolverId,x.capability)===w))throw new Error(`Search action ${w} is already registered`)}for(let t of h)e.push({pluginId:n.id,registration:t,order:e.length});for(let t of m)r.set(P(t.resolverId,t.capability),t);y!==void 0&&a.set(n.id,y),g.length>0&&s.set(n.id,g)});return i.set(n.id,f),l=f.catch(()=>{}),f.catch(()=>{i.delete(n.id)}),f},async waitForPendingPlugins(){await Promise.all(i.values())},async execute(n,c){if(n.query.trim().length===0)return R("INVALID_REQUEST","Search query must not be empty");let f=[...e].sort((g,d)=>+(g.registration.fallback===!0)-+(d.registration.fallback===!0)||(g.registration.priority??0)-(d.registration.priority??0)||g.order-d.order),h=/^[a-z][\w-]*:\s*$/iu.test(n.query),m=/^[a-z][\w-]*:/iu.test(n.query);for(let g of f){if(h&&!g.registration.fallback)continue;let d=g.registration.resolver,S;try{c.signal?.throwIfAborted(),S=await d.tryResolve(n,c)}catch(t){return R("RESOLVE_FAILED",b(t,`Resolver ${d.id} failed`),d.id,t)}if(!K(S))return R("INVALID_RESOLVER_RESULT",`Resolver ${d.id} returned an invalid result`,d.id);if(S.kind!=="not-handled"){if(S.kind==="failed")return R("RESOLVE_FAILED",b(S.error,`Resolver ${d.id} failed`),d.id,S.error);try{let t=await d.format(S.payload,c);return Q(t)?{content:g.registration.fallback&&m?[{type:"text",text:h?"Search fallback: empty protocol query; searched the original text.":"Search fallback: unhandled protocol query; searched the original text."},...t.content]:t.content,details:{resolverId:d.id,payload:t.details},...t.usage!==void 0&&{usage:t.usage}}:R("FORMAT_FAILED",`Resolver ${d.id} formatter returned an invalid result`,d.id)}catch(t){return R("FORMAT_FAILED",b(t,`Resolver ${d.id} formatter failed`),d.id,t)}}}let y=`No search resolver handled ${n.query}`;return M(R("NO_RESOLVER",y),y)},runAction(n,c,f,h,m){let y=r.get(P(f,c));if(y===void 0)throw new Error(`Search reference does not support ${c}`);return y.execute(n,h,m)},renderDescriptions(){return[...a.values()].flatMap(n=>{let c=F(n);return c===void 0?[]:[c]})},renderPromptGuidelines(){return[...s.values()].flat().flatMap(n=>{let c=F(n);return c===void 0?[]:[c]})},renderer(n){return e.find(({registration:c})=>c.resolver.id===n)?.registration.resolver.renderResult}};return u}o(q,"createSearchCore");function z(e){if(!E(e)||!E(e.resolver))throw new TypeError("Invalid search resolver registration");let r=e.resolver;if(typeof r.id!="string"||r.id.trim().length===0||typeof r.tryResolve!="function"||typeof r.format!="function")throw new TypeError("Invalid search resolver registration");if(e.priority!==void 0&&(typeof e.priority!="number"||!Number.isFinite(e.priority)))throw new TypeError("Invalid search resolver priority")}o(z,"assertResolver");function _(e){if(!E(e)||typeof e.resolverId!="string"||e.resolverId.trim().length===0||typeof e.capability!="string"||e.capability.trim().length===0||typeof e.execute!="function")throw new TypeError("Invalid search action registration")}o(_,"assertAction");function E(e){return typeof e=="object"&&e!==null}o(E,"isRecord");function K(e){if(typeof e!="object"||e===null||!("kind"in e))return!1;let r=e.kind;return r==="not-handled"||r==="resolved"&&"payload"in e||r==="failed"&&"error"in e}o(K,"isAttempt");function Q(e){return typeof e=="object"&&e!==null&&Array.isArray(e.content)}o(Q,"isAgentToolResult");function R(e,r,s,a){return{content:[{type:"text",text:r}],details:{failure:{code:e,message:r,...s!==void 0&&{resolverId:s},...a!==void 0&&{cause:a}}}}}o(R,"failure");function L(e){if(typeof e=="function")return e;if(typeof e!="string"||e.trim().length===0)throw new TypeError("Search description must not be empty");return e.trim()}o(L,"normalizeDescriptionSource");function F(e){let r=typeof e=="function"?e():e;if(r!==void 0){if(typeof r!="string"||r.trim().length===0)throw new TypeError("Search description must not be empty");return r.trim()}}o(F,"renderDescription");function P(e,r){return`${e}:${r}`}o(P,"actionKey");function b(e,r){return!(e instanceof Error)||e.message.trim().length===0?r:e instanceof SyntaxError?e.message:`${r}: ${e.message}`}o(b,"messageFor");import{readFile as Y}from"node:fs/promises";import X from"node:os";import T from"node:path";var Z=3e4;function H(e=process.env,r=X.homedir(),s=process.cwd()){let a=e.PI_CODING_AGENT_DIR?.trim(),i=a===void 0||a.length===0?T.join(r,".pi","agent"):T.resolve(a);return{globalPath:T.join(i,"pi-agent-ide","search.json"),projectPath:T.resolve(s,".pi","pi-agent-ide","search.json")}}o(H,"resolveSearchConfigPaths");async function V(e){let[r,s]=await Promise.all([G(e.globalPath),G(e.projectPath)]),a=s!==void 0?s:r;return{timeoutMs:a===void 0?Z:a}}o(V,"loadSearchConfig");async function G(e){let r;try{r=await Y(e,"utf8")}catch(l){if(ee(l))return;throw new Error(`Cannot read Pi Agent IDE search config at ${e}`,{cause:l})}let s;try{s=JSON.parse(r)}catch(l){throw new Error(`Invalid JSON in Pi Agent IDE search config at ${e}`,{cause:l})}if(!W(s))throw new TypeError(`Pi Agent IDE search config at ${e} must be a JSON object`);let a=Object.keys(s).find(l=>l!=="timeoutMs");if(a!==void 0)throw new TypeError(`Pi Agent IDE search config at ${e} contains unknown key ${a}`);let i=s.timeoutMs;if(i==null)return i;if(typeof i!="number"||!Number.isSafeInteger(i)||i<=0)throw new TypeError(`timeoutMs must be a positive integer or null in Pi Agent IDE search config at ${e}`);return i}o(G,"readTimeout");function ee(e){return W(e)&&e.code==="ENOENT"}o(ee,"isMissingFile");function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(W,"isRecord");var J=Symbol("search-timeout"),A=class extends Error{static{o(this,"SearchTimeoutError")}constructor(r){super(r),this.name="SearchTimeoutError"}};async function U(e,r,s){if(e===null)return s(r);let a=new AbortController,i=r===void 0?a.signal:AbortSignal.any([r,a.signal]),l,u=new Promise(n=>{l=setTimeout(()=>{n(J),a.abort()},e)});try{let n=await Promise.race([s(i),u]);if(n===J)throw new A(`Search timed out after ${re(e)}. Try a smaller path scope.`);return n}finally{clearTimeout(l)}}o(U,"runWithSearchTimeout");function re(e){if(e%1e3!==0)return`${String(e)}ms`;let r=e/1e3;return`${String(r)} ${r===1?"second":"seconds"}`}o(re,"formatDuration");var ie=p.Object({query:p.String({minLength:1,description:"Text to find, a Boolean expression, or a prefixed query described below, such as files:*.ts. Quote text to keep it literal, or use regex:<pattern> for regular-expression matching."}),path:p.Optional(p.String({description:"Optional file or directory scope for local search"})),include:p.Optional(p.String({description:"Optional include glob for local search"})),exclude:p.Optional(p.String({description:"Optional exclude glob for local search"})),caseSensitive:p.Optional(p.Boolean({description:"Match letter case in local search"})),wholeWord:p.Optional(p.Boolean({description:"Match complete words in local search"})),limit:p.Optional(p.Integer({minimum:1,maximum:1e3,description:"Maximum results (default 100)"}))},{additionalProperties:!1});function se(e,r){let s=[...e.path===void 0?[]:[{text:`in ${e.path}`,color:"accent",underline:!0,truncate:"start"}],...e.include===void 0?[]:[{text:`include ${e.include}`}],...e.exclude===void 0?[]:[{text:`exclude ${e.exclude}`}],...e.caseSensitive===!0?[{text:"case sensitive"}]:[],...e.wholeWord===!0?[{text:"whole word"}]:[],...e.limit===void 0?[]:[{text:`limit ${String(e.limit)}`}]];return{tool:"search",primary:{text:JSON.stringify(e.query),color:"accent",truncate:"end"},qualifiers:s,details:ae(e),expanded:r}}o(se,"searchCallModel");async function B(e){let r=q(),s=new N,a=e.events.on($,i=>{if(!O(i))throw new Error("Invalid pi-agent-search plugin registration request");i.accept(r.registerPlugin(i.plugin))});e.on("session_shutdown",a),e.registerTool(j({name:"search",label:"search",get description(){return["Use search to locate text, file paths and code structures in the workspace.",...r.renderDescriptions()].join(`
2
+ `)},promptSnippet:"Search files and text with literals or regular expressions, plus syntax trees and language symbols",get promptGuidelines(){return["Use the narrowest useful search query and scope; broaden when needed.",...r.renderPromptGuidelines()]},parameters:ie,renderCall(i,l,u){return k(u.lastComponent,se(i,u.expanded),l)},renderResult(i,l,u,n){let c=i.details,f=c?.resolverId===void 0?void 0:r.renderer(c.resolverId);if(f!==void 0){let h={...i,details:c?.payload};return f(h,l,u,n)}return ce(i,l,u)},async execute(i,l,u,n,c){let f=await V(H(process.env,oe.homedir(),c.cwd));return U(f.timeoutMs,u,async h=>(await r.waitForPendingPlugins(),r.execute(l,{cwd:c.cwd,...h!==void 0&&{signal:h},...n!==void 0&&{onUpdate:o(m=>{n(m)},"onUpdate")}})))}},s)),e.events.emit(D,{protocol:I,apiVersion:C}),await r.waitForPendingPlugins()}o(B,"registerSearchCore");function ae(e){return[{label:"query",value:JSON.stringify(e.query)},...v("path",e.path),...v("include",e.include),...v("exclude",e.exclude),...v("caseSensitive",e.caseSensitive===void 0?void 0:String(e.caseSensitive)),...v("wholeWord",e.wholeWord===void 0?void 0:String(e.wholeWord)),...v("limit",e.limit===void 0?void 0:String(e.limit))]}o(ae,"searchCallDetails");function v(e,r){return r===void 0?[]:[{label:e,value:r}]}o(v,"optionalDetail");function ce(e,r,s){let a=e.content.flatMap(u=>u.type==="text"?[u.text]:[]).join(`
3
+ `),i=r.expanded?a:a.split(`
4
+ `).slice(0,8).join(`
5
+ `),l=!r.expanded&&a.split(`
6
+ `).length>8?`
7
+ ${s.fg("dim",`${te("app.tools.expand")} to expand`)}`:"";return new ne(`${s.fg("muted",i)}${l}`,0,0)}o(ce,"fallbackResult");export{B as default};
package/dist/entry-46.js CHANGED
@@ -1 +1,11 @@
1
- import{a as b}from"./chunk-KH5KPBCR.js";import{d as a}from"./chunk-34ZQTTU2.js";import"./chunk-MTTKFJV6.js";import"./chunk-ERVMDQGX.js";import"./chunk-VFBLX4TG.js";import"./chunk-E2RESHYR.js";import"./chunk-T2RPMEM2.js";import"./chunk-EEH4WYI7.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as createSearchSessionId,b as default};
1
+ import{a as f,b as X,c as z,d as de,g as J}from"./chunk-JJVXUL5U.js";import"./chunk-LQYZG62K.js";import{a as H}from"./chunk-ERVMDQGX.js";import{a as F,b as I}from"./chunk-VFBLX4TG.js";import{a as j}from"./chunk-E2RESHYR.js";import{a as _,b as q}from"./chunk-T2RPMEM2.js";import{a as V}from"./chunk-WNMGUALD.js";import{a as B,b as W,d as G}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import{t as O,u as P}from"./chunk-RAZOACDD.js";import{d as L,e as v}from"./chunk-N34ATN52.js";import{a as k}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";var Q={protocol:F,apiVersion:1,id:"search-text",setup(e){e.addSetupCheck({id:"ripgrep",async inspect(t){let r=f(t.env.PI_CODING_AGENT_DIR);return await L(r,t.cwd,t.env)?{}:{actions:[{id:"ripgrep-unavailable",message:"Local search is unavailable because ripgrep was not found"}]}}}),e.addCheck({id:"ripgrep",title:"Local search",async run(t){let r=t.env.PI_CODING_AGENT_DIR,n=f(r),i=await v(n,["--version"],t.cwd,t.env);return[i.ok?{status:"pass",message:"ripgrep is available",detail:i.detail}:{status:"fail",message:"ripgrep is not available",detail:i.detail}]}})}};import ie from"node:path";import{spawn as he}from"node:child_process";import y from"node:path";function K(e,t,r,n){let i=t.limit??100,o=["--files","--hidden","--no-config","--no-ignore-parent","--glob","!.git/**"];for(let a of U(t.include))o.push("--glob",a);for(let a of U(t.exclude))o.push("--glob",`!${a}`);return t.path!==void 0&&o.push(t.path),new Promise((a,l)=>{let c=he(f(),o,{cwd:r,stdio:["ignore","pipe","pipe"]}),u="",m="";c.stdout.setEncoding("utf8"),c.stderr.setEncoding("utf8"),c.stdout.on("data",h=>u+=h),c.stderr.on("data",h=>m+=h);let N=s(()=>{c.kill("SIGTERM")},"abort");n?.addEventListener("abort",N,{once:!0}),c.once("error",l),c.once("close",h=>{if(n?.removeEventListener("abort",N),n?.aborted===!0){l(n.reason instanceof Error?n.reason:new Error("File search aborted"));return}if(h!==0&&h!==1){l(new Error(m.trim()||`rg exited with code ${String(h)}`));return}let M=u.split(`
2
+ `).filter(Boolean).map(p=>y.relative(r,y.resolve(r,p))).filter(p=>me(p,e)).sort((p,ue)=>p.localeCompare(ue));a({files:M.slice(0,i),complete:M.length<=i})})})}s(K,"searchFiles");function U(e){return e?.split(",").map(t=>t.trim()).filter(Boolean)??[]}s(U,"splitGlobs");function me(e,t){if(/[*?[\]{}]/u.test(t)){let r=t.replace(/^\.\//u,"");return y.matchesGlob(r.includes("/")?e:y.basename(e),r)}return pe(e,t)}s(me,"matchFile");function pe(e,t){if(t.length===0)return!0;let r=0,n=e.toLowerCase();for(let i of t.toLowerCase()){if(r=n.indexOf(i,r),r===-1)return!1;r+=1}return!0}s(pe,"fuzzyMatch");import Re from"node:path";import{keyText as re}from"@earendil-works/pi-coding-agent";import{Text as Te,truncateToWidth as S,visibleWidth as d,wrapTextWithAnsi as Ce}from"@earendil-works/pi-tui";import $ from"node:path";import{pathToFileURL as fe}from"node:url";function A(e,t,r,n,i){let o=new Map;for(let l of t){let c=$.resolve(l.source);o.set(c,[...o.get(c)??[],l])}let a=[...o].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>ge(l,c,n));return{...i!==void 0&&{sessionId:i},query:e,matchCount:t.length,fileCount:a.length,complete:r,files:a}}s(A,"createSearchToolDetails");function x(e){if(!R(e)||typeof e.query!="string"||!b(e.matchCount)||!b(e.fileCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||!Array.isArray(e.files)||!e.files.every(Se))return!1;let t=e.files;return e.fileCount===t.length&&e.matchCount===t.reduce((r,n)=>r+n.matchCount,0)}s(x,"isSearchToolDetails");function ge(e,t,r){let n=new Map;for(let o of t){let a=n.get(o.lineNumber);if(a!==void 0&&a.text!==o.lineText)throw new Error(`Search results disagree about line ${String(o.lineNumber)} in ${e}.`);let l=a??{lineNumber:o.lineNumber,text:o.lineText,ranges:[]};l.ranges.push({from:o.startColumn,to:o.endColumn}),n.set(o.lineNumber,l)}let i=[...n.values()].sort((o,a)=>o.lineNumber-a.lineNumber).map(o=>{let a=[...o.ranges].sort((l,c)=>l.from-c.from||l.to-c.to);return{lineNumber:o.lineNumber,text:o.text,matchCount:a.length,ranges:a}});return{path:xe(e,r),link:fe(e).href,matchCount:t.length,lines:i}}s(ge,"createSearchResultFile");function Se(e){return!R(e)||typeof e.path!="string"||typeof e.link!="string"||!b(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(ye)?!1:e.matchCount===e.lines.reduce((t,r)=>t+r.matchCount,0)}s(Se,"isSearchResultFile");function ye(e){return R(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&b(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&e.ranges.every(t=>be(t,e.text))}s(ye,"isSearchResultLine");function be(e,t){return R(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=t.length}s(be,"isSearchResultRange");function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(R,"isRecord");function b(e){return Number.isSafeInteger(e)&&e>=0}s(b,"isCount");function xe(e,t){let r=$.relative(t,e);return r.length>0&&!r.startsWith("..")&&!$.isAbsolute(r)?r:e}s(xe,"displaySource");function Y(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}s(Y,"sourceText");function Z(e,t){let{files:r,...n}=e,i=Y(t);return{...n,storedFiles:r.map(({lines:o,...a})=>({...a,lines:o.map(l=>[l.lineNumber,O(l.text,i),l.ranges])}))}}s(Z,"compactSearchDetails");function ee(e,t){if("files"in e)return e;let{storedFiles:r,...n}=e,i=Y(t);return{...n,files:r.map(({lines:o,...a})=>({...a,lines:o.map(([l,c,u])=>({lineNumber:l,text:P(c,i),ranges:u,matchCount:u.length}))}))}}s(ee,"restoreSearchDetails");var te=new WeakMap,T=12,$e={".ts":{label:"TS",color:"accent"},".tsx":{label:"TX",color:"accent"},".js":{label:"JS",color:"warning"},".jsx":{label:"JX",color:"warning"},".json":{label:"{}",color:"warning"},".md":{label:"MD",color:"mdHeading"},".py":{label:"PY",color:"accent"},".rs":{label:"RS",color:"accent"},".go":{label:"GO",color:"accent"},".css":{label:"CS",color:"accent"},".html":{label:"<>",color:"accent"}};function ne(e,t,r,n){if(typeof e.details=="object"){let a=te.get(e.details);a===void 0&&(a=ee(e.details,e.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
3
+ `)),te.set(e.details,a)),e={...e,details:a}}if(t.isPartial||n.isError||!x(e.details)){let a=e.content[0],l=a?.type==="text"?a.text:"",c=n.isError?"error":t.isPartial?"dim":"toolOutput";return new Te(r.fg(c,l),0,0)}let o=(n.lastComponent instanceof C?n.lastComponent:void 0)??new C(e.details,r,t.expanded);return o.update(e.details,r,t.expanded),o}s(ne,"renderSearchResult");var C=class{constructor(t,r,n){this.details=t;this.theme=r;this.expanded=n}static{s(this,"SearchResultPanel")}cached;update(t,r,n){this.details===t&&this.theme===r&&this.expanded===n||(this.details=t,this.theme=r,this.expanded=n,this.invalidate())}render(t){if(this.cached?.width===t)return this.cached.lines;if(t<4){let u=[S(oe(this.details),Math.max(1,t))];return this.cached={width:t,lines:u},u}let r=t-2,n=Ae(this.details,this.expanded),i=ve(this.details.files),o=n.flatMap(u=>we(u,r,i,this.theme)),a=Ee(o,this.expanded,r,this.theme),l=[ke(this.details,r,this.theme),...a];l.push(this.theme.fg("borderMuted",`\u2570${"\u2500".repeat(r)}\u256F`));let c=l.map(u=>S(u,t));return this.cached={width:t,lines:c},c}invalidate(){this.cached=void 0}};function Ae(e,t){let r=e.files.length===0?[{kind:"empty"}]:e.files.flatMap(o=>[{kind:"file",file:o},...o.lines.map(a=>({kind:"line",file:o,line:a}))]);if(t||r.length<=T)return r;let n=r.slice(0,T-1);for(;n.at(-1)?.kind==="file";)n.pop();let i=n.reduce((o,a)=>o+(a.kind==="line"?a.line.matchCount:0),0);return[...n,{kind:"omitted",matches:e.matchCount-i}]}s(Ae,"searchViewport");function Ee(e,t,r,n){if(t||e.length<=T)return e;let i=`${re("app.tools.expand")} to expand`,o=g(n.fg("dim",` \u2026 output truncated \xB7 ${i}`),r,n);return[...e.slice(0,T-1),o]}s(Ee,"compactRenderedRows");function we(e,t,r,n){if(e.kind==="file")return[g(De(e.file,t,n),t,n,!0)];if(e.kind==="line")return Ne(e.line,t,r,n);if(e.kind==="omitted"){let i=`${re("app.tools.expand")} to expand`;return[g(n.fg("dim",` \u2026 ${String(e.matches)} more ${w(e.matches,"match","matches")} \xB7 ${i}`),t,n)]}return[g(n.fg("dim"," No matches found"),t,n)]}s(we,"renderPanelRow");function De(e,t,r){let n=Oe(e.path,r),i=r.fg("accent",r.bold(String(e.matchCount))),o=d(n)+d(i)+4,a=Math.max(1,t-o),l=Le(e.path,a),c=Pe(l,e.link,r),u=` ${n} ${c}`,m=" ".repeat(Math.max(1,t-d(u)-d(i)-1));return S(`${u}${m}${i} `,t)}s(De,"renderFileHeader");function Ne(e,t,r,n){let i=String(e.lineNumber).padStart(r),o=` ${n.fg("dim",i)} ${n.fg("borderMuted","\u2502")} `,a=Math.max(1,t-d(o)-1),l=Ce(Me(e,n),a),c=" ".repeat(d(o));return l.map((u,m)=>g(`${m===0?o:c}${u}`,t,n))}s(Ne,"renderMatchLine");function Me(e,t){let r="",n=0;for(let i of e.ranges){i.from>n&&(r+=t.fg("toolOutput",E(e.text.slice(n,i.from))));let o=E(e.text.slice(i.from,i.to));r+=t.bg("selectedBg",t.fg("accent",t.bold(o))),n=i.to}return n<e.text.length&&(r+=t.fg("toolOutput",E(e.text.slice(n)))),r}s(Me,"renderHighlightedLine");function ke(e,t,r){let n=s(a=>r.fg("borderMuted",a),"frame"),i=S(` ${oe(e)} `,Math.max(0,t-1),""),o="\u2500".repeat(Math.max(0,t-d(i)-1));return`${n("\u256D\u2500")}${r.fg("accent",i)}${n(`${o}\u256E`)}`}s(ke,"renderTopBorder");function oe(e){return e.matchCount===0?"No matches":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${w(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${w(e.fileCount,"file","files")}`}s(oe,"searchSummary");function g(e,t,r,n=!1){let i=S(e,t),o=`${i}${" ".repeat(Math.max(0,t-d(i)))}`,a=n?r.bg("selectedBg",o):o,l=r.fg("borderMuted","\u2502");return`${l}${a}${l}`}s(g,"framed");function Oe(e,t){let r=Re.extname(e).toLowerCase(),n=$e[r]??{label:"\u25C7 ",color:r.length===0?"muted":"accent"};return t.fg(n.color,t.bold(n.label))}s(Oe,"fileBadge");function Pe(e,t,r){let n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),i=n===-1?"":e.slice(0,n+1),o=n===-1?e:e.slice(n+1),a=r.fg("muted",i)+r.underline(r.fg("accent",o));return t.includes("\x07")||t.includes("\x1B")?a:`\x1B]8;;${t}\x07${a}\x1B]8;;\x07`}s(Pe,"fileLink");function Le(e,t){return d(e)<=t?e:t<=1?"\u2026":`\u2026${e.slice(-(t-1))}`}s(Le,"truncatePath");function E(e){let t="";for(let r of e){if(r===" "){t+=" ".repeat(4);continue}let n=k(r.codePointAt(0));t+=n<32||n===127?"\uFFFD":r}return t}s(E,"safeText");function ve(e){let t=1;for(let r of e)for(let n of r.lines)t=Math.max(t,n.lineNumber);return Math.max(3,String(t).length)}s(ve,"maximumLineNumberWidth");function w(e,t,r){return e===1?t:r}s(w,"plural");function ae(e){return ce("text",e,X)}s(ae,"createTextResolver");function se(e){return ce("regex",e,t=>t.query.startsWith("regex:")?{...t,query:t.query.slice(6),regex:!0}:void 0)}s(se,"createRegexResolver");function le(){return{id:"files",async tryResolve(e,t){if(!e.query.startsWith("files:"))return{kind:"not-handled"};let r=e.query.slice(6).trim(),n=await K(r,e,t.cwd,t.signal);return{kind:"resolved",payload:{query:r,...n}}},format(e){let t=e;return{content:[{type:"text",text:[t.complete?`${String(t.files.length)} files`:`${String(t.files.length)}+ files (limit reached)`,...t.files].join(`
4
+ `)}],details:{query:t.query,files:t.files,complete:t.complete}}}}}s(le,"createFileResolver");function ce(e,t,r){return{id:e,async tryResolve(n,i){let o=r(n);if(o===void 0)return{kind:"not-handled"};let a=await z(o,i.cwd,i.signal);return{kind:"resolved",payload:{request:{...n,query:a.query},...a,recipe:{...o,originalQuery:n.query}}}},async format(n,i){let o=n;if(o.matches.length===0)return{content:[{type:"text",text:[...o.notices,"No matches found."].join(`
5
+ `)}],details:A(o.request.query,[],o.complete,i.cwd)};let a=await t.register(o.request.query,o.matches,o.complete,i.cwd,i.signal,o.recipe);return{content:[{type:"text",text:[...o.notices,Fe(a,i.cwd)].join(`
6
+ `)}],details:A(a.query,a.matches,a.complete,i.cwd,a.id)}},renderResult:ne}}s(ce,"createMatchResolver");function Fe(e,t){let r=new Set(e.matches.map(l=>l.source)).size,n=e.matches.length,i=e.complete?`SEARCH#${e.id}:all:line / SEARCH#${e.id}:all:match \u2014 ${String(n)} ${D(n,"match","matches")} in ${String(r)} ${D(r,"file","files")}`:`${String(n)}+ matches in ${String(r)} ${D(r,"file","files")} (limit reached; no all anchors were registered)`,o,a=["Anchors: SEARCH#HASH:N:line (line), SEARCH#HASH:N:match (exact match), SEARCH#HASH:all:line (each unique containing line), SEARCH#HASH:all:match (every exact match)",i];for(let[l,c]of e.matches.entries()){o!==void 0&&o!==c.source&&a.push("");let u=He(c.source,t);a.push(`${u}:${String(c.lineNumber)}:${String(c.startColumn+1)}-${String(c.endColumn+1)} SEARCH#${e.id}:${String(l+1)}:line SEARCH#${e.id}:${String(l+1)}:match`,` ${Ie(c)}`),o=c.source}return e.complete||a.push("","Increase limit and search again before applying a complete replacement."),a.join(`
7
+ `)}s(Fe,"formatSearchSession");function Ie(e){let r=Math.max(0,e.startColumn-64),n=Math.min(e.lineText.length,e.endColumn+64);return`${r>0?"\u2026":""}${e.lineText.slice(r,e.startColumn)}\u27E6${e.lineText.slice(e.startColumn,e.endColumn)}\u27E7${e.lineText.slice(e.endColumn,n)}${n<e.lineText.length?"\u2026":""}`}s(Ie,"previewMatch");function He(e,t){let r=ie.relative(t,e);return r.length>0&&!r.startsWith("..")&&!ie.isAbsolute(r)?r:e}s(He,"displaySource");function D(e,t,r){return e===1?t:r}s(D,"plural");async function _e(e){let t=new J;e.on("tool_result",async(r,n)=>{if(r.toolName!=="replace"||r.isError||typeof r.details!="object"||r.details===null)return;let i=await t.observeAfterEdit([r.input.path,r.input.start,r.input.end],n.signal);if(i.length!==0)return{content:[...r.content,{type:"text",text:["Original search observed after editing (not task validation):",...i.map(o=>{let{query:a,fallbacks:l,...c}=o.scope;return[`SEARCH#${o.sessionId}: ${JSON.stringify(o.query)}`,`Scope and options: ${JSON.stringify(c)}`,o.error===void 0?`Matches: ${o.matches}${o.complete===!0?"; complete search.":"+; incomplete search, lower bound only."}`:`Search failed: ${o.error}. Applied edits remain applied.`,...o.notices??[]].join(`
8
+ `)})].join(`
9
+ `)}],details:{...r.details,searchObservations:i}}}),e.on("tool_result",r=>{if(r.toolName!=="search"||typeof r.details!="object"||r.details===null)return;let n=r.details;if(x(n.payload))return{details:{...n,payload:Z(n.payload,r.content.flatMap(i=>i.type==="text"?[i.text]:[]).join(`
10
+ `))}}}),await Promise.all([H(e,Q),j(e,{protocol:_,apiVersion:q,id:"local",setup(r){r.addResolver({resolver:se(t),priority:-10}),r.addResolver({resolver:le(),priority:-10}),r.addResolver({resolver:ae(t),fallback:!0}),r.describe(["Local queries try literal terms first, then unquoted terms as regex when no literal results exist, then separate words for ordinary multi-word queries. Quoted terms stay literal. Boolean conditions stay intact across fallback. Uppercase AND/OR, infix NOT, ||, and space-separated | are Boolean operators; unspaced | and regex groups/classes belong to regex terms. Parentheses containing Boolean operators group Boolean conditions. regex:<pattern> forces regex-only matching; files:<pattern> searches file paths: glob patterns use *, **, ?, character classes and braces; other queries use case-insensitive subsequence matching. Slash-containing globs match cwd-relative paths; basename globs match at any depth.","The result says when a query was broadened. Empty or unknown prefixes are searched as plain text. A recognized prefixed query returns its own results or error; it does not silently become a text search.","SEARCH#HASH:N:line selects one containing line; :match selects its exact match. :all:line selects all unique containing lines and :all:match selects all matches. Read returns containing lines for both forms. A SEARCH resource can be used as a read path or mutation path/anchor; omit the file path for an all-selection spanning files.","Use SEARCH references exactly as returned to select the matching content. A single-result reference becomes stale when its file changes; obtain a fresh result before using it again. An :all reference refreshes the original query when a selected file changes. Limited or incomplete searches do not provide :all selections."].join(`
11
+ `))}}),V(e,{protocol:B,apiVersion:W,id:"search-anchors",setup(r){r.addAnchorResolver({resolver:t.anchorResolver(),resources:t.resourceResolver(),kind:G,type:"auxiliary",describeInPrompt:!1})}})])}s(_e,"registerTextSearch");export{de as createSearchSessionId,_e as default};
package/dist/entry-47.js CHANGED
@@ -1 +1 @@
1
- import{d as a,e as b,f as c,g as d}from"./chunk-34ZQTTU2.js";import"./chunk-MTTKFJV6.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{d as SearchSessionStore,c as allocateSearchSessionId,a as createSearchSessionId,b as createSearchSessionIdentity};
1
+ import{d as a,e as b,f as c,g as d}from"./chunk-JJVXUL5U.js";import"./chunk-LQYZG62K.js";import"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{d as SearchSessionStore,c as allocateSearchSessionId,a as createSearchSessionId,b as createSearchSessionIdentity};
package/dist/entry-48.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-2SKAED2I.js";import"./chunk-EI7MMDWY.js";export{a as TextAnchor,b as attachTextAnchorRenderer,p as createTextContentConverter,m as createTextDocument,c as getTextAnchorRenderer,i as getTextSourceLine,g as isTextAnchorRecoveryOutcome,f as isTextAnchorResolutionAttempt,e as isTextAnchorResolver,k as isTextLinePresenter,l as isTextPresenterRegistration,s as isTextTargetResolutionAttempt,q as isTextualMediaType,o as renderPresentedTextDocument,h as renderPresentedTextRows,d as renderTextAnchor,n as renderTextDocument,u as restoreText,t as storeText,r as textFromAgentContent,j as withTextSourceLine};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-RAZOACDD.js";import"./chunk-EI7MMDWY.js";export{a as TextAnchor,b as attachTextAnchorRenderer,p as createTextContentConverter,m as createTextDocument,c as getTextAnchorRenderer,i as getTextSourceLine,g as isTextAnchorRecoveryOutcome,f as isTextAnchorResolutionAttempt,e as isTextAnchorResolver,k as isTextLinePresenter,l as isTextPresenterRegistration,s as isTextTargetResolutionAttempt,q as isTextualMediaType,o as renderPresentedTextDocument,h as renderPresentedTextRows,d as renderTextAnchor,n as renderTextDocument,u as restoreText,t as storeText,r as textFromAgentContent,j as withTextSourceLine};
package/dist/entry-49.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-5BWUVAR4.js";import"./chunk-EEH4WYI7.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{a as d}from"./chunk-WNMGUALD.js";import{a as s,b as l,c}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import{a as i}from"./chunk-RAZOACDD.js";import{a as t}from"./chunk-EI7MMDWY.js";var o=class extends i{static{t(this,"ConstantTextAnchor")}constructor(n,r){super(n,r)}};function p(){return{id:"file-position",description:"`begin` and `end` select the first and last existing lines.",renderFull(e){return e},renderCompact(e){return e==="begin"?"file start":"file end"},tryResolve(e,n){return Promise.resolve(a(e,n))}}}t(p,"createConstantTextAnchorResolver");function a(e,n){return e!=="begin"&&e!=="end"?{kind:"not-handled"}:n.lines.length===0?{kind:"failed",error:new Error(`${e} cannot resolve in an empty file`)}:{kind:"resolved",anchor:new o(e,e==="begin"?1:n.lines.length)}}t(a,"resolveConstantAnchor");async function T(e){await d(e,{protocol:s,apiVersion:l,id:"text-anchor-constant",setup(r){r.addAnchorResolver({resolver:p(),kind:c,type:"constant"})}})}t(T,"registerConstantTextAnchors");export{T as default};
package/dist/entry-50.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-SJYDLHEF.js";import"./chunk-MTTKFJV6.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as createExactTextAnchorResolver,c as findExactTextMatches,b as resolveExactTextAnchor};
1
+ import{a,b,c}from"./chunk-ZXN3TWWW.js";import"./chunk-LQYZG62K.js";import"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as createExactTextAnchorResolver,c as findExactTextMatches,b as resolveExactTextAnchor};
package/dist/entry-51.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-HOBTFFQR.js";import"./chunk-SJYDLHEF.js";import"./chunk-MTTKFJV6.js";import"./chunk-EEH4WYI7.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{a as m}from"./chunk-ZXN3TWWW.js";import"./chunk-LQYZG62K.js";import{a as f}from"./chunk-WNMGUALD.js";import{a as c,b as u,c as s}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import{readFileSync as z}from"node:fs";import w from"node:path";function x(e){let n=b(e.settings,"recovery.exactText");n!==void 0&&p(n,["fuzzyEnabled","threshold","exactCandidateLimit","fuzzyCandidateLimit","maxFileSizeMiB","maxQuerySizeKiB","seedLimit","blockLineVariance"],"recovery.exactText");let t=i(o=>n===void 0?void 0:n[o],"value");return{fuzzyEnabled:g(t("fuzzyEnabled"),"fuzzyEnabled")??!0,threshold:d(t("threshold"),"threshold",0,1)??.8,exactCandidateLimit:a(t("exactCandidateLimit"),"exactCandidateLimit",1,100)??20,fuzzyCandidateLimit:a(t("fuzzyCandidateLimit"),"fuzzyCandidateLimit",1,20)??5,maxFileSizeMiB:d(t("maxFileSizeMiB"),"maxFileSizeMiB",.01,100)??20,maxQuerySizeKiB:d(t("maxQuerySizeKiB"),"maxQuerySizeKiB",.01,4096)??1024,seedLimit:a(t("seedLimit"),"seedLimit",1,10)??3,blockLineVariance:a(t("blockLineVariance"),"blockLineVariance",0,10)??2,contextLines:e.contextLines,timeoutMs:e.timeoutMs}}i(x,"parseExactTextRecoveryConfig");function l(e,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError(`${n} must be an object`);return Object.fromEntries(Object.entries(e))}i(l,"objectRecord");function b(e,n){return e===void 0?void 0:l(e,n)}i(b,"optionalObject");function p(e,n,t){let o=new Set(n),r=Object.keys(e).find(y=>!o.has(y));if(r!==void 0)throw new TypeError(`${t} contains unknown key ${r}`)}i(p,"assertKeys");function g(e,n){if(e===void 0||typeof e=="boolean")return e;throw new TypeError(`${n} must be a boolean`)}i(g,"optionalBoolean");function d(e,n,t,o){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<t||e>o)throw new RangeError(`${n} must be between ${t} and ${o}`);return e}}i(d,"optionalNumber");function a(e,n,t,o){let r=d(e,n,t,o);if(r!==void 0&&!Number.isInteger(r))throw new TypeError(`${n} must be an integer`);return r}i(a,"optionalInteger");async function E(e){await f(e,{protocol:c,apiVersion:u,id:"text-anchor-exact",setup(t){t.addAnchorResolver({resolver:m(x(t.recoveryConfig("exactText"))),kind:s,type:"auxiliary",describeInPrompt:!1,priority:1e4})}})}i(E,"registerExactTextAnchor");export{E as default};
package/dist/entry-52.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-PETQCA7G.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{b as createLineHashAnchor,e as createLineHashAnchorResolver,c as formatLineHashAnchor,a as hashLine,d as renderLineHashLines};
1
+ import{a,b,c,d,e}from"./chunk-P6T3Q7LB.js";import"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{b as createLineHashAnchor,e as createLineHashAnchorResolver,c as formatLineHashAnchor,a as hashLine,d as renderLineHashLines};
package/dist/entry-53.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-6SMFVLTY.js";import"./chunk-PETQCA7G.js";import"./chunk-ORAPGW7W.js";import"./chunk-JASLOB2X.js";import"./chunk-EEH4WYI7.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{b as x,e as T}from"./chunk-P6T3Q7LB.js";import{a as l}from"./chunk-ORAPGW7W.js";import{a as d,b as m}from"./chunk-JASLOB2X.js";import{a as P}from"./chunk-WNMGUALD.js";import{a as u,b as h,c as f}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import{i as p}from"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";function g(){return{id:"line-hash",present(n,o){let i=n.lines.map(e=>{let t=o.resolvedBy==="filesystem"?{lineNumber:e.lineNumber,content:e.content}:p(e);return t===void 0?void 0:{anchor:x(t.lineNumber,t.content),lineNumber:t.lineNumber}}),a=Math.max(0,...i.map(e=>e?.anchor.value.length??0)),r=Math.max(0,...i.map(e=>String(e?.lineNumber??"").length)),E=n.lines.map((e,t)=>{let c=i[t];return c===void 0?e:{...e,presentation:{...e.presentation,prefix:`${c.anchor.value.padStart(a)}|${e.presentation?.prefix??""}`,compactPrefix:e.presentation?.compactPrefix??`${String(c.lineNumber).padStart(r)} \u2502 `}}});return{...n,lines:E}}}}s(g,"createLineHashPresenter");async function R(n){let o=g(),i={protocol:d,apiVersion:m,id:"text-anchor-line-hash",setup(r){r.addView({view:"anchors",presenter:o}),r.describe('views: ["anchors"] \u2014 LINE#HASH references for editing individual source lines.')}},a={protocol:u,apiVersion:h,id:"text-anchor-line-hash",setup(r){r.addAnchorResolver({resolver:T(),kind:f,type:"major"}),r.addTextPresenter({presenter:o})}};await Promise.all([l(n,i),P(n,a)])}s(R,"registerLineHashTextAnchor");export{R as default};
package/dist/entry-55.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-EEH4WYI7.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-EI7MMDWY.js";export{a as connectTextEditorPlugin};
1
+ import{a}from"./chunk-WNMGUALD.js";import"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import"./chunk-RAZOACDD.js";import"./chunk-EI7MMDWY.js";export{a as connectTextEditorPlugin};
package/dist/entry-58.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import"./chunk-RAZOACDD.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
package/dist/entry-60.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-MTTKFJV6.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as TextSelectionAnchor};
1
+ import{a}from"./chunk-LQYZG62K.js";import"./chunk-RAZOACDD.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as TextSelectionAnchor};
package/dist/entry-61.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-TG6H6EOI.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-EI7MMDWY.js";export{a as TEXT_EDITOR_POST_EDIT_REGISTER_EVENT,e as connectTextEditorPostEditHandler,d as isTextMutationResultContributionData,b as isTextPostEditHandlerRegistration,c as isTextPostEditHandlerRegistrationRequest};
1
+ import{a,b,c,d,e,f,g}from"./chunk-RIGRP3FD.js";import"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import"./chunk-RAZOACDD.js";import"./chunk-EI7MMDWY.js";export{a as TEXT_EDITOR_POST_EDIT_REGISTER_EVENT,g as connectTextEditorPostEditHandler,c as isDiffStatusContribution,b as isFormattingContribution,f as isTextMutationResultContributionData,d as isTextPostEditHandlerRegistration,e as isTextPostEditHandlerRegistrationRequest};
package/dist/entry-62.js CHANGED
@@ -1 +1 @@
1
- import{a,b,d as c}from"./chunk-KNMWCDDK.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{b as FileMutationResult,a as FileRange,c as computeChangedRanges};
1
+ import{a,b,d as c}from"./chunk-6ACQQBUY.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{b as FileMutationResult,a as FileRange,c as computeChangedRanges};
package/dist/entry-67.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c}from"./chunk-XNXQYPVT.js";import{c as a}from"./chunk-VSP2QQPQ.js";import"./chunk-YHUTTZC6.js";import"./chunk-EI7MMDWY.js";export{a as getToolCallInterception,c as registerToolCallAnnotationSink,b as registerToolCallInterceptor};
1
+ import{a as b,b as c}from"./chunk-4LUW26BX.js";import{c as a}from"./chunk-GIRAEVUJ.js";import"./chunk-YHUTTZC6.js";import"./chunk-EI7MMDWY.js";export{a as getToolCallInterception,c as registerToolCallAnnotationSink,b as registerToolCallInterceptor};
package/dist/entry-69.js CHANGED
@@ -1 +1,59 @@
1
- import{a}from"./chunk-6XQQBKPE.js";import"./chunk-OVUYPHDE.js";import"./chunk-YPHXLAQF.js";import"./chunk-VCCMVQXU.js";import"./chunk-XNXQYPVT.js";import"./chunk-STUZZM5B.js";import"./chunk-MBUXFKIW.js";import"./chunk-TG6H6EOI.js";import"./chunk-KNMWCDDK.js";import"./chunk-VSP2QQPQ.js";import"./chunk-MTTKFJV6.js";import"./chunk-YHUTTZC6.js";import"./chunk-ORAPGW7W.js";import"./chunk-JASLOB2X.js";import"./chunk-266RH77Z.js";import"./chunk-EW2KVKCN.js";import"./chunk-2SKAED2I.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as default};
1
+ import{a as oe,b as Ce,c as Se}from"./chunk-OVUYPHDE.js";import{a as St,b as Mt,c as Ge}from"./chunk-YPHXLAQF.js";import{a as Xe}from"./chunk-VCCMVQXU.js";import{b as qe,c as kt}from"./chunk-4LUW26BX.js";import{a as ze}from"./chunk-STUZZM5B.js";import{a as Pt}from"./chunk-MBUXFKIW.js";import{b as re,c as be}from"./chunk-6ACQQBUY.js";import{b as fe,f as We,g as Ve}from"./chunk-GIRAEVUJ.js";import{a as N}from"./chunk-LQYZG62K.js";import"./chunk-YHUTTZC6.js";import{a as mt}from"./chunk-ORAPGW7W.js";import{a as gt,b as ht}from"./chunk-JASLOB2X.js";import{a as wt,b as vt,c as Et,d as At,e as bt,f as Ct}from"./chunk-RIGRP3FD.js";import{a as Ee,b as Ae,c as L,d as O,e as xt,f as Tt,g as pe,h as He,i as Ue,j as yt,m as Rt}from"./chunk-THSCUT2L.js";import{b as J,e as ve}from"./chunk-S3ZPXWX7.js";import{b as ct,d as we,f as ut,g as pt,h as ft,l as je,m as ne}from"./chunk-RAZOACDD.js";import{a as E}from"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";import{Type as Wn}from"typebox";function Ke(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}d(Ke,"isRecord");function Vn(t){if(Ke(t))return typeof t.name=="string"?t.name:Ke(t.function)&&typeof t.function.name=="string"?t.function.name:void 0}d(Vn,"toolName");function It(t){t.registerTool({name:"edit",label:"edit",description:"",promptGuidelines:["Use the smallest useful source view: reuse sufficient content and anchors, search for known text, or inspect structure when locating a declaration. Read nearby context when boundaries are unclear; resolve ambiguity rather than guessing.","Use an available anchor when it selects exactly the intended text; otherwise use minimal unique exact text. Keep the edit limited to the intended content.","When search broadens to separate words, treat its results as location hints. Refine the query before using those matches for replacement.","Submit independent mutations together in one tool-call block. They are evaluated against the original file contents. Combine overlapping changes into one mutation. A rejected mutation does not cancel other valid mutations; check each result and retry only changes that were not applied."],parameters:Wn.Object({},{additionalProperties:!1}),execute(){throw new Error("edit is not available.")}}),t.on("before_provider_request",e=>{if(!(!Ke(e.payload)||!Array.isArray(e.payload.tools)))return{...e.payload,tools:e.payload.tools.filter(n=>Vn(n)!=="edit")}})}d(It,"registerBuiltinEditFilter");var $t=new WeakMap;function Lt(t,e){$t.set(t,e)}d(Lt,"setTextAnchorRecoveryReader");function Ot(t,e,n){return $t.get(t)?.(e,n)}d(Ot,"readTextAnchorRecovery");import{diffLines as Gn}from"diff";function Dt(t,e={}){let n=t.source?`${t.source}:`:"",r=e.includeAnchor===!1||t.anchor===void 0?"":`${t.anchor} \u2014 `;return`[${t.severity.toUpperCase()}] ${r}${n}${t.code}: ${t.message}`}d(Dt,"formatHint");var Ft=5,qn=5,Bt={error:0,warning:1,info:2,hint:3};function _t(t,e){let n=t.data.afterDocument,r=t.data.snapshot?.content??t.data.beforeContentMap?.[e]??void 0,o=t.data.afterContent??n?.content;if(r===void 0||o===void 0)return Xn(t,e);let i=Ze(o),s=Math.max(1,i.length),a=Je(r,o,s),l=Ye(t,o,s,a),c=ge(l,s),p=t.hints.filter(v=>v.source==="compiler"&&v.severity==="error"),m=Qe(p,c),g=ge([...l,...m.filter(v=>!ie(v.line,c)).map(v=>({start:v.line,end:v.line}))],s),f=a.filter(v=>v.kind==="added").length,x=a.filter(v=>v.kind==="removed").length,S=[`${e} +${f} -${x}`],P=new Set(m),h=t.data.scopeMarkers??{};for(let v=0;v<g.length;v+=1){v>0&&S.push("...");let w=E(g[v]);for(let u of a){if(!Jn(u,w))continue;if(u.kind==="removed"){S.push({marker:"-",prefix:"|",content:u.text});continue}if(n!==void 0){let T=n.lines[E(u.afterLine)-1],A=T?.presentation?.prefix??"",C=T?.presentation?.suffix??"",k=Me(E(u.afterLine),t.hints,c,P),M=k.length>0?` ${k.join(" ")}`:"";S.push({marker:u.kind==="added"?"+":" ",prefix:A,content:u.text,suffix:`${C}${M}`});continue}let R=E(u.afterLine),b=Me(R,t.hints,c,P,h[String(R)]??h[R]),y=b.length>0?` ${b.join(" ")}`:"";S.push({marker:u.kind==="added"?"+":" ",prefix:"|",content:u.text,suffix:y})}}return jt(S)}d(_t,"renderAgentDiff");function jt(t){let e=ft(t.filter(zn)),n=0;return t.map(r=>typeof r=="string"?r:E(e[n++]))}d(jt,"renderDiffEntries");function zn(t){return typeof t!="string"}d(zn,"isPresentedTextRow");function Xn(t,e){let r=(t.diffs.find(a=>Qn(a)===e)??t.diffs[0]??"").split(`
2
+ `).filter(a=>!a.startsWith("--- ")&&!a.startsWith("+++ ")&&!a.startsWith("@@ ")&&!a.startsWith("\\ No newline")),o=r.filter(a=>a.startsWith("+")).length,i=r.filter(a=>a.startsWith("-")).length,s=[`${e} +${o} -${i}`];for(let a of r){let l=a[0];if(l!=="+"&&l!=="-"&&l!==" "){s.push(a);continue}s.push({marker:l,prefix:"|",content:a.slice(1)})}return jt(s)}d(Xn,"renderUnavailableSourceDiff");function Je(t,e,n){let r=[],o=1,i=1;for(let s of Gn(t,e))for(let a of Yn(s.value))if(s.added)r.push({kind:"added",text:a,afterLine:i,positionLine:i}),i+=1;else if(s.removed){let l=Math.max(1,Math.min(i,n));r.push({kind:"removed",text:a,beforeLine:o,positionLine:l}),o+=1}else r.push({kind:"context",text:a,beforeLine:o,afterLine:i,positionLine:i}),o+=1,i+=1;return r}d(Je,"buildDiffLines");function Ye(t,e,n,r){let o=t.data.rawChanges??[];if(o.length>0)return o.map(s=>({start:Nt(e,s.fromB),end:Nt(e,Math.max(s.fromB,s.toB-(s.toB>s.fromB?1:0)))}));let i=r.filter(s=>s.kind!=="context").map(s=>s.positionLine);return i.length===0?[]:[{start:Math.max(1,Math.min(...i)),end:Math.min(n,Math.max(...i))}]}d(Ye,"editRanges");function ge(t,e){if(e===0)return[];let n=t.map(o=>({start:Math.max(1,Math.min(e,o.start)-Ft),end:Math.min(e,Math.max(o.start,o.end)+Ft)})).sort((o,i)=>o.start-i.start);if(n.length===0)return[];let r=[E(n[0])];for(let o of n.slice(1)){let i=E(r.at(-1));o.start<=i.end+1?i.end=Math.max(i.end,o.end):r.push(o)}return r}d(ge,"expandAndMerge");function Qe(t,e){let n=t.filter(o=>ie(o.line,e)).sort((o,i)=>o.line-i.line),r=t.filter(o=>!ie(o.line,e)).sort(Kn);return[...n,...r.slice(0,Math.max(0,qn-n.length))]}d(Qe,"selectSyntaxHints");function Kn(t,e){return Bt[t.severity]-Bt[e.severity]||t.line-e.line||t.column-e.column||t.code.localeCompare(e.code)}d(Kn,"compareHints");function Me(t,e,n,r,o){let i=[];o!==void 0&&o.length>0&&i.push(`<!-- ${o.join(" ")} -->`);let s=ie(t,n),a=e.filter(l=>l.line===t&&(s||r.has(l)));return a.length>0&&i.push(`<!-- lsp: ${a.map(l=>Dt(l,{includeAnchor:!1})).join(" | ")} -->`),i}d(Me,"metadataForLine");function Jn(t,e){return t.positionLine>=e.start&&t.positionLine<=e.end}d(Jn,"isDiffLineVisible");function ie(t,e){return e.some(n=>t>=n.start&&t<=n.end)}d(ie,"isLineVisible");function Nt(t,e){let n=Math.max(0,Math.min(t.length,e));return t.slice(0,n).split(`
3
+ `).length}d(Nt,"lineAtOffset");function Ze(t){if(t.length===0)return[];let e=t.replaceAll(`\r
4
+ `,`
5
+ `).replaceAll("\r",`
6
+ `);return e.endsWith(`
7
+ `)?e.slice(0,-1).split(`
8
+ `):e.split(`
9
+ `)}d(Ze,"splitLines");function Yn(t){if(t.length===0)return[];let n=t.replaceAll(`\r
10
+ `,`
11
+ `).replaceAll("\r",`
12
+ `).split(`
13
+ `);return n.at(-1)===""&&n.pop(),n}d(Yn,"splitPartLines");function Qn(t){return/^--- (.+)$/m.exec(t)?.[1]}d(Qn,"extractDiffPath");function Ht(t){if(t.length===0)return;let e=[],n=new Map,r=[],o=0;for(let i of t){let s=i.data.operations,a=i.data.rawChanges;if(!i.ok||i.isPartial||i.warnings.length>0||i.errors.length>0||(i.data.hints?.length??0)>0||(i.data.diffStatuses?.length??0)>0||!i.path||!s?.length||s.some(c=>c.operation!=="replace")||!a?.length||s.reduce((c,p)=>c+p.changes,0)!==a.length)return;let l=[];for(let c of a){let p=JSON.stringify([c.removedText,c.insertedText]),m=n.get(p);m===void 0&&(m=e.length,n.set(p,m),e.push({removedText:c.removedText,insertedText:c.insertedText,count:0}));let g=e[m];if(g===void 0)throw new Error("Missing replacement group");g.count++,l[m]=(l[m]??0)+1,o++}r.push({path:i.path,groups:l,formatting:i.data.formatting?.status??"not-reported"})}if(e.length!==o)return{groups:e,files:r,changes:o}}d(Ht,"groupReplacements");function Ut(t){return[`Applied ${t.changes} replacements in ${t.files.length} files.`,"Exact applied replacements (before any additional formatting; not a full final-file view):",...t.groups.map((e,n)=>`G${n+1}: ${JSON.stringify(e.removedText)} -> ${JSON.stringify(e.insertedText)} (${e.count} replacements)`),"Files (complete):",...t.files.map(e=>`${e.path}: ${e.groups.flatMap((n,r)=>n?[`G${r+1} x ${n}`]:[]).join(", ")}; formatting: ${e.formatting}`)].join(`
14
+ `)}d(Ut,"renderGroupedReplacements");function Wt(t,e){let n=t.data.snapshot?.content??t.data.beforeContentMap?.[e],r=t.data.afterContent??t.data.afterDocument?.content;if(n==null||r===void 0)return[e];let o=Ze(r),i=Math.max(1,o.length),s=Je(n,r,i),a=Ye(t,r,i,s),l=ge(a,i),c=t.hints.filter(x=>x.source==="compiler"&&x.severity==="error"),p=Qe(c,l),m=ge([...a,...p.filter(x=>!ie(x.line,l)).map(x=>({start:x.line,end:x.line}))],i),g=new Set(p),f=[e];for(let x=0;x<m.length;x+=1){x>0&&f.push("...");let S=E(m[x]);f.push(`Final text, lines ${S.start}\u2013${S.end}:`);for(let P=S.start;P<=S.end;P+=1){let h=o[P-1]??"",v=Me(P,t.hints,l,g),w=v.length===0?"":` ${v.join(" ")}`,u=t.data.resultPresentation==="major-anchor"?t.data.afterDocument?.lines[P-1]?.presentation?.prefix??"":"";f.push(`${u}${h}${w}`)}}return f}d(Wt,"renderFinalStateFragment");var V=class{static{d(this,"FileMutationAgentResult")}results;constructor(e){this.results=Array.isArray(e)?e:[e]}toText(){let e=Ht(this.results);return e!==void 0?Ut(e):Array.from(this.results,r=>this.formatSingle(r)).join(`
15
+
16
+ `)}toTextContent(){return{type:"text",text:this.toText()}}formatSingle(e){return e.isPartial?"gate progress":e.ok?e.diffs.length===0&&e.files.length===0?"<empty-result>":this.formatSuccess(e):this.formatFailure(e)}formatFailure(e){if(e.errors.some(s=>s.code==="STALE_ANCHOR")&&e.staleEdits.length>0&&!e.staleDiagnostic)return this.formatStaleFailure(e);let n=[`EDIT_FAILED (${e.errors.length} error${e.errors.length===1?"":"s"})`,""];if(e.path&&n.push(`Path: ${e.path}`),e.editRange){let s=e.editRange.end.anchor==="?"?e.editRange.start.anchor:e.editRange.end.anchor;n.push(`Requested range: ${e.editRange.start.anchor} .. ${s}`)}if(e.failurePoint&&n.push(`Failure point: ${e.failurePoint}`),e.expectedAnchor&&n.push(`Expected anchor: ${e.expectedAnchor}`),e.currentAnchor&&n.push(`Current anchor: ${e.currentAnchor}`),(e.internalErrorType||e.internalErrorMessage)&&(n.push(`Internal error type: ${e.internalErrorType??"unknown"}`),n.push(`Internal error message: ${e.internalErrorMessage??"unknown"}`),n.push("Operator hint: this is a tool bug, not an agent edit mistake."),n.push("")),e.recovery){n.push("Recovery:");for(let s of e.recovery.split(`
17
+ `))n.push(` ${s}`);n.push("")}if(e.freshAnchors&&e.freshAnchors.length>0){n.push("Fresh nearby anchors:");for(let s of e.freshAnchors)n.push(` ${s}`)}for(let s of e.diffs){let a=/^--- (.+)$/m.exec(s)?.[1]??e.path??"<unknown file>";n.push(..._t(e,a))}if(e.files.length>0){let s=e.createdFiles,a=e.overwrittenFiles;if(s.length>0){n.push(""),n.push("Created:");for(let l of s){let c=l.size===void 0?"":` (${l.size} bytes)`;n.push(` ${l.path}${c}`)}}if(a.length>0){n.push(""),n.push("Edited:");for(let l of a)n.push(` ${l.path}`)}}let r=e.warnings.filter(s=>s.severity==="syntax"),o=e.warnings.filter(s=>s.severity==="diagnostic");if(r.length>0){n.push(""),n.push("Syntax diagnostics:");for(let s of r)for(let a of s.messages)n.push(` ${a}`)}if(r.length===0&&o.length>0){n.push(""),n.push("Diagnostics:");for(let s of o)for(let a of s.messages)n.push(` ${a}`)}if(e.proposedDiff&&n.push("","Proposed diff was not applied:",e.proposedDiff),e.editIndex!==void 0&&n.push("",`Edit index: ${e.editIndex}`),e.editIndices!==void 0&&e.editIndices.length>0&&n.push("",`Edit indices: ${e.editIndices.join(", ")}`),e.staleDiagnostic){let s=e.staleDiagnostic;if(n.push("",`target: ${e.path??"?"}`),n.push(`line: ${s.lineNumber}`,""),n.push("expected:"),n.push(` ${s.expected.lineNumber}#${s.expected.hash} (original text unavailable)`),n.push("","current:"),n.push(` ${s.current.lineNumber}#${s.current.hash} ${s.current.text}`),n.push("",`anchor_hash_changed: ${s.anchorHashChanged}`),s.currentContext.length>0){n.push("","current_context:");for(let a of s.currentContext){let l=a.lineNumber===s.lineNumber?">>":" ";n.push(` ${l} ${a.lineNumber}#${a.hash} ${a.text}`)}}}let i=e.errors.some(s=>s.code==="MUTATION_REJECTED");e.fileChangedStatement!==void 0?n.push("",e.fileChangedStatement):i||n.push("","No file was changed.");for(let s of e.errors){n.push("");let a=s.code==="MUTATION_REJECTED";a||n.push(`Failed: ${s.code??"ERROR"}`),s.path&&s.path!==e.path&&n.push(`${a?"":" "}Path: ${s.path}`),s.reason&&n.push(`${a?"":" "}Reason: ${s.reason}`)}return e.hints.length>0&&(n.push(""),n.push("---"),n.push("LSP diagnostics detected. You MUST fix all LSP issues before the result is accepted.")),n.join(`
18
+ `)}formatStaleFailure(e){let n=["EDIT_FAILED",""];if(e.staleEdits.length>0){n.push(`All ${e.staleEdits.length} edits have stale anchors:`);for(let r of e.staleEdits)n.push(`edits[${r.index}]: STALE_ANCHOR (${r.failurePoint})`);n.push("")}if(e.freshAnchors&&e.freshAnchors.length>0){n.push("Current nearby anchors:");for(let r of e.freshAnchors)n.push(` ${r}`)}return n.join(`
19
+ `)}formatSuccess(e){let n=e.data.operations??[],r={replace:"Replaced selected text",insert:"Inserted new text",delete:"Deleted selected text",copy:"Copied selected text",move:"Moved selected text",write:"Wrote file content",undo:"Restored file content",stage:"Staged selected changes",unstage:"Unstaged selected changes"},o=[n.length===0?"Changes applied.":n.map(({operation:i,changes:s})=>`${r[i]??`Applied ${i}`}: ${s} text change(s) in this file.`).join(`
20
+ `),`Formatting: ${e.data.formatting?.status??"not-reported"}${e.data.formatting?.formatter===void 0?"":` (${e.data.formatting.formatter})`}.`];for(let i of e.diffs){let s=/^--- (.+)$/m.exec(i)?.[1]??e.path??"<unknown file>";o.push(Wt(e,s).join(`
21
+ `))}if(e.diffs.length===0)for(let i of e.files)o.push(i.path);return o.join(`
22
+
23
+ `)}};var Vt=new WeakMap;function ke(t){return Vt.get(t)}d(ke,"resolvedTextAnchorType");var $=class extends Error{constructor(n,r,o,i,s,a,l){super(n,o);this.resolverId=r;this.rejection=i;this.recovery=s;this.recoverAgain=a;this.originalRecoveryContext=l}static{d(this,"TextAnchorResolutionError")}async refreshRecovery(n){let r=n===void 0?this.originalRecoveryContext:n;this.recoverAgain!==void 0&&r!==void 0&&(this.recovery=await this.recoverAgain(r))}},Pe=class{static{d(this,"TextAnchorRegistry")}#e=[];add(e){if(typeof e.kind!="string"||e.kind.trim().length===0)throw new TypeError("Text anchor resolver kind must be a non-empty string");let n=e.resolver.id;if(this.#e.some(({resolver:r})=>r.id===n))throw new Error(`Text anchor resolver ${n} is already registered`);if(e.type==="major"&&this.#e.some(({type:r})=>r==="major"))throw new Error("A major text anchor resolver is already registered");this.#e.push({resolver:e.resolver,...e.resources!==void 0&&{resources:e.resources},kind:e.kind,type:e.type,priority:e.priority??0,order:this.#e.length,describeInPrompt:e.describeInPrompt??!0})}assertCanAdd(e){let n=new Set(this.#e.map(({resolver:o})=>o.id)),r=this.#e.some(({type:o})=>o==="major");for(let o of e){if(typeof o.kind!="string"||o.kind.trim().length===0)throw new TypeError("Text anchor resolver kind must be a non-empty string");if(n.has(o.resolver.id))throw new Error(`Text anchor resolver ${o.resolver.id} is already registered`);if(n.add(o.resolver.id),o.type==="major"){if(r)throw new Error("A major text anchor resolver is already registered");r=!0}}}snapshot(){return new et([...this.#e].sort((e,n)=>e.priority-n.priority||e.order-n.order))}renderPromptSection(e){let n=this.#e.filter(({describeInPrompt:r,kind:o})=>r&&(e===void 0||e.has(o))).map(({resolver:r})=>er(r)).filter(r=>r!==void 0);return n.length===0?void 0:["Text editor anchors:",...n,"Pass structured anchors exactly as shown."].join(`
24
+ `)}},et=class{constructor(e){this.resolvers=e}static{d(this,"TextAnchorRegistrySnapshot")}async inspect(e,n,r){for(let o=0;o<e.length;o+=1)try{await this.resolve(E(e[o]),r,new Set(n[o]))}catch(i){return i instanceof $?i.rejection===void 0?{kind:"invalid",anchorIndex:o,reason:i.message}:{kind:"invalid",anchorIndex:o,reason:i.rejection.reason,rejectionCode:i.rejection.code,...i.rejection.contextRange!==void 0&&{contextRange:i.rejection.contextRange}}:{kind:"failed",reason:"Text anchor resolution failed",cause:i}}return{kind:"valid"}}async resolveResources(e,n,r){for(let{kind:o,resolver:i,resources:s}of this.resolvers){if(s===void 0||r!==void 0&&!r.has(o))continue;let a;try{a=await s.tryResolve(e,n)}catch(l){throw new $(`Text anchor resource resolver ${i.id} failed for "${e}"`,i.id,{cause:l})}if(!yt(a))throw new $(`Text anchor resource resolver ${i.id} returned an invalid result for "${e}"`,i.id,{cause:a});if(a.kind!=="not-handled"){if(a.kind==="failed")throw new $(`Text anchor resource resolver ${i.id} failed for "${e}"`,i.id,{cause:a.error});if(a.kind==="rejected")throw new $(a.rejection.reason,i.id,void 0,a.rejection);return a.targets}}}async resolve(e,n,r){if(n.lines.length===0)throw new $(`Anchor "${e}" cannot resolve in an empty file`);for(let{kind:o,resolver:i,type:s}of this.resolvers){if(r!==void 0&&!r.has(o))continue;let a,l;try{if(l=i.normalize?.(e)??e,typeof l!="string"||l.length===0)throw new TypeError("Text anchor normalization must return non-empty text");a=await i.tryResolve(l,n)}catch(c){throw new $(`Text anchor resolver ${i.id} failed for "${e}"`,i.id,{cause:c})}if(!ut(a))throw new $(`Text anchor resolver ${i.id} returned an invalid result for "${e}"`,i.id,{cause:a});if(a.kind!=="not-handled"){if(a.kind==="failed")throw new $(`Text anchor resolver ${i.id} failed for "${e}"`,i.id,{cause:a.error});if(a.kind==="rejected"){let c=i.recover===void 0?void 0:p=>tr(i,l,a.rejection,p);throw new $(a.rejection.reason,i.id,void 0,a.rejection,void 0,c,n)}if(a.anchor.value!==l||a.anchor.lineNumber>n.lines.length)throw new $(`Text anchor resolver ${i.id} resolved "${e}" outside the current text`,i.id,{cause:a});if(N.is(a.anchor)&&!Zn(a.anchor,n))throw new $(`Text anchor resolver ${i.id} resolved "${e}" outside the current text`,i.id,{cause:a});return ct(a.anchor,i,i.id),Vt.set(a.anchor,s),a.anchor}}throw new $(`No text anchor resolver handled "${e}"`)}};function Zn(t,e){return t.source!==e.source?!1:t.ranges.every(n=>{let r=e.lines[n.start.lineNumber-1],o=e.lines[n.end.lineNumber-1],i=o===void 0&&n.end.lineNumber===e.lines.length+1&&n.end.column===0&&/(?:\r\n|\r|\n)$/u.test(e.content);return r!==void 0&&(o!==void 0||i)&&n.start.column<=r.length&&(i||n.end.column<=(o?.length??-1))})}d(Zn,"isSelectionWithinContext");function er(t){let e=typeof t.description=="string"?t.description:t.description();if(e!==void 0){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Text anchor resolver ${t.id} description must be non-empty text`);return`- ${e.trim().replaceAll(`
25
+ `," ")}`}}d(er,"renderResolverDescription");async function tr(t,e,n,r){if(t.recover===void 0)return{kind:"unavailable"};try{let o=await t.recover(e,{...r,rejection:n});return pt(o)&&nr(o,r)?o:{kind:"failed",error:new Error(`Text anchor resolver ${t.id} returned invalid recovery`)}}catch(o){return{kind:"failed",error:o}}}d(tr,"runAnchorRecovery");function nr(t,e){return t.kind!=="candidates"||t.total<t.candidates.length?t.kind!=="candidates":t.candidates.every(({rank:n,range:r},o)=>{let i=e.lines[r.start.lineNumber-1],s=e.lines[r.end.lineNumber-1];return n===o+1&&i!==void 0&&s!==void 0&&r.start.column<=i.length&&r.end.column<=s.length&&(r.start.lineNumber<r.end.lineNumber||r.start.column<=r.end.column)})}d(nr,"recoveryFitsContext");import{ChangeSet as rr,Text as Gt}from"@codemirror/state";var se=class{constructor(e){this.content=e;this.#e=ir(e),this.#n=e.includes(`\r
26
+ `)?`\r
27
+ `:`
28
+ `}static{d(this,"TextChangeDocument")}#e;#n;get length(){return this.content.length}lineRange(e,n){let r=Math.min(e,n),o=Math.max(e,n);return this.#t(r),this.#t(o),{from:E(this.#e[r-1]),to:this.#e[o]??this.content.length}}range(e,n,r,o){let i=this.#o(e,n),s=this.#o(r,o);if(s<i)throw new RangeError(`Text range ${i}-${s} is reversed.`);return{from:i,to:s}}text(e){return this.#s(e),this.content.slice(e.from,e.to)}replaceLines(e,n,r){let o=this.lineRange(e,n);return{...o,insert:this.#i(o,r)}}deleteLines(e,n){let r=this.lineRange(e,n);return r.to===this.content.length&&r.from>0&&!he(this.content)?{from:lr(this.content,r.from),to:r.to,insert:""}:{...r,insert:""}}insertBeforeLine(e,n){this.#t(e);let r=E(this.#e[e-1]);return{from:r,to:r,insert:this.#r(n)}}insertAfterLine(e,n){this.#t(e);let r=this.#e[e];if(r!==void 0)return{from:r,to:r,insert:this.#r(n)};let o=this.content.length>0&&!he(this.content)?this.#n:"";return{from:this.content.length,to:this.content.length,insert:o+ar(n)}}replaceAll(e){return{from:0,to:this.content.length,insert:e}}#i(e,n){let r=this.text(e);return he(r)&&!he(n)?n+E(sr(r)):n}#r(e){return he(e)?e:e+this.#n}#o(e,n){if(this.#t(e),!Number.isInteger(n)||n<0)throw new RangeError(`Column ${n} is outside line ${e}.`);let r=E(this.#e[e-1]),o=this.#e[e],i=o??this.content.length;if(o!==void 0&&(i-=1,this.content[i-1]==="\r"&&(i-=1)),r+n>i)throw new RangeError(`Column ${n} is outside line ${e}.`);return r+n}#t(e){if(!Number.isInteger(e)||e<1||e>this.#e.length)throw new RangeError(`Line ${e} is outside the document.`)}#s(e){if(e.from<0||e.to<e.from||e.to>this.content.length)throw new RangeError(`Text range ${e.from}-${e.to} is outside the document.`)}};function Y(t,e){let n=e.map((s,a)=>({change:s,index:a})).sort((s,a)=>s.change.from-a.change.from||s.index-a.index).map(({change:s})=>s);if(or(t.length,n),n.some(s=>t.slice(s.from,s.to)===s.insert))throw new Error("Text changes must change the document.");let r=Gt.of([t]),o=rr.of(n.map(s=>({...s,insert:Gt.of([s.insert])})),r.length),i=[];return o.iterChanges((s,a,l,c,p)=>{i.push({fromBefore:s,toBefore:a,fromAfter:l,toAfter:c,removedText:t.slice(s,a),insertedText:p.toString()})}),{content:o.apply(r).toString(),changes:i}}d(Y,"applyTextChanges");function or(t,e){let n;for(let r of e){if(!Number.isInteger(r.from)||!Number.isInteger(r.to)||r.from<0||r.to<r.from||r.to>t)throw new RangeError(`Text change ${r.from}-${r.to} is outside the document.`);if(n!==void 0&&(r.from<n.from||r.from<n.to))throw new Error("Text changes must be ordered and must not overlap.");n=r}}d(or,"validateChanges");function ir(t){let e=[0],n=/\r\n|\n/gu,r;for(;(r=n.exec(t))!==null;)e.push(r.index+r[0].length);return e}d(ir,"findLineStarts");function he(t){return t.endsWith(`
29
+ `)}d(he,"endsWithLineBreak");function sr(t){return t.endsWith(`\r
30
+ `)?`\r
31
+ `:t.endsWith(`
32
+ `)?`
33
+ `:void 0}d(sr,"lineBreakOf");function ar(t){return t.replace(/(?:\r\n|\n)$/u,"")}d(ar,"removeTrailingLineBreak");function lr(t,e){return t[e-2]==="\r"&&t[e-1]===`
34
+ `?e-2:e-1}d(lr,"previousLineBreakStart");var Ie=class{static{d(this,"BatchExecutionJournal")}entries;constructor(e){this.entries=new Map(e.map(n=>[n,{callId:n,state:"pending",recovered:!1}]))}reporter(e=!1){return{start:d(n=>{this.transition(n,{state:"running",recovered:e})},"start"),complete:d((n,r)=>{this.transition(n,{state:"completed",result:r,recovered:e})},"complete"),fail:d((n,r)=>{this.transition(n,{state:`failed-${r.effect}`,failure:r,...r.result!==void 0&&{result:r.result},recovered:e})},"fail")}}block(e,n,r){this.transition(e,{state:"blocked",result:n,blockedDetails:r,recovered:!1})}skip(e,n){this.transition(e,{state:"failed-not-applied",failure:{error:new Error(n),effect:"not-applied"},recovered:!1,reason:n})}markRunningUnknown(e){for(let n of this.entries.values())n.state==="running"&&this.transition(n.callId,{state:"failed-unknown",failure:{error:e,effect:"unknown"},recovered:n.recovered})}get(e){let n=this.entries.get(e);if(!n)throw new Error(`Unknown batch call ${e}.`);return n}snapshot(){return[...this.entries.values()].map(e=>({...e}))}transition(e,n){if(!this.entries.has(e))throw new Error(`Unknown batch call ${e}.`);this.entries.set(e,{callId:e,...n})}};function q(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}d(q,"isObjectNotArray");var me=new Map,qt=new WeakMap,$e=new Map;function Yt(t){$e.set(t.callId,t);let e=me.get(t.callId);e?.blockedCalls.every(n=>n.callId!==t.callId)&&(e.blockedCalls.push(t),e.journal.block(t.callId,t.result,t.details))}d(Yt,"registerBlockedToolCall");function dr(){me.clear(),$e.clear()}d(dr,"clearCoordinatorCalls");function zt(t){if(!(!q(t)||t.type!=="toolCall"||typeof t.id!="string"||typeof t.name!="string")&&q(t.arguments))return{id:t.id,name:t.name,arguments:t.arguments}}d(zt,"asRawToolCall");function Xt(t,e){return t.definitions.find(n=>n.sourceTools.includes(e))}d(Xt,"definitionFor");function Kt(t,e){e.renderArgumentPatch!==void 0&&t.onRenderArguments?.(e.call.id,e.renderArgumentPatch)}d(Kt,"publishRenderArguments");function Jt(t,e,n){if(!q(e)||e.role!=="assistant"||!Array.isArray(e.content))return;let r=e.content,o,i;for(let s=0;s<r.length;){let a=zt(r[s]),l=a?Xt(t,a.name):void 0,c=a&&l?l.resolveCall(a,o===l?i:void 0):void 0;if(!l||!c){o=void 0,i=void 0,s+=1;continue}Kt(l,c);let p=[c],m=s+1;for(;m<r.length;){let f=zt(r[m]);if(!f||Xt(t,f.name)!==l)break;let x=l.resolveCall(f,E(p.at(-1)).state);if(!x)break;Kt(l,x),p.push(x),m+=1}let g=E(p.at(-1));if(n&&p.length>=2){let f=p.map(({call:h})=>h),x=new Ie(f.map(h=>h.id)),S=f.flatMap(h=>{let v=$e.get(h.id);return v===void 0?[]:[v]}),P={definition:l,candidates:p,calls:f,carrierId:g.call.id,batchId:`${String(Date.now())}-${String(t.nextBatchId++)}`,remainingCallIds:new Set(f.map(h=>h.id)),journal:x,blockedCalls:S};for(let h of S)x.block(h.callId,h.result,h.details);for(let h of f)me.set(h.id,P)}o=l,i=g.state,s=m}}d(Jt,"rewriteMessage");function cr(t,e){let n=e.payload;if(!q(n)||!Array.isArray(n.tools))return;let r=new Set(t.definitions.map(o=>o.syntheticTool));return{...n,tools:n.tools.filter(o=>{if(!q(o))return!0;let i=typeof o.name=="string"?o.name:void 0,s=q(o.function)&&typeof o.function.name=="string"?o.function.name:void 0;return i===void 0&&s===void 0?!0:(i===void 0||!r.has(i))&&(s===void 0||!r.has(s))})}}d(cr,"filterProviderTools");function ur(t,e,n){let r=q(t.details)?t.details:{};return{...t,details:{...r,agenticIdeBatch:{batchId:e,calls:n}}}}d(ur,"markBatchResult");function pr(t){return t.calls.map(e=>({id:e.id,name:e.name}))}d(pr,"batchDisplayCalls");function fr(t,e,n,r){return t.execution??=(async()=>{let o,i;try{let a=t.candidates.filter(({call:p})=>t.journal.get(p.id).state!=="blocked"),l=t.definition.buildArguments(a);o=await t.definition.execute(t.carrierId,l,e,n,r,t.journal.reporter());let c=t.definition.splitResult?.(o,t.calls,t.candidates);for(let[p,m]of c??[])t.journal.get(p).state==="completed"&&t.journal.reporter().complete(p,m)}catch(a){i=a,t.journal.markRunningUnknown(a)}await gr(t,e,r);let s=hr(t,i);return o===void 0?{perCallResults:s}:{aggregate:o,perCallResults:s}})(),t.execution}d(fr,"ensureBatchExecution");async function gr(t,e,n){let r=t.definition.recovery;if(!r)return;let o={batchId:t.batchId,calls:t.calls,candidates:t.candidates,journal:t.journal.snapshot(),blockedCalls:t.blockedCalls,cwd:n.cwd,signal:e,ctx:n},i=new Set(r.select(o)),s=t.candidates.filter(({call:a})=>{let l=t.journal.get(a.id).state;return i.has(a.id)&&(l==="pending"||l==="failed-not-applied")});if(s.length!==0)try{let a=await r.execute({...o,selected:s,reporter:t.journal.reporter(!0)});for(let[l,c]of a.results)s.some(({call:p})=>p.id===l)?t.journal.reporter(!0).complete(l,c):t.journal.get(l).state==="completed"&&t.journal.reporter().complete(l,c);for(let[l,c]of a.skipped??[])t.journal.skip(l,c)}catch(a){for(let{call:l}of s){let c=t.journal.get(l.id).state;(c==="pending"||c==="running"||c==="failed-not-applied")&&t.journal.reporter(!0).fail(l.id,{error:a,effect:c==="running"?"unknown":"not-applied"})}}}d(gr,"recoverBatch");function hr(t,e){return new Map(t.calls.map(n=>{let r=t.journal.get(n.id);if(r.result){let s=q(r.result.details)?r.result.details:{};return[n.id,{...r.result,details:{...s,batchRecovery:{batchId:t.batchId,state:r.state,recovered:r.recovered,...r.reason!==void 0&&{reason:r.reason}}}}]}let o=r.failure?.error??e??r.reason,i=o instanceof Error?o.message:typeof o=="string"?o:"call did not execute";return[n.id,{content:[{type:"text",text:`${n.name} failed: ${i}`}],details:{batchRecovery:{batchId:t.batchId,state:r.state,recovered:r.recovered,...r.reason!==void 0&&{reason:r.reason}}},isError:!0}]}))}d(hr,"finalBatchResults");function mr(t,e){if(t.remainingCallIds.delete(e),!(t.remainingCallIds.size>0))for(let n of t.calls)me.delete(n.id),$e.delete(n.id)}d(mr,"releaseBatchCall");async function Qt(t,e,n,r,o){let i=me.get(t);if(!i)return e();try{if(i.definition.splitResult===void 0&&i.carrierId!==t)return{content:[{type:"text",text:""}],details:{agenticIdeBatchSuppressed:!0}};let s=await fr(i,n,r,o);if(i.definition.splitResult!==void 0){let a=s.perCallResults?.get(t);if(!a)throw new Error(`Missing split batch result for tool call ${t}.`);return ur(a,i.batchId,pr(i))}return s.aggregate?s.aggregate:await e()}finally{mr(i,t)}}d(Qt,"executeWithBatchCoordinator");function xr(t){let e=qt.get(t);if(!e){let n={definitions:[],registered:!1,nextBatchId:1};qt.set(t,n),e=n}return e.registered||(e.registered=!0,t.on("message_update",n=>{Jt(e,n.message,!1)}),t.on("message_end",n=>{Jt(e,n.message,!0)}),t.on("before_provider_request",n=>cr(e,n)),t.on("agent_end",()=>{dr()})),e}d(xr,"coordinatorFor");function Zt(t,e){let n=xr(t),r={sourceTools:e.sourceTools,syntheticTool:e.syntheticTool,resolveCall:d((o,i)=>e.resolveCall(o,i),"resolveCall"),buildArguments:d(o=>e.buildArguments(o),"buildArguments"),execute:e.execute,...e.onRenderArguments!==void 0&&{onRenderArguments:e.onRenderArguments},...e.recovery!==void 0&&{recovery:e.recovery},...e.splitResult!==void 0&&{splitResult:d((o,i,s)=>E(e.splitResult)(o,i,s),"splitResult")}};n.definitions.push(r)}d(Zt,"registerToolBatch");function Tr(t){return t.data.inputPath??t.data.path??t.files[0]?.path??t.errors[0]?.path}d(Tr,"resultPath");function nn(t,e){let n=t.details,r=en(e,n?.results??[],n?.callIdsByResult??[]),o=en(e,n?.displayResults??n?.results??[],n?.callIdsByDisplayResult??n?.callIdsByResult??[]);return new Map(e.map(i=>{let s=tn(r.get(i.id)??[]),a=tn(o.get(i.id)??[]);return[i.id,{content:s.length===0?[{type:"text",text:"Batch edit applied; the final file result is in the last successful tool call for that file."}]:[new V(s).toTextContent()],details:{results:a}}]}))}d(nn,"splitTextBatchResult");function en(t,e,n){let r=new Map(t.map(o=>[o.id,[]]));for(let[o,i]of e.entries()){let s=n[o];s!==void 0&&r.get(s)?.push(i)}return r}d(en,"groupResultsByCall");function tn(t){let e=new Map,n=[];for(let o of t){let i=Tr(o);if(i===void 0||!o.ok){n.push(o);continue}let s=e.get(i)??[];s.push(o),e.set(i,s)}return[...[...e].map(([o,i])=>yr(o,i)),...n]}d(tn,"coalesceResults");function yr(t,e){let n=E(e[0]),r=E(e.at(-1)),o=n.beforeContentMap?.[t],i=r.data.afterContent;if(e.length===1||typeof o!="string"||typeof i!="string")return r;let s=be(t,o,i),a=n.files.find(c=>c.path===t),l=r.files.find(c=>c.path===t);return new re({...r.data,diffs:[s.diff],files:[a??l??{path:t,action:"edited"}],editCount:e.reduce((c,p)=>c+(p.editCount??0),0),addedLines:s.stats.added,removedLines:s.stats.removed,beforeContentMap:{...r.beforeContentMap,[t]:o},afterContent:i,afterDocument:r.data.afterDocument,warnings:e.flatMap(c=>c.warnings),hints:e.flatMap(c=>c.hints)})}d(yr,"mergePathResults");var z=class extends Error{constructor(n,r,o,i,s){super(s.message,{cause:s});this.toolName=n;this.field=r;this.source=o;this.anchor=i;this.resolution=s}static{d(this,"TextMutationAnchorResolutionError")}},Q=class extends AggregateError{constructor(n){super(n,`${n.length} text anchors could not resolve`);this.failures=n}static{d(this,"TextMutationAnchorAggregateError")}};function xe(t,e,n,r,o){return t instanceof $?new z(e,n,r,o,t):t}d(xe,"contextualizeTextMutationAnchorError");import Rr from"node:path";import{defineTool as wr}from"@earendil-works/pi-coding-agent";function on(t,e,n,r,o){let i=t.getToolRenderer(e.name),s=Ve(wr({name:e.name,label:e.name,promptSnippet:e.promptSnippet,promptGuidelines:e.promptGuidelines===void 0?void 0:[...e.promptGuidelines],description:e.description,parameters:e.parameters,prepareArguments:d(a=>vr(e.parameters,a,e.source.inherited?e.source.field:void 0,o(),e.anchors??[]),"prepareArguments"),...i?.renderShell!==void 0&&{renderShell:i.renderShell},...i?.renderCall!==void 0&&{renderCall:i.renderCall},...i?.renderResult!==void 0&&{renderResult:i.renderResult},async execute(a,l,c,p,m){return pn(a,d(()=>Mr(t,e,l,c,m,(f,x)=>n.resolveArguments(a,{[fe]:{[f]:x}}),o()),"directExecute"),c,p,m)}}),n);return Object.defineProperty(s,"description",{enumerable:!0,get(){return[e.description,e.source.inherited?`When ${e.source.field} is omitted, the tool can reuse the file identified by the supplied anchor, the last read, or the preceding edit in the same batch.`:"",r()??""].filter(Boolean).join(`
35
+ `)}}),s}d(on,"createTextTool");function vr(t,e,n,r,o){let i=e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},s=t.required,a=t.properties,l=o.some(c=>oe(c,i[c.field]));if(n!==void 0&&!(n in i)&&r!==void 0&&!l&&(i[n]=r),Array.isArray(s))for(let c of s)typeof c=="string"&&!(c in i)&&a?.[c]?.type==="string"&&(i[c]="");return i}d(vr,"prepareGuardedArguments");async function sn(t,e,n,r,o){let i=new Map,s=new Map,a=new Set,l=new Map,c=new Set,p=[...new Set((e.anchors??[]).flatMap(h=>h.kinds))],m=d(async(h,v,w)=>{try{return await t.resolveTextAnchorResources(h,p,r)}catch(u){throw xe(u,e.name,v,w,h)}},"resolveTargets");for(let h of e.anchors??[]){let v=n[h.field];if(!oe(h,v))continue;let w=await m(v,h.field,typeof n[h.sourceField]=="string"?String(n[h.sourceField]):"");if(w===void 0)continue;i.set(h.field,w);let u=s.get(h.sourceField);if(u!==void 0&&!Er(u,w))throw new Error(`Incompatible targets for ${h.sourceField}.`);s.set(h.sourceField,tt(s.get(h.sourceField)??[],w))}for(let h of[e.source,...e.source.targets??[]]){let v=n[h.field];if(typeof v!="string"||v.length===0)continue;let w=await m(v,h.field,v);w!==void 0&&(a.add(h.field),l.set(h.field,w),s.set(h.field,tt(s.get(h.field)??[],w)))}let g=new Map,f=[e.source,...e.source.targets??[]];for(let h of f){let v=n[h.field],w=typeof v=="string"&&v.length>0?v:void 0,u="fallbackTo"in h?g.get(h.fallbackTo):void 0,R=s.get(h.field);if(R!==void 0){if(w!==void 0&&!a.has(h.field)){let T=R.filter(A=>dn(w,A.source,r.cwd));if(T.length===0)throw new Error(`Anchor does not belong to ${w}.`);T.length!==R.length&&(R=T,s.set(h.field,T),c.add(h.field))}g.set(h.field,E(R[0]).source);continue}let b=h.field===e.source.field&&e.source.inherited===!0&&!(h.field in n)?o:void 0,y=w??u??b;if(y===void 0)throw new Error(`${h.field} is required`);g.set(h.field,y)}let x=new Map,S=new Map;for(let h of e.anchors??[]){let v=l.get(h.sourceField),w=e.anchors?.find(b=>b.sourceField===h.sourceField),u=oe(h,n[h.field]),R=a.has(h.sourceField);!u&&!R||v!==void 0&&R&&h.field===w?.field&&S.set(h.field,v)}for(let h of e.anchors??[]){let v=i.get(h.field),w=n[h.field];if(typeof w=="string"&&!oe(h,w))continue;let u=g.get(h.sourceField);if(v!==void 0)x.set(h.field,u!==void 0&&(v.length===1||c.has(h.sourceField))?[u]:[...new Set(v.map(R=>R.source))]);else if(u!==void 0){let R=s.get(h.sourceField),b=n[h.field];x.set(h.field,R!==void 0&&typeof b=="string"&&b.length>0?[...new Set(R.map(y=>y.source))]:[u])}}let P=[...s.values()].flat().reduce((h,v)=>tt(h,[v]),[]);return{fields:g,anchors:x,implicitTargets:S,targets:P,resources:[...new Set([...g.values(),...P.map(h=>h.source)])]}}d(sn,"resolveMutationSources");function Er(t,e){let n=new Set(t.map(o=>o.source)),r=new Set(e.map(o=>o.source));return n.size===r.size&&[...n].every(o=>r.has(o))}d(Er,"sameTargetSources");function tt(t,e){let n=new Map;for(let r of[...t,...e]){let o=n.get(r.source);if(o===void 0){n.set(r.source,r);continue}let i=[...o.ranges??[],...r.ranges??[]];n.set(r.source,{source:r.source,...i.length>0&&{ranges:an(i)}})}return[...n.values()]}d(tt,"mergeTargets");function an(t){let e=new Map;for(let n of t){let r=JSON.stringify({start:n.start,end:n.end}),o=e.get(r);e.set(r,{...n,...o?.linewise===!0||n.linewise===!0?{linewise:!0}:{}})}return[...e.values()]}d(an,"deduplicateRanges");function Ar(t,e){let n=t.split(/\r\n|\r|\n/u),r=n[e-1];if(r===void 0)throw new Error(`Position anchor line ${e} is outside the source.`);let o=e<n.length;return{start:{lineNumber:e,column:0},end:o?{lineNumber:e+1,column:0}:{lineNumber:e,column:r.length},linewise:!0}}d(Ar,"naturalLineSelection");function br(t,e,n,r){let o=new Set([...n.keys(),...r.keys()]);return new Map([...o].map(i=>{let s=n.get(i),a=r.get(i);if(s===void 0)return[i,E(a)];if(a===void 0)return[i,s];let c=[...(N.is(s)?s:new N(e,i,[Ar(t(i).content,s.lineNumber)])).ranges,...a.ranges].sort((m,g)=>m.start.lineNumber-g.start.lineNumber||m.start.column-g.start.column),p=an(c);for(let m=1;m<p.length;m++){let g=E(p[m-1]),f=E(p[m]);if(f.start.lineNumber<g.end.lineNumber||f.start.lineNumber===g.end.lineNumber&&f.start.column<g.end.column)throw new Error(`Anchor ${e} selections overlap or are ambiguous.`)}return[i,new N(e,i,p)]}))}d(br,"mergeResolvedAnchors");function ln(t,e,n,r,o,i,s){let a=new Map([...o].map(([f,x])=>[f,new se(x)])),l=new Map,c=new Set,p=d(f=>{let x=r.fields.get(f);if(x===void 0)throw new Error(`Unknown mutation source field ${f}`);return x},"sourceFor"),m=d(f=>{let x=a.get(f);if(x===void 0)throw new Error(`Unknown mutation resource ${f}`);return x},"documentFor"),g=d(f=>{let x=l.get(f);if(x!==void 0)return x;let S=(async()=>{let P=(t.anchors??[]).find(R=>R.field===f),h=e[f],v=r.anchors.get(f),w=r.implicitTargets.get(f);if(P===void 0)throw new Error(`Mutation tool ${t.name} tried to resolve undeclared anchor ${f}`);let u=typeof h=="string"&&v!==void 0?new Map(await Promise.all(v.map(async R=>{try{let b=await i(R,h,P.kinds);ke(b)==="major"&&c.add(R);let y=we(b,h,{source:R,anchor:b});return s?.(f,{kind:"resolved",full:y.full,compact:y.compact,resolverId:y.resolverId}),[R,b]}catch(b){throw s?.(f,{kind:"failed"}),xe(b,t.name,f,R,h)}}))):void 0;if(w!==void 0){let R=new Map(w.map(b=>[b.source,new N(f,b.source,b.ranges??[])]));return u===void 0?R:br(m,f,u,R)}if(u===void 0)throw new Error(`Mutation tool ${t.name} tried to resolve undeclared anchor ${f}`);return u})();return l.set(f,S),S},"resolveAnchors");return{cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal},sourceDocument:m(p(t.source.field)),sourceFor:p,documentFor:m,targetDocument(f){if((t.source.targets??[]).every(x=>x.field!==f))throw new Error(`Mutation tool ${t.name} tried to access undeclared target ${f}`);return m(p(f))},resolveAnchors:g,async resolveAnchor(f){let x=await g(f);if(x.size!==1)throw new Error(`Anchor ${f} selects multiple resources; use an operation that supports a search set.`);return E(x.values().next().value)},resultPresentationFor(f){return[...c].some(x=>dn(x,f,n.cwd))?"major-anchor":"plain"}}}d(ln,"createMutationContext");function Cr(t,e){return{...t,resultPresentations:new Map([...t.edits.keys()].map(n=>[n,e.resultPresentationFor(n)]))}}d(Cr,"withResultPresentations");var Sr=new Set(["replace","delete","insert","copy","move"]);async function Le(t,e,n){if(!Sr.has(t.name))return;let r=[];if(await Promise.all((t.anchors??[]).map(async o=>{if(oe(o,e[o.field]))try{await n.resolveAnchors(o.field)}catch(i){if(i instanceof z){r.push(i);return}throw i}})),r.length>0)throw new Q(r)}d(Le,"preflightMutationAnchors");function dn(t,e,n){return rn(t,n)===rn(e,n)}d(dn,"sameResource");function rn(t,e){if(/^[a-z][a-z\d+.-]*:\/\//iu.test(t))return t;let n=t.startsWith("@")?t.slice(1):t;return Rr.resolve(e,n)}d(rn,"resourceIdentity");async function cn(t,e){let n=t.getMutationTools().find(r=>r.name===e.tool);if(n===void 0)return{kind:"failed",reason:`Unknown mutation tool ${e.tool}`};try{let r=await sn(t,n,e.input,e);return await t.previewTexts(r.resources.map(o=>({source:o,read:!0,...n.name==="write"&&{allowReadFailure:!0}})),{cwd:e.cwd,...e.signal!==void 0&&{signal:e.signal}},async(o,i)=>{let s=ln(n,e.input,e,r,o,i);await Le(n,e.input,s);let a=await n.mutate(s,e.input);return{changes:new Map([...a.edits].map(([l,c])=>[l,c.changes])),result:a}})}catch(r){return{kind:"failed",reason:r instanceof Error?r.message:String(r)}}}d(cn,"previewTextMutation");async function Mr(t,e,n,r,o,i,s){let a=Se(e,n),l=await t.executeEdit(e.name,{cwd:o.cwd,input:n,...r!==void 0&&{signal:r}},async c=>{try{let p=await sn(t,e,c.input,c,s),m=await t.editTexts(p.resources.map(g=>({source:g,read:!0,...e.name==="write"&&{allowReadFailure:!0}})),{cwd:c.cwd,intent:e.intent??"edit",...c.signal!==void 0&&{signal:c.signal}},async(g,f)=>{let x=ln(e,c.input,c,p,g,f,i);await Le(e,c.input,x);let S=await e.mutate(x,c.input),P=Cr(S,x);return{changes:new Map([...S.edits].map(([h,v])=>[h,v.changes])),result:P}});return await Pr(m,Se(e,c.input))}catch(p){return Lr(Se(e,c.input),"INVALID_REQUEST",Dr(p),p)}});return kr(t,l,a,o,e.name)}d(Mr,"executeTextMutation");function un(t,e){let n=new Map,r=e[t.source.field];if(typeof r!="string"||r.length===0)throw new Error(`${t.source.field} is required`);n.set(t.source.field,r);for(let o of t.source.targets??[]){let i=e[o.field],s=n.get(o.fallbackTo),a=typeof i=="string"&&i.length>0?i:s;if(a===void 0)throw new Error(`${o.field} is required`);n.set(o.field,a)}return n}d(un,"mutationSources");function Oe(t,e,n,r=t.after.content,o="plain",i=1,s=[],a){let l=t.before.content,c=t.after.content,p=Y(l,n.changes),m=be(e,l,r),g=t.postEditContributions.map(x=>x.data).find(Ct),f=p.changes.map((x,S)=>({editIndex:S,fromA:x.fromBefore,toA:x.toBefore,fromB:x.fromAfter,toB:x.toAfter,removedText:x.removedText,insertedText:x.insertedText}));return new re({...g,...a===void 0?{}:{diffPeerRanges:a},operations:s,diffStatuses:t.postEditContributions.map(x=>x.data).filter(Et).flatMap(x=>x.diffStatuses),formatting:t.postEditContributions.map(x=>x.data).find(vt)?.formatting??{status:"not-reported"},ok:!0,path:e,diffs:[m.diff],files:[{path:e,action:n.action}],editCount:i,addedLines:m.stats.added,removedLines:m.stats.removed,beforeContentMap:{[e]:l},afterContent:c,rawChanges:f,afterDocument:t.after,resultPresentation:o})}d(Oe,"buildSuccessfulTextMutationResult");async function Pr(t,e){if(t.kind==="failed"||t.result.afterWrite===void 0)return t;try{return await t.result.afterWrite(),t}catch(n){return{kind:"failed",failure:{code:"POST_WRITE_FAILED",source:e,message:`Post-write action failed for ${e}`,cause:n},completed:t.resources.map(r=>r.source)}}}d(Pr,"completeTextMutation");async function kr(t,e,n,r,o){if(e.kind==="failed")return ae(n,e.failure.code,e.failure.message,"not-applied");let i=e.state.result;if(!Or(i))return ae(n,"INVALID_RESULT","Text editor returned an invalid edit result.","unknown");if(i.kind==="failed"){let l=await nt(t,i.failure,r);if(l!==void 0)return l;let c=i.completed.length===0?"":` Completed writes: ${i.completed.join(", ")}.`,p=i.completed.length===0?"not-applied":"applied",m=`${i.failure.message.replace(/[.!?]+$/u,"")}.${c}`;return ae(n,i.failure.code,m,p)}let s=i.result,a=i.resources.flatMap(l=>{let c=l.source,p=s.edits.get(c);return p===void 0?[]:[Oe(l,c,p,void 0,s.resultPresentations.get(c)??"plain",1,[{operation:o,changes:p.changes.length}])]});return{content:[new V(a).toTextContent()],details:{results:a}}}d(kr,"buildToolResult");async function nt(t,e,n){if(e.cause instanceof Q){let f=await Promise.all(e.cause.failures.map(h=>nt(t,{...e,source:h.source,cause:h},n))),x=[],S=[],P=[];for(let h of f)if(h!==void 0){x.push(...h.details.results??[]),S.push(...h.details.anchorRecoveries??[]);for(let v of h.content)v.type==="text"&&P.push(v.text)}return x.length===0?void 0:{content:[{type:"text",text:P.join(`
36
+
37
+ `)}],details:{results:x,anchorRecoveries:S}}}if(!(e.cause instanceof z))return;let r=e.cause,o=r.resolution;o.recovery===void 0&&await o.refreshRecovery();let i=o.recovery;if(i?.kind==="timed-out")return ae(r.source,e.code,`${e.message}; recovery timed out`,"not-applied");let s=i?.kind==="candidates"?$r(i.candidates.map(({range:f})=>f),t.recoveryContextLines()):o.rejection?.contextRange===void 0?[]:[o.rejection.contextRange];if(s.length===0)return;let a=await Promise.all(s.map(f=>Ot(t,{path:r.source,...f},{cwd:n.cwd,...n.signal!==void 0&&{signal:n.signal}}))),l=[];for(let f of a){if(f===void 0||f.isError===!0)return;l.push(...f.content.filter(x=>x.type==="text").map(x=>x.text))}let c=new re({ok:!1,path:r.source,errors:[{path:r.source,code:e.code,reason:e.message}]}),p=l.join(`
38
+ `),m=o.rejection?.code;return{content:[{type:"text",text:m==="stale"?Pt({guardId:"stale-anchor",effect:"not-applied",toolName:r.toolName,field:r.field,path:r.source,anchor:r.anchor,...p.length>0&&{context:p}},o.message):Ir(r,m,o.message,p)}],details:{results:[c],effect:"not-applied",anchorRecovery:!0,...i?.kind==="candidates"&&{anchorRecoveries:[{field:r.field,path:r.source,anchor:r.anchor,total:i.total,candidates:i.candidates}]}}}}d(nt,"anchorFailureToolResult");function Ir(t,e,n,r){let o=e==="ambiguous"?"is ambiguous":e==="missing"?"was not found":e==="invalid"?"is invalid":"could not be resolved",i=e==="ambiguous"?"Use a unique text span or one of the candidate anchors below.":"If the intended text is represented below, use its candidate anchor. Otherwise, reread the relevant section and choose a current anchor.",s=r.length===0?"":`
39
+
40
+ ${r}`;return`[SYSTEM] ${t.toolName} blocked: ${t.field} anchor "${t.anchor}" ${o}. ${i} (${n})${s}`}d(Ir,"formatRejectedAnchorMessage");function $r(t,e){let n=t.map(o=>({offset:Math.max(1,o.start.lineNumber-e),limit:o.end.lineNumber-o.start.lineNumber+1+e*2})).sort((o,i)=>o.offset-i.offset),r=[];for(let o of n){let i=r[r.length-1];if(i===void 0||o.offset>i.offset+i.limit){r.push(o);continue}let s=Math.max(i.offset+i.limit,o.offset+o.limit);r[r.length-1]={offset:i.offset,limit:s-i.offset}}return r}d($r,"recoveryWindows");async function rt(t,e,n,r="not-applied"){return r==="not-applied"?await nt(t,e,n)??ae(e.source,e.code,e.message,r):ae(e.source,e.code,e.message,r)}d(rt,"buildFailedTextMutationResult");function ae(t,e,n,r){let o=new re({ok:!1,path:t,errors:[{path:t,code:e,reason:n}]});return{content:[new V(o).toTextContent()],details:{results:[o],effect:r}}}d(ae,"failureToolResult");function Lr(t,e,n,r){return{kind:"failed",failure:{code:e,source:t,message:n,...r!==void 0&&{cause:r}},completed:[]}}d(Lr,"failedResourceEdit");function Or(t){return typeof t=="object"&&t!==null&&(t.kind==="completed"||t.kind==="failed")}d(Or,"isResourcesEditOutcome");function Dr(t){return t instanceof Error?t.message:String(t)}d(Dr,"errorMessage");var gn=new WeakMap;function hn(t,e){gn.set(t,e)}d(hn,"setTextEditBatchRenderArgumentSink");function mn(t,e){let n=[],r=new Map,o=d((s,a)=>gn.get(e)?.(s,a),"renderArguments"),i={sourceTools:n,syntheticTool:"__pi_agent_text_editor_batch",resolveCall(s,a){let l=r.get(s.name);if(l===void 0)return;let c=s.arguments[l.source.field],p=!(typeof c=="string"&&c.length>0)&&l.source.inherited?a?.source:void 0,m=typeof c=="string"&&c.length>0?c:p;return m===void 0?void 0:{call:s,state:{source:m,registration:l},...p!==void 0&&{renderArgumentPatch:{[l.source.field]:p}}}},buildArguments(s){return{edits:s.map(({call:l,state:c})=>({...l.arguments,[c.registration.source.field]:c.source,callId:l.id,op:c.registration.name,path:c.source}))}},execute:d((s,a,l,c,p,m)=>Fr(e,r,a,l,c,p,m,o),"execute"),splitResult:nn,onRenderArguments:o};e.onMutationTool(s=>{r.set(s.name,s),n.push(s.name)}),kt(t,Yt),Zt(t,i)}d(mn,"registerTextEditBatching");async function Fr(t,e,n,r,o,i,s,a){let l=n.edits.map(y=>{let T=e.get(y.op);if(T===void 0)throw new Error(`Unknown text mutation tool: ${y.op}.`);let{callId:A,op:C,...k}=y;return{callId:A,input:k,registration:T,sources:un(T,k)}}),c=new Set(l.map(({registration:y})=>y.intent??"edit")),p=c.size>1?"mixed":c.values().next().value??"edit",m=new Map;for(let y of l){for(let T of y.sources.values()){let A=m.get(T),C=y.registration.name==="write"&&T===y.sources.get(y.registration.source.field);m.set(T,{source:T,read:!0,...(A?.allowReadFailure===!0||C)&&{allowReadFailure:!0}})}s.start(y.callId)}let g;try{g=await t.editTexts([...m.values()],{cwd:i.cwd,intent:p,...r!==void 0&&{signal:r}},async(y,T)=>{let A=[],C=[],k=new Map;for(let M of l){let D=d(I=>{let F=M.sources.get(I);if(F===void 0)throw new Error(`Unknown mutation source field ${I}`);return F},"sourceFor"),G=d(I=>{let F=y.get(I);if(F===void 0)throw new Error(`Unknown mutation resource ${I}`);return new se(F)},"documentFor"),ye=new Set,ce=d((I,F)=>{a(M.callId,{[fe]:{[I]:F}})},"publishAnchorRenderPatch"),Re=d(async I=>{let F=(M.registration.anchors??[]).find(U=>U.field===I),B=M.input[I],H=F===void 0?void 0:M.sources.get(F.sourceField);if(F===void 0||typeof B!="string"||H===void 0)throw ce(I,{kind:"failed"}),new Error(`Unable to resolve mutation anchor ${I}`);try{let U=await T(H,B,F.kinds);ke(U)==="major"&&ye.add(H);let ue=we(U,B,{source:H,anchor:U});return ce(I,{kind:"resolved",full:ue.full,compact:ue.compact,resolverId:ue.resolverId}),new Map([[H,U]])}catch(U){throw ce(I,{kind:"failed"}),xe(U,M.registration.name,I,H,B)}},"resolveAnchors");try{let I={cwd:i.cwd,...r!==void 0&&{signal:r},sourceDocument:G(D(M.registration.source.field)),sourceFor:D,documentFor:G,targetDocument:d(B=>G(D(B)),"targetDocument"),resolveAnchors:Re,async resolveAnchor(B){let H=await Re(B);return E(H.values().next().value)}};await Le(M.registration,M.input,I);let F=await M.registration.mutate(I,M.input);for(let[B,H]of F.edits){let U=k.get(B)??[];if(H.changes.some(ue=>U.some(Un=>Nr(Un,ue))))throw new Error(`Text mutation ${M.callId} overlaps an earlier successful mutation.`)}A.push({callId:M.callId,mutation:{...F,operation:M.registration.name,resultPresentations:new Map([...F.edits.keys()].map(B=>[B,ye.has(B)?"major-anchor":"plain"]))}});for(let[B,H]of F.edits)k.set(B,[...k.get(B)??[],...H.changes])}catch(I){C.push({callId:M.callId,source:M.sources.get(M.registration.source.field)??"",error:I,effect:"not-applied"})}}return{changes:k,result:{mutations:A,failures:C}}})}catch(y){return fn(t,l.map(({callId:T})=>T),y,i,s)}if(g.kind==="failed")return fn(t,l.map(({callId:y})=>y),g.failure,i,s);let f=[],x=[...g.result.failures];for(let y of g.result.mutations)try{await y.mutation.afterWrite?.(),f.push(y)}catch(T){x.push({callId:y.callId,source:y.mutation.edits.keys().next().value??"",error:T,effect:"applied"})}let S=[],P=[],h=[],v=[],w=new Map,u=new Map,R=new Map,b=new Map;for(let{callId:y,mutation:T}of f){R.set(y,[]);let A=[...T.edits].flatMap(([C,k])=>{let M=g.resources.find(G=>G.source===C);if(M===void 0)return[];let D=Y(M.before.content,k.changes).content;return[Oe(M,C,k,D,T.resultPresentations.get(C)??"plain",1,[{operation:T.operation,changes:k.changes.length}],f.flatMap(G=>G.callId===y?[]:(G.mutation.edits.get(C)?.changes??[]).map(({from:ye,to:ce,insert:Re})=>({from:ye,to:ce,insert:Re}))))]});b.set(y,A),h.push(...A),v.push(...A.map(()=>y));for(let C of T.edits.keys())w.set(C,y),u.set(C,T.resultPresentations.get(C)??"plain")}for(let[y,T]of w){let A=g.resources.find(M=>M.source===y),C=g.result.mutations.flatMap(({mutation:M})=>{let D=M.edits.get(y);return D===void 0?[]:[D]});if(A===void 0||C.length===0)continue;let k=Oe(A,y,{changes:C.flatMap(M=>M.changes),action:C.some(M=>M.action==="overwritten")?"overwritten":"edited"},A.after.content,u.get(y)??"plain",C.length,f.flatMap(({mutation:M})=>{let D=M.edits.get(y);return D===void 0?[]:[{operation:M.operation,changes:D.changes.length}]}));R.get(T)?.push(k),S.push(k),P.push(T)}for(let{callId:y}of f){let T=R.get(y)??[],A=b.get(y)??[];s.complete(y,ot(T,T.map(()=>y),A,A.map(()=>y)))}for(let y of x){let T=y.error instanceof Q?y.error.failures:y.error instanceof z?[y.error]:[];for(let k of T){let M=g.resources.find(({source:D})=>D===k.source);M!==void 0&&await k.resolution.refreshRecovery({source:M.source,content:M.after.content,lines:M.after.lines.map(({content:D})=>D),cwd:i.cwd,...r!==void 0&&{signal:r}})}let A=await rt(t,{code:y.effect==="applied"?"POST_WRITE_FAILED":"INVALID_REQUEST",source:y.source,message:xn(y.error),cause:y.error},i,y.effect),C=A.details.results??[];s.fail(y.callId,{error:y.error,effect:y.effect,result:A}),S.push(...C),P.push(...C.map(()=>y.callId)),h.push(...C),v.push(...C.map(()=>y.callId))}return o?.({content:[{type:"text",text:"post-edit progress"}],details:{results:[...S],callIdsByResult:[...P],displayResults:[...h],callIdsByDisplayResult:[...v]}}),ot(S,P,h,v)}d(Fr,"executeRegisteredTextBatch");async function fn(t,e,n,r,o){let i=n,s=Br(n)?n:{code:"INVALID_REQUEST",source:"",message:xn(i),cause:i},a=e[0],l=await rt(t,s,r);for(let p of e)o.fail(p,{error:i,effect:"not-applied",...p===a&&{result:l}});let c=l.details.results??[];return ot(c,c.map(()=>a??""))}d(fn,"failTextBatch");function Br(t){return typeof t=="object"&&t!==null&&typeof t.code=="string"&&typeof t.source=="string"&&typeof t.message=="string"}d(Br,"isTextResourceEditFailure");function Nr(t,e){return t.from===t.to&&e.from===e.to?!1:t.from===t.to?t.from>e.from&&t.from<e.to:e.from===e.to?e.from>t.from&&e.from<t.to:t.from<e.to&&e.from<t.to}d(Nr,"textChangesConflict");function xn(t){return t instanceof Error?t.message:String(t)}d(xn,"errorMessage");function ot(t,e,n=t,r=e){return{content:[new V(t).toTextContent()],details:{results:t,callIdsByResult:e,displayResults:n,callIdsByDisplayResult:r}}}d(ot,"textBatchResult");function pn(t,e,n,r,o){return Qt(t,e,n,r,o)}d(pn,"executeTextToolWithBatch");import{readFileSync as _r}from"node:fs";import jr from"node:path";function Rn(t){let e=jr.join(t,".pi","pi-agent-ide","text-editor.json"),n;try{n=JSON.parse(_r(e,"utf8"))}catch(s){if(Ur(s))return{contextLines:5,timeoutMs:2e3,sections:{}};throw new Error(`Invalid text editor config at ${e}`,{cause:s})}let r=Tn(n,"text editor config");if(Hr(r,["recovery","renderer"],"text editor config"),r.recovery===void 0)return{contextLines:5,timeoutMs:2e3,sections:{}};let o=Tn(r.recovery,"recovery"),i=Object.fromEntries(Object.entries(o).filter(([s])=>s!=="contextLines"&&s!=="timeoutMs"));return{contextLines:yn(o.contextLines,"contextLines",0,20,5),timeoutMs:yn(o.timeoutMs,"timeoutMs",1,1e4,2e3),sections:i}}d(Rn,"loadTextEditorConfig");function wn(t,e){if(e.length===0)throw new TypeError("Recovery config section name must be non-empty");return{contextLines:t.contextLines,timeoutMs:t.timeoutMs,settings:t.sections[e]}}d(wn,"recoverySection");function Tn(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} must be an object`);return Object.fromEntries(Object.entries(t))}d(Tn,"record");function Hr(t,e,n){let r=Object.keys(t).find(o=>!e.includes(o));if(r!==void 0)throw new TypeError(`${n} contains unknown key ${r}`)}d(Hr,"assertKeys");function yn(t,e,n,r,o){if(t===void 0)return o;if(!Number.isInteger(t)||typeof t!="number"||t<n||t>r)throw new RangeError(`${e} must be an integer between ${n} and ${r}`);return t}d(yn,"integer");function Ur(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}d(Ur,"isMissingFile");function Cn(t){let e=Rn(process.cwd()),n=[],r=new Pe,o=[],i=[],s=new Map,a=new Set,l=new Map,c=[],p=[],m=new Set,g=new Map,f=new Set,x=new Set,S=[],P=new Map,h=Promise.resolve(),v=d(u=>{Kr(u,n,o,c,p);let R=new Set;for(let T of u.mutationTools??[]){if(Ce(T),g.has(T.name)||R.has(T.name))throw new Error(`Mutation tool ${T.name} is already registered`);R.add(T.name)}for(let T of u.toolRenderers??[])if(!Xe(T))throw new TypeError("Plugin provided an invalid text editor tool renderer");r.assertCanAdd(u.anchorResolvers.map(({registration:T})=>T));let b=u.presenters??[],y=new Set(i.map(({registration:T})=>T.presenter.id));for(let T of b){if(!je(T.registration))throw new TypeError(`Plugin ${T.pluginId} provided an invalid text presenter`);if(y.has(T.registration.presenter.id))throw new Error(`Text presenter ${T.registration.presenter.id} is already registered`);y.add(T.registration.presenter.id)}for(let T of u.resolvers)n.push({resolver:T.registration.resolver,priority:T.registration.priority??0,order:n.length});for(let T of u.anchorResolvers)r.add(T.registration);for(let T of b)i.push({...T,order:i.length});o.push(...u.handlers),S.push(...u.mutationGuards??[]),c.push(...u.promptContributions),p.push(...u.writablePromptContributions);for(let T of u.toolRenderers??[]){let A=P.get(T.tool);P.set(T.tool,oo(A,T))}for(let T of u.tools)m.add(T);for(let T of u.mutationTools??[])bn(T,g,m,f,t,w);for(let T of u.mutationToolListeners??[])An(T,g),f.add(T);for(let T of u.editCompletionListeners??[])x.add(T)},"registerContributions"),w={addAnchorResolver(u){if(!Ue(u))throw new TypeError("Invalid text anchor resolver");r.add(u)},addMutationTool(u){bn(u,g,m,f,t,w)},getMutationTools(){return[...g.values()]},onMutationTool(u){return An(u,g),f.add(u),()=>f.delete(u)},onDidEdit(u){return x.add(u),()=>x.delete(u)},getToolRenderer(u){return P.get(u)},inspectTextAnchors(u){return vn(u,[...n],r.snapshot())},resolveTextAnchorResources(u,R,b){return r.snapshot().resolveResources(u,b,new Set(R))},textTargetResolver(){return{id:"text-editor-anchors",tryResolve:d(async(u,R)=>{let b=await r.snapshot().resolveResources(u,R);return b===void 0?{kind:"not-handled"}:{kind:"resolved",targets:b}},"tryResolve")}},resolveAnchorInText(u){let R={source:u.source,content:u.content,lines:u.content.length===0?[]:u.content.split(/\r?\n/u),cwd:u.cwd,...u.signal!==void 0&&{signal:u.signal}};return r.snapshot().resolve(u.value,R)},editText(u,R,b){let y=[...n].sort((A,C)=>A.priority-C.priority||A.order-C.order),T=[...i].sort((A,C)=>(A.registration.priority??0)-(C.registration.priority??0)||A.order-C.order);return Gr(u,R,y,r.snapshot(),T,[...s.values()],[...x],b)},editTexts(u,R,b){let y=[...n].sort((A,C)=>A.priority-C.priority||A.order-C.order),T=[...i].sort((A,C)=>(A.registration.priority??0)-(C.registration.priority??0)||A.order-C.order);return Vr(u,R,y,r.snapshot(),T,[...s.values()],[...x],[...S],b)},previewTexts(u,R,b){let y=[...n].sort((T,A)=>T.priority-A.priority||T.order-A.order);return Wr(u,R,y,r.snapshot(),b)},async executeEdit(u,R,b){if(!pe(u))throw new Error(`Unsupported text editor tool ${String(u)}`);let y=o.filter(D=>D.tool===u),T=await qr(R,y,u);if(T.kind==="failed")return T;let A=await b(T.state),C={...T.state,result:A},k=await En("text-edit",C,y,u);if(k.kind==="failed")return k;let M=await En("text-post-edit",k.state,y,u);return M.kind==="failed"?M:{kind:"completed",state:M.state}},registerPostEditHandler(u){if(!At(u))throw new TypeError("Invalid text editor post-edit handler registration");if(s.has(u.id))throw new Error(`Post-edit handler ${u.id} is already registered`);return s.set(u.id,u),()=>{s.get(u.id)===u&&s.delete(u.id)}},registerTool(u){if(!pe(u))throw new TypeError("Invalid text editor tool ID");m.add(u)},registerPlugin(u){let R=zr(u);if(R!==void 0)return Promise.reject(R);let b=l.get(u.id);if(b?.plugin===u)return b.ready;if(b!==void 0)return Promise.reject(new Error(`Plugin ${u.id} is already registered`));let y={status:"pending"},T=Xr(u.id,v,k=>vn(k,[...n],r.snapshot()),k=>w.onMutationTool(k),k=>w.onDidEdit(k),k=>cn(w,k),k=>wn(e,k)),A=h.then(async()=>{try{await u.setup(T.api),T.commit(),y.status="active";return}catch(k){throw T.close(),k}}),C={lifecycle:y,plugin:u,ready:A};return l.set(u.id,C),a.add(A),h=A.catch(()=>{}),A.then(()=>{a.delete(A)},()=>{a.delete(A),l.get(u.id)===C&&l.delete(u.id)}),A},recoveryContextLines(){return e.contextLines},renderGeneralPromptGuideline(u){let R=[],b=[];for(let T of l.values()){if(T.lifecycle.status!=="active")continue;let A=p.find(k=>k.pluginId===T.plugin.id);if(A===void 0)continue;let C=eo(A.description);C!==void 0&&b.push(to(T.plugin.id,C))}b.length>0&&R.push(["Text edits support these writable resources:",...b].join(`
41
+ `));let y=r.renderPromptSection(u);return y!==void 0&&R.push(y),R.length===0?void 0:no(R.join(`
42
+
43
+ `))},renderToolPromptGuideline(u){let R=[];for(let b of l.values()){if(b.lifecycle.status!=="active")continue;let y=c.find(T=>T.pluginId===b.plugin.id&&T.tool===u);y!==void 0&&R.push(y.description)}return R.length===0?void 0:R.join(`
44
+ `)},async waitForPendingPlugins(){await Promise.all(a)}};return w}d(Cn,"createTextEditorCore");async function vn(t,e,n){let r={cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}};for(let{resolver:o}of[...e].sort((i,s)=>i.priority-s.priority||i.order-s.order)){let i;try{i=await o.tryResolve(t.source,r)}catch(l){return{kind:"failed",reason:`Resolver ${o.id} failed`,cause:l}}if(!ve(i))return{kind:"failed",reason:`Resolver ${o.id} returned an invalid result`,cause:i};if(i.kind==="not-handled")continue;if(i.kind==="failed")return{kind:"failed",reason:`Resolver ${o.id} failed`,cause:i.error};let{resource:s}=i;if(s.read===void 0)return{kind:"failed",reason:`Resource ${s.source} is not readable text`};let a;try{a=await s.read(t.signal===void 0?{}:{signal:t.signal})}catch(l){return{kind:"failed",reason:`Unable to read ${s.source}`,cause:l}}return!J(a)||a.length!==1||a[0].type!=="text"?{kind:"failed",reason:`Resource ${s.source} is not readable text`,cause:a}:n.inspect(t.anchors,t.kinds,{source:s.source,content:a[0].text,lines:a[0].text.length===0?[]:a[0].text.split(/\r?\n/u),cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})}return{kind:"failed",reason:`No resolver handled ${t.source}`}}d(vn,"inspectTextResource");async function Wr(t,e,n,r,o){try{let i=new Map(t.map(m=>[m.source,m])),s=[...i.keys()];if(s.length===0||s.some(m=>m.length===0))return{kind:"failed",reason:"No source was provided"};let a=new Map;for(let m of s){let g=E(i.get(m)),f=await Sn(m,g.read,g.allowReadFailure??!1,e,n);if("failure"in f)return{kind:"failed",reason:f.failure.message};a.set(m,f)}let l=new Map([...a].map(([m,g])=>[m,g.before.content])),c=await o(l,(m,g,f)=>{let x=a.get(m);if(x===void 0)throw new Error(`Anchor refers to undeclared resource ${m}`);return r.resolve(g,x.anchorContext,f===void 0?void 0:new Set(f))});return{kind:"completed",resources:s.map(m=>{let g=E(a.get(m)),f=c.changes.get(m),x=f===void 0?{content:g.before.content,changes:[]}:Y(g.before.content,f);return{path:m,existed:g.existed,beforeRanges:x.changes.map(({fromBefore:S,toBefore:P})=>({from:S,to:P})),...g.resource.link!==void 0&&{link:g.resource.link},beforeContent:g.before.content,afterContent:x.content,ranges:x.changes.map(({fromAfter:S,toAfter:P})=>({from:S,to:P}))}})}}catch(i){return{kind:"failed",reason:i instanceof Error?i.message:String(i)}}}d(Wr,"previewTextResources");async function Vr(t,e,n,r,o,i,s,a,l){let c=new Map(t.map(w=>[w.source,w])),p=[...c.keys()];if(p.length===0||p.some(w=>w.length===0))return{kind:"failed",failure:{code:"INVALID_REQUEST",source:p.find(u=>u.length===0)??"",message:"No source was provided"},completed:[]};let m=new Map;for(let w of p){let u=E(c.get(w)),R=await Sn(w,u.read,u.allowReadFailure??!1,e,n);if("failure"in R)return{kind:"failed",failure:R.failure,completed:[]};m.set(w,R)}let g=new Map([...m].map(([w,u])=>[w,u.before.content])),f=await l(g,(w,u,R)=>{let b=m.get(w);if(b===void 0)throw new Error(`Anchor refers to undeclared resource ${w}`);return r.resolve(u,b.anchorContext,R===void 0?void 0:new Set(R))});for(let w of f.changes.keys())if(!m.has(w))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:w,message:`Text edit produced an undeclared resource ${w}`},completed:[]};let x=new Map;for(let[w,u]of f.changes){let R=E(m.get(w));x.set(w,Y(R.before.content,u))}let S={resources:p.flatMap(w=>{let u=E(m.get(w)),R=x.get(w);return R===void 0||R.content===u.before.content?[]:[{source:u.resource.source,existed:u.existed,before:u.before,after:ne(u.resource.source,R.content),changes:R.changes}]})};for(let w of a){let u;try{u=await w.guard(S,e)}catch(R){return{kind:"failed",failure:{code:"PLUGIN_FAILED",source:p[0]??"",message:`Mutation guard ${w.id} failed`,cause:R},completed:[]}}if(u.kind==="rejected")return{kind:"failed",failure:{code:"MUTATION_REJECTED",source:S.resources[0]?.source??p[0]??"",message:u.rejection.message},completed:[]}}let P=[],h=[],v=[];for(let w of p){let u=x.get(w)?.content,R=E(m.get(w));if(u===void 0||u===R.before.content)continue;let b=[{type:"text",text:u}];if(!J(b))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:w,message:`Text edit for ${w} produced invalid content`},completed:P};try{await R.resource.write(b,e.signal===void 0?{}:{signal:e.signal})}catch(y){let T=[];for(let A of[w,...h].reverse()){let C=E(m.get(A));try{await C.resource.write([{type:"text",text:C.before.content}],{})}catch{T.push(A)}}return{kind:"failed",failure:{code:"WRITE_FAILED",source:w,resolverId:R.resolverId,message:T.length===0?`Unable to write ${w}; completed writes were rolled back`:`Unable to write ${w}; rollback failed for ${T.join(", ")}`,cause:y},completed:T}}h.push(w),P.push(w)}for(let w of h){let u=E(x.get(w)).content,R=E(m.get(w));v.push(await Mn({requestedSource:R.requestedSource,outcomeSource:R.requestedSource,resource:R.resource,resolvedBy:R.resolverId,existed:R.existed,before:R.before,requestedText:u,context:e,presenters:o,postEditHandlers:i,editCompletionListeners:s,result:f.result}))}return{kind:"completed",resources:v,result:f.result}}d(Vr,"editTextResources");async function Sn(t,e,n,r,o){for(let{resolver:i}of o){let s;try{s=await i.tryResolve(t,r)}catch(p){return{failure:{code:"RESOLVE_FAILED",source:t,resolverId:i.id,message:`Resolver ${i.id} failed`,cause:p}}}if(!ve(s))return{failure:{code:"INVALID_RESOLVER_RESULT",source:t,resolverId:i.id,message:`Resolver ${i.id} returned an invalid result`,cause:s}};if(s.kind==="not-handled")continue;if(s.kind==="failed")return{failure:{code:"RESOLVE_FAILED",source:t,resolverId:i.id,message:`Resolver ${i.id} failed`,cause:s.error}};if(s.resource.write===void 0||e&&s.resource.read===void 0)return{failure:{code:"UNSUPPORTED_CAPABILITY",source:s.resource.source,resolverId:i.id,message:`Resource ${s.resource.source} does not support text editing`}};let a="",l=e;if(e){let p;try{p=await E(s.resource.read)(r.signal===void 0?{}:{signal:r.signal})}catch(m){if(!n)return{failure:{code:"READ_FAILED",source:s.resource.source,resolverId:i.id,message:`Unable to read ${s.resource.source}`,cause:m}};l=!1,p=[{type:"text",text:""}]}if(!J(p)||p.length!==1||p[0].type!=="text")return{failure:{code:"UNSUPPORTED_CONTENT",source:s.resource.source,resolverId:i.id,message:`Resource ${s.resource.source} is not editable text`,cause:p}};a=p[0].text}let c=ne(s.resource.source,a);return{requestedSource:t,resource:s.resource,resolverId:i.id,existed:l,before:c,anchorContext:{source:s.resource.source,content:c.content,lines:c.lines.map(p=>p.content),cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}}}}return{failure:{code:"NO_RESOLVER",source:t,message:`No resolver handled ${t}`}}}d(Sn,"prepareTextResource");async function Mn(t){let e=ne(t.resource.source,t.requestedText),n={source:t.requestedSource,resourceSource:t.resource.source,resolvedBy:t.resolvedBy,cwd:t.context.cwd,before:t.before,requestedAfter:e,...t.context.signal!==void 0&&{signal:t.context.signal}},r=[];for(let c of t.postEditHandlers)try{let p=await c.handler(n);p!==void 0&&r.push({id:c.id,data:p})}catch{}let o=t.requestedText;if(t.resource.read!==void 0)try{let c=await t.resource.read(t.context.signal===void 0?{}:{signal:t.context.signal});J(c)&&c.length===1&&c[0].type==="text"&&(o=c[0].text)}catch{}let i=ne(t.resource.source,o),s={source:t.requestedSource,resourceSource:t.resource.source,resolvedBy:t.resolvedBy,cwd:t.context.cwd,existed:t.existed,before:t.before,after:i,intent:t.context.intent??"edit"};for(let c of t.editCompletionListeners)try{await c(s)}catch{}let a=i,l={purpose:"edit-diff",source:t.resource.source,cwd:t.context.cwd,resolvedBy:t.resolvedBy,...t.context.signal!==void 0&&{signal:t.context.signal}};for(let{registration:c}of t.presenters)a=await c.presenter.present(a,l);return{kind:"completed",source:t.outcomeSource,resolvedBy:t.resolvedBy,before:t.before,after:a,result:t.result,postEditContributions:r}}d(Mn,"finalizeTextResource");async function Gr(t,e,n,r,o,i,s,a){if(t.length===0)return{kind:"failed",failure:{code:"INVALID_REQUEST",source:t,message:"No source was provided"}};for(let{resolver:l}of n){let c;try{c=await l.tryResolve(t,e)}catch(h){return{kind:"failed",failure:{code:"RESOLVE_FAILED",source:t,resolverId:l.id,message:`Resolver ${l.id} failed`,cause:h}}}if(!ve(c))return{kind:"failed",failure:{code:"INVALID_RESOLVER_RESULT",source:t,resolverId:l.id,message:`Resolver ${l.id} returned an invalid result`,cause:c}};if(c.kind==="not-handled")continue;if(c.kind==="failed")return{kind:"failed",failure:{code:"RESOLVE_FAILED",source:t,resolverId:l.id,message:`Resolver ${l.id} failed`,cause:c.error}};let p=c.resource;if(p.read===void 0||p.write===void 0)return{kind:"failed",failure:{code:"UNSUPPORTED_CAPABILITY",source:p.source,resolverId:l.id,message:`Resource ${p.source} does not support text editing`}};let m;try{m=await p.read({...e.signal!==void 0&&{signal:e.signal}})}catch(h){return{kind:"failed",failure:{code:"READ_FAILED",source:p.source,resolverId:l.id,message:`Unable to read ${p.source}`,cause:h}}}if(!J(m))return{kind:"failed",failure:{code:"INVALID_RESOURCE_CONTENT",source:p.source,resolverId:l.id,message:`Resource ${p.source} returned invalid content`,cause:m}};let g=m[0];if(m.length!==1||g.type!=="text")return{kind:"failed",failure:{code:"UNSUPPORTED_CONTENT",source:p.source,resolverId:l.id,message:`Resource ${p.source} is not editable text`}};let f=ne(p.source,g.text),x={source:p.source,content:f.content,lines:f.lines.map(h=>h.content),cwd:e.cwd,...e.signal!==void 0&&{signal:e.signal}},S=await a(g.text,(h,v)=>r.resolve(h,x,v===void 0?void 0:new Set(v))),P=[{type:"text",text:S.text}];if(!J(P))return{kind:"failed",failure:{code:"INVALID_WRITE_CONTENT",source:p.source,resolverId:l.id,message:`Text edit for ${p.source} produced invalid content`,cause:S}};try{await p.write(P,{...e.signal!==void 0&&{signal:e.signal}})}catch(h){return{kind:"failed",failure:{code:"WRITE_FAILED",source:p.source,resolverId:l.id,message:`Unable to write ${p.source}`,cause:h}}}return Mn({requestedSource:t,outcomeSource:p.source,resource:p,resolvedBy:l.id,existed:!0,before:f,requestedText:S.text,context:e,presenters:o,postEditHandlers:i,editCompletionListeners:s,result:S.result})}return{kind:"failed",failure:{code:"NO_RESOLVER",source:t,message:`No resolver handled ${t}`}}}d(Gr,"editTextResource");async function qr(t,e,n){let r=t;for(let o of e)if(o.registration.stage==="text-pre-edit")try{r=await o.registration.handler(r)}catch(i){return{kind:"failed",failure:Pn(o.pluginId,n,"text-pre-edit",i)}}return{kind:"completed",state:r}}d(qr,"runPreEditHandlers");async function En(t,e,n,r){let o=e;for(let i of n)if(i.registration.stage===t)try{o=await i.registration.handler(o)}catch(s){return{kind:"failed",failure:Pn(i.pluginId,r,t,s)}}return{kind:"completed",state:o}}d(En,"runResultHandlers");function Pn(t,e,n,r){return{code:"PLUGIN_FAILED",pluginId:t,tool:e,stage:n,message:`Plugin ${t} failed during ${n}`,cause:r}}d(Pn,"pluginFailure");function zr(t){if(t.protocol!==Ee)return new Error(`Plugin ${t.id} uses an unsupported protocol`);if(t.apiVersion!==Ae)return new Error(`Plugin ${t.id} uses an unsupported API version`);if(t.id.trim().length===0)return new Error("Plugin ID must not be empty")}d(zr,"getPluginValidationError");function Xr(t,e,n,r,o,i,s){let a={resolvers:[],anchorResolvers:[],presenters:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationTools:[],mutationToolListeners:[],editCompletionListeners:[],mutationGuards:[],toolRenderers:[]},l="setup",c=d(()=>{if(l==="closed")throw new Error(`Plugin ${t} API is closed`)},"assertAvailable"),p=d(g=>({addHandler(f){if(c(),!ze(f))throw new TypeError(`Plugin ${t} provided an invalid handler for ${g}`);let x={pluginId:t,registration:f,tool:g};if(l==="setup"){Yr(a.handlers,x),a.handlers.push(x);return}e({resolvers:[],anchorResolvers:[],handlers:[x],promptContributions:[],writablePromptContributions:[],tools:[]})},describe(f){c();let x={description:it(`Plugin prompt description for ${g}`,f),pluginId:t,tool:g};if(l==="setup"){Qr(a.promptContributions,x),a.promptContributions.push(x);return}e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[x],writablePromptContributions:[],tools:[]})}}),"createToolApi");return{api:{addMutationTool(g){if(c(),Ce(g),l==="setup"){E(a.mutationTools).push(g);return}e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationTools:[g]})},addToolRenderer(g){if(c(),!Xe(g))throw new TypeError(`Plugin ${t} provided an invalid text editor tool renderer`);if(l==="setup"){E(a.toolRenderers).push(g);return}e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],toolRenderers:[g]})},addMutationGuard(g){if(c(),g.id.trim().length===0||typeof g.guard!="function")throw new TypeError(`Plugin ${t} provided an invalid mutation guard`);if(l==="setup"){E(a.mutationGuards).push(g);return}e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[],mutationGuards:[g]})},onMutationTool(g){return c(),l==="setup"?(E(a.mutationToolListeners).push(g),()=>{let f=E(a.mutationToolListeners).indexOf(g);f!==-1&&E(a.mutationToolListeners).splice(f,1)}):r(g)},onDidEdit(g){if(c(),typeof g!="function")throw new TypeError(`Plugin ${t} provided an invalid edit completion listener`);return l==="setup"?(E(a.editCompletionListeners).push(g),()=>{let f=E(a.editCompletionListeners).indexOf(g);f!==-1&&E(a.editCompletionListeners).splice(f,1)}):o(g)},inspectTextAnchors(g){return c(),n(g)},recoveryConfig(g){return c(),s(g)},previewMutation(g){return c(),i(g)},addResolver(g){if(c(),!He(g))throw new TypeError(`Plugin ${t} provided an invalid resource resolver`);let f={pluginId:t,registration:g};if(l==="setup"){Jr(a.resolvers,f),a.resolvers.push(f);return}e({resolvers:[f],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},addAnchorResolver(g){if(c(),!Ue(g))throw new TypeError(`Plugin ${t} provided an invalid text anchor resolver`);let f={pluginId:t,registration:g};if(l==="setup"){a.anchorResolvers.push(f);return}e({resolvers:[],anchorResolvers:[f],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},addTextPresenter(g){if(c(),!je(g))throw new TypeError(`Plugin ${t} provided an invalid text presenter`);let f={pluginId:t,registration:g};if(l==="setup"){E(a.presenters).push(f);return}e({resolvers:[],anchorResolvers:[],presenters:[f],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[]})},describe(g){if(c(),a.writablePromptContributions.length>0)throw new Error(`Plugin ${t} provides more than one writable resource description`);let f={description:Zr(g),pluginId:t};if(l==="setup"){a.writablePromptContributions.push(f);return}e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[f],tools:[]})},tool(g){if(c(),!pe(g))throw new Error(`Plugin ${t} provided an invalid tool ID`);return l==="setup"?a.tools.includes(g)||a.tools.push(g):e({resolvers:[],anchorResolvers:[],handlers:[],promptContributions:[],writablePromptContributions:[],tools:[g]}),p(g)}},close(){l="closed"},commit(){if(l!=="setup")throw new Error(`Plugin ${t} setup contributions cannot be committed`);e(a),l="active"}}}d(Xr,"createPluginContributionController");function Kr(t,e,n,r,o){let i=new Set(e.map(({resolver:c})=>c.id));for(let c of t.resolvers){if(!He(c.registration))throw new TypeError(`Plugin ${c.pluginId} provided an invalid resource resolver`);let p=c.registration.resolver.id;if(i.has(p))throw new Error(`Resource resolver ${p} is already registered`);i.add(p)}let s=new Set(n.map(De));for(let c of t.handlers){if(!ze(c.registration))throw new TypeError(`Plugin ${c.pluginId} provided an invalid handler for ${c.tool}`);let p=De(c);if(s.has(p))throw new Error(`Plugin ${c.pluginId} already handles ${c.registration.stage} for ${c.tool}`);s.add(p)}let a=new Set(r.map(Fe));for(let c of t.promptContributions){let p=Fe(c);if(a.has(p))throw new Error(`Plugin ${c.pluginId} describes ${c.tool} more than once`);a.add(p)}let l=new Set(o.map(({pluginId:c})=>c));for(let c of t.writablePromptContributions){if(l.has(c.pluginId))throw new Error(`Plugin ${c.pluginId} provides more than one writable resource description`);l.add(c.pluginId)}for(let c of t.tools)if(!pe(c))throw new TypeError("Plugin provided an invalid tool ID")}d(Kr,"validateContributionDraft");function Jr(t,e){let n=e.registration.resolver.id;if(t.some(r=>r.registration.resolver.id===n))throw new Error(`Resource resolver ${n} is already registered`)}d(Jr,"assertNoDraftResolver");function Yr(t,e){if(t.some(n=>De(n)===De(e)))throw new Error(`Plugin ${e.pluginId} already handles ${e.registration.stage} for ${e.tool}`)}d(Yr,"assertNoDraftHandler");function Qr(t,e){if(t.some(n=>Fe(n)===Fe(e)))throw new Error(`Plugin ${e.pluginId} describes ${e.tool} more than once`)}d(Qr,"assertNoDraftDescription");function De(t){return`${t.pluginId}\0${t.tool}\0${t.registration.stage}`}d(De,"handlerKey");function Fe(t){return`${t.pluginId}\0${t.tool}`}d(Fe,"descriptionKey");function Zr(t){if(typeof t=="string")return it("Writable resource prompt description",t);if(typeof t=="function")return t;throw new TypeError("Writable resource prompt description must be a string or callback")}d(Zr,"normalizeDescriptionSource");function eo(t){if(typeof t=="string")return t;let e=t();return e===void 0?void 0:it("Writable resource prompt description",e)}d(eo,"renderDescriptionSource");function it(t,e){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.replaceAll(`\r
45
+ `,`
46
+ `).replaceAll("\r",`
47
+ `).split(`
48
+ `).map(o=>o.trimEnd());for(;n[0]?.trim().length===0;)n.shift();for(;n.at(-1)?.trim().length===0;)n.pop();let r=n.join(`
49
+ `);if(r.trim().length===0)throw new Error(`${t} is empty`);return r}d(it,"normalizeDescription");function to(t,e){let[n,...r]=e.split(`
50
+ `);return[`- \`${ro(t)}\` \u2014 ${n??""}`,...r.map(o=>` ${o}`)].join(`
51
+ `)}d(to,"renderPromptEntry");function no(t){let[e,...n]=t.split(`
52
+ `);return[e??"",...n.map(r=>r.length===0?r:` ${r}`)].join(`
53
+ `)}d(no,"indentGuidelineContinuation");function ro(t){return t.replaceAll("`","\\`")}d(ro,"escapeInlineCode");function oo(t,e){let n=e.fallback===!0?{...e,...t,tool:e.tool}:{...t,...e,tool:e.tool},{fallback:r,...o}=n;return o}d(oo,"mergeToolRenderer");function An(t,e){for(let n of e.values())t(n)}d(An,"replayMutationTools");function bn(t,e,n,r,o,i){if(Ce(t),e.has(t.name))throw new Error(`Mutation tool ${t.name} is already registered`);e.set(t.name,t),n.add(t.name);for(let s of r)s(t);o?.(t,i)}d(bn,"addMutationRegistration");var kn=5;function In(t){return{id:"text-editor-anchors",async resolve(e){let n;try{n=await t.resolveAnchorInText({source:e.source,content:e.text.content,value:e.fragment,cwd:e.cwd,...e.signal!==void 0&&{signal:e.signal}})}catch(r){return r instanceof $&&await r.refreshRecovery(),{kind:"failed",message:so(r)}}return{kind:"resolved",originLine:io(n)}}}}d(In,"createReadFragmentResolver");function io(t){return N.is(t)?E(t.ranges[0]).start.lineNumber:t.lineNumber}d(io,"anchorOriginLine");function so(t){if(!(t instanceof $))return t instanceof Error?t.message:String(t);let e=[t.message],n=t.recovery;if(n?.kind==="candidates"&&n.candidates.length>0){for(let o of n.candidates.slice(0,kn))e.push(`Candidate: line ${o.range.start.lineNumber}`);let r=n.total-Math.min(n.candidates.length,kn);r>0&&e.push(`(+${r} more candidates)`)}return e.join(`
54
+ `)}d(so,"describeAnchorError");async function st(t){let e=new We,n=d(()=>{Ge(t),qe(t,e.annotate)},"connectInterceptionRendering");n(),t.on("session_start",n),t.on("session_shutdown",()=>{Ge(t),qe(t),e.clear()});let r=new Set,o=Cn((l,c)=>{r.add(l.name),t.registerTool(on(c,l,e,()=>[(l.anchors?.length??0)>0?c.renderGeneralPromptGuideline(new Set(l.anchors?.flatMap(p=>p.kinds))):void 0,c.renderToolPromptGuideline(l.name)].filter(p=>p!==void 0).join(`
55
+
56
+ `)||void 0,()=>Mt(t)?.source))});hn(o,e.resolveArguments),t.on("tool_result",l=>{if(St(t,l.details),r.has(l.toolName)&&ao(l.details))return{isError:!0}});let i;await mt(t,{protocol:gt,apiVersion:ht,id:"text-anchor-recovery",setup(l){i=l,l.addTargetResolver({resolver:o.textTargetResolver()}),l.addFragmentResolver(In(o)),l.describe("path#anchor \u2014 source around a returned line or scope anchor, e.g. notes.txt#12#A4F0. SEARCH# references go directly in path, without a file prefix. offset/limit select context relative to each location; output keeps original line numbers.")}}),Lt(o,(l,c)=>{if(i===void 0)throw new Error("Text anchor recovery requires pi-agent-read");return i.read({...l,views:["anchors"]},c)});let s=t.events.on(Tt,l=>{if(!Rt(l))throw new Error("Invalid pi-agent-text-editor plugin registration request");l.accept(o.registerPlugin(l.plugin))});t.on("session_shutdown",s);let a=t.events.on(wt,l=>{if(!bt(l))throw new Error("Invalid pi-agent-text-editor post-edit handler registration request");l.accept(o.registerPostEditHandler(l.registration))});return t.on("session_shutdown",a),t.events.emit(xt,{protocol:Ee,apiVersion:Ae}),await o.waitForPendingPlugins(),o}d(st,"registerTextEditorCore");function ao(t){if(!Be(t))return!1;let e=t.batchRecovery;if(Be(e)&&typeof e.state=="string"&&e.state!=="completed")return!0;let n=t.results;return Array.isArray(n)&&n.some(r=>Be(r)?(Be(r.data)?r.data:r).ok===!1:!1)}d(ao,"isFailedTextMutationResult");function Be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}d(Be,"isRecord");import{Type as _}from"typebox";function Z(t,e){let n=[...t.values()];if(!n.every(r=>!N.is(r))){if(n.some(r=>!N.is(r)))throw new Error(`Anchor ${e} resolved to incompatible selection types.`);return t}}d(Z,"textSelections");function $n(t,e){if(Z(t,e)!==void 0)throw new Error(`Anchor ${e} cannot use a search selection as a line endpoint.`);if(t.size!==1)throw new Error(`Anchor ${e} must resolve in one resource.`);return E(t.values().next().value)}d($n,"lineAnchor");function le(t,e,n,r=!1){if(e.size!==1)throw new Error(`Anchor ${n} must resolve in one resource.`);let[o,i]=E(e.entries().next().value);if(N.is(i)){if(i.ranges.length!==1)throw new Error(`Anchor ${n} must select one match for this operation.`);let a=E(i.ranges[0]),l=t.documentFor(o),c=at(t,o,a),p=r?lt(a):co(a);if(p!==void 0){let m=l.lineRange(a.start.lineNumber,p);return{source:o,...m,selection:!1,preservesTrailingLineBreak:!0,linewiseStartLine:a.start.lineNumber,linewiseEndLine:p}}return{source:o,...c,selection:!0,preservesTrailingLineBreak:!1}}let s=t.documentFor(o).lineRange(i.lineNumber,i.lineNumber);return{source:o,...s,selection:!1,preservesTrailingLineBreak:!0,linewiseStartLine:i.lineNumber,linewiseEndLine:i.lineNumber}}d(le,"singleAnchorSpan");function W(t,e,n,r,o){let i=le(t,e,r),s=n===void 0?i:le(t,n,o);if(i.source!==s.source)throw new Error(`Anchors ${r} and ${o} must resolve in one resource.`);if(i.from>s.from)throw new Error(`Anchor ${r} must not come after ${o}.`);if(n===void 0)return i;let a=le(t,e,r,!0),l=le(t,n,o,!0);return{source:a.source,from:a.from,to:l.to,selection:!1,preservesTrailingLineBreak:!0}}d(W,"anchorSpanRange");function Ne(t,e,n){let r=t.documentFor(e).content.includes(`\r
57
+ `)?`\r
58
+ `:`
59
+ `;return n.replace(/\r\n|\r|\n/gu,r)}d(Ne,"targetText");function ee(t,e,n){if(n==="")return Te(t,e);let r=t.documentFor(e.source),o=Ne(t,e.source,n),i=r.text(e);if(e.preservesTrailingLineBreak&&!/(?:\r\n|\r|\n)$/u.test(o)){let s=/(?:\r\n|\r|\n)$/u.exec(i)?.[0];s!==void 0&&(o+=s)}return{from:e.from,to:e.to,insert:o}}d(ee,"replaceAnchorSpan");function Te(t,e){let n=t.documentFor(e.source).content;if(!e.selection&&e.to===n.length&&e.from>0&&!/(?:\r\n|\r|\n)$/u.test(n)){let r=n.slice(0,e.from),o=/(?:\r\n|\r|\n)$/u.exec(r);if(o!==null)return{from:e.from-o[0].length,to:e.to,insert:""}}return{from:e.from,to:e.to,insert:""}}d(Te,"deleteAnchorSpan");function de(t,e,n,r){let o=le(t,e,n,!0),i=Ne(t,o.source,r),s=o.linewiseEndLine??$n(e,n).lineNumber;return[o.source,t.documentFor(o.source).insertAfterLine(s,i)]}d(de,"insertionAfterAnchor");function Ln(t,e,n,r){let o=le(t,e,n,!0),i=Ne(t,o.source,r),s=o.linewiseStartLine??$n(e,n).lineNumber;return[o.source,t.documentFor(o.source).insertBeforeLine(s,i)]}d(Ln,"insertionBeforeAnchor");function lo(t){let e=[];for(let n of t){let r=e.at(-1);r?.linewise===!0&&n.linewise===!0&&r.end.lineNumber===n.start.lineNumber&&r.end.column===n.start.column?e[e.length-1]={...r,end:n.end}:e.push(n)}return e}d(lo,"coalesceAdjacentLinewiseRanges");function _e(t,e,n){return new Map([...e].map(([r,o])=>[r,(n.length===0?lo(o.ranges):o.ranges).map(i=>{let s=at(t,r,i);return ee(t,{source:r,...s,selection:i.linewise!==!0,preservesTrailingLineBreak:i.linewise===!0},n)})]))}d(_e,"selectionChanges");function On(t,e,n,r=!1){return new Map([...e].map(([o,i])=>[o,[...new Set(i.ranges.map(s=>(at(t,o,s),r?s.start.lineNumber:lt(s))))].map(s=>{let a=t.documentFor(o),l=Ne(t,o,n);return r?a.insertBeforeLine(s,l):a.insertAfterLine(s,l)})]))}d(On,"insertionChanges");function at(t,e,n){return t.documentFor(e).range(n.start.lineNumber,n.start.column,n.end.lineNumber,n.end.column)}d(at,"selectionRange");function co(t){if(t.linewise===!0)return lt(t)}d(co,"linewiseSelectionEndLine");function lt(t){return t.end.column===0&&t.end.lineNumber>t.start.lineNumber?t.end.lineNumber-1:t.end.lineNumber}d(lt,"containingEndLine");var uo=_.Object({path:_.Optional(_.String({description:"Source file path, or a returned SEARCH# reference selecting the text to copy"})),start:_.Optional(_.String({description:"Anchor or unique exact text. Alone, selects that fragment; a line anchor selects only its line. Required unless path supplies a SEARCH# selection. With end, selects a whole-line range."})),end:_.Optional(_.String({description:"Optional anchor or unique exact text. Range includes start's first line through end's last line, even for SEARCH :match. Mixed types allowed; boundaries must be unique, in one file, and forward-ordered. Omit when start already selects the intended content; do not repeat start. The end line is included, not a stopping point before it."})),target:_.Optional(_.String({description:"Target resource reference or file path; a returned SEARCH# reference may select the destination; defaults to the source"})),targetStart:_.Optional(_.String({description:"Registered anchor or unique exact text in the destination. Required unless target already selects one destination range. Without targetEnd, inserts after the last containing line, keeping the selected text. With targetEnd, replacement starts at the first containing line. SEARCH :match also uses these line boundaries."})),targetEnd:_.Optional(_.String({description:"Optional inclusive destination end. Replaces whole lines through the last line containing this anchor, including SEARCH :match. May differ in type from targetStart; both must resolve uniquely in the target file and in forward order. Omit to insert after targetStart instead."}))},{additionalProperties:!1}),Dn={name:"copy",description:"Use copy to duplicate existing text within or between files while keeping the source. Select the source and destination without reproducing the text in your call. The copy is inserted at the destination or replaces a destination range.",promptSnippet:"Make precise file edits by copying text within or between files using exact matches or anchors",parameters:uo,source:{field:"path",inherited:!0,targets:[{field:"target",fallbackTo:"path"}]},anchors:[{field:"start",sourceField:"path",kinds:[L,O]},{field:"end",sourceField:"path",kinds:[L,O],optional:!0},{field:"targetStart",sourceField:"target",kinds:[L,O]},{field:"targetEnd",sourceField:"target",kinds:[L,O],optional:!0}],pair:["start","end"],mutate:d(async(t,e)=>{let n=await t.resolveAnchors("start"),r=e.end===void 0?void 0:await t.resolveAnchors("end"),o=W(t,n,r,"start","end"),i=t.documentFor(o.source).text(o),s=await t.resolveAnchors("targetStart");if(e.targetEnd===void 0){let[c,p]=de(t,s,"targetStart",i);return{edits:new Map([[c,{changes:[p],action:"edited"}]])}}let a=await t.resolveAnchors("targetEnd"),l=W(t,s,a,"targetStart","targetEnd");return{edits:new Map([[l.source,{changes:[ee(t,l,i)],action:"edited"}]])}},"mutate")};import{Type as te}from"typebox";var po=te.Object({path:te.Optional(te.String({description:"Source resource reference or file path. A returned SEARCH# reference can select deletion ranges."})),start:te.Optional(te.String({description:"Anchor or unique exact text. Alone, selects that fragment; a line anchor selects only its line. Required unless path supplies a SEARCH# selection. With end, selects a whole-line range."})),end:te.Optional(te.String({description:"Optional anchor or unique exact text. Range includes start's first line through end's last line, even for SEARCH :match. Mixed types allowed; boundaries must be unique, in one file, and forward-ordered. Omit when start already selects the intended content; do not repeat start. The end line is included, not a stopping point before it."}))},{additionalProperties:!1}),Fn={name:"delete",description:"Use delete to remove an existing text fragment or an inclusive range of whole lines. Select only the content to remove; surrounding text is kept.",promptSnippet:"Make precise file edits by deleting text using exact matches or anchors",parameters:po,source:{field:"path",inherited:!0},anchors:[{field:"start",sourceField:"path",kinds:[L,O],optional:!0},{field:"end",sourceField:"path",kinds:[L,O],optional:!0}],pair:["start","end"],mutate:d(async(t,e)=>{let n=await t.resolveAnchors("start"),r=Z(n,"start");if(e.end===void 0&&r!==void 0){let s=_e(t,r,"");return{edits:new Map([...s].map(([a,l])=>[a,{changes:l,action:"edited"}]))}}let o=e.end===void 0?void 0:await t.resolveAnchors("end"),i=W(t,n,o,"start","end");return{edits:new Map([[i.source,{changes:[Te(t,i)],action:"edited"}]])}},"mutate")};import{Type as X}from"typebox";var fo=X.Object({path:X.Optional(X.String({description:"Source resource reference or file path. A returned SEARCH# reference can select insertion positions."})),anchor:X.Optional(X.String({description:"Registered anchor or unique exact text locating the insertion. Required unless path already supplies a SEARCH selection. Inserts after the last containing line by default, or before the first containing line when before is true. This includes SEARCH :match and multiline exact text; the selected text is kept. Multiple matches on the same insertion line produce one insertion."})),text:X.String({description:"New text only. The tool supplies the line boundary; do not prefix a newline just to start a new line. For example, 'NEW' inserts one line, while '\\nNEW' intentionally adds a blank line before it. A missing trailing newline is supplied before following text; additional newlines remain intentional blank lines. When appending after an unterminated final line, the tool supplies the separator before the new text and removes one trailing newline from the payload. Payload line endings follow the destination file's LF/CRLF style."}),before:X.Optional(X.Boolean({description:"Defaults to false: insert after the last containing line. True: insert before the first containing line. The anchor's text and its lines are kept."}))},{additionalProperties:!1}),Bn={name:"insert",description:"Use insert to add new text before or after selected lines while keeping existing text. Insertion is line-based, including for exact-text and SEARCH :match anchors.",promptSnippet:"Make precise file edits by inserting text before or after exact matches or anchors",parameters:fo,source:{field:"path",inherited:!0},anchors:[{field:"anchor",sourceField:"path",kinds:[L,O]}],mutate:d(async(t,e)=>{let n=await t.resolveAnchors("anchor"),r=Z(n,"anchor");if(r!==void 0){let a=On(t,r,e.text,e.before);return{edits:new Map([...a].map(([l,c])=>[l,{changes:c,action:"edited"}]))}}let o=e.before===!0?Ln:de,[i,s]=o(t,n,"anchor",e.text);return{edits:new Map([[i,{changes:[s],action:"edited"}]])}},"mutate")};import{Type as j}from"typebox";var go=j.Object({path:j.Optional(j.String({description:"Source file path, or a returned SEARCH# reference selecting the text to move"})),start:j.Optional(j.String({description:"Anchor or unique exact text. Alone, selects that fragment; a line anchor selects only its line. Required unless path supplies a SEARCH# selection. With end, selects a whole-line range."})),end:j.Optional(j.String({description:"Optional anchor or unique exact text. Range includes start's first line through end's last line, even for SEARCH :match. Mixed types allowed; boundaries must be unique, in one file, and forward-ordered. Omit when start already selects the intended content; do not repeat start. The end line is included, not a stopping point before it."})),target:j.Optional(j.String({description:"Target resource reference or file path; a returned SEARCH# reference may select the destination; defaults to the source"})),targetStart:j.Optional(j.String({description:"Registered anchor or unique exact text in the destination. Required unless target already selects one destination range. Without targetEnd, inserts after the last containing line, keeping the selected text. With targetEnd, replacement starts at the first containing line. SEARCH :match also uses these line boundaries."})),targetEnd:j.Optional(j.String({description:"Optional inclusive destination end. Replaces whole lines through the last line containing this anchor, including SEARCH :match. May differ in type from targetStart; both must resolve uniquely in the target file and in forward order. Omit to insert after targetStart instead."}))},{additionalProperties:!1}),Nn={name:"move",description:"Use move to relocate existing text within or between files. Select the source and destination without reproducing the text in your call. The selected text is removed from the source and inserted at the destination, or replaces a destination range.",promptSnippet:"Make precise file edits by moving text within or between files using exact matches or anchors",parameters:go,source:{field:"path",inherited:!0,targets:[{field:"target",fallbackTo:"path"}]},anchors:[{field:"start",sourceField:"path",kinds:[L,O]},{field:"end",sourceField:"path",kinds:[L,O],optional:!0},{field:"targetStart",sourceField:"target",kinds:[L,O]},{field:"targetEnd",sourceField:"target",kinds:[L,O],optional:!0}],pair:["start","end"],mutate:d(async(t,e)=>{let n=await t.resolveAnchors("start"),r=e.end===void 0?void 0:await t.resolveAnchors("end"),o=W(t,n,r,"start","end"),i=t.documentFor(o.source).text(o),s=Te(t,o),a=await t.resolveAnchors("targetStart"),l,c;if(e.targetEnd===void 0)[l,c]=de(t,a,"targetStart",i);else{let p=await t.resolveAnchors("targetEnd"),m=W(t,a,p,"targetStart","targetEnd");l=m.source,c=ee(t,m,i)}if(o.source===l&&ho(s,c))throw new Error("Move target must not overlap or touch its source range.");return o.source===l?{edits:new Map([[l,{changes:[s,c],action:"edited"}]])}:{edits:new Map([[o.source,{changes:[s],action:"edited"}],[l,{changes:[c],action:"edited"}]])}},"mutate")};function ho(t,e){return t.from<=e.to&&e.from<=t.to}d(ho,"rangesTouch");import{Type as K}from"typebox";var mo=K.Object({path:K.Optional(K.String({description:"Source resource reference or file path. A returned SEARCH# reference can select replacement ranges."})),start:K.Optional(K.String({description:"Anchor or unique exact text. Alone, selects that fragment; a line anchor selects only its line. Required unless path supplies a SEARCH# selection. With end, selects a whole-line range."})),end:K.Optional(K.String({description:"Optional anchor or unique exact text. Range includes start's first line through end's last line, even for SEARCH :match. Mixed types allowed; boundaries must be unique, in one file, and forward-ordered. Omit when start already selects the intended content; do not repeat start. The end line is included, not a stopping point before it."})),text:K.String({description:"Replacement text. Empty text removes the selection; a whole-line selection removes its lines without inserting a blank line. Adjacent unselected lines are kept."})},{additionalProperties:!1}),_n={name:"replace",description:"Use replace to change an existing text fragment, an inclusive line range, or every selected search match. Exact text must be unique; SEARCH#...:all:match selects every returned match for replacement.",promptSnippet:"Make precise file edits by replacing text using exact matches or anchors",parameters:mo,source:{field:"path",inherited:!0},anchors:[{field:"start",sourceField:"path",kinds:[L,O]},{field:"end",sourceField:"path",kinds:[L,O],optional:!0}],pair:["start","end"],mutate:d(async(t,e)=>{let n=await t.resolveAnchors("start"),r=Z(n,"start");if(e.end===void 0&&r!==void 0){let s=_e(t,r,e.text);return{edits:new Map([...s].map(([a,l])=>[a,{changes:l,action:"edited"}]))}}let o=e.end===void 0?void 0:await t.resolveAnchors("end"),i=W(t,n,o,"start","end");return{edits:new Map([[i.source,{changes:[ee(t,i,e.text)],action:"edited"}]])}},"mutate")};import{Type as dt}from"typebox";var xo=dt.Object({path:dt.String({description:"Path to the file to create or overwrite"}),content:dt.String({description:"File content"})},{additionalProperties:!1}),jn={name:"write",description:"Use write to create a new file or deliberately replace a file's entire contents. Supply the complete new text; existing contents are overwritten.",promptSnippet:"Create or overwrite files",parameters:xo,source:{field:"path"},anchors:[],mutate:d((t,e)=>({edits:new Map([[e.path,{changes:[t.sourceDocument.replaceAll(e.content)],action:"overwritten"}]])}),"mutate")};function Hn(t,e){e.addMutationTool(jn),e.addMutationTool(_n),e.addMutationTool(Bn),e.addMutationTool(Fn),e.addMutationTool(Dn),e.addMutationTool(Nn)}d(Hn,"registerTextEditorTools");async function To(t){let e=await st(t);It(t),process.argv.includes("--old-tools")||Hn(t,e),mn(t,e)}d(To,"registerTextEditor");export{To as default};