pi-agent-ide 0.2.0 → 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 (494) hide show
  1. package/CHANGELOG.md +57 -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-N34ATN52.js +1 -0
  16. package/dist/{chunk-PETQCA7G.js → chunk-P6T3Q7LB.js} +1 -1
  17. package/dist/chunk-QIJMV2P2.js +2 -0
  18. package/dist/chunk-QJFRAMK7.js +2 -0
  19. package/dist/{chunk-2SKAED2I.js → chunk-RAZOACDD.js} +2 -2
  20. package/dist/chunk-RIGRP3FD.js +1 -0
  21. package/dist/chunk-S3ZPXWX7.js +2 -0
  22. package/dist/{chunk-266RH77Z.js → chunk-THSCUT2L.js} +1 -1
  23. package/dist/{chunk-EEH4WYI7.js → chunk-WNMGUALD.js} +1 -1
  24. package/dist/chunk-WZI4YC2O.js +1 -0
  25. package/dist/{chunk-5A25RATC.js → chunk-X6MPU7UO.js} +3 -3
  26. package/dist/{chunk-QNZVPFSP.js → chunk-XF5PVZOS.js} +1 -1
  27. package/dist/{chunk-SJYDLHEF.js → chunk-ZXN3TWWW.js} +1 -1
  28. package/dist/entry-0.js +1 -1
  29. package/dist/entry-10.js +1 -1
  30. package/dist/entry-11.js +1 -1
  31. package/dist/entry-13.js +1 -1
  32. package/dist/entry-14.js +1 -1
  33. package/dist/entry-18.js +1 -1
  34. package/dist/entry-19.js +1 -1
  35. package/dist/entry-20.js +1 -1
  36. package/dist/entry-21.js +2 -1
  37. package/dist/entry-22.js +1 -1
  38. package/dist/entry-23.js +1 -1
  39. package/dist/entry-24.js +1 -1
  40. package/dist/entry-25.js +1 -1
  41. package/dist/entry-26.js +7 -1
  42. package/dist/entry-27.js +1 -1
  43. package/dist/entry-28.js +1 -1
  44. package/dist/entry-29.js +1 -1
  45. package/dist/entry-30.js +1 -1
  46. package/dist/entry-31.js +4 -1
  47. package/dist/entry-32.js +8 -1
  48. package/dist/entry-33.js +1 -1
  49. package/dist/entry-34.js +1 -1
  50. package/dist/entry-35.js +1 -1
  51. package/dist/entry-36.js +1 -1
  52. package/dist/entry-37.js +1 -1
  53. package/dist/entry-38.js +1 -1
  54. package/dist/entry-39.js +1 -1
  55. package/dist/entry-4.js +1 -1
  56. package/dist/entry-40.js +14 -1
  57. package/dist/entry-41.js +1 -1
  58. package/dist/entry-42.js +1 -1
  59. package/dist/entry-43.js +1 -1
  60. package/dist/entry-44.js +1 -1
  61. package/dist/entry-45.js +7 -1
  62. package/dist/entry-46.js +11 -1
  63. package/dist/entry-47.js +1 -1
  64. package/dist/entry-48.js +1 -1
  65. package/dist/entry-49.js +1 -1
  66. package/dist/entry-50.js +1 -1
  67. package/dist/entry-51.js +1 -1
  68. package/dist/entry-52.js +1 -1
  69. package/dist/entry-53.js +1 -0
  70. package/dist/entry-54.js +0 -1
  71. package/dist/entry-55.js +1 -0
  72. package/dist/entry-56.js +0 -1
  73. package/dist/entry-57.js +1 -1
  74. package/dist/entry-58.js +1 -1
  75. package/dist/entry-59.js +1 -1
  76. package/dist/entry-60.js +1 -1
  77. package/dist/entry-61.js +1 -1
  78. package/dist/entry-62.js +1 -0
  79. package/dist/entry-63.js +0 -1
  80. package/dist/entry-64.js +1 -0
  81. package/dist/entry-65.js +0 -1
  82. package/dist/entry-66.js +1 -1
  83. package/dist/entry-67.js +1 -1
  84. package/dist/entry-68.js +1 -1
  85. package/dist/entry-69.js +59 -1
  86. package/dist/entry-70.js +4 -1
  87. package/dist/entry-71.js +1 -1
  88. package/dist/entry-72.js +29 -1
  89. package/dist/entry-73.js +2 -1
  90. package/dist/entry-74.js +1 -1
  91. package/dist/entry-75.js +1 -1
  92. package/dist/entry-76.js +1 -1
  93. package/dist/entry-77.js +3 -1
  94. package/dist/entry-78.js +1 -1
  95. package/dist/entry-79.js +1 -1
  96. package/dist/entry-80.js +1 -0
  97. package/dist/pi-agent-ide.js +2 -13
  98. package/docs/configuration.md +57 -1
  99. package/docs/extensions.md +4 -2
  100. package/docs/generated/tool-catalog/cmake.md +5 -5
  101. package/docs/generated/tool-catalog/csharp.md +5 -5
  102. package/docs/generated/tool-catalog/css.md +7 -7
  103. package/docs/generated/tool-catalog/dart.md +9 -0
  104. package/docs/generated/tool-catalog/dockerfile.md +5 -5
  105. package/docs/generated/tool-catalog/elixir.md +9 -0
  106. package/docs/generated/tool-catalog/html.md +7 -6
  107. package/docs/generated/tool-catalog/index.md +9 -0
  108. package/docs/generated/tool-catalog/javascript.md +8 -8
  109. package/docs/generated/tool-catalog/json.md +7 -7
  110. package/docs/generated/tool-catalog/julia.md +8 -0
  111. package/docs/generated/tool-catalog/kotlin.md +6 -5
  112. package/docs/generated/tool-catalog/markdown.md +6 -6
  113. package/docs/generated/tool-catalog/powershell.md +9 -0
  114. package/docs/generated/tool-catalog/python.md +6 -6
  115. package/docs/generated/tool-catalog/r.md +9 -0
  116. package/docs/generated/tool-catalog/scala.md +9 -0
  117. package/docs/generated/tool-catalog/svelte.md +9 -0
  118. package/docs/generated/tool-catalog/typescript.md +9 -8
  119. package/docs/generated/tool-catalog/vue.md +9 -0
  120. package/docs/generated/tool-catalog/yaml.md +6 -6
  121. package/docs/generated/tool-catalog/zig.md +9 -0
  122. package/docs/tools.md +1 -1
  123. package/node_modules/pi-agent-doctor/package.json +10 -3
  124. package/node_modules/pi-agent-doctor/runtime/entry-20.js +1 -0
  125. package/node_modules/pi-agent-doctor/src/catalog.ts +27 -1
  126. package/node_modules/pi-agent-doctor/src/evidence.ts +118 -0
  127. package/node_modules/pi-agent-doctor/src/executable.ts +63 -17
  128. package/node_modules/pi-agent-filesystem/index.ts +2 -2
  129. package/node_modules/pi-agent-filesystem/package.json +7 -7
  130. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  131. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  132. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  133. package/node_modules/pi-agent-filesystem-text/runtime/entry-24.js +2 -0
  134. package/node_modules/pi-agent-ide-ast/package.json +11 -11
  135. package/node_modules/pi-agent-ide-ast/runtime/entry-25.js +0 -1
  136. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +2 -0
  137. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +3 -0
  138. package/node_modules/pi-agent-ide-ast/src/ast/outline.ts +92 -19
  139. package/node_modules/pi-agent-ide-ast/src/extension.ts +9 -14
  140. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +60 -0
  141. package/node_modules/pi-agent-ide-ast/src/scope-resolver.ts +1 -1
  142. package/node_modules/pi-agent-ide-changes/index.ts +1 -5
  143. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  144. package/node_modules/pi-agent-ide-changes/runtime/entry-27.js +0 -1
  145. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +1 -7
  146. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +1 -5
  147. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  148. package/node_modules/pi-agent-ide-formatter/src/catalog.ts +131 -13
  149. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +12 -7
  150. package/node_modules/pi-agent-ide-formatter/src/registry.ts +20 -8
  151. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  152. package/node_modules/pi-agent-ide-languages/src/languages.ts +15 -0
  153. package/node_modules/pi-agent-ide-lint/index.ts +4 -1
  154. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  155. package/node_modules/pi-agent-ide-lint/src/catalog.ts +196 -39
  156. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +23 -3
  157. package/node_modules/pi-agent-ide-lint/src/diagnostics.ts +73 -33
  158. package/node_modules/pi-agent-ide-lint/src/registry.ts +20 -8
  159. package/node_modules/pi-agent-ide-lsp/index.ts +1 -12
  160. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  161. package/node_modules/pi-agent-ide-lsp/runtime/entry-32.js +2 -0
  162. package/node_modules/pi-agent-ide-lsp/src/catalog.ts +161 -7
  163. package/node_modules/pi-agent-ide-lsp/src/diagnostic-source.ts +10 -10
  164. package/node_modules/pi-agent-ide-lsp/src/doctor-plugin.ts +2 -4
  165. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +162 -12
  166. package/node_modules/pi-agent-ide-lsp/src/lsp/file-watchers.ts +88 -0
  167. package/node_modules/pi-agent-ide-lsp/src/lsp/initialization-options.ts +14 -0
  168. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +8 -4
  169. package/node_modules/pi-agent-ide-lsp/src/lsp/registry.ts +69 -34
  170. package/node_modules/pi-agent-ide-lsp/src/lsp/transport-writer.ts +24 -0
  171. package/node_modules/pi-agent-ide-lsp/src/lsp/types.ts +5 -0
  172. package/node_modules/pi-agent-image/package.json +3 -3
  173. package/node_modules/pi-agent-image/src/image-converter.ts +1 -1
  174. package/node_modules/pi-agent-invariant/package.json +2 -2
  175. package/node_modules/pi-agent-pdf/package.json +3 -3
  176. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +1 -1
  177. package/node_modules/pi-agent-read/package.json +11 -11
  178. package/node_modules/pi-agent-read/runtime/entry-39.js +0 -1
  179. package/node_modules/pi-agent-read/runtime/entry-40.js +2 -0
  180. package/node_modules/pi-agent-read/src/api/rendering.ts +3 -0
  181. package/node_modules/pi-agent-read/src/core/read-core.ts +6 -26
  182. package/node_modules/pi-agent-read/src/core/tools/read/native-resource-renderer.ts +74 -0
  183. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +28 -7
  184. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +35 -30
  185. package/node_modules/pi-agent-resource/package.json +2 -2
  186. package/node_modules/pi-agent-resource/src/content-conversion/content-description.ts +1 -8
  187. package/node_modules/pi-agent-search/package.json +7 -7
  188. package/node_modules/pi-agent-search/runtime/entry-44.js +0 -1
  189. package/node_modules/pi-agent-search/src/core/extension.ts +7 -5
  190. package/node_modules/pi-agent-search/src/core/search-core.ts +10 -0
  191. package/node_modules/pi-agent-search-text/index.ts +42 -33
  192. package/node_modules/pi-agent-search-text/package.json +9 -9
  193. package/node_modules/pi-agent-search-text/runtime/entry-46.js +1 -0
  194. package/node_modules/pi-agent-search-text/src/file-search.ts +9 -1
  195. package/node_modules/pi-agent-search-text/src/resolvers.ts +1 -1
  196. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -0
  197. package/node_modules/pi-agent-search-text/src/search-session.ts +48 -0
  198. package/node_modules/pi-agent-text/package.json +3 -3
  199. package/node_modules/pi-agent-text/runtime/entry-48.js +1 -0
  200. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  201. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  202. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-49.js +2 -0
  203. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  204. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-50.js +0 -1
  205. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +2 -0
  206. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +2 -6
  207. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  208. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-52.js +0 -1
  209. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-53.js +2 -0
  210. package/node_modules/pi-agent-text-editor/package.json +22 -22
  211. package/node_modules/pi-agent-text-editor/runtime/entry-68.js +0 -1
  212. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +3 -0
  213. package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +71 -1
  214. package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +4 -12
  215. package/node_modules/pi-agent-text-editor/src/core/extension.ts +7 -9
  216. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +27 -2
  217. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +38 -0
  218. package/node_modules/pi-agent-text-editor/src/core/mutation-result/final-state-fragment.ts +2 -0
  219. package/node_modules/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +81 -0
  220. package/node_modules/pi-agent-text-editor/src/core/text-anchor-registry.ts +5 -2
  221. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +23 -0
  222. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +5 -9
  223. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +54 -14
  224. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +45 -43
  225. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +18 -8
  226. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +7 -4
  227. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +13 -5
  228. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +18 -8
  229. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -5
  230. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +2 -1
  231. package/node_modules/pi-agent-text-editor-argument-order/package.json +3 -3
  232. package/node_modules/pi-agent-text-editor-overwrite/package.json +4 -4
  233. package/node_modules/pi-agent-text-editor-renderer/index.ts +5 -1
  234. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  235. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +7 -0
  236. package/node_modules/pi-agent-text-editor-renderer/src/diff-renderer.ts +1 -1
  237. package/node_modules/pi-agent-text-editor-renderer/src/diff-viewport.ts +11 -2
  238. package/node_modules/pi-agent-text-editor-renderer/src/frozen-viewport.ts +140 -52
  239. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +52 -4
  240. package/node_modules/pi-agent-text-editor-renderer/src/mutation-result.ts +53 -1
  241. package/node_modules/pi-agent-text-editor-renderer/src/persisted-result.ts +8 -2
  242. package/node_modules/pi-agent-text-editor-renderer/src/render-resource.ts +10 -0
  243. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +5 -3
  244. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  245. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +2 -0
  246. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  247. package/node_modules/pi-agent-tool-call-interception/src/index.ts +3 -0
  248. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  249. package/node_modules/pi-agent-tool-ui/runtime/entry-75.js +1 -0
  250. package/node_modules/pi-agent-web/index.ts +1 -6
  251. package/node_modules/pi-agent-web/package.json +7 -7
  252. package/node_modules/pi-agent-web-html/package.json +3 -3
  253. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  254. package/node_modules/pi-agent-web-image/package.json +4 -4
  255. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  256. package/node_modules/pi-agent-web-text/package.json +4 -4
  257. package/node_modules/pi-agent-web-text/runtime/entry-80.js +2 -0
  258. package/package.json +35 -35
  259. package/src/api/plugin-protocol.ts +2 -0
  260. package/src/api/text-editor.ts +7 -0
  261. package/src/api/tool-config/formatters.json +70 -12
  262. package/src/api/tool-config/linters.json +148 -66
  263. package/src/api/tool-config/lsp-servers.json +142 -7
  264. package/src/api/tool-config.ts +60 -24
  265. package/src/code-view/diagnostic-view.ts +14 -10
  266. package/src/composite/builtin-extensions.ts +148 -66
  267. package/src/composite/extensions-config.ts +18 -0
  268. package/src/core/diagnostic-entry.ts +94 -0
  269. package/src/core/diagnostic-store.ts +43 -21
  270. package/src/core/extension.ts +39 -17
  271. package/src/doctor/config-writer.ts +14 -1
  272. package/src/doctor/discovery.ts +13 -68
  273. package/src/doctor/run.ts +33 -1
  274. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +2 -2
  275. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  276. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  277. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  278. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  279. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-24.js +2 -0
  280. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-21.js +2 -0
  281. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +1 -6
  282. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  283. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  284. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  285. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  286. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  287. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  288. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-80.js +2 -0
  289. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +2 -0
  290. package/src/extensions/pi-agent-read/package.json +11 -11
  291. package/src/extensions/pi-agent-read/runtime/entry-39.js +0 -1
  292. package/src/extensions/pi-agent-read/runtime/entry-40.js +2 -0
  293. package/src/extensions/pi-agent-read/src/api/rendering.ts +3 -0
  294. package/src/extensions/pi-agent-read/src/core/read-core.ts +6 -26
  295. package/src/extensions/pi-agent-read/src/core/tools/read/native-resource-renderer.ts +74 -0
  296. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +28 -7
  297. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +35 -30
  298. package/src/extensions/pi-agent-search/package.json +7 -7
  299. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +42 -33
  300. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  301. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-46.js +1 -0
  302. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +1 -0
  303. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +9 -1
  304. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +1 -1
  305. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -0
  306. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +48 -0
  307. package/src/extensions/pi-agent-search/runtime/entry-44.js +0 -1
  308. package/src/extensions/pi-agent-search/runtime/entry-45.js +2 -0
  309. package/src/extensions/pi-agent-search/src/core/extension.ts +7 -5
  310. package/src/extensions/pi-agent-search/src/core/search-core.ts +10 -0
  311. package/src/extensions/pi-agent-text-editor/package.json +22 -22
  312. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  313. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-49.js +2 -0
  314. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  315. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-50.js +0 -1
  316. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +2 -0
  317. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +2 -6
  318. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  319. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-52.js +0 -1
  320. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +2 -0
  321. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/package.json +3 -3
  322. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/package.json +4 -4
  323. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +5 -1
  324. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  325. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +7 -0
  326. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-renderer.ts +1 -1
  327. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-viewport.ts +11 -2
  328. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/frozen-viewport.ts +140 -52
  329. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +52 -4
  330. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-result.ts +53 -1
  331. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/persisted-result.ts +8 -2
  332. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/render-resource.ts +10 -0
  333. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +5 -3
  334. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  335. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +2 -0
  336. package/src/extensions/pi-agent-text-editor/runtime/entry-68.js +0 -1
  337. package/src/extensions/pi-agent-text-editor/runtime/entry-69.js +2 -0
  338. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +3 -0
  339. package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +71 -1
  340. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +4 -12
  341. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +7 -9
  342. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +27 -2
  343. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +38 -0
  344. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/final-state-fragment.ts +2 -0
  345. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +81 -0
  346. package/src/extensions/pi-agent-text-editor/src/core/text-anchor-registry.ts +5 -2
  347. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +23 -0
  348. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +5 -9
  349. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +54 -14
  350. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +45 -43
  351. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +18 -8
  352. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +7 -4
  353. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +13 -5
  354. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +18 -8
  355. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -5
  356. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +2 -1
  357. package/src/pi-agent-ide.ts +11 -0
  358. package/src/plugins/pi-agent-ide-ast/package.json +11 -11
  359. package/src/plugins/pi-agent-ide-ast/runtime/entry-25.js +0 -1
  360. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +2 -0
  361. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +3 -0
  362. package/src/plugins/pi-agent-ide-ast/src/ast/outline.ts +92 -19
  363. package/src/plugins/pi-agent-ide-ast/src/extension.ts +9 -14
  364. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +60 -0
  365. package/src/plugins/pi-agent-ide-ast/src/scope-resolver.ts +1 -1
  366. package/src/plugins/pi-agent-ide-changes/index.ts +1 -5
  367. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  368. package/src/plugins/pi-agent-ide-changes/runtime/entry-27.js +0 -1
  369. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +1 -7
  370. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +1 -5
  371. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +1 -8
  372. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  373. package/src/plugins/pi-agent-ide-formatter/src/catalog.ts +131 -13
  374. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +12 -7
  375. package/src/plugins/pi-agent-ide-formatter/src/registry.ts +20 -8
  376. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  377. package/src/plugins/pi-agent-ide-languages/src/languages.ts +15 -0
  378. package/src/plugins/pi-agent-ide-lint/index.ts +4 -1
  379. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  380. package/src/plugins/pi-agent-ide-lint/src/catalog.ts +196 -39
  381. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +23 -3
  382. package/src/plugins/pi-agent-ide-lint/src/diagnostics.ts +73 -33
  383. package/src/plugins/pi-agent-ide-lint/src/registry.ts +20 -8
  384. package/src/plugins/pi-agent-ide-lsp/index.ts +1 -12
  385. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  386. package/src/plugins/pi-agent-ide-lsp/runtime/entry-32.js +2 -0
  387. package/src/plugins/pi-agent-ide-lsp/src/catalog.ts +161 -7
  388. package/src/plugins/pi-agent-ide-lsp/src/diagnostic-source.ts +10 -10
  389. package/src/plugins/pi-agent-ide-lsp/src/doctor-plugin.ts +2 -4
  390. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +162 -12
  391. package/src/plugins/pi-agent-ide-lsp/src/lsp/file-watchers.ts +88 -0
  392. package/src/plugins/pi-agent-ide-lsp/src/lsp/initialization-options.ts +14 -0
  393. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +8 -4
  394. package/src/plugins/pi-agent-ide-lsp/src/lsp/registry.ts +69 -34
  395. package/src/plugins/pi-agent-ide-lsp/src/lsp/transport-writer.ts +24 -0
  396. package/src/plugins/pi-agent-ide-lsp/src/lsp/types.ts +5 -0
  397. package/src/post-edit/gate.ts +44 -15
  398. package/src/toolchain/types.ts +4 -0
  399. package/dist/chunk-34ZQTTU2.js +0 -2
  400. package/dist/chunk-476MR2QB.js +0 -1
  401. package/dist/chunk-4KQOODGE.js +0 -13
  402. package/dist/chunk-4SQQKEVD.js +0 -16
  403. package/dist/chunk-52BM6J6I.js +0 -6
  404. package/dist/chunk-5BWUVAR4.js +0 -1
  405. package/dist/chunk-6DN7NO7L.js +0 -1
  406. package/dist/chunk-6SMFVLTY.js +0 -1
  407. package/dist/chunk-7NDBZ4WX.js +0 -1
  408. package/dist/chunk-AP7Z3VWC.js +0 -1
  409. package/dist/chunk-BYWAG6X3.js +0 -6
  410. package/dist/chunk-E4SECPF4.js +0 -1
  411. package/dist/chunk-EW2KVKCN.js +0 -2
  412. package/dist/chunk-F6SESI3P.js +0 -4
  413. package/dist/chunk-GTK5AREE.js +0 -2
  414. package/dist/chunk-HOBTFFQR.js +0 -1
  415. package/dist/chunk-IMVCVPMP.js +0 -3
  416. package/dist/chunk-IOCABSRL.js +0 -1
  417. package/dist/chunk-KP37XTDI.js +0 -1
  418. package/dist/chunk-KYVOMBO5.js +0 -1
  419. package/dist/chunk-LFV6G5Z3.js +0 -1
  420. package/dist/chunk-MB6VVVAF.js +0 -2
  421. package/dist/chunk-NI2NK4JU.js +0 -1
  422. package/dist/chunk-OIL6BB2S.js +0 -33
  423. package/dist/chunk-PODWLGNO.js +0 -6
  424. package/dist/chunk-QW5O42QJ.js +0 -2
  425. package/dist/chunk-SSZB66C3.js +0 -3
  426. package/dist/chunk-TG6H6EOI.js +0 -1
  427. package/dist/chunk-TNWYEXFG.js +0 -1
  428. package/dist/chunk-U4D6FT66.js +0 -1
  429. package/dist/chunk-VUNCBASK.js +0 -10
  430. package/dist/chunk-VWVLBOMU.js +0 -8
  431. package/dist/chunk-W3XYKJ5H.js +0 -1
  432. package/dist/chunk-XGUAL3CA.js +0 -1
  433. package/dist/chunk-YQTLJ5ZV.js +0 -58
  434. package/node_modules/pi-agent-filesystem/runtime/entry-20.js +0 -2
  435. package/node_modules/pi-agent-ide-ast/runtime/entry-24.js +0 -1
  436. package/node_modules/pi-agent-ide-changes/runtime/entry-26.js +0 -1
  437. package/node_modules/pi-agent-image/runtime/entry-32.js +0 -1
  438. package/node_modules/pi-agent-read/src/core/tools/read/views.ts +0 -29
  439. package/node_modules/pi-agent-resource/runtime/entry-40.js +0 -1
  440. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-48.js +0 -2
  441. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-49.js +0 -1
  442. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-51.js +0 -1
  443. package/node_modules/pi-agent-text-editor/runtime/entry-53.js +0 -1
  444. package/node_modules/pi-agent-tool-call-interception/runtime/entry-73.js +0 -1
  445. package/node_modules/pi-agent-web/runtime/entry-75.js +0 -2
  446. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-21.js +0 -2
  447. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-20.js +0 -2
  448. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-76.js +0 -2
  449. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-75.js +0 -2
  450. package/src/extensions/pi-agent-read/runtime/entry-35.js +0 -1
  451. package/src/extensions/pi-agent-read/src/core/tools/read/views.ts +0 -29
  452. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-45.js +0 -2
  453. package/src/extensions/pi-agent-search/runtime/entry-41.js +0 -1
  454. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-48.js +0 -2
  455. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-49.js +0 -1
  456. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-51.js +0 -1
  457. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/runtime/entry-69.js +0 -2
  458. package/src/extensions/pi-agent-text-editor/runtime/entry-53.js +0 -1
  459. package/src/plugins/pi-agent-ide-ast/runtime/entry-24.js +0 -1
  460. package/src/plugins/pi-agent-ide-changes/runtime/entry-26.js +0 -1
  461. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-21.js +0 -0
  462. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-22.js +0 -0
  463. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-23.js +0 -0
  464. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-28.js +0 -0
  465. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-29.js +0 -0
  466. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-30.js +0 -0
  467. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-31.js +0 -0
  468. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-33.js +0 -0
  469. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-34.js +0 -0
  470. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-35.js +0 -0
  471. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-41.js +0 -0
  472. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-45.js +0 -0
  473. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-47.js +0 -0
  474. /package/node_modules/{pi-agent-text-editor-argument-order → pi-agent-text-editor}/runtime/entry-69.js +0 -0
  475. /package/node_modules/{pi-agent-text-editor-overwrite → pi-agent-text-editor-argument-order}/runtime/entry-70.js +0 -0
  476. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor-overwrite}/runtime/entry-71.js +0 -0
  477. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-72.js +0 -0
  478. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-74.js +0 -0
  479. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-76.js +0 -0
  480. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-77.js +0 -0
  481. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-78.js +0 -0
  482. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-79.js +0 -0
  483. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-22.js +0 -0
  484. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-23.js +0 -0
  485. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-77.js +0 -0
  486. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-78.js +0 -0
  487. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-79.js +0 -0
  488. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-overwrite → pi-agent-text-editor-argument-order}/runtime/entry-70.js +0 -0
  489. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-renderer → pi-agent-text-editor-overwrite}/runtime/entry-71.js +0 -0
  490. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-72.js +0 -0
  491. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-28.js +0 -0
  492. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-29.js +0 -0
  493. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-30.js +0 -0
  494. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-31.js +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2 — 2026-09-08
4
+
5
+ ### Agent guidance
6
+
7
+ - Clarify tool descriptions and input parameters so agents can choose the right read, search, or edit operation. Keep tool-specific details with each tool and shared workflow rules in the system prompt.
8
+ - Explain how to reuse anchors, recover from broadened searches, and batch independent edits without retrying changes that already applied.
9
+
10
+ ### Editing and search
11
+
12
+ - Fix ranges that mix exact text, line anchors, and search references. Explicit start and end anchors select inclusive whole lines; insert, copy, and move destinations use the containing line boundaries.
13
+ - Fix empty replacements of whole-line selections so they remove the lines instead of leaving a blank line.
14
+ - Preserve unselected line breaks when deleting exact search matches at the end of a file.
15
+ - Fix `files:` glob matching, including nested paths, basename patterns, character classes, and brace alternatives.
16
+ - Report applied edit counts and formatting outcomes. Group repeated replacements into a compact summary with every affected file, and rerun referenced searches to report remaining matches within their original scope.
17
+
18
+ ### Reading
19
+
20
+ - Show a compact, source-numbered AST overview when a supported code file exceeds the read limit. Reduce detail until it fits, and keep ordinary truncation when no usable outline is available.
21
+ - Fix AST outline positions for CRLF text and characters such as emoji.
22
+ - Remove the standalone `lines` view. Use `anchors` for source line numbers with edit references.
23
+ - Preserve Pi's native read presentation for skills, agent context files, and Pi documentation when no extra views are requested.
24
+
25
+ ### Interface and configuration
26
+
27
+ - Keep local diffs aligned after formatting shifts lines. Report changes outside the displayed area or changes that cannot be assigned to one edit instead of showing misleading hunks.
28
+ - Show formatting status alongside diffs and visible background diagnostic summaries with per-file counts and expandable provider details. Send automatic notifications only for actual findings; keep pending, unavailable, and empty reports out of both the chat and the agent's context.
29
+ - Add `noAnimations` and `noPostProcessing` settings, with matching `--pi-agent-ide-no-animations` and `--pi-agent-ide-no-post-processing` flags. These can disable edit animations or automatic post-edit checks and formatting while keeping explicit reads and requested edits available.
30
+ - Name the actual formatter, linter, or language-server executable in formatting results and diagnostic messages. Show diagnostic tool names beside their counts even when the entry is collapsed.
31
+ - Deliver new diagnostic findings immediately to the chat and agent. Late findings wake an idle agent without waiting for another user message; duplicate and empty reports stay silent.
32
+ - Load built-in extension entry modules only when selected, avoiding imports for disabled built-ins.
33
+
34
+ ## 0.2.1 — 2026-09-07
35
+
36
+ ### Stability and Windows
37
+
38
+ - Keep Pi running when a language server closes its transport during initialization, requests, or notifications. Failed LSP connections remain unavailable rather than appearing healthy.
39
+ - Resolve Windows executable suffixes and project-local command shims consistently, including paths with spaces and Python virtual environment `Scripts` directories.
40
+ - Stop treating every `package.json` as a request to install JSONLint. Doctor now uses JSONLint settings or an explicit dependency as evidence.
41
+
42
+ ### Expanded language support
43
+
44
+ - Add and correct built-ins for Kotlin, Swift, Dart, PowerShell, Ruby, Lua, R, Scala, Elixir, Zig, Julia, frontend frameworks, and infrastructure formats.
45
+ - Match native basenames such as Dockerfile and CMakeLists.txt. Limit Angular language support to projects with its native root marker, and use the correct language IDs for JSX and TSX.
46
+ - Support language-server configuration and workspace-folder requests, file watchers, and requested save notifications. Preserve diagnostic versions when file content has not changed.
47
+ - Support project-relative paths in LSP initialization options, multiline diagnostic reports, zero-based tool columns, and diagnostics at the end of a file.
48
+ - Parse line-oriented diagnostics from both output streams, including JSONLint errors written to stderr.
49
+ - Installed tool versions and native project settings remain prerequisites; support does not imply every tool version or operating system has been verified.
50
+
51
+ ### Native language toolchains
52
+
53
+ - Prefer native formatter and linter settings when choosing built-ins. Find project tools in Python virtual environments and Composer's `vendor/bin`, as well as `node_modules/.bin`.
54
+ - Report missing native tools through Doctor instead of silently choosing an unrelated formatter.
55
+ - Fix CSharpier detection and diagnostic commands or parsers for .NET, Go, PHP, HTML, CSS, and Java. Keep project-wide lint findings attached to the correct file.
56
+ - Treat a failed linter with no parsed findings as a failure, not a clean check.
57
+ - Use the language server's advertised diagnostic mode, fixing Java and Go servers that publish diagnostics without supporting pull requests.
58
+ - Verify native mini-projects with real formatting, lint, language diagnostics, and separate compiler or behavior checks before and after formatting.
59
+
3
60
  ## 0.2.0 — 2026-09-05
4
61
 
5
62
  ### Editing and search
@@ -1,4 +1,4 @@
1
- import{d as w,h as P}from"./chunk-VSP2QQPQ.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as _}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as D,parse as z}from"partial-json";function B(o,e=D.ALL){if(!(!o||o.trim().length===0))try{let t=z(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(B,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),s=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),i=e.filterEntries?.(s,t)??s,d=new Set(i.map(c=>c.index));for(let c of s)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of i)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as L}from"@earendil-works/pi-ai";var M=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function N(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((s,i)=>{if(!s)return;let d=i.modelRegistry.getProvider(s.provider);if(!d)return;let u=r.get(s.provider);if(u){if(u.subscribers.add(a),u.api===s.api&&d.streamSimple===u.wrapper)return;u.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:u.wrapper});return}let m=d.streamSimple[M];if(m){if(m.subscribers.add(a),r.set(s.provider,m),m.api===s.api)return;m.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>F(c,p,v,C,g),"wrapper"),E={api:s.api,delegate:c,wrapper:b,subscribers:g};b[M]=E;let f=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...f,api:s.api,streamSimple:b}),r.set(s.provider,E)},"install");o.on("before_provider_request",(s,i)=>{a.context=i,l(i.model,i)}),o.on("turn_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("agent_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("session_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("model_select",(s,i)=>{a.context=i,l(s.model,i)}),o.on("session_shutdown",()=>{for(let[s,i]of r)i.subscribers.delete(a),i.subscribers.size===0&&o.unregisterProvider(s);r.clear(),a.context=void 0})}y(N,"registerStreamingInterceptorProvider");function F(o,e,t,n,r){let a=L(),l=new AbortController,s=n?.signal,i=!1,d=Q(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(f=>{for(let p of r)p.markStreamEventProcessed(f)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return s&&(s.aborted?l.abort():s.addEventListener("abort",E,{once:!0})),(async()=>{try{let f=o(e,t,{...n,signal:l.signal});for await(let p of f){if(i)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),H(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),W(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);i=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};U(a,b,I,u,m,c,g);let{errorMessage:T,...j}=I;a.push({type:"done",reason:"toolUse",message:{...j,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(f){if(i)return;let p=d,v=s?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:f instanceof Error?f.message:String(f)};a.push({type:"error",reason:v,error:C}),a.end()}finally{s?.removeEventListener("abort",E)}})(),a}y(F,"wrapStream");function H(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(H,"rememberStartEvent");function W(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(W,"rememberEndEvent");function U(o,e,t,n,r,a,l){for(let[s,i]of t.content.entries())if(n.has(s)){if(i.type==="text"&&!r.has(s)){let d={type:"text_end",contentIndex:s,content:i.text,partial:t};e(d),o.push(d)}else if(i.type==="thinking"&&!a.has(s)){let d={type:"thinking_end",contentIndex:s,content:i.thinking,partial:t};e(d),o.push(d)}else if(i.type==="toolCall"&&!l.has(s)){let d={type:"toolcall_end",contentIndex:s,toolCall:i,partial:t};e(d),o.push(d)}}}y(U,"emitMissingEndEvents");function Q(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Q,"emptyAssistantMessage");var V="agentic-ide-partial-tool-recovery",$="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
1
+ import{d as w,h as P}from"./chunk-GIRAEVUJ.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as _}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as D,parse as z}from"partial-json";function B(o,e=D.ALL){if(!(!o||o.trim().length===0))try{let t=z(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(B,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),s=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),i=e.filterEntries?.(s,t)??s,d=new Set(i.map(c=>c.index));for(let c of s)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of i)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as L}from"@earendil-works/pi-ai";var M=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function N(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((s,i)=>{if(!s)return;let d=i.modelRegistry.getProvider(s.provider);if(!d)return;let u=r.get(s.provider);if(u){if(u.subscribers.add(a),u.api===s.api&&d.streamSimple===u.wrapper)return;u.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:u.wrapper});return}let m=d.streamSimple[M];if(m){if(m.subscribers.add(a),r.set(s.provider,m),m.api===s.api)return;m.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>F(c,p,v,C,g),"wrapper"),E={api:s.api,delegate:c,wrapper:b,subscribers:g};b[M]=E;let f=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...f,api:s.api,streamSimple:b}),r.set(s.provider,E)},"install");o.on("before_provider_request",(s,i)=>{a.context=i,l(i.model,i)}),o.on("turn_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("agent_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("session_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("model_select",(s,i)=>{a.context=i,l(s.model,i)}),o.on("session_shutdown",()=>{for(let[s,i]of r)i.subscribers.delete(a),i.subscribers.size===0&&o.unregisterProvider(s);r.clear(),a.context=void 0})}y(N,"registerStreamingInterceptorProvider");function F(o,e,t,n,r){let a=L(),l=new AbortController,s=n?.signal,i=!1,d=Q(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(f=>{for(let p of r)p.markStreamEventProcessed(f)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return s&&(s.aborted?l.abort():s.addEventListener("abort",E,{once:!0})),(async()=>{try{let f=o(e,t,{...n,signal:l.signal});for await(let p of f){if(i)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),H(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),W(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);i=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};U(a,b,I,u,m,c,g);let{errorMessage:T,...j}=I;a.push({type:"done",reason:"toolUse",message:{...j,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(f){if(i)return;let p=d,v=s?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:f instanceof Error?f.message:String(f)};a.push({type:"error",reason:v,error:C}),a.end()}finally{s?.removeEventListener("abort",E)}})(),a}y(F,"wrapStream");function H(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(H,"rememberStartEvent");function W(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(W,"rememberEndEvent");function U(o,e,t,n,r,a,l){for(let[s,i]of t.content.entries())if(n.has(s)){if(i.type==="text"&&!r.has(s)){let d={type:"text_end",contentIndex:s,content:i.text,partial:t};e(d),o.push(d)}else if(i.type==="thinking"&&!a.has(s)){let d={type:"thinking_end",contentIndex:s,content:i.thinking,partial:t};e(d),o.push(d)}else if(i.type==="toolCall"&&!l.has(s)){let d={type:"toolcall_end",contentIndex:s,toolCall:i,partial:t};e(d),o.push(d)}}}y(U,"emitMissingEndEvents");function Q(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Q,"emptyAssistantMessage");var V="agentic-ide-partial-tool-recovery",$="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
2
  `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r)return{content:r.content,details:r.details,isError:!0}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=B(a,_.OBJ|_.ARR)??{},s=J(a),i=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:i,toolName:n,args:l,complete:s!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!s&&Object.keys(l).length===0)return;let u=s!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=s??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:i,batchEntries:this.getBatchEntries(i),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let s=!this.completeArgumentContentIndices.has(e.contentIndex),i;s&&(this.completeArgumentContentIndices.add(e.contentIndex),i=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),i}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=O(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=O(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit($,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=Y(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let s={content:[{type:"text",text:e.message.content}],details:w(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:s,...r&&{blockExecution:!0}}),s}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,i=(h.IsObjectNotArray(l)&&h.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(i))for(let d of i)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,s=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],i=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:s,blockedToolCallIds:i,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?ee(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function O(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(O,"toolStreamEventKey");function Y(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(Y,"abortReason");function J(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}y(J,"parseCompleteArguments");function Z(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(i=>h.IsObjectNotArray(i.data)?i.data:i),a=n===void 0?r:r.filter(i=>i.path===n),s=(a.length>0?a:r).flatMap(i=>{let d=i.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(s)]}y(Z,"freshAnchorsAfterRecovery");function X(o,e){let n=o.indexOf(`
3
3
 
4
4
  Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
@@ -1 +1 @@
1
- import{d}from"./chunk-EW2KVKCN.js";import{a as n}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as a}from"typebox/value";var o=e.Function([],e.Unknown()),l=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number()),renderResult:e.Optional(o),preserveTruncatedOutput:e.Optional(e.Boolean())}),s=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),R=e.Object({id:e.String({pattern:"\\S"}),priority:e.Optional(e.Number()),resolve:o}),p=e.Object({view:e.String({pattern:"\\S"}),includes:e.Optional(e.Array(e.String({pattern:"\\S"}))),presenter:e.Object({id:e.String(),present:o}),priority:e.Optional(e.Number())}),u=e.Object({resolvedBy:e.String({pattern:"\\S"}),contentKind:e.Union([e.Literal("text"),e.Literal("any")])}),y=e.Union([e.Object({stage:e.Literal("pre-read"),handler:o}),e.Object({stage:e.Literal("read"),when:u,handler:o}),e.Object({stage:e.Literal("post-read"),handler:o})]);function v(t){if(!a.Check(s,t))return!1;let r=t,i=r.resolver;return typeof i.id=="string"&&i.id.length>0&&typeof i.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}n(v,"isTextTargetResolverRegistration");function f(t){if(!a.Check(l,t))return!1;let r=t;return d(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}n(f,"isResourceResolverRegistration");function T(t){return a.Check(y,t)}n(T,"isReadHandlerRegistration");function S(t){return a.Check(p,t)}n(S,"isReadViewRegistration");function P(t){return a.Check(R,t)}n(P,"isFragmentResolverRegistration");function k(t){return c(t)?t.kind==="not-handled"?!0:t.kind==="failed"?typeof t.message=="string"&&t.message.length>0:t.kind==="resolved"&&typeof t.originLine=="number":!1}n(k,"isReadFragmentResolution");function c(t){return typeof t=="object"&&t!==null}n(c,"isRecord");export{v as a,f as b,T as c,S as d,P as e,k as f};
1
+ import{d}from"./chunk-S3ZPXWX7.js";import{a as n}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as a}from"typebox/value";var o=e.Function([],e.Unknown()),l=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number()),renderResult:e.Optional(o),preserveTruncatedOutput:e.Optional(e.Boolean())}),s=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),R=e.Object({id:e.String({pattern:"\\S"}),priority:e.Optional(e.Number()),resolve:o}),p=e.Object({view:e.String({pattern:"\\S"}),includes:e.Optional(e.Array(e.String({pattern:"\\S"}))),presenter:e.Object({id:e.String(),present:o}),priority:e.Optional(e.Number())}),u=e.Object({resolvedBy:e.String({pattern:"\\S"}),contentKind:e.Union([e.Literal("text"),e.Literal("any")])}),y=e.Union([e.Object({stage:e.Literal("pre-read"),handler:o}),e.Object({stage:e.Literal("read"),when:u,handler:o}),e.Object({stage:e.Literal("post-read"),handler:o})]);function v(t){if(!a.Check(s,t))return!1;let r=t,i=r.resolver;return typeof i.id=="string"&&i.id.length>0&&typeof i.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}n(v,"isTextTargetResolverRegistration");function f(t){if(!a.Check(l,t))return!1;let r=t;return d(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}n(f,"isResourceResolverRegistration");function T(t){return a.Check(y,t)}n(T,"isReadHandlerRegistration");function S(t){return a.Check(p,t)}n(S,"isReadViewRegistration");function P(t){return a.Check(R,t)}n(P,"isFragmentResolverRegistration");function k(t){return c(t)?t.kind==="not-handled"?!0:t.kind==="failed"?typeof t.message=="string"&&t.message.length>0:t.kind==="resolved"&&typeof t.originLine=="number":!1}n(k,"isReadFragmentResolution");function c(t){return typeof t=="object"&&t!==null}n(c,"isRecord");export{v as a,f as b,T as c,S as d,P as e,k as f};
@@ -0,0 +1,14 @@
1
+ import{a as I,b as k}from"./chunk-XF5PVZOS.js";import{j as N,k as y}from"./chunk-X6MPU7UO.js";import"./chunk-RAZOACDD.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as U}from"node:fs/promises";import Y from"node:path";async function E(e){let n=[],t=await U(e,{withFileTypes:!0});for(let i of t){let o=Y.join(e,i.name);i.isDirectory()?n.push(...await E(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}s(E,"collectFiles");import{readFile as K}from"node:fs/promises";var v=256*1024;async function L(e){let n=await K(e);if(n.byteLength>v)throw new Error(`File exceeds the ${v}-byte AST outline limit: ${e}`);if(n.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${e}`);let t=n.toString("utf8").replaceAll(`\r
2
+ `,`
3
+ `),i=t.endsWith(`
4
+ `)?t.slice(0,-1):t,o=i.length===0?[]:i.split(`
5
+ `);return{content:t,lines:o}}s(L,"readTextFile");var H=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".c",".cc",".hh",".hxx",".cpp",".cxx",".h",".hpp",".json",".jsonc",".yaml",".yml",".toml"]),X=new Set([".json",".jsonc",".yaml",".yml",".toml"]),R=new Set(["class_declaration","class_definition","class_specifier","enum_declaration","enum_definition","enum_item","enum_specifier","export_statement","function_declaration","function_definition","function_item","impl_item","interface_declaration","lexical_declaration","namespace_definition","mod_item","public_field_definition","method_definition","method_signature","property_signature","field_declaration","struct_item","struct_specifier","trait_item","type_alias_declaration","type_item","variable_declaration","assignment"]),q=new Set(["module","program","source_file"]),Z=new Set(["import_declaration","import_from_statement","import_statement","use_declaration"]),A=new Set(["arrow_function","function_declaration","function_definition","function_item","function_expression","method_definition"]),z=new Set(["public_field_definition","variable_declarator","assignment"]),C=new Set(["field_identifier","identifier","property_identifier","shorthand_property_identifier_pattern","type_identifier"]);function T(e){return H.has(h.extname(e).toLowerCase())}s(T,"isSupportedOutlinePath");var w={failureLabel:"PEEK_FAILED",emptyReason:"no entries to peek.",recovery:['Call peek with { peers: [{ path: "path/to/file.ts" }, ...] }.']},G={failureLabel:"AST_OUTLINE_FAILED",emptyReason:"no AST outline was produced."};function Pe(e){return y([e],G)}s(Pe,"formatAstOutline");var W=class{constructor(n=Number.POSITIVE_INFINITY){this.maxDepth=n}static{s(this,"AstOutlineManager")}fallbackScopeManager=new k;async readFileOutline(n,t){let i=P(n,t),o=h.relative(t,i)||i;if(!T(i))throw new Error(`AST outline is not supported for ${o}.`);let r=await L(i);return this.readDocumentOutline(i,t,r.lines)}async readDocumentOutline(n,t,i,o){let r=P(n,t),c=h.relative(t,r)||r;if(!T(r))throw new Error(`AST outline is not supported for ${c}.`);let a=await I(r,t,i);if(!a)throw new Error(`No AST parser is available for ${c}.`);if(Number.isFinite(this.maxDepth)&&a.rootNode.hasError)throw new Error(`Cannot build an automatic outline from invalid syntax in ${c}.`);let u=i.join(`
6
+ `);for(let d=this.maxDepth;;d-=1){let l=await this.createSourceViewBlock(a.rootNode,r,c,t,i,u,h.extname(r).toLowerCase(),void 0,void 0,d);if(o===void 0||o(l)||d<=0||!Number.isFinite(d))return l}}async formatFile(n,t){let i=P(n,t),o=h.relative(t,i)||i;if(!T(i)){let r=await L(i);return y([J(i,o,r.lines)],w)}try{return y([await this.readFileOutline(i,t)],w)}catch(r){let c=r instanceof Error?r.message:String(r);return y([M(o,c)],w)}}async formatSymbol(n,t){let o=(await E(t)).filter(r=>T(r)).sort();for(let r of o){let c;try{c=await L(r)}catch{continue}let a;try{a=await I(r,t,c.lines)}catch{continue}if(!a)continue;let u=te(a.rootNode,n);if(!u)continue;let d=h.relative(t,r)||r,l=await this.createSourceViewBlock(u,r,d,t,c.lines,c.content,h.extname(r).toLowerCase(),n,[`defined in: ${d}:${u.startPosition.row+1}`]);return y([l],w)}return y([M("",`symbol not found: ${n}`,"PEEK_NOT_FOUND")],w)}async createSourceViewBlock(n,t,i,o,r,c,a,u,d,l=this.maxDepth){let f=ie(n,c,a,l),m=await Q(this.fallbackScopeManager,t,o,r),g=ee(m),_=f.map(S=>{let p=S.sourceLine,x=p===void 0?void 0:r[p-1]??"",O=(p===void 0?void 0:g.get(p))?.map($=>` <!-- ${$} -->`).join("")??"";return N({content:S.content,...!(p===void 0||x===void 0)&&{sourceLine:{source:t,lineNumber:p,content:x}},...O.length>0&&{suffix:O}})});return{path:i,...u!==void 0&&{heading:u},...d!==void 0&&{details:d},startLine:n.startPosition.row+1,endLine:n.endPosition.row+1,totalLines:r.length,renderedLines:_}}};function J(e,n,t){return{path:n,startLine:t.length>0?1:0,endLine:t.length,totalLines:t.length,renderedLines:t.map((i,o)=>N({content:i,sourceLine:{source:e,lineNumber:o+1,content:i}}))}}s(J,"formatUnsupportedSourceBlock");function M(e,n,t="PEEK_FAILED"){return{path:e,startLine:0,endLine:0,totalLines:0,renderedLines:[],status:"failed",error:n,code:t}}s(M,"failedSourceViewBlock");function Q(e,n,t,i){return e.getDocumentScopes(n,t,i)}s(Q,"getOutlineScopes");function ee(e){let n=new Map;for(let t of e){let i=n.get(t.startLine)??[];i.push(t.beginAnchor.value),n.set(t.startLine,i);let o=n.get(t.endLine)??[];o.push(t.endScopeAnchor.value),n.set(t.endLine,o)}return n}s(ee,"buildScopeMarkers");function P(e,n){return e.startsWith("file://")?decodeURIComponent(e.slice(7)):h.isAbsolute(e)?e:h.resolve(n,e)}s(P,"resolvePath");function te(e,n){let t,i=s(o=>{if(!t){if(R.has(o.type)&&ne(o)===n){t=re(o);return}for(let r of o.namedChildren)i(r)}},"visit");return i(e),t}s(te,"findSymbol");function ne(e){let n=e.childForFieldName("name");if(n&&C.has(n.type))return n.text;for(let t of e.namedChildren)if(C.has(t.type))return t.text;if(e.type==="lexical_declaration"||e.type==="variable_declaration")return e.namedChildren.find(o=>o.type==="variable_declarator")?.childForFieldName("name")?.text;if(e.type==="function_definition"){let t=e.childForFieldName("declarator");return t?B(t):void 0}}s(ne,"getNodeName");function B(e){if(C.has(e.type))return e.text;for(let n of e.namedChildren){let t=B(n);if(t)return t}}s(B,"findNestedName");function re(e){let n=e.parent;return n&&(n.type==="export_statement"||n.type==="decorated_definition"||n.type==="template_declaration")?n:e}s(re,"unwrapDeclaration");function ie(e,n,t,i){let o=[];X.has(t)?V(e,t,o,i):D(e,t,o,!1,i);let r=oe(n,e.startIndex),c=se(n,e.endIndex),a=o.filter(l=>l.start>=r&&l.end<=c).sort((l,f)=>f.start-l.start),u=ae(n,r,c);for(let l of a){let f=l.start-r,m=l.end-r,g=ce(l);u.splice(f,m-f,...g)}for(;u.length>0&&/\s/u.test(b(u.at(-1)).char);)u.pop();let d=[[]];for(let l of u)l.char===`
7
+ `?d.push([]):b(d.at(-1)).push(l);return d.map(l=>{let f=[...new Set(l.flatMap(m=>m.sourceLine===void 0?[]:[m.sourceLine]))];return{content:l.map(m=>m.char).join(""),...f.length===1&&{sourceLine:f[0]}}})}s(ie,"renderNodeLines");function oe(e,n){return e.lastIndexOf(`
8
+ `,Math.max(0,n-1))+1}s(oe,"lineStartAt");function se(e,n){let t=e.indexOf(`
9
+ `,n);return t===-1?e.length:t}s(se,"lineEndAt");function ae(e,n,t){let i=e.slice(0,n).split(`
10
+ `).length,o=[];for(let r=n;r<t;r+=1){let c=b(e[r]);o.push({char:c,sourceLine:i}),c===`
11
+ `&&(i+=1)}return o}s(ae,"mapSourceRange");function ce(e){let n=e.lineSourceLines??[],t=0,i=[];for(let o=0;o<e.text.length;o+=1){let r=b(e.text[o]),c=n[t];i.push(c===void 0?{char:r}:{char:r,sourceLine:c}),r===`
12
+ `&&(t+=1)}return i}s(ce,"mapReplacement");function j(e,n,t,i){return t<i||e.namedChildCount===0?!1:(n.push({start:e.startIndex,end:e.endIndex,text:"\u2026",lineSourceLines:[e.startPosition.row+1]}),!0)}s(j,"collapseDeepNode");function V(e,n,t,i,o=0){if(!j(e,t,o,i))for(let r of e.namedChildren){if(le(r,n)){ue(r)||t.push({start:r.startIndex,end:r.endIndex,text:"\u2026",lineSourceLines:[r.startPosition.row+1]});continue}V(r,n,t,i,o+1)}}s(V,"collectDataReplacements");function le(e,n){return(n===".json"||n===".jsonc"?["string","number","true","false","null"]:n===".yaml"||n===".yml"?["string_scalar","integer_scalar","float_scalar","boolean_scalar","null_scalar","block_scalar"]:["string","integer","float","boolean","date_time","offset_date_time","local_date_time","local_date","local_time"]).includes(e.type)}s(le,"isDataScalar");function ue(e){let n=e.parent;for(;n&&!n.type.endsWith("pair")&&n.type!=="pair"&&n.type!=="table";)n=n.parent;let t=n?.namedChildren[0];return t!==void 0&&t.startIndex<=e.startIndex&&t.endIndex>=e.endIndex}s(ue,"isDataKey");function D(e,n,t,i,o,r=0){if(j(e,t,r,o))return;let c=Number.isFinite(o)&&e.type==="expression_statement";if(i&&!de(e)&&!c){t.push({start:e.startIndex,end:e.endIndex,text:"\u2026",lineSourceLines:[e.startPosition.row+1]});return}if(A.has(e.type)){let a=pe(e);if(a){let u=fe(a,n);t.push({start:a.startIndex,end:a.endIndex,text:u.text,lineSourceLines:u.lineSourceLines});return}}if(z.has(e.type)){let a=e.childForFieldName("value");if(a&&!A.has(a.type)){t.push({start:a.startIndex,end:a.endIndex,text:"\u2026",lineSourceLines:[a.startPosition.row+1]});return}}for(let a of e.namedChildren)D(a,n,t,q.has(e.type),o,r+1)}s(D,"collectReplacements");function de(e){return R.has(e.type)||Z.has(e.type)||e.type==="comment"||e.type.startsWith("preproc")}s(de,"isTopLevelInterfaceNode");function pe(e){let n=e.childForFieldName("body");return n||e.namedChildren.find(t=>t.type==="block"||t.type==="compound_statement"||t.type==="statement_block")}s(pe,"findBody");function fe(e,n){let t=e.startPosition.row+1,i=e.endPosition.row+1;if(n===".py")return{text:"...",lineSourceLines:[t]};let o=e.text.split(`
13
+ `),r=o[0]??"",c=o.at(-1)??"",a=r.indexOf("{"),u=c.lastIndexOf("}");if(a===-1||u===-1)return{text:"\u2026",lineSourceLines:[t]};if(o.length===1){let p=r.slice(a+1,u);return p.trim()===""?{text:e.text,lineSourceLines:[t]}:{text:r.slice(0,a+1)+F(p)+r.slice(u),lineSourceLines:[t]}}let d=r.slice(a+1),l=c.slice(0,u),f=o.slice(1,-1).some(p=>p.trim()!==""),m=d.trim()!=="",g=l.trim()!=="";if(!f&&!m&&!g)return{text:e.text,lineSourceLines:o.map((p,x)=>t+x)};let _=[],S=[];if(_.push(m?r.slice(0,a+1)+F(d):r),S.push(t),!m&&f){let p=o.slice(1,-1).find(x=>x.trim()!=="")?.match(/^\s*/u)?.[0]??"";_.push(`${p}\u2026`),S.push(void 0)}return _.push(g?F(l)+c.slice(u):c),S.push(i),{text:_.join(`
14
+ `),lineSourceLines:S}}s(fe,"renderBodyPlaceholder");function F(e){let n=/^\s*/u.exec(e)?.[0]??"",t=/\s*$/u.exec(e)?.[0]??"";return`${n}\u2026${t}`}s(F,"maskSegment");export{W as AstOutlineManager,Pe as formatAstOutline,T as isSupportedOutlinePath};
@@ -4,4 +4,4 @@ import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";
4
4
  `);return e.endsWith(`
5
5
  `)?e.slice(0,-1).split(`
6
6
  `).length:e.split(`
7
- `).length}s(h,"countDiffLines");function E(i,e){let t=c(i,e),r=[],n=0;for(let a of t){let o=h(a.value);o!==0&&(a.removed||(a.added&&r.push({start:n+1,end:n+o}),n+=o))}return R(r)}s(E,"computeChangedRanges");function R(i){if(i.length===0)return[];let e=[...i].sort((r,n)=>r.start-n.start),t=[d(e[0])];for(let r=1;r<e.length;r++){let n=d(t.at(-1)),a=d(e[r]);a.start<=n.end+1?n.end=Math.max(n.end,a.end):t.push(a)}return t}s(R,"mergeAdjacentRanges");export{f as a,g as b,D as c,E as d};
7
+ `).length}s(h,"countDiffLines");function y(i,e){let t=c(i,e),r=[],n=0;for(let a of t){let o=h(a.value);o!==0&&(a.removed||(a.added&&r.push({start:n+1,end:n+o}),n+=o))}return E(r)}s(y,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,n)=>r.start-n.start),t=[d(e[0])];for(let r=1;r<e.length;r++){let n=d(t.at(-1)),a=d(e[r]);a.start<=n.end+1?n.end=Math.max(n.end,a.end):t.push(a)}return t}s(E,"mergeAdjacentRanges");export{f as a,g as b,D as c,y as d};
@@ -0,0 +1,7 @@
1
+ import{a as z}from"./chunk-WZI4YC2O.js";import"./chunk-3YK4XMWB.js";import{a as M,b as J,c as V,d as U,f as q}from"./chunk-VFBLX4TG.js";import{c as N,d as h}from"./chunk-KVGQG43U.js";import{d as E}from"./chunk-N34ATN52.js";import{a as O}from"./chunk-ZC65Z3CK.js";import{a as L,b as _,c as F}from"./chunk-JMVDFOTQ.js";import{a as c}from"./chunk-EI7MMDWY.js";import{mkdir as ie,readFile as B,writeFile as re}from"node:fs/promises";async function G(n,t){await ie(N(n),{recursive:!0});let e=[],o=t.filter(r=>r.recipe.formatter!==void 0),i=t.filter(r=>r.recipe.linter!==void 0),s=t.filter(r=>r.recipe.lsp!==void 0);if(o.length>0){let r=h(n,"formatters"),a=await S(r,{version:1,formatters:{}}),u=P(a,"formatters");for(let l of o)u[l.recipe.id]??=l.recipe.formatter;await R(r,a)&&e.push(r)}if(i.length>0){let r=h(n,"linters"),a=await S(r,{version:1,linters:{}}),u=P(a,"linters");for(let l of i)u[l.recipe.id]??=l.recipe.linter;await R(r,a)&&e.push(r)}if(s.length>0){let r=h(n,"lsp-servers"),a=await S(r,{version:1,servers:{}}),u=P(a,"servers");for(let l of s){let d=O(l.recipe.lsp);u[l.recipe.id]??={command:d.command,transport:"stdio",rootMarkers:d.rootMarkers,...d.initializationOptions!==void 0&&{initializationOptions:d.initializationOptions},...d.settings!==void 0&&{settings:d.settings},...d.requireRootMarker!==void 0&&{requireRootMarker:d.requireRootMarker},languages:Object.fromEntries(Object.entries(d.languageIds).map(([p,f])=>[p,{extensions:f,...d.fileNames?.[p]&&{fileNames:d.fileNames[p]}}])),capabilities:["diagnostics"]}}await R(r,a)&&e.push(r)}return e}c(G,"writeSuggestedConfigs");async function S(n,t){try{let e=JSON.parse(await B(n,"utf8"));if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${n} must contain an object`);return e}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return t;throw e}}c(S,"readObject");function P(n,t){let e=n[t];if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} must be an object`);return e}c(P,"objectMember");async function R(n,t){let e=`${JSON.stringify(t,null,2)}
2
+ `;return await B(n,"utf8").catch(()=>{})===e?!1:(await re(n,e,"utf8"),!0)}c(R,"writeJson");var C=class{static{c(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(t){let e=this.plugins.get(t.id);if(e!==void 0)return e;let o=this.queue.then(async()=>{let i=!0,s=[],r=[],a=[],u=[],l={addLanguage:c(d=>{b(d,s,t.id,"language",()=>i)},"addLanguage"),addToolRecipe:c(d=>{b(d,r,t.id,"tool recipe",()=>i)},"addToolRecipe"),addSetupCheck:c(d=>{b(d,a,t.id,"setup check",()=>i)},"addSetupCheck"),addCheck:c(d=>{b(d,u,t.id,"check",()=>i)},"addCheck")};try{await t.setup(l)}finally{i=!1}W(this.languages,s,"language"),W(this.recipes,r,"tool recipe"),this.languages.push(...s),this.recipes.push(...r),this.setupChecks.push(...a),this.checks.push(...u)});return this.plugins.set(t.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(t.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function H(n,t){let e=[],o=[];for(let i of n.setupChecks)try{let s=await i.value.inspect(t);e.push(...(s.selections??[]).map(r=>({...r,pluginId:i.pluginId}))),o.push(...(s.actions??[]).map(r=>({...r,pluginId:i.pluginId})))}catch{}return{selections:e,actions:o}}c(H,"runContributedSetupChecks");async function X(n,t){let e=[];for(let o of n.checks)try{e.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(t)})}catch(i){e.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:i instanceof Error?i.message:String(i)}]})}return e}c(X,"runContributedChecks");function W(n,t,e){for(let o of t){let i=n.find(s=>s.value.id===o.value.id)?.pluginId;if(i!==void 0)throw new Error(`${e} ${o.value.id} is already owned by doctor plugin ${i}`)}}c(W,"assertAvailable");function b(n,t,e,o,i){if(!i())throw new Error(`Doctor plugin ${e} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(t.some(s=>s.value.id===n.id))throw new Error(`Doctor plugin ${e} registered ${o} ${n.id} twice`);t.push({pluginId:e,value:n})}c(b,"add");import fe from"node:path";import{readFile as se}from"node:fs/promises";async function Y(n,t,e,o=process.env){let i=await z(n,e.map(a=>a.value)),s=await ce(n),r=[];for(let a of e){let u=a.value;if(u.languages.every(v=>!t.has(v)))continue;let l=[],d=1,p=i.get(u.id),f=p?.config;f!==void 0&&(d+=6,l.push(`project config: ${f}`)),s.has(`${u.kind}:${u.id}`)&&(d+=6,l.push("Pi Agent IDE config"));let w=p?.dependency;w!==void 0&&(d+=4,l.push(`project dependency: ${w}`));let m=await ae(n,u.executables,o);m!==void 0&&(d+=3,l.push(`executable: ${m}`)),r.push({pluginId:a.pluginId,recipe:u,score:d,evidence:l,...m&&{executable:m}})}return r.sort((a,u)=>u.score-a.score||a.recipe.id.localeCompare(u.recipe.id))}c(Y,"discoverRecipeCandidates");function K(n,t,e=[]){let o=new Map,i=new Map(e.map(s=>[`${s.kind}:${s.languageId}`,s.toolId]));for(let s of t)for(let r of["formatter","linter","lsp"]){let a=i.get(`${r}:${s}`),u=a===void 0?4:7,l=n.filter(p=>p.recipe.kind===r&&p.recipe.languages.includes(s)&&p.executable!==void 0&&p.recipe.id!==a&&p.score>=u),d=l[0];d!==void 0&&(l.filter(p=>p.score===d.score).length>1||o.set(`${d.recipe.kind}:${d.recipe.id}`,d))}return[...o.values()]}c(K,"selectSuggestedRecipes");async function ae(n,t,e){for(let o of t)if(await E(o,n,e))return o}c(ae,"firstExecutable");async function ce(n){let t=new Set;for(let[e,o,i]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{let s=JSON.parse(await se(h(n,e),"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s[o];if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let u of Object.keys(a))t.add(`${i}:${u}`)}catch{}return t}c(ce,"managedRecipeIds");import{execFile as de}from"node:child_process";import{readdir as ue}from"node:fs/promises";import y from"node:path";import{promisify as le}from"node:util";var pe=le(de),ge=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Q(n,t){t?.throwIfAborted();try{let o=(await pe("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:t})).stdout.split("\0").filter(Boolean).map(i=>y.resolve(n,i)).filter(i=>!ee(i));return t?.throwIfAborted(),o.length>0?o:await k(n,t)}catch{return t?.throwIfAborted(),k(n,t)}}c(Q,"collectProjectFiles");function Z(n,t){let e=new Map;for(let o of t){let i=new Set(o.extensions.map(a=>a.toLowerCase())),s=new Set(o.fileNames),r=n.filter(a=>!a.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")&&(i.has(y.extname(a).toLowerCase())||s.has(y.basename(a))));r.length>0&&e.set(o.id,r)}return e}c(Z,"detectProjectLanguages");async function k(n,t){t?.throwIfAborted();let e=[];for(let o of await ue(n,{withFileTypes:!0})){if(o.isDirectory()&&ge.has(o.name))continue;let i=y.join(n,o.name);ee(i)||(o.isDirectory()?e.push(...await k(i,t)):o.isFile()&&e.push(i))}return e}c(k,"walk");function ee(n){return n.split(y.sep).join("/").includes("/.pi/pi-agent-ide/")}c(ee,"isManagedIdeConfig");async function $(n,t,e=process.env,o){o?.throwIfAborted();let i=await Q(t,o);o?.throwIfAborted();let s=Z(i,n.languages.map(p=>p.value)),r=new Set(s.keys()),a={cwd:t,files:i,detectedLanguageIds:r,detectedLanguages:s,env:e},[u,l]=await Promise.all([Y(t,r,n.recipes,e),H(n,a)]),d=new Map;for(let p of r)for(let f of["formatter","linter","lsp"]){if(l.selections.some(g=>g.languageId===p&&g.kind===f))continue;let w=u.filter(g=>g.recipe.kind===f&&g.recipe.languages.includes(p)),m=c(g=>g.score-(g.executable===void 0?0:3),"nativeScore"),v=Math.max(1,...w.map(m));for(let g of w){if(g.executable!==void 0||m(g)!==v||v<=1)continue;let T=`${f}-${g.recipe.id}-unavailable`;d.set(T,{id:T,pluginId:g.pluginId,message:`Native project setup selects ${g.recipe.id}, but its executable is unavailable. Install ${g.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:t,files:i,detectedLanguages:s,candidates:u,selections:l.selections,actions:[...l.actions,...d.values()],suggestions:K(u,r,l.selections)}}c($,"inspectDoctorSetup");async function I(n,t,e=process.env){let o=await $(n,t,e),i=new Set(o.detectedLanguages.keys()),s={cwd:t,files:o.files,detectedLanguageIds:i,detectedLanguages:o.detectedLanguages,env:e},r=await X(n,s),a=[{status:"pass",message:`Project: ${t}`},o.files.length>0?{status:"pass",message:`${o.files.length} project files inspected`}:{status:"warn",message:"No project files found"},i.size>0?{status:"pass",message:`Detected: ${[...i].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...o,sections:[{title:"Project",pluginId:"doctor",findings:a},...r]}}c(I,"runDoctor");function D(n){let t=["Pi Agent IDE doctor",""];for(let e of n.sections){t.push(`${e.title} (${e.pluginId})`);for(let o of e.findings)t.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&t.push(` \`${o.detail}\``);t.push("")}if(n.actions.length>0){t.push("Setup needs attention");for(let e of n.actions)t.push(` ${e.message} [${e.pluginId}]`);t.push("")}if(n.suggestions.length>0){t.push("Suggested configuration");for(let e of n.suggestions){let o=e.evidence.length>0?` \u2014 ${e.evidence.join(", ")}`:"";t.push(` ${e.recipe.kind.padEnd(9)} ${e.recipe.id} [${e.pluginId}]${o}`)}t.push("")}return t.join(`
3
+ `).trimEnd()}c(D,"formatDoctorReport");function j(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(t=>t.findings.some(e=>e.status==="fail"))}c(j,"doctorNeedsWork");function te(n){let t=n.candidates.map(e=>({owner:e.pluginId,id:e.recipe.id,kind:e.recipe.kind,languages:e.recipe.languages,evidence:e.evidence,documentation:e.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",D(n),"","Relevant registered recipes:",JSON.stringify(t,null,2),"",`Project root: ${fe.resolve(n.cwd)}`].join(`
4
+ `)}c(te,"buildDoctorAgentPrompt");import{createHash as me}from"node:crypto";var he="doctor",x=3;function ne(n,t){let e=L(n,ye(t));e!==void 0&&e.catch(()=>{})}c(ne,"registerDoctorTipProvider");function ye(n){return{protocol:_,apiVersion:F,id:he,async getTip(t){let e=await n(t),o=we(e);if(o.length===0)return;let i=o.slice(0,x).map(s=>`\u2022 ${s.message}`);return o.length>x&&i.push(`\u2022 ${o.length-x} more`),{id:`doctor-setup-${De(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...i,"Run /pi-agent-ide-doctor"].join(`
5
+ `)}}}}c(ye,"createDoctorTipProvider");function we(n){let t=n.actions.map(o=>({id:`action:${o.pluginId}:${o.id}`,message:o.message})),e=n.suggestions.map(o=>{let i=o.recipe.languages.filter(r=>n.detectedLanguages.has(r)).join(", "),s={formatter:"formatting",linter:"linting",lsp:"language support"}[o.recipe.kind];return{id:`suggestion:${o.pluginId}:${o.recipe.kind}:${o.recipe.id}`,message:`Use ${o.recipe.name} for ${i} ${s}`}});return[...t,...e].sort((o,i)=>o.id.localeCompare(i.id))}c(we,"setupItems");function De(n){return me("sha256").update(n.map(t=>`${t.id}\0${t.message}`).join("\0")).digest("hex").slice(0,12)}c(De,"fingerprint");async function oe(n){let t=new C;ne(n,async i=>(await t.waitForPlugins(),$(t.snapshot(),i.cwd,process.env,i.signal)));let e,o=n.events.on(U,i=>{if(!q(i))throw new Error("Invalid doctor plugin registration request");i.accept(t.registerPlugin(i.plugin))});n.on("session_shutdown",o),n.registerCommand("pi-agent-ide-doctor",{description:"Check and configure Pi Agent IDE for this project",handler:c(async(i,s)=>{await t.waitForPlugins();let r=await I(t.snapshot(),s.cwd);A(n,D(r));let a=new Set(i.trim().split(/\s+/u).filter(Boolean));if(r.suggestions.length>0&&!a.has("--no-apply")&&(a.has("--apply")||s.hasUI&&await s.ui.confirm("Apply suggested configuration?","Add detected tools to .pi/pi-agent-ide/. Existing entries and native tool settings are kept."))){let d=await G(s.cwd,r.suggestions),p=d.length===0?"Pi Agent IDE configs are already up to date":`Updated ${d.length} Pi Agent IDE config ${d.length===1?"file":"files"}`;s.ui.notify(p,"info"),r=await I(t.snapshot(),s.cwd),A(n,D(r))}if(!j(r)&&!a.has("--agent"))return;(a.has("--agent")||s.hasUI&&await s.ui.confirm("Ask the agent to finish setup?","The agent will receive this redacted report and relevant plugin recipes."))&&(e=s.cwd,n.sendUserMessage(te(r)))},"handler")}),n.on("agent_end",async(i,s)=>{let r=e;if(r===void 0)return;e=void 0;let a=await I(t.snapshot(),r,process.env);A(n,`Doctor recheck after agent setup
6
+
7
+ ${D(a)}`),j(a)?s.ui.notify("Pi Agent IDE setup still needs attention","warning"):s.ui.notify("Pi Agent IDE setup is ready","info")}),n.events.emit(V,{protocol:M,apiVersion:1}),await t.waitForPlugins()}c(oe,"registerDoctor");function A(n,t){n.sendMessage({customType:"pi-agent-ide-doctor",content:t,display:!0},{triggerTurn:!1})}c(A,"sendReport");export{oe as default};
@@ -0,0 +1,6 @@
1
+ import{a as r}from"./chunk-EI7MMDWY.js";var c=new TextEncoder().encode("%PDF-"),b=1024;function w(){return{id:"pdf",description:"PDF paths and URLs return the document's readable content.",async tryConvert(e,t){let n=f(t.signal);if(n!==void 0)return{kind:"failed",error:n};if(!h(e.bytes))return T(e.mediaType)?{kind:"failed",error:new TypeError(`${e.source} is not a valid PDF document`)}:{kind:"not-handled"};try{return{kind:"converted",content:await y(e.bytes,t.signal)}}catch(o){return{kind:"failed",error:f(t.signal)??new TypeError(`Unable to read PDF document ${e.source}: ${A(o)}`,{cause:o})}}}}}r(w,"createPdfContentConverter");function h(e){let t=Math.min(e.length,b+c.length);for(let n=0;n+c.length<=t;n+=1)if(c.every((o,s)=>e[n+s]===o))return!0;return!1}r(h,"isPdf");async function y(e,t){i(t);let{getDocument:n}=await import("pdfjs-dist/legacy/build/pdf.mjs");i(t);let o=n({data:new Uint8Array(e),useSystemFonts:!0}),s,u=r(()=>s??=o.destroy(),"destroy"),l=r(()=>{u()},"abort");t?.addEventListener("abort",l,{once:!0});try{let d=await o.promise;i(t);let g=[];for(let a=1;a<=d.numPages;a+=1){i(t);let m=await d.getPage(a),P=await m.getTextContent();i(t);let p=x(P.items);g.push([`## Page ${a} of ${d.numPages}`,"",p.length===0?"[No extractable text on this page.]":p].join(`
2
+ `)),m.cleanup()}return[{type:"text",text:["# PDF document",...g].join(`
3
+
4
+ `)}]}finally{t?.removeEventListener("abort",l),await u().catch(()=>{})}}r(y,"createPdfContent");function x(e){let t="";for(let n of e)!C(n)||n.str.length===0||(t.length>0&&!E(t)&&!v(n.str)&&(t+=" "),t+=n.str,n.hasEOL===!0&&!t.endsWith(`
5
+ `)&&(t+=`
6
+ `));return t.trim()}r(x,"extractPageText");function C(e){return typeof e=="object"&&e!==null&&"str"in e&&typeof e.str=="string"}r(C,"isPdfTextItem");function v(e){return/^\s/u.test(e)}r(v,"startsWithWhitespace");function E(e){return/\s$/u.test(e)}r(E,"endsWithWhitespace");function T(e){return e?.split(";",1)[0]?.trim().toLowerCase()==="application/pdf"}r(T,"isPdfMediaType");function A(e){return e instanceof Error?e.message:String(e)}r(A,"errorMessage");function i(e){let t=f(e);if(t!==void 0)throw t}r(i,"throwIfAborted");function f(e){if(e?.aborted!==!0)return;if(e.reason instanceof Error)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}r(f,"cancellationError");export{w as a,h as b,y as c};
@@ -0,0 +1,3 @@
1
+ import{b as v,c as E,d as S,e as I,g as _}from"./chunk-JMVDFOTQ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{truncateToWidth as k,wrapTextWithAnsi as R}from"@earendil-works/pi-tui";var O="PI AGENT IDE",N=/\/[a-z][\w-]*/giu,m=class{constructor(t,r){this.tip=t;this.theme=r}static{s(this,"TipCallout")}cached;render(t){if(this.cached?.width===t)return this.cached.lines;let r=L(this.tip,this.theme,t);return this.cached={width:t,lines:r},r}invalidate(){this.cached=void 0}};function L(e,t,r){if(r<=0)return[];if(r<=2)return[t.fg("accent",r===1?"\u2502":"\u2502 ")];let i=r-2,n=t.fg("accent",t.bold(O))+t.fg("dim"," \xB7 ")+t.bold(e.title),o=e.body.split(`
2
+ `).map(c=>c.length===0?"":$(c,t)),a=[n,...o].flatMap(c=>D(c,i)),d=t.fg("accent","\u2502");return a.map(c=>k(`${d} ${c}`,r))}s(L,"renderTip");function D(e,t){return e.length===0?[""]:R(e,t)}s(D,"wrapLine");function $(e,t){let r="",i=0;for(let n of e.matchAll(N)){let o=n.index;r+=t.fg("muted",e.slice(i,o)),r+=t.fg("accent",t.bold(n[0])),i=o+n[0].length}return r+t.fg("muted",e.slice(i))}s($,"styleBodyLine");var y=class{static{s(this,"TipCore")}providers=new Map;registerProvider(t){if(!/^[a-z0-9][a-z0-9.-]*$/u.test(t.id))return Promise.reject(new Error(`Invalid tip provider ID: ${t.id}`));let r=this.providers.get(t.id);return r!==void 0?r===t?Promise.resolve():Promise.reject(new Error(`Tip provider ${t.id} is already registered`)):(this.providers.set(t.id,t),Promise.resolve())}get isEmpty(){return this.providers.size===0}async collectTips(t){let r=[];for(let i of this.providers.values()){if(t.signal?.aborted)break;try{let n=await M(i,t);n!==void 0&&z(n)&&r.push({providerId:i.id,tip:n})}catch{}}return r}};async function M(e,t){let r=t.signal;if(r===void 0)return e.getTip(t);if(r.aborted)return;let i=s(()=>{},"abort"),n=new Promise(o=>{i=s(()=>o(void 0),"abort"),r.addEventListener("abort",i,{once:!0})});try{return await Promise.race([e.getTip(t),n])}finally{r.removeEventListener("abort",i)}}s(M,"collectTip");function z(e){return typeof e.id=="string"&&/^[a-z0-9][a-z0-9.-]*$/u.test(e.id)&&typeof e.title=="string"&&e.title.trim().length>0&&typeof e.body=="string"&&e.body.trim().length>0}s(z,"isTip");import{randomUUID as U}from"node:crypto";import{mkdir as P,readFile as V,rename as G,rm as b,stat as J,writeFile as Y}from"node:fs/promises";import{setTimeout as F}from"node:timers/promises";import{homedir as K}from"node:os";import f from"node:path";var l=1,W=10,B=5e3,Q=6e4,u=Promise.resolve();function X(e=process.env){let t=e.PI_CODING_AGENT_DIR??f.join(K(),".pi","agent");return f.join(t,"pi-agent-ide","tips.json")}s(X,"resolveTipStatePath");var h=class{constructor(t=X()){this.statePath=t}static{s(this,"TipStateStore")}async shownFor(t){let r=await g(this.statePath);return new Set(r.projects[t]??[])}async claimIfUnseen(t,r,i){let n=u.then(async()=>{try{return await w(this.statePath,async()=>{let o=await g(this.statePath),a=new Set(o.projects[t]??[]);if(a.has(r)||i!==void 0&&a.has(i))return!1;a.add(r);let d={version:l,projects:{...o.projects,[t]:[...a]}};return await T(this.statePath,d),!0})}catch{return!0}});return u=n.then(()=>{},()=>{}),n}async markShown(t,r){if(r.length===0)return;u=u.then(async()=>{await w(this.statePath,async()=>{let n=await g(this.statePath),o=new Set(n.projects[t]??[]);for(let d of r)o.add(d);let a={version:l,projects:{...n.projects,[t]:[...o]}};await T(this.statePath,a)})}).catch(()=>{}),await u}async unmarkShown(t,r){u=u.then(async()=>{try{await w(this.statePath,async()=>{let n=await g(this.statePath),o=new Set(n.projects[t]??[]);if(!o.delete(r))return;let a={version:l,projects:{...n.projects,[t]:[...o]}};await T(this.statePath,a)})}catch{}}).catch(()=>{}),await u}};function j(e){return f.resolve(e)}s(j,"normalizeProjectPath");async function g(e){try{let t=JSON.parse(await V(e,"utf8"));return H(t)?t:C()}catch{return C()}}s(g,"readState");async function w(e,t){let r=`${e}.lock`;await P(f.dirname(e),{recursive:!0});let i=Date.now();for(;;)try{await P(r);break}catch(n){if(q(n)!=="EEXIST")throw n;try{if(Date.now()-(await J(r)).mtimeMs>Q){await b(r,{recursive:!0,force:!0});continue}}catch{}if(Date.now()-i>=B)throw new Error(`Timed out waiting for startup-tip state lock: ${r}`,{cause:n});await F(W)}try{return await t()}finally{await b(r,{recursive:!0,force:!0})}}s(w,"withStateLock");function q(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}s(q,"errorCode");async function T(e,t){try{await P(f.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${U()}.tmp`;try{await Y(r,`${JSON.stringify(t,null,2)}
3
+ `,"utf8"),await G(r,e)}finally{await b(r,{force:!0})}}catch{}}s(T,"writeState");function C(){return{version:l,projects:{}}}s(C,"emptyState");function H(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version!==l||typeof t.projects!="object"||t.projects===null?!1:Object.values(t.projects).every(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"))}s(H,"isState");var A="pi-agent-ide-startup-tip";function Z(e){let t=new y,r=new h;e.registerEntryRenderer(A,(a,d,p)=>{let c=a.data;if(!(typeof c.title!="string"||typeof c.body!="string"))return new m({title:c.title,body:c.body},p)});let i=e.events.on(I,a=>{if(!_(a))throw new Error("Invalid tip provider registration request");a.accept(t.registerProvider(a.provider))});e.on("session_shutdown",i);let n,o=Promise.resolve();e.on("session_start",(a,d)=>{n?.abort(),n=new AbortController;let p=n.signal;o=o.then(()=>tt(e,t,r,a.reason,d,p)).catch(()=>{})}),e.on("session_shutdown",async()=>{n?.abort(),await o}),e.events.emit(S,{protocol:v,apiVersion:E})}s(Z,"registerTips");async function tt(e,t,r,i,n,o){if(n.mode!=="tui"||(o.throwIfAborted(),t.isEmpty))return;let a=await t.collectTips({cwd:n.cwd,mode:n.mode,hasUI:n.hasUI,signal:o,reason:i});if(o.throwIfAborted(),a.length===0)return;let d=j(n.cwd);for(let p of a){let c=et(p.providerId,p.tip.id);if(await r.claimIfUnseen(d,c,p.tip.id)){if(o.aborted){await r.unmarkShown(d,c);return}try{e.appendEntry(A,p.tip);return}catch(x){throw await r.unmarkShown(d,c),x}}}}s(tt,"displayTip");function et(e,t){return JSON.stringify([e,t])}s(et,"tipIdentity");export{Z as default};
@@ -0,0 +1,4 @@
1
+ import{g as F}from"./chunk-RIGRP3FD.js";import{a as A}from"./chunk-WNMGUALD.js";import{a as $,b as C}from"./chunk-THSCUT2L.js";import"./chunk-S3ZPXWX7.js";import"./chunk-RAZOACDD.js";import{a as I,b as E,c as S,d as k,g as R}from"./chunk-KZBAJFCV.js";import{a as D}from"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";var p=[],m=[],v=[];function w(i,t,e){if(t.some(o=>o.name===e))throw new Error(`[pi-agent-ide] ${i} "${e}" is already registered. Use a unique name.`)}d(w,"assertUniqueName");function j(i){let t=new Set;for(let e of i){let o=`${e.kind}:${e.name}`;if(t.has(o))throw new Error(`[pi-agent-ide] ${e.kind} "${e.name}" is registered twice by one plugin.`);switch(t.add(o),e.kind){case"compiler":{w(e.kind,m,e.name);break}case"formatter":{w(e.kind,p,e.name);break}case"linter":{w(e.kind,v,e.name);break}}}for(let e of i)switch(e.kind){case"compiler":{m.push(e);break}case"formatter":{p.push(e);break}case"linter":{v.push(e);break}}}d(j,"registerTools");async function N(i,t){let e=[];for(let o of i)try{await o.detect(t)&&e.push(o)}catch(n){console.error(`[pi-agent-ide] detect failed for "${o.name}":`,n)}return e.sort((o,n)=>n.priority-o.priority),U(e),e}d(N,"filterActive");function U(i){let t=new Map;for(let e of i)for(let o of e.extensions){let n=`${o}@${e.priority}`,c=t.get(n);if(c!==void 0)throw new Error(`[pi-agent-ide] priority conflict: tools "${c}" and "${e.name}" both claim "${o}" at priority ${e.priority}.`);t.set(n,e.name)}}d(U,"assertNoPriorityConflicts");async function _(i){let[t,e]=await Promise.all([N(p,i),N(m.filter(o=>o.syntaxOnly===!0),i)]);return{ctx:i,formatters:t,compilers:e,linters:[]}}d(_,"warmupFormatting");function P(){p.length=0,m.length=0,v.length=0}d(P,"resetRegistry");import{readFile as b}from"node:fs/promises";import g from"node:path";var h=class{constructor(t,e={}){this.sources=t;this.options=e}static{d(this,"DiagnosticStore")}files=new Map;dirty=new Set;sent=new Map;queue=[];running=0;disposed=!1;changeListeners=new Set;onDidChange(t){return this.changeListeners.add(t),()=>this.changeListeners.delete(t)}schedule(t,e,{cwd:o}){this.disposed||this.ensure(t,e,o)}async read(t,{cwd:e}){this.assertActive();let o=g.resolve(e,t),n=await b(o,"utf8");this.assertActive();let c=this.ensure(o,n,e);await Y(Promise.all(c.jobs),this.options.readWaitMs??5e3),this.assertActive();let s=await b(o,"utf8");this.assertActive();let r=this.ensure(o,s,e);return{filePath:o,content:r.content,results:[...r.results.values()]}}async takeNotifications(t){let e=[];for(let o of[...this.dirty]){if(o.cwd!==g.resolve(t)||(this.dirty.delete(o),!await this.isCurrent(o)))continue;let n=[...o.results.values()].filter(a=>a.status!=="pending"&&a.status!=="unavailable"&&a.diagnostics.length>0),c=this.key(o.filePath,o.cwd),s=JSON.stringify(n);if(this.sent.get(c)===s||(this.sent.set(c,s),n.length===0))continue;let r=n.map(a=>{let l=["error","warning","info","hint"].flatMap(f=>{let u=a.diagnostics.filter(y=>y.severity===f).length;return u>0?[`${u} ${f}`]:[]});return`${a.source} ${l.join(", ")}${a.status==="snapshot"?" (snapshot; completion unknown)":a.status==="unversioned"?" (unversioned)":""}`}).join("; ");e.push({filePath:g.relative(t,o.filePath),results:n,text:`${JSON.stringify(g.relative(t,o.filePath))}: ${r}.`})}return e}dispose(){this.disposed=!0,this.changeListeners.clear();for(let t of this.files.values())t.controller.abort();this.files.clear(),this.dirty.clear(),this.sent.clear(),this.pump()}key(t,e){return JSON.stringify([g.resolve(e),g.resolve(e,t)])}ensure(t,e,o){let n=this.key(t,o),c=this.files.get(n);if(c?.content===e)return c;c?.controller.abort(),c&&this.dirty.delete(c);let s={cwd:g.resolve(o),filePath:g.resolve(o,t),content:e,controller:new AbortController,results:new Map,jobs:[],publications:new Map};this.files.set(n,s),this.sources.length===0&&s.results.set("diagnostics",{source:"diagnostics",status:"unavailable",diagnostics:[],reason:"No diagnostic sources registered"}),this.dirty.add(s);for(let r of this.sources){s.results.set(r.id,{source:r.id,status:"pending",diagnostics:[]});let a=new Promise(l=>{this.queue.push(async()=>{try{await this.check(s,r)}finally{l()}})});s.jobs.push(a)}return queueMicrotask(()=>this.pump()),s}pump(){for(;this.running<(this.options.concurrency??4)&&this.queue.length>0;){let t=this.queue.shift();if(!t)break;this.running++,t().finally(()=>{this.running--,this.pump()})}}active(t){return!this.disposed&&!t.controller.signal.aborted}assertActive(){if(this.disposed)throw new Error("Diagnostics session has ended")}async isCurrent(t){if(!this.active(t))return!1;let e=await b(t.filePath,"utf8").catch(()=>{});return this.active(t)&&e===t.content}async publish(t,e,o){let n=(t.publications.get(e)??0)+1;if(t.publications.set(e,n),!await this.isCurrent(t)||t.publications.get(e)!==n)return;let c={...o,source:o.source??e};if(JSON.stringify(t.results.get(e))!==JSON.stringify(c)){t.results.set(e,c),this.dirty.add(t);for(let s of this.changeListeners)s(t.cwd)}}async check(t,e){if(!await this.isCurrent(t))return;let o=new AbortController,n=AbortSignal.any([o.signal,t.controller.signal]);if(n.aborted)return;let c,s;try{let r=new Promise((l,f)=>{s=d(()=>f(n.reason),"onAbort"),n.addEventListener("abort",s,{once:!0}),c=setTimeout(()=>o.abort(new Error("Diagnostic check timed out")),this.options.checkTimeoutMs??3e4)}),a=await Promise.race([e.diagnose(t.filePath,{cwd:t.cwd,content:t.content,signal:n,publish:d(l=>{n.aborted||this.publish(t,e.id,l)},"publish")}),r]);await this.publish(t,e.id,a)}catch(r){await this.publish(t,e.id,{status:"unavailable",diagnostics:[],reason:r instanceof Error?r.message:String(r)})}finally{clearTimeout(c),s&&n.removeEventListener("abort",s)}}};async function Y(i,t){let e;try{await Promise.race([i,new Promise(o=>{e=setTimeout(o,t)})])}finally{clearTimeout(e)}}d(Y,"waitAtMost");function O(){let i=new Map,t=[],e=new h(t),o=Promise.resolve();return{diagnostics:e,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 s=o.then(async()=>{let r=[],a=[],l=!0,f={addTool(u){if(!l)throw new Error(`Plugin ${n.id} setup is already complete`);X(u),r.push(u)},addDiagnosticSource(u){if(!l)throw new Error(`Plugin ${n.id} setup is already complete`);H(u),a.push(u)},readDiagnostics(u,y){return e.read(u,y)}};try{await n.setup(f)}catch(u){throw l=!1,u}l=!1,W(t,a),j(r),t.push(...a)});return i.set(n.id,s),o=s.catch(()=>{}),s.catch(()=>{i.delete(n.id)}),s},async waitForPendingPlugins(){await Promise.all(i.values())}}}d(O,"createIdeCore");function W(i,t){let e=new Set(i.map(o=>o.id));for(let o of t){if(e.has(o.id))throw new Error(`Diagnostic source ${o.id} is already registered`);e.add(o.id)}}d(W,"assertUniqueDiagnosticSources");function X(i){if(!M(i))throw new TypeError("IDE tool must be an object");let t=i.kind,e=t==="compiler"?i.compile:t==="formatter"?i.format:t==="linter"?i.lint:void 0;if(e===void 0||typeof e!="function"||typeof i.detect!="function"||typeof i.name!="string"||i.name.trim().length===0||typeof i.priority!="number"||!Number.isFinite(i.priority)||!Array.isArray(i.extensions)||i.extensions.length===0||i.extensions.some(o=>typeof o!="string"||o.length===0))throw new TypeError("Invalid pi-agent-ide tool contribution")}d(X,"assertIdeTool");function H(i){if(!M(i)||typeof i.id!="string"||i.id.trim().length===0||typeof i.diagnose!="function")throw new TypeError("Invalid pi-agent-ide diagnostic source contribution")}d(H,"assertDiagnosticSource");function M(i){return typeof i=="object"&&i!==null}d(M,"isRecord");import{Text as z}from"@earendil-works/pi-tui";var x="ide-diagnostic-summary";function q(i){return{filePath:i.filePath,sources:i.results.map(t=>{let e={error:0,warning:0,info:0,hint:0};for(let o of t.diagnostics)e[o.severity]++;return{source:t.source,status:t.status,counts:e}})}}d(q,"diagnosticEntryData");function B(i,t,e=!1){return{render(o){let n=i.sources.filter(r=>r.status!=="pending"&&r.status!=="unavailable"&&Object.values(r.counts).some(a=>a>0));if(n.length===0)return[];let c=n.map(r=>`${L(r.counts,t)} ${t.fg("dim",`(${T(r.source)})`)}`+(r.status==="ready"?"":` \xB7 ${t.fg("dim",r.status)}`)).join(" \xB7 "),s=[`${t.fg("accent","Diagnostics")} ${t.fg("toolTitle",T(i.filePath))} \xB7 ${c}`];if(e)for(let r of n)s.push(` ${t.fg("dim",T(r.source))} \xB7 ${L(r.counts,t)} \xB7 ${t.fg("dim",r.status)}`);return new z(s.join(`
2
+ `),0,0).render(o)},invalidate(){}}}d(B,"renderDiagnosticEntry");function V(i){i.registerEntryRenderer(x,(t,e,o)=>B(D(t.data),o,e.expanded))}d(V,"registerDiagnosticEntryRenderer");function L(i,t){return["error","warning","info","hint"].filter(e=>i[e]>0).map(e=>{let o=i[e],n=e==="info"||o===1?e:`${e}s`,c=o>0&&(e==="error"||e==="warning")?e:"muted";return t.fg(c,`${o} ${n}`)}).join(", ")}d(L,"renderCounts");function T(i){return i.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}d(T,"plain");import G from"node:path";async function J(i){if(!G.isAbsolute(i.resourceSource))return{formatting:{status:"unavailable"}};let t;try{let e=await _({cwd:i.cwd}),o=G.extname(i.resourceSource).toLowerCase(),n=d(a=>a.extensions.includes(o)||a.extensions.includes("*"),"matches"),c=e.compilers.find(n);if(c&&(await c.compile({filePath:i.resourceSource},e.ctx)).syntaxErrors.length>0)return{formatting:{status:"skipped-syntax"}};let s=e.formatters.find(n);if(!s)return{formatting:{status:"unavailable"}};t=s.name;let r=await s.format({filePath:i.resourceSource},e.ctx);return r.formatter===null?{formatting:{status:"unavailable"}}:(t=r.formatter??s.name,{formatting:{status:r.ok?r.edits>0?"changed":"unchanged":"failed",formatter:t},...r.ok?{diffStatuses:[{text:`Formatted (${t})`,tone:"success"}]}:{}})}catch{return{formatting:{status:"failed",...t===void 0?{}:{formatter:t}}}}}d(J,"runIdePostEditGate");import K from"node:path";async function Q(i){i.registerFlag("old-tools",{description:"Use the old IDE and text editor tools",type:"boolean",default:!1}),P();let t=O();V(i);let e=i.events.on(k,r=>{if(!R(r))throw new Error("Invalid pi-agent-ide plugin registration request");r.accept(t.registerPlugin(r.plugin))});i.on("session_shutdown",()=>{e(),t.diagnostics.dispose(),P()}),F(i,{id:"pi-agent-ide",handler:d(r=>i.getFlag("pi-agent-ide-no-post-processing")===!0?Promise.resolve({formatting:{status:"disabled"}}):J(r),"handler")}),i.events.emit(S,{protocol:I,apiVersion:3}),await A(i,{protocol:$,apiVersion:C,id:"ide-diagnostics",setup(r){r.onDidEdit(a=>{i.getFlag("pi-agent-ide-no-post-processing")!==!0&&K.isAbsolute(a.resourceSource)&&t.diagnostics.schedule(a.resourceSource,a.after.content,{cwd:a.cwd})})}});let o=Promise.resolve(),n=!1,c=d(()=>n,"isClosed"),s=t.diagnostics.onDidChange(r=>{o=o.then(async()=>{if(n)return;let a=await t.diagnostics.takeNotifications(r);if(!(c()||a.length===0)){i.sendMessage({customType:"ide-diagnostics",display:!1,content:`File diagnostics:
3
+ ${a.map(l=>l.text).join(`
4
+ `)}`},{triggerTurn:!0,deliverAs:"steer"});for(let l of a)i.appendEntry(x,q(l))}}).catch(a=>{console.error("Diagnostic delivery failed",a)})});i.on("session_shutdown",()=>{n=!0,s()}),await t.waitForPendingPlugins()}d(Q,"registerPiAgentIde");export{Q as default};
@@ -1,2 +1,2 @@
1
- import{a as w,f as _}from"./chunk-YHUTTZC6.js";import{a as l}from"./chunk-EI7MMDWY.js";import{Container as D,Text as H,truncateToWidth as E,visibleWidth as W}from"@earendil-works/pi-tui";var v="pi-agent-text-editor/tool-call-interception",h=Symbol("pi-agent-tool-call-interception/annotation"),k=Symbol("pi-agent-tool-call-interception/render-argument-patch"),y=Symbol("pi-agent-tool-call-interception/anchor-render-patch");function x(n){if(!C(n))return;let e=n[v];return Y(e)?e:void 0}l(x,"getToolCallInterception");function M(n,e,o){let t={annotation:e,...o!==void 0&&{blocked:{reason:o}}};return C(n)?{...n,[v]:t}:{[v]:t,agentDetails:n??null}}l(M,"withToolCallInterceptionDetails");function Q(n,e){return{...n,details:M(n.details,{kind:"blocked",reason:e},e)}}l(Q,"withBlockedToolResult");function j(n,e){if(n===void 0)return!1;let o=n,t=e,r=Reflect.ownKeys(e);return r.length===Reflect.ownKeys(n).length&&r.every(d=>o[d]===t[d])}l(j,"sameArgumentPatch");function U(n,e){let o={...n,...e},t=b(n),r=b(e);return(t!==void 0||r!==void 0)&&(o[y]={...t,...r}),o}l(U,"mergeArgumentPatches");function O(n){if(n===void 0||!(y in n))return n;let e={...n};return delete e[y],e}l(O,"argumentPatchWithoutAnchorRendering");function b(n){if(n!==void 0)return n[y]}l(b,"anchorRenderPatchFromArguments");var L=class{static{l(this,"ToolCallInterceptionRenderStore")}entries=new Map;annotate=l((e,o)=>{let t=this.entries.get(e);this.entries.set(e,{annotation:o,renderArgumentPatch:t?.renderArgumentPatch,invalidate:t?.invalidate}),t?.invalidate?.()},"annotate");bind(e,o){let t=this.entries.get(e);return this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:t?.renderArgumentPatch,invalidate:o}),t?.annotation}get(e){return this.entries.get(e)?.annotation}resolveArguments=l((e,o)=>{let t=this.entries.get(e),r=U(t?.renderArgumentPatch,o);j(t?.renderArgumentPatch,r)||(this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:r,invalidate:t?.invalidate}),t?.invalidate?.())},"resolveArguments");getRenderArgumentPatch(e){return this.entries.get(e)?.renderArgumentPatch}complete(e){this.entries.delete(e)}clear(){this.entries.clear()}},P=class{constructor(e,o,t,r,d,s){this.component=e;this.theme=o;this.state=t;this.annotations=r;this.toolCallId=d;this.backgroundAnsi=s}static{l(this,"AnnotatedToolCall")}get inner(){return this.component}update(e,o,t,r){this.component=e,this.theme=o,this.state=t,this.backgroundAnsi=r}render(e){let o=this.component.render(e),t=this.annotations.get(this.toolCallId)??this.state[h],r;if(t===void 0)r=o;else{let d=F(t,this.theme);if(o.length===0)r=[E(d,e)];else{let s=` \u2190 ${d}`,a=W(s);r=a>=e?[E(s.trimStart(),e,""),...o.slice(1)]:[`${E(o[0]??"",e-a,"")}${s}`,...o.slice(1)]}}return B(r,this.backgroundAnsi)}invalidate(){this.component.invalidate()}},I=class{constructor(e,o){this.component=e;this.backgroundAnsi=o}static{l(this,"EnclosingBackgroundComponent")}get inner(){return this.component}update(e,o){this.component=e,this.backgroundAnsi=o}render(e){return B(this.component.render(e),this.backgroundAnsi)}invalidate(){this.component.invalidate()}};function B(n,e){return e===void 0?[...n]:n.map(o=>_(o,e))}l(B,"preserveBackgroundLines");function V(n,e){let o=n.renderCall,t=n.renderResult,r=n.renderShell!=="self";return{...n,get promptGuidelines(){return n.promptGuidelines},renderCall(d,s,a){let i=a.state,c=e.bind(a.toolCallId,a.invalidate),u=e.getRenderArgumentPatch(a.toolCallId)??i[k],T=b(u),R=O(u);u!==void 0&&(i[k]=u),T!==void 0&&(i[y]=T);let p=R===void 0?d:{...R,...d};c!==void 0&&(i[h]=c);let g=a.lastComponent instanceof P?a.lastComponent:void 0,f;try{f=o?.(p,s,{...a,args:p,lastComponent:g?.inner})??K(n.name,s)}catch{f=K(n.name,s)}let A=r?w(s,a):void 0;return g!==void 0?(g.update(f,s,i,A),g):new P(f,s,i,e,a.toolCallId,A)},renderResult(d,s,a,i){let c=i.state,u=e.getRenderArgumentPatch(i.toolCallId)??c[k],T=b(u),R=O(u);u!==void 0&&(c[k]=u),T!==void 0&&(c[y]=T);let p=i.lastComponent instanceof I?i.lastComponent:void 0,g={...i,...R!==void 0&&{args:{...R,...i.args}},lastComponent:p?.inner??i.lastComponent},f=x(d.details)?.annotation,A=e.get(i.toolCallId)??c[h],N=f??(s.isPartial||i.isError?A:void 0);if(N!==void 0){if(c[h]=N,e.complete(i.toolCallId),t!==void 0){let G={...d,content:[],details:void 0};try{t(G,s,a,g)}catch{return new D}}return new D}e.complete(i.toolCallId),Reflect.deleteProperty(c,h);let m;if(t!==void 0)try{m=t(d,s,a,g)}catch{m=$(d,a,i.isError)}else m=$(d,a,i.isError);if(!r)return m;let S=w(a,i);return p!==void 0?(p.update(m,S),p):new I(m,S)}}}l(V,"withToolCallInterceptionRendering");function K(n,e){return new H(e.fg("toolTitle",e.bold(n)),0,0)}l(K,"fallbackCall");function $(n,e,o){let t=n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
1
+ import{a as w,f as _}from"./chunk-YHUTTZC6.js";import{a as l}from"./chunk-EI7MMDWY.js";import{Container as D,Text as H,truncateToWidth as E,visibleWidth as W}from"@earendil-works/pi-tui";var v="pi-agent-text-editor/tool-call-interception",h=Symbol("pi-agent-tool-call-interception/annotation"),k=Symbol("pi-agent-tool-call-interception/render-argument-patch"),y=Symbol("pi-agent-tool-call-interception/anchor-render-patch");function x(n){if(!C(n))return;let e=n[v];return Y(e)?e:void 0}l(x,"getToolCallInterception");function M(n,e,o){let t={annotation:e,...o!==void 0&&{blocked:{reason:o}}};return C(n)?{...n,[v]:t}:{[v]:t,agentDetails:n??null}}l(M,"withToolCallInterceptionDetails");function Q(n,e){return{...n,details:M(n.details,{kind:"blocked",reason:e},e)}}l(Q,"withBlockedToolResult");function j(n,e){if(n===void 0)return!1;let o=n,t=e,r=Reflect.ownKeys(e);return r.length===Reflect.ownKeys(n).length&&r.every(d=>o[d]===t[d])}l(j,"sameArgumentPatch");function U(n,e){let o={...n,...e},t=b(n),r=b(e);return(t!==void 0||r!==void 0)&&(o[y]={...t,...r}),o}l(U,"mergeArgumentPatches");function O(n){if(n===void 0||!(y in n))return n;let e={...n};return delete e[y],e}l(O,"argumentPatchWithoutAnchorRendering");function b(n){if(n!==void 0)return n[y]}l(b,"anchorRenderPatchFromArguments");var L=class{static{l(this,"ToolCallInterceptionRenderStore")}entries=new Map;annotate=l((e,o)=>{let t=this.entries.get(e);this.entries.set(e,{annotation:o,renderArgumentPatch:t?.renderArgumentPatch,invalidate:t?.invalidate}),t?.invalidate?.()},"annotate");bind(e,o){let t=this.entries.get(e);return this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:t?.renderArgumentPatch,invalidate:o}),t?.annotation}get(e){return this.entries.get(e)?.annotation}resolveArguments=l((e,o)=>{let t=this.entries.get(e),r=U(t?.renderArgumentPatch,o);j(t?.renderArgumentPatch,r)||(this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:r,invalidate:t?.invalidate}),t?.invalidate?.())},"resolveArguments");getRenderArgumentPatch(e){return this.entries.get(e)?.renderArgumentPatch}complete(e){this.entries.delete(e)}clear(){this.entries.clear()}},P=class{constructor(e,o,t,r,d,s){this.component=e;this.theme=o;this.state=t;this.annotations=r;this.toolCallId=d;this.backgroundAnsi=s}static{l(this,"AnnotatedToolCall")}get inner(){return this.component}update(e,o,t,r){this.component=e,this.theme=o,this.state=t,this.backgroundAnsi=r}render(e){let o=this.component.render(e),t=this.annotations.get(this.toolCallId)??this.state[h],r;if(t===void 0)r=o;else{let d=F(t,this.theme);if(o.length===0)r=[E(d,e)];else{let s=` \u2190 ${d}`,a=W(s);r=a>=e?[E(s.trimStart(),e,""),...o.slice(1)]:[`${E(o[0]??"",e-a,"")}${s}`,...o.slice(1)]}}return B(r,this.backgroundAnsi)}invalidate(){this.component.invalidate()}},I=class{constructor(e,o){this.component=e;this.backgroundAnsi=o}static{l(this,"EnclosingBackgroundComponent")}get inner(){return this.component}update(e,o){this.component=e,this.backgroundAnsi=o}render(e){return B(this.component.render(e),this.backgroundAnsi)}invalidate(){this.component.invalidate()}};function B(n,e){return e===void 0?[...n]:n.map(o=>_(o,e))}l(B,"preserveBackgroundLines");function V(n,e){let o=n.renderCall,t=n.renderResult,r=n.renderShell!=="self";return{...n,get description(){return n.description},get promptGuidelines(){return n.promptGuidelines},renderCall(d,s,a){let i=a.state,c=e.bind(a.toolCallId,a.invalidate),u=e.getRenderArgumentPatch(a.toolCallId)??i[k],T=b(u),R=O(u);u!==void 0&&(i[k]=u),T!==void 0&&(i[y]=T);let p=R===void 0?d:{...R,...d};c!==void 0&&(i[h]=c);let g=a.lastComponent instanceof P?a.lastComponent:void 0,f;try{f=o?.(p,s,{...a,args:p,lastComponent:g?.inner})??K(n.name,s)}catch{f=K(n.name,s)}let A=r?w(s,a):void 0;return g!==void 0?(g.update(f,s,i,A),g):new P(f,s,i,e,a.toolCallId,A)},renderResult(d,s,a,i){let c=i.state,u=e.getRenderArgumentPatch(i.toolCallId)??c[k],T=b(u),R=O(u);u!==void 0&&(c[k]=u),T!==void 0&&(c[y]=T);let p=i.lastComponent instanceof I?i.lastComponent:void 0,g={...i,...R!==void 0&&{args:{...R,...i.args}},lastComponent:p?.inner??i.lastComponent},f=x(d.details)?.annotation,A=e.get(i.toolCallId)??c[h],N=f??(s.isPartial||i.isError?A:void 0);if(N!==void 0){if(c[h]=N,e.complete(i.toolCallId),t!==void 0){let G={...d,content:[],details:void 0};try{t(G,s,a,g)}catch{return new D}}return new D}e.complete(i.toolCallId),Reflect.deleteProperty(c,h);let m;if(t!==void 0)try{m=t(d,s,a,g)}catch{m=$(d,a,i.isError)}else m=$(d,a,i.isError);if(!r)return m;let S=w(a,i);return p!==void 0?(p.update(m,S),p):new I(m,S)}}}l(V,"withToolCallInterceptionRendering");function K(n,e){return new H(e.fg("toolTitle",e.bold(n)),0,0)}l(K,"fallbackCall");function $(n,e,o){let t=n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
2
2
  `);return t.length===0?new D:new H(e.fg(o?"error":"toolOutput",t),0,0)}l($,"fallbackResult");function F(n,e){let o=n.kind==="stale-anchor",t=o?"\u26A0":"\u2298",r=n.label??(o?"Stale Anchor":"Blocked"),d=n.color??(o?"warning":"error"),s=n.reason===void 0?"":`: ${n.reason}`;return e.fg(d,`${t} ${r}${s}`)}l(F,"renderAnnotation");function Y(n){return!C(n)||!q(n.annotation)?!1:n.blocked===void 0||C(n.blocked)&&typeof n.blocked.reason=="string"}l(Y,"isToolCallInterceptionDetails");function q(n){return!C(n)||typeof n.kind!="string"||n.label!==void 0&&typeof n.label!="string"||n.reason!==void 0&&typeof n.reason!="string"||n.color!==void 0&&typeof n.color!="string"?!1:n.kind==="blocked"?typeof n.reason=="string":n.kind==="custom"?typeof n.label=="string"&&typeof n.color=="string":n.kind==="stale-anchor"||n.kind==="aborted"}l(q,"isToolCallAnnotation");function C(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}l(C,"isRecord");export{v as a,y as b,x as c,M as d,Q as e,L as f,V as g,q as h};
@@ -0,0 +1,2 @@
1
+ import{a as H}from"./chunk-LQYZG62K.js";import{m as w}from"./chunk-RAZOACDD.js";import{a as S}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";import{createHash as le}from"node:crypto";import{readFile as q}from"node:fs/promises";import h from"node:path";import{spawn as Z}from"node:child_process";import W from"node:path";import{createInterface as ee}from"node:readline";import{existsSync as X}from"node:fs";import Y from"node:os";import F from"node:path";function L(e=process.env.PI_CODING_AGENT_DIR??F.join(Y.homedir(),".pi","agent"),n=process.platform){let t=F.join(e,"bin",n==="win32"?"rg.exe":"rg");return X(t)?t:"rg"}c(L,"resolveRipgrepExecutable");async function A(e,n,t){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let r=e.limit??100,o=W.resolve(n,re(e.path??".")),s=["--json","--no-config","--no-ignore-parent","--color=never","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...O(e.include).flatMap(i=>["--glob",i]),...O(e.exclude).flatMap(i=>["--glob",`!${i}`]),"--",e.query,o];if(e.regex!==!0)return R(["--fixed-strings",...s],r,t);try{return await R(["--engine","auto",...s],r,t)}catch(i){if(!te(i))throw i;return R(["--engine","default",...s],r,t)}}c(A,"searchText");function R(e,n,t){return new Promise((r,o)=>{let s=Z(L(),e,{stdio:["ignore","pipe","pipe"]}),i=ee({input:s.stdout}),a=[],l="",u=!1,d,p=c(()=>{s.kill()},"abort"),m=c(()=>{t?.removeEventListener("abort",p),i.close()},"cleanup");s.stderr.setEncoding("utf8"),s.stderr.on("data",f=>{l+=f}),i.on("line",f=>{if(!(u||d!==void 0||f.length===0))try{let g=JSON.parse(f);if(g.type!=="match")return;for(let V of ne(g)){if(a.length===n){u=!0,s.kill();return}a.push(V)}}catch(g){d=g,s.kill()}}),s.once("error",f=>{m(),o(f)}),s.once("close",f=>{if(m(),t?.aborted===!0){let g=new Error("Search was aborted.");g.name="AbortError",o(g);return}if(d!==void 0){o(new Error("Unable to parse ripgrep search output.",{cause:d}));return}if(!u&&f!==0&&f!==1){o(new Error(l.trim()||`ripgrep exited with code ${String(f)}.`));return}a.sort(oe),r({matches:a,complete:!u})}),t?.addEventListener("abort",p,{once:!0}),t?.aborted===!0&&p()})}c(R,"runRipgrep");function te(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}c(te,"isPcre2MatchLimitError");function ne(e){let n=e.data.path.text,t=e.data.lines.text;if(n===void 0||t===void 0||!Number.isSafeInteger(e.data.line_number))return[];let r=t.replace(/(?:\r\n|\n)$/u,""),o=Buffer.from(t),s=[];for(let i of e.data.submatches){if(i.start<0||i.end<=i.start||i.end>o.length)continue;let a=o.subarray(0,i.start).toString("utf8").length,l=o.subarray(0,i.end).toString("utf8").length;s.push({source:W.resolve(n),lineNumber:e.data.line_number,startColumn:a,endColumn:l,matchedText:r.slice(a,l),lineText:r})}return s}c(ne,"matchesFromEvent");function O(e){if(e===void 0)return[];let n=[],t=0,r="";for(let o of e){if(o==="{"?t+=1:o==="}"&&(t=Math.max(0,t-1)),t===0&&(o===","||/\s/u.test(o))){r.length>0&&(n.push(r),r="");continue}r+=o}return r.length>0&&n.push(r),n}c(O,"splitGlobList");function re(e){return e.startsWith("@")?e.slice(1):e}c(re,"stripFilePrefix");function oe(e,n){return e.source.localeCompare(n.source)||e.lineNumber-n.lineNumber||e.startColumn-n.startColumn||e.endColumn-n.endColumn}c(oe,"compareMatches");function C(e,n=!1){let t=$(e);if(!M(t))return n?e:B(e);let r=E(new v(e,t).parse(),n);return`^${r.condition}.*?\\K(${r.match})`}c(C,"compileSearchQuery");function D(e){if(M($(e)))return;let n=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return n.length>1?`(?:${n.map(B).join("|")})`:void 0}c(D,"compileSearchFallbackQuery");function M(e){return e.some(n=>n.quoted===!0||n.type==="and"||n.type==="or"||n.type==="not")}c(M,"containsBooleanSyntax");var v=class{static{c(this,"BooleanQueryParser")}#t;#r;#i=0;constructor(n,t){this.#t=n,this.#r=t}parse(){let n=this.#s(),t=this.#e();if(t.type!=="end"){let r=t.type==="right"?"unexpected ')'.":`unexpected ${ae(t)}.`;throw y(t.offset,r)}return n}#s(){let n=this.#n();for(;this.#e().type==="or";){let t=this.#o(),r=this.#a(`after ${t.value}`);n={kind:"or",left:n,right:this.#c(r)}}return n}#n(){return this.#c(this.#a())}#c(n){let t=n;for(;;){let r=this.#e();if(r.type==="and"||r.type==="not"){this.#o();let o=this.#a(`after ${r.value}`);t={kind:r.type,left:t,right:o};continue}if(r.type==="term"||r.type==="left"){t={kind:"and",left:t,right:this.#a()};continue}return t}}#a(n){let t=this.#e();if(t.type==="term")return this.#o(),{kind:"term",value:t.value,quoted:t.quoted};if(t.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw y(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw y(this.#e().offset,"expected ')'.");return this.#o(),o}if(n===void 0&&(t.type==="and"||t.type==="or"||t.type==="not"))throw y(t.offset,`expected a term before ${t.value}.`);let r=n===void 0?"":` ${n}`;throw y(t.offset,`expected a term${r}.`)}#e(){return this.#r[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let n=this.#e();return this.#i+=1,n}};function $(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(/\s/u.test(r)){t+=1;continue}if(r==="("&&ie(e,t)){n.push({type:"left",value:r,offset:t}),t+=1;continue}if(r===")"){n.push({type:"right",value:r,offset:t}),t+=1;continue}if(_(e,t)){let i=e.charAt(t+1)==="|"?2:1;n.push({type:"or",value:e.slice(t,t+i),offset:t}),t+=i;continue}if(r==="'"||r==='"'){let i=t,a=r,l="";for(t+=1;t<e.length&&e.charAt(t)!==a;)e.charAt(t)==="\\"&&(e.charAt(t+1)===a||e.charAt(t+1)==="\\")&&(t+=1),l+=e.charAt(t++);if(t>=e.length)throw y(i,`unterminated ${a==="'"?"single":"double"}-quoted term.`);if(t+=1,l.length===0)throw y(i,"quoted terms must not be empty.");n.push({type:"term",value:l,offset:i,quoted:!0});continue}let o=t;for(;t<e.length;){let i=e.charAt(t);if(/\s/u.test(i)||i===")"||_(e,t))break;i==="\\"&&t+1<e.length?t+=2:i==="["||i==="("?t=N(e,t)??t+1:t+=1}let s=e.slice(o,t);n.push({type:se(s),value:s,offset:o})}return n.push({type:"end",value:"",offset:e.length}),n}c($,"tokenize");function _(e,n){return e.charAt(n)==="|"&&(e.charAt(n+1)==="|"||/\s/u.test(e.charAt(n-1))&&/\s/u.test(e.charAt(n+1)))}c(_,"isBooleanPipe");function N(e,n){let t=e.charAt(n)==="["?"]":")",r=n+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===t)return r+1;if(t===")"&&(o==="("||o==="[")){let s=N(e,r);if(s===void 0)return;r=s}else r+=1}}}c(N,"regexBlockEnd");function ie(e,n){let t=N(e,n);if(t===void 0)return!0;let r=e.slice(n+1,t-1);return r.trim().length===0?!0:M($(r))}c(ie,"isBooleanGroup");function se(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}c(se,"operatorType");function ae(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}c(ae,"quoteToken");function y(e,n){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${n}`)}c(y,"syntaxError");function E(e,n){if(e.kind==="term"){let o=n&&!e.quoted?e.value:B(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let t=E(e.left,n),r=E(e.right,n);return e.kind==="or"?{condition:`(?:${t.condition}|${r.condition})`,match:`(?:${t.match}|${r.match})`}:e.kind==="not"?{condition:`${t.condition}(?!${r.condition})`,match:t.match}:{condition:`${t.condition}${r.condition}`,match:`(?:${t.match}|${r.match})`}}c(E,"compileExpression");function B(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}c(B,"escapeRegex");function $e(e){let n=C(e.query),t=C(e.query,!0),r=D(e.query),o=[];return t!==n&&o.push({query:t,mode:"regex"}),r!==void 0&&r!==n&&r!==t&&o.push({query:r,mode:"words"}),{...e,query:n,regex:!0,fallbacks:o}}c($e,"createSearchRecipe");async function P(e,n,t){let r=e.query,o=await A(e,n,t),s=[];for(let i of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;t?.throwIfAborted();try{o=await A({...e,query:i.query,regex:!0},n,t),r=i.query,s.push(i.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(a){if(i.mode!=="regex"||!ce(a)||t?.aborted)throw a;s.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:s}}c(P,"runSearchRecipe");function ce(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}c(ce,"isRegexSyntaxError");var ue=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,z=4;function We(e,n,t,r){return U(e,n,t,r).slice(0,z)}c(We,"createSearchSessionId");function U(e,n,t,r){let o=t===void 0?fe(n.map(a=>a.source)):h.resolve(t),s=n.map(a=>({match:a,source:h.relative(o,h.resolve(a.source))})).sort((a,l)=>a.source.localeCompare(l.source)||j(a.match,l.match)).map(({match:a,source:l})=>[l,a.lineNumber,a.startColumn,a.endColumn,a.matchedText,a.lineText]),i=K(r??{query:e,regex:!0},o);return le("sha256").update(JSON.stringify([e,o,i,s])).digest("hex").toUpperCase()}c(U,"createSearchSessionIdentity");function de(e,n){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let t=z;t<=e.length;t+=1){let r=e.slice(0,t);if(!n.has(r))return r}throw new Error("Could not allocate a unique search session id.")}c(de,"allocateSearchSessionId");function K(e,n){return{query:e.query,path:h.resolve(n,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??100,regex:e.regex===!0,fallbacks:e.fallbacks??[]}}c(K,"normalizeRecipe");var Q=class{constructor(n=U){this.createIdentity=n}static{c(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(n,t,r,o,s,i={query:n,regex:!0}){let a=t.map(f=>({...f,source:h.resolve(f.source)})).sort(j),l=await J(a,s),u=this.createIdentity(n,a,o,i),p=this.#r.get(u)??de(u,new Set(this.#t.keys())),m={id:p,query:n,matches:a,complete:r,contentBySource:l,recipe:i,cwd:h.resolve(o)};return this.#r.set(u,p),this.#t.set(p,m),m}async observeAfterEdit(n,t){let r=new Set(n.flatMap(s=>{let i=typeof s=="string"?T(s):void 0;return i===void 0?[]:[i.id]})),o=[];for(let s of r){let i=this.#t.get(s);if(i===void 0)continue;let a={sessionId:s,query:i.recipe.originalQuery??i.query,scope:K(i.recipe,i.cwd)};try{let l=await P(i.recipe,i.cwd,t);o.push({...a,matches:l.matches.length,complete:l.complete,notices:l.notices})}catch(l){o.push({...a,error:l instanceof Error?l.message:String(l)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
2
+ `),renderFull(n){return n},renderCompact(n){let t=T(n);return t===void 0?"selected result":t.selector==="all"?t.mode==="match"?"all matches":"all lines":t.mode==="match"?`match ${String(t.selector)}`:`line ${String(t.selector)}`},tryResolve:c((n,t)=>this.#i(n,t.source,t.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:c((n,t)=>this.#s(n,t.cwd),"tryResolve")}}async#i(n,t,r){let o=T(n);if(o===void 0)return{kind:"not-handled"};let s=this.#t.get(o.id);if(s===void 0)return b();if(o.selector==="all"&&!s.complete)return x();let i=h.resolve(t),a=s;if(o.selector==="all"){if(s.refreshedComplete?.complete===!0)a=s.refreshedComplete;else if(s.refreshedComplete!==void 0&&(a=await this.#n(s,r),!a.complete))return x()}let l=k(a,o.selector,o.mode),u=l.filter(m=>m.source===i);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await I(i,r);if(d===void 0)return b(S(u[0]).lineNumber);if(o.selector==="all"&&d!==a.contentBySource.get(i)){if(a=await this.#n(s,r),!a.complete)return x();l=k(a,o.selector,o.mode),u=l.filter(m=>m.source===i)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==s.contentBySource.get(i))return b(S(u[0]).lineNumber);let p=w(i,d);return{kind:"resolved",anchor:new H(n,i,u.map(m=>G(p,m,o.mode)))}}async#s(n,t){let r=T(n);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return b();if(r.selector==="all"&&!o.complete)return x();let s=o;if(r.selector==="all"){if(o.refreshedComplete?.complete===!0)s=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(s=await this.#n(o),!s.complete))return x();let u=new Set(k(s,r.selector,r.mode).map(d=>d.source));for(let d of u)if(await I(d)!==s.contentBySource.get(d)){if(s=await this.#n(o),!s.complete)return x();break}}let i=k(s,r.selector,r.mode);if(r.selector!=="all"){let u=i[0]?.source;if(u!==void 0&&await I(u)!==s.contentBySource.get(u))return b(i[0]?.lineNumber)}let a=new Map;for(let u of i){let d=a.get(u.source)??[];d.push(G(w(u.source,s.contentBySource.get(u.source)??u.lineText),u,r.mode)),a.set(u.source,d)}let l=[...a].map(([u,d])=>({source:u,ranges:d}));return l.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:l}}async#n(n,t){let r=await P(n.recipe,n.cwd,t),o=r.matches.map(i=>({...i,source:h.resolve(i.source)})).sort(j),s={matches:o,complete:r.complete,contentBySource:await J(o,t)};return this.#t.set(n.id,{...n,refreshedComplete:s}),s}};function T(e){let n=ue.exec(e);if(n!==null)return{id:S(n[1]),selector:n[2]==="all"?"all":Number(n[2]),mode:n[3]==="line"?"line":"match"}}c(T,"parseSearchAnchor");function k(e,n,t){let r=n==="all"?e.matches:[e.matches[n-1]].filter(he);if(t==="match"||n!=="all")return r;let o=new Set;return r.filter(s=>{let i=`${s.source}\0${String(s.lineNumber)}`;return o.has(i)?!1:(o.add(i),!0)})}c(k,"selectMatches");function he(e){return e!==void 0}c(he,"isMatch");function G(e,n,t){if(t==="match")return{start:{lineNumber:n.lineNumber,column:n.startColumn},end:{lineNumber:n.lineNumber,column:n.endColumn}};let r=S(e.lines[n.lineNumber-1]);return{start:{lineNumber:n.lineNumber,column:0},end:{lineNumber:n.lineNumber+(r.lineEnding.length>0?1:0),column:r.lineEnding.length>0?0:r.content.length},linewise:!0}}c(G,"selectionRange");async function J(e,n){let t=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await q(r,{encoding:"utf8",...n!==void 0&&{signal:n}}),s=w(r,o);for(let i of e.filter(a=>a.source===r)){let a=s.lines[i.lineNumber-1]?.content;if(a!==i.lineText||a.slice(i.startColumn,i.endColumn)!==i.matchedText)throw new Error(`Search result in ${r} changed before its anchors were registered.`)}t.set(r,o)}return t}c(J,"snapshotContents");async function I(e,n){try{return await q(e,{encoding:"utf8",...n!==void 0&&{signal:n}})}catch{return}}c(I,"readCurrent");function b(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}c(b,"staleAnchor");function x(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}c(x,"missingCompleteAnchor");function fe(e){if(e.length===0)return".";let n=h.dirname(h.resolve(S(e[0])));for(let t of e.slice(1)){let r=h.resolve(t);for(;!me(n,r);){let o=h.dirname(n);if(o===n)return n;n=o}}return n}c(fe,"commonSourceDirectory");function me(e,n){let t=h.relative(e,n);return t!==".."&&!t.startsWith(`..${h.sep}`)&&!h.isAbsolute(t)}c(me,"isWithin");function j(e,n){return e.source.localeCompare(n.source)||e.lineNumber-n.lineNumber||e.startColumn-n.startColumn||e.endColumn-n.endColumn}c(j,"compareMatches");export{L as a,$e as b,P as c,We as d,U as e,de as f,Q as g};
@@ -0,0 +1,3 @@
1
+ import{c as A}from"./chunk-YHUTTZC6.js";import{i as y,o as D,t as T,u as b}from"./chunk-RAZOACDD.js";import{a as R}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";function fe(e,t){let{lines:n,truncation:r,...o}=e,i=n?.map(u=>{let l=[u.lineNumber,T(u.content,t),u.lineEnding];return(u.presentation!==void 0||u.metadata!==void 0)&&l.push(u.presentation),u.metadata!==void 0&&l.push(u.metadata),l}),{content:d,...s}=r??{};return{...o,...i===void 0?{}:{storedLines:i},...r===void 0?{}:{truncation:s,truncatedText:T(d??"",t)}}}a(fe,"compactReadDetails");function k(e,t){let n=e;if(n.storedLines===void 0&&n.truncatedText===void 0)return e;let{storedLines:r,truncatedText:o,truncation:i,...d}=n;return{...d,...r===void 0?{}:{lines:r.map(([s,u,l,f,m])=>({lineNumber:s,content:b(u,t),lineEnding:l,...f==null?{}:{presentation:f},...m==null?{}:{metadata:m}}))},...i===void 0?{}:{truncation:{...i,content:b(o??"",t)}}}}a(k,"restoreReadDetails");import c from"node:path";import{homedir as H}from"node:os";import{createReadToolDefinition as I,getReadmePath as V}from"@earendil-works/pi-coding-agent";import{Text as q}from"@earendil-works/pi-tui";var w=I(process.cwd()),J=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function S(e,t=process.cwd()){if(typeof e!="object"||e===null)return;let n=e,r=n.path;if(typeof r!="string"||r.length===0||r.includes("#")||!c.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||n.views!==void 0&&(!Array.isArray(n.views)||n.views.length>0)||n.offset!==void 0&&(typeof n.offset!="number"||!Number.isInteger(n.offset)||n.offset<1)||n.limit!==void 0&&(typeof n.limit!="number"||!Number.isInteger(n.limit)||n.limit<1))return;let o=r.startsWith("~/")?c.join(H(),r.slice(2)):r,i=c.resolve(t,o),d=c.basename(i),s=c.relative(c.dirname(V()),i),u=!c.isAbsolute(s)&&(s==="README.md"||s.startsWith(`docs${c.sep}`)||s.startsWith(`examples${c.sep}`));if(!(d!=="SKILL.md"&&!J.has(d)&&!u))return{path:r,...n.offset===void 0?{}:{offset:n.offset},...n.limit===void 0?{}:{limit:n.limit}}}a(S,"nativeReadArguments");function L(e,t){return{...e,args:t,lastComponent:e.lastComponent instanceof q?e.lastComponent:void 0}}a(L,"nativeReadContext");import{getLanguageFromPath as O,getMarkdownTheme as Z,highlightCode as z,keyHint as K}from"@earendil-works/pi-coding-agent";import{Container as M,Markdown as X,Text as Y,truncateToWidth as g,visibleWidth as p,wrapTextWithAnsi as Q}from"@earendil-works/pi-tui";var P=12;function De(e,t,n){let r=S(e,n.cwd);if(r!==void 0)return R(w.renderCall)(r,t,L(n,r));let o=typeof e.path=="string"?e.path:"inherited source",i=typeof e.offset=="number"?e.offset:void 0,d=typeof e.limit=="number"?e.limit:void 0,s=Array.isArray(e.views)?e.views.filter(f=>typeof f=="string"):[],u=[...i===void 0?[]:[{text:i<0?`tail ${String(Math.abs(i))}`:`offset ${String(i)}`}],...d===void 0?[]:[{text:`limit ${String(d)}`}],...s.length===0?[]:[{text:`views ${s.join(",")}`}]],l=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...i===void 0?[]:[{label:"offset",value:String(i)}],...d===void 0?[]:[{label:"limit",value:String(d)}],...s.length===0?[]:[{label:"views",value:s.join(",")}]];return A(n.lastComponent,{tool:"read",primary:{text:o,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:u,details:l,expanded:n.expanded},t)}a(De,"renderReadCall");function Ae(e){let t=new WeakMap;return(n,r,o,i)=>{let d=e.nativeResources?S(i.args,i.cwd):void 0;if(d!==void 0&&!r.isPartial)return R(w.renderResult)({...n,details:{truncation:W(n.details).truncation}},r,o,L(i,d));if(r.isPartial||i.isError){let f=$(n),m=i.isError?"error":"dim";return new Y(o.fg(m,f),0,0)}if(!ae(n))return i.lastComponent instanceof M?i.lastComponent:new M;let s=t.get(n);s===void 0&&(s=k(W(n.details),$(n)),t.set(n,s));let l=(i.lastComponent instanceof h?i.lastComponent:void 0)??new h({result:n,details:s,options:e,expanded:r.expanded,theme:o});return l.update({result:n,details:s,options:e,expanded:r.expanded,theme:o}),l}}a(Ae,"createReadResultRenderer");var h=class{constructor(t){this.state=t}static{a(this,"ReadResultPanel")}cached;update(t){this.state.result===t.result&&this.state.details===t.details&&this.state.options===t.options&&this.state.expanded===t.expanded&&this.state.theme===t.theme||(this.state=t,this.invalidate())}render(t){if(this.cached?.width===t)return this.cached.lines;if(t<8){let l=[g(B(this.state,t),Math.max(1,t))];return this.cached={width:t,lines:l},l}let n=t-2,r=Math.max(1,n-2),o=_(this.state,r),i=te(o,this.state.expanded,this.state.theme),d=[ne(this.state,n,this.state.theme)];for(let l of i)for(let f of Q(l,r))d.push(N(f,n,this.state.theme));let s=ie(this.state.details,this.state.theme);s!==void 0&&d.push(N(s,n,this.state.theme)),d.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(n)}\u256F`));let u=d.map(l=>g(l,t));return this.cached={width:t,lines:u},u}invalidate(){this.cached=void 0}};function _(e,t){let n=G(e.details),r=oe(e.result,n,e.details,!e.expanded);if(e.options.kind==="markdown"||se(e.details,n,e.options.kind)){let s=new X(r,0,0,Z());return v(s.render(t),e.theme)}if(e.options.kind==="code-view"){let s=n===void 0||E(n)?j(r).map(u=>U(u,e.theme,!1)):ee(n,e.theme);return v(s,e.theme)}let o=n===void 0||E(n)?j(r).map(x):n.map(({content:s})=>x(s)),i=C(e.details,n),d=i===void 0?o.map(s=>e.theme.fg("toolOutput",s)):z(o.join(`
2
+ `),i);return v(d,e.theme)}a(_,"renderContentRows");function ee(e,t){return e.map(n=>{let r=y(n);if(r===void 0)return U(n.content,t);let o=O(r.source),i=x(F(n.content));return o===void 0?t.fg("toolOutput",i):z(i,o)[0]??t.fg("toolOutput",i)})}a(ee,"renderCodeViewLines");function F(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}a(F,"stripScopeMarkers");function U(e,t,n=!0){let r=x(n?F(e):e);return/^#{2,3}\s/u.test(r)?t.fg("mdHeading",t.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?t.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?t.fg("accent",t.bold(r)):/^\s*[-*]\s/u.test(r)?t.fg("mdListBullet",r):t.fg("toolOutput",r)}a(U,"renderCodeViewLabel");function te(e,t,n){if(t||e.length<=P)return e;let r=e.slice(0,P-1),o=e.length-r.length;return[...r,`${n.fg("dim",`\u2026 ${String(o)} more ${o===1?"row":"rows"} \xB7 `)}${K("app.tools.expand","to expand")}`]}a(te,"compactRows");function ne(e,t,n){let r=a(d=>n.fg("borderMuted",d),"frame"),o=g(` ${B(e,Math.max(1,t-1))} `,Math.max(0,t-1),""),i="\u2500".repeat(Math.max(0,t-p(o)-1));return`${r("\u256D\u2500")}${o}${r(`${i}\u256E`)}`}a(ne,"renderTopBorder");function B(e,t){let n=e.options.label??ue(C(e.details,G(e.details))),r=e.details.source??"read result",o=re(e.details),i=e.theme.fg("accent",e.theme.bold(n)),d=o===void 0?"":e.theme.fg("dim",` \xB7 ${o}`),s=Math.max(1,t-p(i)-p(d)-2),u=le(r,s);return`${i} ${e.theme.fg("muted",u)}${d}`}a(B,"readTitle");function re(e){if(!(e.startLine===void 0||e.endLine===void 0||e.totalLines===void 0||e.totalLines<=0))return`${String(e.startLine)}\u2013${String(e.endLine)} / ${String(e.totalLines)}`}a(re,"sourceRange");function ie(e,t){let n=e.truncation;if(n?.firstLineExceedsLimit===!0)return t.fg("warning","First source line is larger than the saved read limit");if(n?.truncated===!0)return t.fg("warning",`Saved result contains ${String(n.outputLines)} of ${String(n.totalLines)} rendered rows`)}a(ie,"readStatus");function N(e,t,n){let r=Math.max(0,t-2),o=g(e,r),i=` ${o}${" ".repeat(Math.max(0,r-p(o)))} `,d=n.fg("borderMuted","\u2502");return`${d}${i}${d}`}a(N,"framed");function oe(e,t,n,r){if(t!==void 0)return D({source:n.source??"",content:"",lines:t},{compact:r});let o=$(e);return n.truncation===void 0&&!(n.totalLines!==void 0&&n.endLine!==void 0&&n.endLine<n.totalLines)?o:o.replace(/\n\n\[(?:Showing lines|Output truncated|\d+ more lines in source)[\s\S]*\]$/u,"")}a(oe,"cleanText");function E(e){return e.some(t=>t.presentation!==void 0)}a(E,"hasPresentation");function j(e){let t=e.split(/\r\n|\r|\n/u);return t.at(-1)===""&&/(?:\r\n|\r|\n)$/u.test(e)&&t.pop(),t}a(j,"splitTextRows");function $(e){return e.content.flatMap(t=>t.type==="text"?[t.text]:[]).join(`
3
+ `)}a($,"textBlocks");function G(e){return e.lines}a(G,"readLines");function W(e){return typeof e=="object"&&e!==null?e:{}}a(W,"readDetails");function ae(e){return e.content.some(t=>t.type==="text")}a(ae,"hasTextContent");function C(e,t){let r=t?.map(y).find(o=>o!==void 0)?.source??e.source;return r===void 0?void 0:O(de(r))}a(C,"languageFor");function se(e,t,n){return n==="source"&&C(e,t)==="markdown"}a(se,"isMarkdownSource");function de(e){try{let t=new URL(e);return t.protocol==="file:"?t.pathname:`${t.pathname}${t.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}a(de,"normalizeSourcePath");function x(e){let t="";for(let n of e.replaceAll(" "," ".repeat(4))){let r=R(n.codePointAt(0));t+=r<32||r===127?"\uFFFD":n}return t}a(x,"normalizeText");function ue(e){return e===void 0?"TEXT":{javascript:"JS",json:"JSON",markdown:"MD",python:"PY",rust:"RS",typescript:"TS"}[e]??e.slice(0,4).toUpperCase()}a(ue,"languageLabel");function v(e,t){return e.length===0?[t.fg("dim","Empty content")]:[...e]}a(v,"nonEmptyRows");function le(e,t){return p(e)<=t?e:t<=1?"\u2026":`\u2026${e.slice(-(t-1))}`}a(le,"truncateFromStart");export{fe as a,De as b,Ae as c};
@@ -0,0 +1 @@
1
+ import{b as P,c as $,d as j}from"./chunk-N34ATN52.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import S from"cross-spawn";import{readFile as w,writeFile as R}from"node:fs/promises";import I from"node:os";import l from"node:path";import{fileURLToPath as A}from"node:url";var N=1;function Z(e){return l.win32.basename(y(e[0]))}i(Z,"configuredExecutableName");function M(e){return l.join(e,".pi","pi-agent-ide")}i(M,"projectIdeConfigDirectory");function D(e,n){return l.join(M(e),`${n}.json`)}i(D,"projectIdeConfigPath");function _(e,n,o={}){let t=(o.environment??process.env).PI_CODING_AGENT_DIR?.trim(),a=t===void 0||t.length===0?l.join(o.homeDirectory??I.homedir(),".pi","agent"):l.resolve(t);return{project:D(e,n),global:l.join(a,"extensions","pi-agent-ide",`${n}.json`),builtIn:A(new URL(`tool-config/${n}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}i(_,"resolveToolConfigPaths");async function ee(e,n,o,r={}){let t=_(e,n,r),a=[{layer:"project",sourcePath:t.project,optional:!0},{layer:"global",sourcePath:t.global,optional:!0},{layer:"built-in",sourcePath:t.builtIn,optional:!1}],s=[],f=new Set;for(let d of a){let c=await V(d,n,o);for(let[u,h]of Object.entries(c))f.has(u)||(f.add(u),s.push({id:u,config:h,layer:d.layer,sourcePath:d.sourcePath}))}return{entries:s,paths:t}}i(ee,"loadLayeredToolConfig");function G(e,n,o){let r=l.extname(n).toLowerCase();if(e.extensions.every(s=>!(B(s)===r||s==="*"))&&!e.fileNames?.some(s=>process.platform==="win32"?s.toLowerCase()===l.basename(n).toLowerCase():s===l.basename(n)))return!1;let t=l.relative(o,n).split(l.sep).join("/"),a=i(s=>s?.some(f=>l.matchesGlob(t,f))??!1,"matches");return(e.include===void 0||a(e.include))&&!a(e.exclude)}i(G,"matchesConfiguredFile");function ne(e,n,o,r,t){let a=l.resolve(t,r),s=e.filter(c=>G(c.config,a,t)),f=s.find(c=>c.layer!=="built-in");if(f!==void 0)return f;let d=Math.max(0,...s.map(c=>o.get(c.id)?.score??0));return s.find(c=>n.has(c.id)&&(o.get(c.id)?.score??0)===d)}i(ne,"selectConfiguredEntry");async function oe(e,n,o=process.env){C(e,"process");let r=y(e.command[0]).replaceAll("{project}",n),t=O(e,n,o);return j(r,n,t)}i(oe,"hasConfiguredExecutable");async function J(e,n){C(e,"process");let o=e.command.map(d=>q(d,n)),r=y(o[0]),t=o.slice(1),a=e.cwd==="file"?l.dirname(n.filePath):n.projectRoot,s=e.successExitCodes??[0],f=O(e,n.projectRoot,n.env??process.env);return new Promise((d,c)=>{let u=S(r,t,{cwd:a,env:f,signal:n.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),h="",v="",E=y(u.stdout),x=y(u.stderr),T=!1,b=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);E.setEncoding("utf8"),x.setEncoding("utf8"),E.on("data",g=>{h+=g}),x.on("data",g=>{v+=g}),u.on("error",g=>{clearTimeout(b),c(g)}),u.on("close",g=>{clearTimeout(b),d({ok:!T&&g!==null&&s.includes(g),exitCode:g,stdout:h,stderr:v})})})}i(J,"runConfiguredProcess");async function re(e,n){let o=await w(n.filePath,"utf8"),r=await J(e.run,n);if(!r.ok)return e.output==="in-place"&&await w(n.filePath,"utf8")!==o&&await R(n.filePath,o,"utf8"),{ok:!1,changed:!1};e.output==="stdout"&&r.stdout!==o&&await R(n.filePath,r.stdout,"utf8");let t=await w(n.filePath,"utf8");return{ok:!0,changed:o!==t}}i(re,"runConfiguredFormatter");function te(e){let n=k(e,"formatters");for(let[o,r]of Object.entries(n.entries)){let t=m(r,`formatter ${o}`);if(F(t,`formatter ${o}`),C(t.run,`formatter ${o}.run`),t.output!=="in-place"&&t.output!=="stdout")throw new Error(`formatter ${o}.output must be in-place or stdout`)}return e}i(te,"parseFormattersConfig");function ie(e){let n=k(e,"linters"),o=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,t]of Object.entries(n.entries)){let a=m(t,`linter ${r}`);F(a,`linter ${r}`),C(a.check,`linter ${r}.check`),a.fix!==void 0&&C(a.fix,`linter ${r}.fix`);let s=m(a.diagnostics,`linter ${r}.diagnostics`);if(!o.has(String(s.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(s.columnBase!==void 0&&(s.format!=="regex"||s.columnBase!==0&&s.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(s.format==="regex"&&typeof s.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}i(ie,"parseLintersConfig");function k(e,n){let o=m(e,"tool config");if(o.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:m(o[n],n)}}i(k,"configRoot");function F(e,n){p(e.extensions,`${n}.extensions`,!1),e.fileNames!==void 0&&p(e.fileNames,`${n}.fileNames`,!1),e.include!==void 0&&p(e.include,`${n}.include`,!1),e.exclude!==void 0&&p(e.exclude,`${n}.exclude`,!0)}i(F,"assertMatcher");function C(e,n){let o=m(e,n);if(p(o.command,`${n}.command`,!1),o.cwd!==void 0&&o.cwd!=="project"&&o.cwd!=="file")throw new Error(`${n}.cwd must be project or file`);if(o.timeoutMs!==void 0&&(!Number.isFinite(o.timeoutMs)||Number(o.timeoutMs)<=0))throw new Error(`${n}.timeoutMs must be positive`);if(o.successExitCodes!==void 0&&(!Array.isArray(o.successExitCodes)||o.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${n}.successExitCodes must contain integers`);if(o.env!==void 0){let r=m(o.env,`${n}.env`);if(Object.values(r).some(t=>typeof t!="string"))throw new Error(`${n}.env values must be strings`)}}i(C,"assertProcessConfig");function p(e,n,o){if(!Array.isArray(e)||!o&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${n} must be ${o?"an":"a non-empty"} array of strings`)}i(p,"assertStringArray");function m(e,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${n} must be an object`);return e}i(m,"configRecord");function B(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}i(B,"normalizeExtension");async function V(e,n,o){let r;try{r=await w(e.sourcePath,"utf8")}catch(t){if(e.optional&&U(t))return{};throw new Error(`Cannot read ${e.layer} ${n} config at ${e.sourcePath}: ${L(t)}`,{cause:t})}try{return o(JSON.parse(r))}catch(t){throw new Error(`Invalid ${e.layer} ${n} config at ${e.sourcePath}: ${L(t)}`,{cause:t})}}i(V,"readToolConfigLayer");function U(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}i(U,"isMissingFile");function L(e){return e instanceof Error?e.message:String(e)}i(L,"errorMessage");function O(e,n,o){return $(n,{...P(o),...P(e.env??{})})}i(O,"createConfiguredProcessEnvironment");function q(e,n){let o=l.relative(n.projectRoot,n.filePath);return e.replaceAll("{project}",n.projectRoot).replaceAll("{fileDir}",l.dirname(n.filePath)).replaceAll("{relativeFile}",o).replaceAll("{file}",n.filePath)}i(q,"expandPlaceholders");export{N as a,Z as b,M as c,D as d,_ as e,ee as f,G as g,ne as h,oe as i,J as j,re as k,te as l,ie as m,O as n};
@@ -1 +1 @@
1
- import{a as c}from"./chunk-2SKAED2I.js";import{a as l}from"./chunk-ZC65Z3CK.js";import{a as r}from"./chunk-EI7MMDWY.js";var u=Symbol.for("pi-agent-text-editor/TextSelectionAnchor"),d=class extends c{constructor(t,o,i){let s=i.map(a=>({start:{...a.start},end:{...a.end},...a.linewise===!0&&{linewise:!0}}));g(s);super(t,l(s[0]).start.lineNumber);this.source=o;if(o.length===0)throw new TypeError("Text selection anchor source must be non-empty");this.ranges=s}static{r(this,"TextSelectionAnchor")}[u]=!0;ranges;static is(t){if(!c.is(t))return!1;try{let o=t,i=o.ranges;return o[u]===!0&&typeof o.source=="string"&&o.source.length>0&&Array.isArray(i)&&i.length>0&&i.every(x)}catch{return!1}}};function g(n){if(n.length===0)throw new TypeError("Text selection anchor must contain at least one range");let e;for(let t of n){if(!x(t)||p(t.start,t.end)>0)throw new RangeError("Text selection anchor contains an invalid range");if(e!==void 0&&p(t.start,e.end)<0)throw new Error("Text selection anchor ranges must be ordered and must not overlap");e=t}}r(g,"assertSelectionRanges");function x(n){if(typeof n!="object"||n===null)return!1;let e=n;return f(e.start)&&f(e.end)&&(e.linewise===void 0||typeof e.linewise=="boolean")}r(x,"isTextSelectionRange");function f(n){if(typeof n!="object"||n===null)return!1;let e=n;return Number.isSafeInteger(e.lineNumber)&&(e.lineNumber??0)>=1&&Number.isSafeInteger(e.column)&&(e.column??-1)>=0}r(f,"isTextSelectionPosition");function p(n,e){return n.lineNumber-e.lineNumber||n.column-e.column}r(p,"comparePositions");export{d as a};
1
+ import{a as c}from"./chunk-RAZOACDD.js";import{a as l}from"./chunk-ZC65Z3CK.js";import{a as r}from"./chunk-EI7MMDWY.js";var u=Symbol.for("pi-agent-text-editor/TextSelectionAnchor"),d=class extends c{constructor(t,o,i){let s=i.map(a=>({start:{...a.start},end:{...a.end},...a.linewise===!0&&{linewise:!0}}));g(s);super(t,l(s[0]).start.lineNumber);this.source=o;if(o.length===0)throw new TypeError("Text selection anchor source must be non-empty");this.ranges=s}static{r(this,"TextSelectionAnchor")}[u]=!0;ranges;static is(t){if(!c.is(t))return!1;try{let o=t,i=o.ranges;return o[u]===!0&&typeof o.source=="string"&&o.source.length>0&&Array.isArray(i)&&i.length>0&&i.every(x)}catch{return!1}}};function g(n){if(n.length===0)throw new TypeError("Text selection anchor must contain at least one range");let e;for(let t of n){if(!x(t)||p(t.start,t.end)>0)throw new RangeError("Text selection anchor contains an invalid range");if(e!==void 0&&p(t.start,e.end)<0)throw new Error("Text selection anchor ranges must be ordered and must not overlap");e=t}}r(g,"assertSelectionRanges");function x(n){if(typeof n!="object"||n===null)return!1;let e=n;return f(e.start)&&f(e.end)&&(e.linewise===void 0||typeof e.linewise=="boolean")}r(x,"isTextSelectionRange");function f(n){if(typeof n!="object"||n===null)return!1;let e=n;return Number.isSafeInteger(e.lineNumber)&&(e.lineNumber??0)>=1&&Number.isSafeInteger(e.column)&&(e.column??-1)>=0}r(f,"isTextSelectionPosition");function p(n,e){return n.lineNumber-e.lineNumber||n.column-e.column}r(p,"comparePositions");export{d as a};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import v from"cross-spawn";import{constants as E}from"node:fs";import{access as b,stat as P}from"node:fs/promises";import a from"node:path";function w(e){let r=process.platform==="win32"?"Scripts":"bin";return["node_modules/.bin",`.venv/${r}`,`venv/${r}`,"vendor/bin"].map(o=>a.resolve(e,o))}i(w,"projectExecutableDirectories");function x(e){return process.platform!=="win32"?{...e}:Object.fromEntries(Object.entries(e).map(([r,o])=>[r.toUpperCase(),o]))}i(x,"normalizeProcessEnvironment");function g(e,r){let o=x(r);return o.PATH=[...w(e),o.PATH].filter(Boolean).join(a.delimiter),o}i(g,"projectProcessEnvironment");async function h(e,r,o){let l=g(r,o),f=a.isAbsolute(e)||a.dirname(e)!=="."?[a.resolve(r,e)]:(l.PATH??"").split(a.delimiter).filter(Boolean).map(t=>a.join(process.platform==="win32"?t.replace(/^"|"$/gu,""):t,e)),s=process.platform==="win32"?[...new Set((l.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).flatMap(t=>[t,t.toLowerCase()]))]:[],c=f.flatMap(t=>[t,...s.map(p=>`${t}${p}`)]);for(let t of c)try{if(await b(t,E.X_OK),!(await P(t)).isFile())continue;return!0}catch{}return!1}i(h,"isExecutableAvailable");function A(e,r,o,l){return new Promise(f=>{let s=v(e,r,{cwd:o,env:g(o,l),stdio:["ignore","pipe","pipe"],windowsHide:!0}),c="",t="",p=!1,m=setTimeout(()=>{s.kill(),d(!1,`${e} did not respond within 5 seconds`)},5e3),d=i((n,u)=>{p||(p=!0,clearTimeout(m),f(n?{ok:!0,detail:u}:{ok:!1,detail:u}))},"finish");s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",n=>c+=n),s.stderr?.on("data",n=>t+=n),s.once("error",n=>d(!1,n.message)),s.once("close",n=>{let u=(c.trim()||t.trim()).split(/\r?\n/u)[0];d(n===0,u||`${e} exited with code ${String(n)}`)}),m.unref()})}i(A,"probeExecutable");export{w as a,x as b,g as c,h as d,A as e};
@@ -1 +1 @@
1
- import{a as m}from"./chunk-2SKAED2I.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createHash as g}from"node:crypto";var u=/^([1-9]\d*)#([A-Z0-9]{3,4})$/,x=/(?<![A-Za-z0-9])([1-9]\d*#[A-Z0-9]{3,4})(?![A-Za-z0-9])/g;function A(e){let n=[...e.matchAll(x)],t=n[0];return n.length===1&&t!==void 0?h(t[1]):e}s(A,"normalizeLineHashAnchor");var d=class extends m{static{s(this,"LineHashTextAnchor")}constructor(n,t){super(`${n}#${f(t)}`,n)}};function f(e){return g("sha1").update(e).digest("hex").slice(0,4).toUpperCase()}s(f,"hashLine");function p(e,n){return new d(e,n)}s(p,"createLineHashAnchor");function v(e,n){return p(e,n).value}s(v,"formatLineHashAnchor");function y(e,n=1,t=e.length){let o=Math.max(1,n),r=Math.min(e.length,t);if(r<o)return[];let a=e.map((i,l)=>v(l+1,i)),c=Math.max(0,...a.map(i=>i.length));return e.slice(o-1,r).map((i,l)=>`${h(a[o+l-1]).padStart(c)}|${i}`)}s(y,"renderLineHashLines");function k(){return{id:"line-hash",description:"Use the complete `LINE#HASH` printed before a source line, for example `12#A4F0`; the hash rejects stale text.",normalize:A,renderFull(e){return e},renderCompact(e){return`line ${u.exec(e)?.[1]??"?"}`},tryResolve(e,n){return Promise.resolve(b(e,n))},recover(e,n){let t=u.exec(e);if(t===null)return Promise.resolve({kind:"unavailable"});let o=Number(t[1]),r=Math.min(Math.max(1,o),n.lines.length),a=n.lines[r-1];return a===void 0?Promise.resolve({kind:"unavailable"}):Promise.resolve({kind:"candidates",total:1,candidates:[{rank:1,range:{start:{lineNumber:r,column:0},end:{lineNumber:r,column:a.length}}}]})}}}s(k,"createLineHashAnchorResolver");function b(e,n){let t=u.exec(e);if(t===null)return{kind:"not-handled"};let o=Number(t[1]),r=n.lines[o-1];if(r===void 0||f(r)!==t[2]){let c=Math.max(1,o-5),i=Math.min(n.lines.length,o+5);return{kind:"rejected",rejection:{code:r===void 0?"missing":"stale",reason:r===void 0?"line hash anchor is out of range":"line hash anchor is stale",contextRange:{offset:c,limit:i-c+1}}}}return{kind:"resolved",anchor:p(o,r)}}s(b,"resolveLineHashAnchor");export{f as a,p as b,v as c,y as d,k as e};
1
+ import{a as m}from"./chunk-RAZOACDD.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createHash as g}from"node:crypto";var u=/^([1-9]\d*)#([A-Z0-9]{3,4})$/,x=/(?<![A-Za-z0-9])([1-9]\d*#[A-Z0-9]{3,4})(?![A-Za-z0-9])/g;function A(e){let n=[...e.matchAll(x)],t=n[0];return n.length===1&&t!==void 0?h(t[1]):e}s(A,"normalizeLineHashAnchor");var d=class extends m{static{s(this,"LineHashTextAnchor")}constructor(n,t){super(`${n}#${f(t)}`,n)}};function f(e){return g("sha1").update(e).digest("hex").slice(0,4).toUpperCase()}s(f,"hashLine");function p(e,n){return new d(e,n)}s(p,"createLineHashAnchor");function v(e,n){return p(e,n).value}s(v,"formatLineHashAnchor");function y(e,n=1,t=e.length){let o=Math.max(1,n),r=Math.min(e.length,t);if(r<o)return[];let a=e.map((i,l)=>v(l+1,i)),c=Math.max(0,...a.map(i=>i.length));return e.slice(o-1,r).map((i,l)=>`${h(a[o+l-1]).padStart(c)}|${i}`)}s(y,"renderLineHashLines");function k(){return{id:"line-hash",description:"Use the complete `LINE#HASH` printed before a source line, for example `12#A4F0`; the hash rejects stale text.",normalize:A,renderFull(e){return e},renderCompact(e){return`line ${u.exec(e)?.[1]??"?"}`},tryResolve(e,n){return Promise.resolve(b(e,n))},recover(e,n){let t=u.exec(e);if(t===null)return Promise.resolve({kind:"unavailable"});let o=Number(t[1]),r=Math.min(Math.max(1,o),n.lines.length),a=n.lines[r-1];return a===void 0?Promise.resolve({kind:"unavailable"}):Promise.resolve({kind:"candidates",total:1,candidates:[{rank:1,range:{start:{lineNumber:r,column:0},end:{lineNumber:r,column:a.length}}}]})}}}s(k,"createLineHashAnchorResolver");function b(e,n){let t=u.exec(e);if(t===null)return{kind:"not-handled"};let o=Number(t[1]),r=n.lines[o-1];if(r===void 0||f(r)!==t[2]){let c=Math.max(1,o-5),i=Math.min(n.lines.length,o+5);return{kind:"rejected",rejection:{code:r===void 0?"missing":"stale",reason:r===void 0?"line hash anchor is out of range":"line hash anchor is stale",contextRange:{offset:c,limit:i-c+1}}}}return{kind:"resolved",anchor:p(o,r)}}s(b,"resolveLineHashAnchor");export{f as a,p as b,v as c,y as d,k as e};
@@ -0,0 +1,2 @@
1
+ import{a as o}from"./chunk-EI7MMDWY.js";import{convertToPng as k,formatDimensionNote as x,resizeImage as A}from"@earendil-works/pi-coding-agent";var g=[137,80,78,71,13,10,26,10];function y(){return{id:"image",description:"Image paths and URLs return image content.",async tryConvert(e,n){let i=f(n.signal);if(i!==void 0)return{kind:"failed",error:i};let r=T(e.bytes);if(r.kind==="not-handled")return r;if(r.kind==="invalid")return{kind:"failed",error:new TypeError(`${e.source}: ${r.message}`)};try{let t=await h(e.bytes,r.mimeType),a=f(n.signal);return a!==void 0?{kind:"failed",error:a}:{kind:"converted",content:t}}catch(t){return{kind:"failed",error:f(n.signal)??new TypeError(`Unable to process image ${e.source}`,{cause:t})}}}}}o(y,"createImageContentConverter");function U(e){let n=T(e);return n.kind==="supported"?n.mimeType:null}o(U,"detectSupportedImageMimeType");async function h(e,n){let i=e,r=n,t;if(n==="image/bmp"){let l=await k(Buffer.from(e).toString("base64"),n);if(l===null)throw new TypeError("Unable to convert image/bmp to an inline image format");i=Buffer.from(l.data,"base64"),r=l.mimeType,t=n}let a=await A(i,r);if(a===null)throw new TypeError(`Unable to normalize ${n} within Pi inline image limits`);let u=[];t!==void 0&&t!==a.mimeType&&u.push(`[Image converted from ${t} to ${a.mimeType}.]`);let c=x(a);return c!==void 0&&u.push(c),[{type:"text",text:[`Read image [${a.mimeType}]`,...u].join(`
2
+ `)},{type:"image",data:a.data,mimeType:a.mimeType}]}o(h,"createImageContent");function T(e){return s(e,[255,216,255])?e[3]===247?{kind:"not-handled"}:{kind:"supported",mimeType:"image/jpeg"}:s(e,g)?v(e)?w(e)?{kind:"invalid",message:"Animated PNG is not supported"}:{kind:"supported",mimeType:"image/png"}:{kind:"invalid",message:"Malformed PNG image"}:m(e,0,"GIF87a")||m(e,0,"GIF89a")?{kind:"supported",mimeType:"image/gif"}:m(e,0,"RIFF")&&m(e,8,"WEBP")?{kind:"supported",mimeType:"image/webp"}:m(e,0,"BM")?C(e)?{kind:"supported",mimeType:"image/bmp"}:{kind:"invalid",message:"Malformed BMP image"}:{kind:"not-handled"}}o(T,"inspectImage");function v(e){return e.length>=33&&I(e,g.length)===13&&m(e,12,"IHDR")}o(v,"isPng");function w(e){let n=g.length;for(;n+8<=e.length;){let i=I(e,n),r=n+4;if(m(e,r,"acTL"))return!0;if(m(e,r,"IDAT"))return!1;let t=n+8+i+4;if(t<=n||t>e.length)return!1;n=t}return!1}o(w,"isAnimatedPng");function C(e){if(e.length<26)return!1;let n=p(e,2),i=p(e,10),r=p(e,14);if(n!==0&&(n<26||n>e.length)||i<14+r||i>=e.length||n!==0&&i>=n)return!1;let t,a;if(r===12)t=d(e,22),a=d(e,24);else if(r>=40&&r<=124){if(e.length<30)return!1;t=d(e,26),a=d(e,28)}else return!1;return t===1&&[1,4,8,16,24,32].includes(a)}o(C,"isBmp");function d(e,n){return(e[n]??0)+((e[n+1]??0)<<8)}o(d,"readUint16LE");function I(e,n){return(e[n]??0)*16777216+((e[n+1]??0)<<16)+((e[n+2]??0)<<8)+(e[n+3]??0)}o(I,"readUint32BE");function p(e,n){return(e[n]??0)+((e[n+1]??0)<<8)+((e[n+2]??0)<<16)+(e[n+3]??0)*16777216}o(p,"readUint32LE");function s(e,n){return e.length>=n.length&&n.every((i,r)=>e[r]===i)}o(s,"startsWith");function m(e,n,i){if(e.length<n+i.length)return!1;for(let r=0;r<i.length;r+=1)if(e[n+r]!==i.codePointAt(r))return!1;return!0}o(m,"startsWithAscii");function f(e){if(e?.aborted===!0)return e.reason instanceof Error?e.reason:E()}o(f,"cancellationError");function E(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(E,"abortError");export{y as a,U as b,h as c};
@@ -0,0 +1,2 @@
1
+ import"./chunk-NNCZYO4Q.js";import{c as E}from"./chunk-KCEOTU5Z.js";import"./chunk-YHUTTZC6.js";import{a as A}from"./chunk-ORAPGW7W.js";import{a as I,b as k}from"./chunk-JASLOB2X.js";import{e as f,f as m,g as R,h as D,i as h,l as P}from"./chunk-X6MPU7UO.js";import"./chunk-RAZOACDD.js";import{a as y}from"./chunk-OBWZ5RYN.js";import{a as v,b as w}from"./chunk-KZBAJFCV.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import O from"node:path";var x="diagnostics",S=E({kind:"code-view",label:"Diagnostics"});async function T(o){let i,e=a((r,d)=>{if(i===void 0)throw new Error("IDE diagnostics are not connected");return i(r,{cwd:d})},"collect"),s={protocol:v,apiVersion:3,id:"diagnostics",setup(r){i=r.readDiagnostics}},n=new WeakMap,l=new WeakMap,C={protocol:I,apiVersion:k,id:"diagnostics",setup(r){r.addResolver({resolver:V(e),renderResult:S});let d=P();r.addView({view:"diagnostics",priority:100,presenter:q(e,l)}),r.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(t){return t.state?.resolvedBy==="diagnostics"?d(t):(t.state?.contentKind==="text"&&t.request.views?.includes("diagnostics")&&n.set(t.request,t.state.text),{kind:"continue",context:t})}}),r.addHandler({stage:"post-read",handler(t){let g=n.get(t.request),p=g&&l.get(g),c=t.result,u=c?.content[0];return!p||!c||u?.type!=="text"?{kind:"continue",context:t}:{kind:"continue",context:{...t,result:{...c,content:[{...u,text:`${p}
2
+ ${u.text}`},...c.content.slice(1)]}}}}}),r.describe('diagnostics:<path> \u2014 lint and language-server diagnostics. views: ["diagnostics"] \u2014 diagnostics alongside source text. Diagnostic sources name the actual reporting tools. Automatic notices include findings only and wake an idle agent as soon as results arrive; silence does not prove the file is clean. Use an explicit diagnostic read to check readiness. Pending results and snapshots are not completed checks; an empty snapshot does not prove the file is clean.'),r.addPromptGuideline("Use read with `diagnostics:<path>` or the `diagnostics` view for per-file diagnostics instead of running equivalent checks through Bash. Project builds and tests remain separate verification.")}};await Promise.all([y(o,s),A(o,C)])}a(T,"registerDiagnostics");function V(o){return{id:"diagnostics",tryResolve(i,e){return Promise.resolve(_(i,e.cwd,o))}}}a(V,"createDiagnosticResolver");function _(o,i,e){let s;try{s=f(o,x,i)}catch(n){return{kind:"failed",error:n}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:m(x,s),async read(){let n=await e(s,i);return[R(s,n.content,n.results)]}}}}a(_,"resolveDiagnosticSource");function q(o,i){return{id:"diagnostics",async present(e,s){if(s.purpose!=="read"||!O.isAbsolute(e.source))return e;let n=await o(e.source,s.cwd);if(n.content!==e.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return i.set(e,h(n.results)),D(e,n.results)}}}a(q,"createDiagnosticPresenter");export{T as default};
@@ -1,2 +1,2 @@
1
- import{a as r}from"./chunk-EI7MMDWY.js";import{Type as n}from"typebox";import{Value as C}from"typebox/value";var f=Symbol.for("pi-agent-text/TextAnchor"),u=class{constructor(t,o){this.value=t;this.lineNumber=o;if(t.length===0)throw new TypeError("Text anchor value must be non-empty");if(!Number.isSafeInteger(o)||o<1)throw new RangeError("Text anchor line number must be a positive safe integer")}static{r(this,"TextAnchor")}[f]=!0;static is(t){if(typeof t!="object"||t===null)return!1;try{let o=t;return o[f]===!0&&typeof o.value=="string"&&Number.isSafeInteger(o.lineNumber)&&o.lineNumber>=1}catch{return!1}}toString(){return this.value}},x=new WeakMap;function w(e,t,o){x.set(e,{renderer:t,resolverId:o})}r(w,"attachTextAnchorRenderer");function S(e){return x.get(e)?.renderer}r(S,"getTextAnchorRenderer");function P(e,t,o){let i=x.get(e);if(i===void 0)throw new Error(`No renderer is attached to text anchor "${t}"`);return{...i.renderer,resolverId:i.resolverId,full:i.renderer.renderFull(t,o),compact:i.renderer.renderCompact(t,o)}}r(P,"renderTextAnchor");var a={additionalProperties:!0},l=n.Function([],n.Unknown()),g=n.Object({lineNumber:n.Integer({minimum:1}),column:n.Integer({minimum:0})},a),j=n.Object({rank:n.Integer({minimum:1}),range:n.Object({start:g,end:g},a)},a),L=n.Object({id:n.String({minLength:1}),description:n.Union([n.String(),l]),normalize:n.Optional(l),renderFull:l,renderCompact:l,tryResolve:l,recover:n.Optional(l)},a),O=n.Object({code:n.Union([n.Literal("invalid"),n.Literal("stale"),n.Literal("missing"),n.Literal("ambiguous")]),reason:n.String(),contextRange:n.Optional(n.Object({offset:n.Number(),limit:n.Number()}))}),E=n.Union([n.Object({kind:n.Literal("not-handled")},a),n.Object({kind:n.Literal("resolved"),anchor:n.Unknown()},a),n.Object({kind:n.Literal("rejected"),rejection:O},a),n.Object({kind:n.Literal("failed"),error:n.Unknown()},a)]),N=n.Union([n.Object({kind:n.Literal("unavailable")},a),n.Object({kind:n.Literal("candidates"),candidates:n.Array(j),total:n.Integer({minimum:0})},a),n.Object({kind:n.Literal("timed-out")},a),n.Object({kind:n.Literal("failed"),error:n.Unknown()},a)]);function D(e){return p(L,e)&&y(()=>e.id.trim().length>0)}r(D,"isTextAnchorResolver");function I(e){return p(E,e)&&y(()=>{let t=e;return t.kind!=="resolved"||u.is(t.anchor)})}r(I,"isTextAnchorResolutionAttempt");function M(e){return p(N,e)}r(M,"isTextAnchorRecoveryOutcome");function p(e,t){return y(()=>C.Check(e,t))}r(p,"safeCheck");function y(e){try{return e()}catch{return!1}}r(y,"safeEvaluate");function T(e){if(!e.some(i=>i.marker!==void 0))return e.map(i=>`${i.prefix??""}${i.content}${i.suffix??""}`);let o=Math.max(0,...e.map(i=>i.prefix?.length??0));return e.map(i=>`${i.marker??" "}|${(i.prefix??"").padStart(o," ")}${i.content}${i.suffix??""}`)}r(T,"renderPresentedTextRows");var h="pi-agent-text/source-line";function $(e){let t=e.metadata?.[h];if(U(t))return t}r($,"getTextSourceLine");function F(e,t){return{...e,metadata:{...e.metadata,[h]:t}}}r(F,"withTextSourceLine");function U(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.source=="string"&&t.source.length>0&&typeof t.lineNumber=="number"&&Number.isInteger(t.lineNumber)&&t.lineNumber>0&&typeof t.content=="string"}r(U,"isTextSourceLine");import{Type as d}from"typebox";import{Value as W}from"typebox/value";var q=d.Function([],d.Unknown()),R=d.Object({id:d.String({minLength:1}),present:q}),B=d.Object({presenter:R,priority:d.Optional(d.Number())});function _(e){return A(R,e)}r(_,"isTextLinePresenter");function z(e){return A(B,e)}r(z,"isTextPresenterRegistration");function K(e,t){return{source:e,content:t,lines:H(t)}}r(K,"createTextDocument");function V(e){return e.lines.map(t=>`${t.content}${t.lineEnding}`).join("")}r(V,"renderTextDocument");function Y(e,t={}){let o=e.lines.flatMap(s=>[...s.presentation?.before??[],G(s,t.compact===!0),...s.presentation?.after??[]]),i=T(o),c=0;return e.lines.map(s=>{let m=1+(s.presentation?.before?.length??0)+(s.presentation?.after?.length??0),k=i.slice(c,c+m).join(`
2
- `);return c+=m,`${k}${s.lineEnding}`}).join("")}r(Y,"renderPresentedTextDocument");function G(e,t){let o=t&&e.presentation?.compactPrefix!==void 0?e.presentation.compactPrefix:e.presentation?.prefix,i=t&&e.presentation?.compactSuffix!==void 0?e.presentation.compactSuffix:e.presentation?.suffix;return{content:e.content,...o!==void 0&&{prefix:o},...i!==void 0&&{suffix:i},...e.presentation?.marker!==void 0&&{marker:e.presentation.marker}}}r(G,"presentedRowFor");function H(e){if(e.length===0)return[];let t=[],o=/([^\r\n]*)(\r\n|\r|\n|$)/gu,i;for(;(i=o.exec(e))!==null&&i[0].length!==0;)t.push({lineNumber:t.length+1,content:i[1]??"",lineEnding:i[2]??""});return t}r(H,"splitTextLines");function A(e,t){try{return W.Check(e,t)}catch{return!1}}r(A,"safeCheck");var J=new Set(["application/ecmascript","application/graphql","application/javascript","application/json","application/sql","application/toml","application/x-httpd-php","application/x-javascript","application/x-ndjson","application/x-www-form-urlencoded","application/x-yaml","application/xml","application/yaml"]);function Q(){return{id:"text",description:"UTF-8 text.",tryConvert(e,t){return Promise.resolve(X(e,t))}}}r(Q,"createTextContentConverter");function X(e,t){let o=ee(t.signal);if(o!==void 0)return{kind:"failed",error:o};try{return{kind:"converted",content:[{type:"text",text:new TextDecoder("utf8",{fatal:!0}).decode(e.bytes)}]}}catch(i){return b(e.mediaType)?{kind:"failed",error:new TypeError(`${e.source} is not valid UTF-8 text`,{cause:i})}:{kind:"not-handled"}}}r(X,"convertText");function b(e){if(e===void 0)return!1;let t=e.split(";",1)[0]?.trim().toLowerCase()??"";return t.startsWith("text/")||J.has(t)||t.endsWith("+json")||t.endsWith("+xml")}r(b,"isTextualMediaType");function Z(e){let t=e[0];if(e.length!==1||t.type!=="text")throw new TypeError("Text resources require exactly one text block");return t.text}r(Z,"textFromAgentContent");function ee(e){if(e?.aborted===!0)return e.reason instanceof Error?e.reason:te()}r(ee,"cancellationError");function te(){let e=new Error("The operation was aborted");return e.name="AbortError",e}r(te,"abortError");function ne(e){if(e===null||typeof e!="object")return!1;let t=e;if(t.kind==="not-handled")return!0;if(t.kind==="failed")return"error"in t;if(t.kind==="rejected"){let o=t.rejection;return o!==null&&typeof o=="object"&&["invalid","stale","missing","ambiguous"].includes(o.code)&&typeof o.reason=="string"}return t.kind!=="resolved"||!Array.isArray(t.targets)||t.targets.length===0?!1:t.targets.every(o=>{if(o===null||typeof o!="object")return!1;let i=o.source,c=o.ranges;return typeof i=="string"&&i.length>0&&(c===void 0||Array.isArray(c)&&c.every(re))})}r(ne,"isTextTargetResolutionAttempt");function re(e){if(e===null||typeof e!="object")return!1;let t=e;return v(t.start)&&v(t.end)&&(t.linewise===void 0||typeof t.linewise=="boolean")}r(re,"isTextSelectionRange");function v(e){if(e===null||typeof e!="object")return!1;let t=e;return Number.isInteger(t.lineNumber)&&t.lineNumber>=1&&Number.isInteger(t.column)&&t.column>=0}r(v,"isTextSelectionPosition");function oe(e,t){if(e.length<16)return e;let o=t.indexOf(e);return o<0?e:[o,e.length]}r(oe,"storeText");function ie(e,t){return typeof e=="string"?e:t.slice(e[0],e[0]+e[1])}r(ie,"restoreText");export{u as a,w as b,S as c,P as d,D as e,I as f,M as g,T as h,$ as i,F as j,_ as k,z as l,K as m,V as n,Y as o,Q as p,b as q,Z as r,ne as s,oe as t,ie as u};
1
+ import{a as r}from"./chunk-EI7MMDWY.js";import{Type as n}from"typebox";import{Value as C}from"typebox/value";var f=Symbol.for("pi-agent-text/TextAnchor"),u=class{constructor(t,o){this.value=t;this.lineNumber=o;if(t.length===0)throw new TypeError("Text anchor value must be non-empty");if(!Number.isSafeInteger(o)||o<1)throw new RangeError("Text anchor line number must be a positive safe integer")}static{r(this,"TextAnchor")}[f]=!0;static is(t){if(typeof t!="object"||t===null)return!1;try{let o=t;return o[f]===!0&&typeof o.value=="string"&&Number.isSafeInteger(o.lineNumber)&&o.lineNumber>=1}catch{return!1}}toString(){return this.value}},x=new WeakMap;function w(e,t,o){x.set(e,{renderer:t,resolverId:o})}r(w,"attachTextAnchorRenderer");function S(e){return x.get(e)?.renderer}r(S,"getTextAnchorRenderer");function P(e,t,o){let i=x.get(e);if(i===void 0)throw new Error(`No renderer is attached to text anchor "${t}"`);return{...i.renderer,resolverId:i.resolverId,full:i.renderer.renderFull(t,o),compact:i.renderer.renderCompact(t,o)}}r(P,"renderTextAnchor");var a={additionalProperties:!0},l=n.Function([],n.Unknown()),g=n.Object({lineNumber:n.Integer({minimum:1}),column:n.Integer({minimum:0})},a),j=n.Object({rank:n.Integer({minimum:1}),range:n.Object({start:g,end:g},a)},a),L=n.Object({id:n.String({minLength:1}),description:n.Union([n.String(),l]),normalize:n.Optional(l),renderFull:l,renderCompact:l,tryResolve:l,recover:n.Optional(l)},a),O=n.Object({code:n.Union([n.Literal("invalid"),n.Literal("stale"),n.Literal("missing"),n.Literal("ambiguous")]),reason:n.String(),contextRange:n.Optional(n.Object({offset:n.Number(),limit:n.Number()}))}),E=n.Union([n.Object({kind:n.Literal("not-handled")},a),n.Object({kind:n.Literal("resolved"),anchor:n.Unknown()},a),n.Object({kind:n.Literal("rejected"),rejection:O},a),n.Object({kind:n.Literal("failed"),error:n.Unknown()},a)]),N=n.Union([n.Object({kind:n.Literal("unavailable")},a),n.Object({kind:n.Literal("candidates"),candidates:n.Array(j),total:n.Integer({minimum:0})},a),n.Object({kind:n.Literal("timed-out")},a),n.Object({kind:n.Literal("failed"),error:n.Unknown()},a)]);function D(e){return p(L,e)&&y(()=>e.id.trim().length>0)}r(D,"isTextAnchorResolver");function I(e){return p(E,e)&&y(()=>{let t=e;return t.kind!=="resolved"||u.is(t.anchor)})}r(I,"isTextAnchorResolutionAttempt");function M(e){return p(N,e)}r(M,"isTextAnchorRecoveryOutcome");function p(e,t){return y(()=>C.Check(e,t))}r(p,"safeCheck");function y(e){try{return e()}catch{return!1}}r(y,"safeEvaluate");function T(e){if(!e.some(i=>i.marker!==void 0))return e.map(i=>`${i.prefix??""}${i.content}${i.suffix??""}`);let o=Math.max(0,...e.map(i=>i.prefix?.length??0));return e.map(i=>`${i.marker??" "}|${(i.prefix??"").padStart(o," ")}${i.content}${i.suffix??""}`)}r(T,"renderPresentedTextRows");var h="pi-agent-text/source-line";function $(e){let t=e.metadata?.[h];if(F(t))return t}r($,"getTextSourceLine");function U(e,t){return{...e,metadata:{...e.metadata,[h]:t}}}r(U,"withTextSourceLine");function F(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.source=="string"&&t.source.length>0&&typeof t.lineNumber=="number"&&Number.isInteger(t.lineNumber)&&t.lineNumber>0&&typeof t.content=="string"}r(F,"isTextSourceLine");import{Type as d}from"typebox";import{Value as W}from"typebox/value";var q=d.Function([],d.Unknown()),R=d.Object({id:d.String({minLength:1}),present:q}),B=d.Object({presenter:R,priority:d.Optional(d.Number())});function _(e){return A(R,e)}r(_,"isTextLinePresenter");function z(e){return A(B,e)}r(z,"isTextPresenterRegistration");function K(e,t){return{source:e,content:t,lines:H(t)}}r(K,"createTextDocument");function V(e){return e.lines.map(t=>`${t.content}${t.lineEnding}`).join("")}r(V,"renderTextDocument");function Y(e,t={}){let o=e.lines.flatMap(s=>[...s.presentation?.before??[],G(s,t.compact===!0),...s.presentation?.after??[]]),i=T(o),c=0;return e.lines.map(s=>{let m=1+(s.presentation?.before?.length??0)+(s.presentation?.after?.length??0),k=i.slice(c,c+m).join(`
2
+ `);return c+=m,`${k}${s.lineEnding}`}).join("")}r(Y,"renderPresentedTextDocument");function G(e,t){let o=t&&e.presentation?.compactPrefix!==void 0?e.presentation.compactPrefix:e.presentation?.prefix,i=t&&e.presentation?.compactSuffix!==void 0?e.presentation.compactSuffix:e.presentation?.suffix;return{content:e.content,...o!==void 0&&{prefix:o},...i!==void 0&&{suffix:i},...e.presentation?.marker!==void 0&&{marker:e.presentation.marker}}}r(G,"presentedRowFor");function H(e){if(e.length===0)return[];let t=[],o=/([^\r\n]*)(\r\n|\r|\n|$)/gu,i;for(;(i=o.exec(e))!==null&&i[0].length!==0;)t.push({lineNumber:t.length+1,content:i[1]??"",lineEnding:i[2]??""});return t}r(H,"splitTextLines");function A(e,t){try{return W.Check(e,t)}catch{return!1}}r(A,"safeCheck");var J=new Set(["application/ecmascript","application/graphql","application/javascript","application/json","application/sql","application/toml","application/x-httpd-php","application/x-javascript","application/x-ndjson","application/x-www-form-urlencoded","application/x-yaml","application/xml","application/yaml"]);function Q(){return{id:"text",description:"Text file paths and URLs return their text.",tryConvert(e,t){return Promise.resolve(X(e,t))}}}r(Q,"createTextContentConverter");function X(e,t){let o=ee(t.signal);if(o!==void 0)return{kind:"failed",error:o};try{return{kind:"converted",content:[{type:"text",text:new TextDecoder("utf8",{fatal:!0}).decode(e.bytes)}]}}catch(i){return b(e.mediaType)?{kind:"failed",error:new TypeError(`${e.source} is not valid UTF-8 text`,{cause:i})}:{kind:"not-handled"}}}r(X,"convertText");function b(e){if(e===void 0)return!1;let t=e.split(";",1)[0]?.trim().toLowerCase()??"";return t.startsWith("text/")||J.has(t)||t.endsWith("+json")||t.endsWith("+xml")}r(b,"isTextualMediaType");function Z(e){let t=e[0];if(e.length!==1||t.type!=="text")throw new TypeError("Text resources require exactly one text block");return t.text}r(Z,"textFromAgentContent");function ee(e){if(e?.aborted===!0)return e.reason instanceof Error?e.reason:te()}r(ee,"cancellationError");function te(){let e=new Error("The operation was aborted");return e.name="AbortError",e}r(te,"abortError");function ne(e){if(e===null||typeof e!="object")return!1;let t=e;if(t.kind==="not-handled")return!0;if(t.kind==="failed")return"error"in t;if(t.kind==="rejected"){let o=t.rejection;return o!==null&&typeof o=="object"&&["invalid","stale","missing","ambiguous"].includes(o.code)&&typeof o.reason=="string"}return t.kind!=="resolved"||!Array.isArray(t.targets)||t.targets.length===0?!1:t.targets.every(o=>{if(o===null||typeof o!="object")return!1;let i=o.source,c=o.ranges;return typeof i=="string"&&i.length>0&&(c===void 0||Array.isArray(c)&&c.every(re))})}r(ne,"isTextTargetResolutionAttempt");function re(e){if(e===null||typeof e!="object")return!1;let t=e;return v(t.start)&&v(t.end)&&(t.linewise===void 0||typeof t.linewise=="boolean")}r(re,"isTextSelectionRange");function v(e){if(e===null||typeof e!="object")return!1;let t=e;return Number.isInteger(t.lineNumber)&&t.lineNumber>=1&&Number.isInteger(t.column)&&t.column>=0}r(v,"isTextSelectionPosition");function oe(e,t){if(e.length<16)return e;let o=t.indexOf(e);return o<0?e:[o,e.length]}r(oe,"storeText");function ie(e,t){return typeof e=="string"?e:t.slice(e[0],e[0]+e[1])}r(ie,"restoreText");export{u as a,w as b,S as c,P as d,D as e,I as f,M as g,T as h,$ as i,U as j,_ as k,z as l,K as m,V as n,Y as o,Q as p,b as q,Z as r,ne as s,oe as t,ie as u};
@@ -0,0 +1 @@
1
+ import{a as u,e as c,k as l}from"./chunk-THSCUT2L.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";import{Value as a}from"typebox/value";var g=`${u}/post-edit/register`;function h(e){return a.Check(t.Object({formatting:t.Object({status:t.Union(["disabled","unavailable","skipped-syntax","unchanged","changed","failed","not-reported"].map(n=>t.Literal(n))),formatter:t.Optional(t.String())})}),e)}r(h,"isFormattingContribution");function w(e){return a.Check(t.Object({diffStatuses:t.Array(t.Object({text:t.String({minLength:1}),tone:t.Optional(t.Union(["muted","success","warning","error"].map(n=>t.Literal(n))))}))}),e)}r(w,"isDiffStatusContribution");var p=t.Function([],t.Unknown()),x=t.Object({id:t.String({minLength:1}),handler:p}),y=t.Object({registration:x,accept:p});function E(e){return a.Check(x,e)}r(E,"isTextPostEditHandlerRegistration");function b(e){return a.Check(y,e)}r(b,"isTextPostEditHandlerRegistrationRequest");function P(e){if(typeof e!="object"||e===null)return!1;let n=e;return Array.isArray(n.hints)&&typeof n.scopeMarkers=="object"&&n.scopeMarkers!==null&&Array.isArray(n.warnings)}r(P,"isTextMutationResultContributionData");function S(e,n){if(!E(n))throw new TypeError("Invalid text editor post-edit handler registration");let o,d=r(()=>{let s={registration:n,accept(f){if(o!==void 0)throw new Error(`Post-edit handler ${n.id} was accepted more than once`);o=f}};return e.events.emit(g,s),o!==void 0},"announce"),i=r(()=>{},"unsubscribeReady");i=e.events.on(c,s=>{if(!l(s))throw new Error("Invalid pi-agent-text-editor core readiness event");if(!d())throw new Error("pi-agent-text-editor core announced readiness without accepting the post-edit handler");i()}),e.on("session_shutdown",()=>{i(),o?.()}),d()&&i()}r(S,"connectTextEditorPostEditHandler");export{g as a,h as b,w as c,E as d,b as e,P as f,S as g};
@@ -0,0 +1,2 @@
1
+ import{a as o}from"./chunk-EI7MMDWY.js";function G(t,e){if(e.length===0)return;let c=t.trim();if(c.length===0||/[\r\n]/u.test(c))throw new TypeError("Content provider summary must be one non-empty line");return[c,...e.map(({description:a})=>a)].join(`
2
+ `)}o(G,"renderContentDescription");import{Type as i}from"typebox";import{Value as tt}from"typebox/value";import{Type as n}from"typebox";import{Value as W}from"typebox/value";var C={additionalProperties:!0},E=n.Function([],n.Unknown()),u=n.String({minLength:1}),Y=n.Object({type:n.Literal("text"),text:n.String(),textSignature:n.Optional(n.String())},C),B=n.Object({type:n.Literal("image"),data:n.String(),mimeType:n.String()},C),z=n.Object({type:n.Literal("custom"),kind:u,data:n.Unknown()},C),J=n.Array(n.Union([Y,B,z]),{minItems:1}),$=n.Union([n.Object({source:u,link:n.Optional(u),read:E,write:n.Optional(n.Never())},C),n.Object({source:u,link:n.Optional(u),read:n.Optional(n.Never()),write:E},C),n.Object({source:u,link:n.Optional(u),read:E,write:E},C)]),M=n.Object({id:u,tryResolve:E},C),Q=n.Union([n.Object({kind:n.Literal("not-handled")},C),n.Object({kind:n.Literal("resolved"),resource:$},C),n.Object({kind:n.Literal("failed"),error:n.Unknown()},C)]);function A(t){return x(J,t)?b(()=>t.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}o(A,"isAgentContent");function H(t){return x($,t)?b(()=>{let e=t,c=!("read"in e)||typeof e.read=="function",a=!("write"in e)||typeof e.write=="function";return c&&a}):!1}o(H,"isResource");function X(t){return x(M,t)}o(X,"isResourceResolver");function Z(t){return x(Q,t)?b(()=>{let e=t;return e.kind!=="resolved"||H(e.resource)}):!1}o(Z,"isResourceResolutionAttempt");function x(t,e){return b(()=>W.Check(t,e))}o(x,"safeCheck");function b(t){try{return t()}catch{return!1}}o(b,"safeEvaluate");var d={additionalProperties:!0},et=i.Function([],i.Unknown()),k=i.String({minLength:1}),nt=i.Object({provider:k,capability:i.Union([i.Literal("read"),i.Literal("write")])},d),ot=i.Object({source:k,bytes:i.Unknown(),mediaType:i.Optional(i.String())},d),rt=i.Object({signal:i.Optional(i.Unknown())},d),it=i.Object({id:k,description:k,tryConvert:et},d),st=i.Union([i.Object({kind:i.Literal("not-handled")},d),i.Object({kind:i.Literal("converted"),content:i.Unknown()},d),i.Object({kind:i.Literal("failed"),error:i.Unknown()},d)]),ct=i.Object({target:i.Unknown(),converter:i.Unknown(),priority:i.Optional(i.Number())},d);function f(t){return g(nt,t)&&v(()=>t.provider.trim().length>0)}o(f,"isContentTarget");function j(t){return g(ot,t)?v(()=>{let e=t;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}o(j,"isContentInput");function I(t){return g(rt,t)?v(()=>{let e=t;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}o(I,"isContentConversionContext");function q(t){return g(it,t)?v(()=>{let e=t;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}o(q,"isContentConverter");function _(t){return g(st,t)?v(()=>{let e=t;return e.kind!=="converted"||A(e.content)}):!1}o(_,"isContentConversionAttempt");function l(t){return g(ct,t)?v(()=>{let e=t;return f(e.target)&&q(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}o(l,"isContentConverterRegistration");function g(t,e){return v(()=>tt.Check(t,e))}o(g,"safeCheck");function v(t){try{return t()}catch{return!1}}o(v,"safeEvaluate");var N=class extends Error{static{o(this,"UnsupportedContentError")}source;target;constructor(e,c){super(`No content converter for ${e} in ${c.provider}/${c.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=c}};function V(t){if(!f(t))throw new TypeError("Invalid content target");let e={...t},c=[],a=o(()=>[...c].sort((r,s)=>r.priority-s.priority||r.order-s.order),"snapshotConverters");return{target:e,register(r){if(!l(r))throw new TypeError("Invalid content converter registration");if(!R(e,r.target))throw new Error(`Content converter ${r.converter.id} targets ${r.target.provider}/${r.target.capability}, not ${e.provider}/${e.capability}`);if(c.some(({converter:s})=>s.id===r.converter.id))throw new Error(`Content converter ${r.converter.id} is already registered for ${e.provider}/${e.capability}`);c.push({converter:r.converter,priority:r.priority??0,order:c.length})},listDescriptions(){return a().map(({converter:r})=>({id:r.id,description:r.description}))},async convert(r,s){if(!j(r))throw new TypeError("Invalid content input");if(!I(s))throw new TypeError("Invalid content conversion context");P(s.signal);let p=a();for(let{converter:O}of p){P(s.signal);let T=await O.tryConvert(r,s);if(P(s.signal),!_(T))throw new TypeError(`Content converter ${O.id} returned an invalid outcome`);if(T.kind!=="not-handled"){if(T.kind==="failed")throw T.error;return T.content}}throw new N(r.source,e)}}}o(V,"createContentRunner");function R(t,e){return t.provider===e.provider&&t.capability===e.capability}o(R,"targetsEqual");function P(t){t?.throwIfAborted()}o(P,"throwIfAborted");import{Type as m}from"typebox";import{Value as at}from"typebox/value";var y="pi-agent-resource/content-conversion",S=2,w=`${y}/host/ready`,h=`${y}/converter/register`,K={additionalProperties:!0},pt=m.Function([],m.Unknown()),Ct=m.Object({protocol:m.Literal(y),apiVersion:m.Literal(S),target:m.Unknown()},K),ut=m.Object({registration:m.Unknown(),accept:pt},K);function D(t){return F(Ct,t)&&L(()=>f(t.target))}o(D,"isContentHostReady");function U(t){return F(ut,t)&&L(()=>l(t.registration))}o(U,"isContentConverterRegistrationRequest");function F(t,e){return L(()=>at.Check(t,e))}o(F,"safeCheck");function L(t){try{return t()}catch{return!1}}o(L,"safeEvaluate");function dt(t,e){let c=V(e),a=t.events.on(h,r=>{if(!U(r))throw new Error("Invalid content converter registration request");if(!R(c.target,r.registration.target))return;let s;try{c.register(r.registration),s=Promise.resolve()}catch(p){s=Promise.reject(p instanceof Error?p:new Error("Content converter registration failed",{cause:p}))}r.accept(s)});return t.on("session_shutdown",a),t.events.emit(w,{protocol:y,apiVersion:S,target:c.target}),{target:c.target,listDescriptions(){return c.listDescriptions()},convert(r,s){return c.convert(r,s)}}}o(dt,"createContentHost");function mt(t,e){if(!l(e))throw new TypeError("Invalid content converter registration");let c=o(()=>{let s,p={registration:e,accept(O){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=O}};return t.events.emit(h,p),s},"announce"),a=o(()=>{},"unsubscribe");a=t.events.on(w,s=>{if(!D(s))throw new Error("Invalid content conversion host readiness event");if(!R(e.target,s.target))return;let p=c();if(p===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);a(),p.catch(()=>{})}),t.on("session_shutdown",a);let r=c();if(r!==void 0)return a(),r}o(mt,"connectContentConverter");export{G as a,A as b,H as c,X as d,Z as e,f,j as g,I as h,q as i,_ as j,l as k,N as l,V as m,R as n,y as o,S as p,w as q,h as r,D as s,U as t,dt as u,mt as v};