pi-agent-ide 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +13 -8
  3. package/dist/chunk-3SE372WC.js +3 -0
  4. package/dist/chunk-5MSNYFDE.js +1 -0
  5. package/dist/chunk-5VSE5X5R.js +2 -0
  6. package/dist/chunk-6DZA4CLO.js +4 -0
  7. package/dist/chunk-6EYWFBNG.js +0 -0
  8. package/dist/{chunk-ORAPGW7W.js → chunk-72EEL2DW.js} +1 -1
  9. package/dist/chunk-7JYQMAEL.js +14 -0
  10. package/dist/{chunk-T2RPMEM2.js → chunk-7UGNGK7Y.js} +1 -1
  11. package/dist/{chunk-STUZZM5B.js → chunk-AADJ2KIB.js} +1 -1
  12. package/dist/{chunk-XF5PVZOS.js → chunk-B5KB2I7J.js} +1 -1
  13. package/dist/chunk-DQF5QMJ2.js +1 -0
  14. package/dist/chunk-EJ5OACQM.js +1 -0
  15. package/dist/chunk-GFW5QPQV.js +2 -0
  16. package/dist/{chunk-LQYZG62K.js → chunk-GUTQ3PWL.js} +1 -1
  17. package/dist/chunk-HGPUI7F3.js +1 -0
  18. package/dist/{chunk-OBWZ5RYN.js → chunk-HKMBQLEK.js} +1 -1
  19. package/dist/chunk-ITSNK5YG.js +7 -0
  20. package/dist/chunk-J34VKQGJ.js +1 -0
  21. package/dist/chunk-KAB3AYA2.js +1 -0
  22. package/dist/{chunk-76WHES5H.js → chunk-M5L42DWE.js} +5 -5
  23. package/dist/chunk-M5MJP7Z2.js +1 -0
  24. package/dist/chunk-NMFQGKPE.js +2 -0
  25. package/dist/chunk-NTYXZ3EL.js +3 -0
  26. package/dist/{chunk-P6T3Q7LB.js → chunk-QDST6VIU.js} +1 -1
  27. package/dist/chunk-ROXXK6TW.js +0 -0
  28. package/dist/{chunk-WNMGUALD.js → chunk-TI5GMJ7Q.js} +1 -1
  29. package/dist/{chunk-4ZTEPMJO.js → chunk-TPIHQYK2.js} +1 -1
  30. package/dist/chunk-XSTHESNR.js +25 -0
  31. package/dist/{chunk-THSCUT2L.js → chunk-Y7ZMR4LT.js} +1 -1
  32. package/dist/chunk-YHADTHQM.js +1 -0
  33. package/dist/{chunk-KZBAJFCV.js → chunk-Z3VC3S2T.js} +1 -1
  34. package/dist/{chunk-ZXN3TWWW.js → chunk-ZM4L5AGN.js} +1 -1
  35. package/dist/{chunk-E2RESHYR.js → chunk-ZTYWHL2F.js} +1 -1
  36. package/dist/entry-0.js +1 -1
  37. package/dist/entry-1.js +1 -1
  38. package/dist/entry-10.js +1 -1
  39. package/dist/entry-12.js +1 -1
  40. package/dist/entry-13.js +1 -1
  41. package/dist/entry-14.js +1 -1
  42. package/dist/entry-2.js +1 -1
  43. package/dist/entry-21.js +1 -1
  44. package/dist/entry-24.js +1 -1
  45. package/dist/entry-25.js +1 -1
  46. package/dist/entry-26.js +10 -5
  47. package/dist/entry-28.js +1 -1
  48. package/dist/entry-29.js +1 -1
  49. package/dist/entry-31.js +3 -3
  50. package/dist/entry-32.js +6 -5
  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 +12 -8
  57. package/dist/entry-42.js +1 -1
  58. package/dist/entry-43.js +1 -1
  59. package/dist/entry-44.js +1 -1
  60. package/dist/entry-45.js +4 -4
  61. package/dist/entry-46.js +10 -10
  62. package/dist/entry-47.js +1 -1
  63. package/dist/entry-48.js +1 -1
  64. package/dist/entry-49.js +1 -1
  65. package/dist/entry-50.js +1 -1
  66. package/dist/entry-51.js +1 -1
  67. package/dist/entry-52.js +1 -1
  68. package/dist/entry-53.js +1 -1
  69. package/dist/entry-54.js +1 -0
  70. package/dist/entry-55.js +0 -1
  71. package/dist/entry-56.js +1 -0
  72. package/dist/entry-57.js +0 -1
  73. package/dist/entry-58.js +1 -1
  74. package/dist/entry-59.js +1 -1
  75. package/dist/entry-60.js +1 -1
  76. package/dist/entry-61.js +1 -1
  77. package/dist/entry-62.js +1 -1
  78. package/dist/entry-63.js +1 -0
  79. package/dist/entry-64.js +0 -1
  80. package/dist/entry-65.js +1 -0
  81. package/dist/entry-66.js +0 -1
  82. package/dist/entry-67.js +1 -1
  83. package/dist/entry-68.js +1 -1
  84. package/dist/entry-69.js +1 -59
  85. package/dist/entry-70.js +123 -4
  86. package/dist/entry-71.js +30 -1
  87. package/dist/entry-72.js +2 -29
  88. package/dist/entry-73.js +1 -2
  89. package/dist/entry-74.js +1 -1
  90. package/dist/entry-75.js +1 -1
  91. package/dist/entry-76.js +3 -1
  92. package/dist/entry-77.js +1 -3
  93. package/dist/entry-78.js +1 -1
  94. package/dist/entry-79.js +1 -1
  95. package/dist/pi-agent-ide.js +3 -2
  96. package/docs/configuration.md +32 -11
  97. package/docs/tools.md +17 -0
  98. package/node_modules/pi-agent-doctor/package.json +1 -1
  99. package/node_modules/pi-agent-filesystem/package.json +6 -6
  100. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  101. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  102. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  103. package/node_modules/pi-agent-ide-ast/package.json +9 -9
  104. package/node_modules/pi-agent-ide-ast/src/extension.ts +4 -3
  105. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +68 -45
  106. package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +8 -1
  107. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +83 -5
  108. package/node_modules/pi-agent-ide-changes/index.ts +21 -5
  109. package/node_modules/pi-agent-ide-changes/package.json +6 -6
  110. package/node_modules/pi-agent-ide-changes/src/last-text-transaction-store.ts +10 -0
  111. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +4 -2
  112. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  113. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +26 -8
  114. package/node_modules/pi-agent-ide-formatter/src/registry.ts +9 -1
  115. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  116. package/node_modules/pi-agent-ide-lint/index.ts +46 -17
  117. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  118. package/node_modules/pi-agent-ide-lint/src/registry.ts +9 -1
  119. package/node_modules/pi-agent-ide-lsp/index.ts +126 -8
  120. package/node_modules/pi-agent-ide-lsp/package.json +9 -8
  121. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +61 -0
  122. package/node_modules/pi-agent-ide-lsp/src/diagnostic-source.ts +18 -3
  123. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +4 -0
  124. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +40 -0
  125. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +21 -32
  126. package/node_modules/pi-agent-ide-lsp/src/lsp/registry.ts +15 -2
  127. package/node_modules/pi-agent-ide-lsp/src/lsp/rename.ts +1 -1
  128. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +32 -5
  129. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +138 -0
  130. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +9 -2
  131. package/node_modules/pi-agent-image/package.json +2 -2
  132. package/node_modules/pi-agent-invariant/package.json +1 -1
  133. package/node_modules/pi-agent-pdf/package.json +2 -2
  134. package/node_modules/pi-agent-read/package.json +6 -6
  135. package/node_modules/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  136. package/node_modules/pi-agent-read/src/api/read-parameters.ts +29 -0
  137. package/node_modules/pi-agent-read/src/api/tools/read.ts +73 -1
  138. package/node_modules/pi-agent-read/src/core/read-core.ts +26 -2
  139. package/node_modules/pi-agent-read/src/core/tools/read/output-truncation.ts +1 -1
  140. package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +113 -0
  141. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +64 -14
  142. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +15 -0
  143. package/node_modules/pi-agent-read/src/core/tools/read/temp-resource-store.ts +35 -126
  144. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +73 -44
  145. package/node_modules/pi-agent-resource/package.json +1 -1
  146. package/node_modules/pi-agent-resource/src/resolver.ts +2 -0
  147. package/node_modules/pi-agent-resource/src/resource.ts +2 -0
  148. package/node_modules/pi-agent-search/package.json +3 -3
  149. package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  150. package/node_modules/pi-agent-search/src/api/search-parameters.ts +25 -0
  151. package/node_modules/pi-agent-search/src/api/search.ts +55 -1
  152. package/node_modules/pi-agent-search/src/core/extension.ts +2 -23
  153. package/node_modules/pi-agent-search/src/core/search-core.ts +28 -3
  154. package/node_modules/pi-agent-search-text/index.ts +44 -4
  155. package/node_modules/pi-agent-search-text/package.json +6 -6
  156. package/node_modules/pi-agent-search-text/src/search-session.ts +65 -25
  157. package/node_modules/pi-agent-text/package.json +2 -2
  158. package/node_modules/pi-agent-text/src/text-document.ts +5 -0
  159. package/node_modules/pi-agent-text/src/text-target.ts +4 -0
  160. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  161. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  162. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  163. package/node_modules/pi-agent-text-anchor-line-hash/src/read-handler.ts +1 -0
  164. package/node_modules/pi-agent-text-editor/index.ts +1 -3
  165. package/node_modules/pi-agent-text-editor/package.json +34 -24
  166. package/node_modules/pi-agent-text-editor/runtime/entry-69.js +0 -1
  167. package/node_modules/pi-agent-text-editor/src/api/apply-renderer.ts +3 -0
  168. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  169. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +15 -0
  170. package/node_modules/pi-agent-text-editor/src/api/last-resolved-resource.ts +5 -0
  171. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +15 -1
  172. package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +3 -0
  173. package/node_modules/pi-agent-text-editor/src/api/tool-renderer.ts +3 -0
  174. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +237 -0
  175. package/node_modules/pi-agent-text-editor/src/core/apply/final-mutations.ts +50 -0
  176. package/node_modules/pi-agent-text-editor/src/core/apply/format-source.ts +11 -0
  177. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +208 -0
  178. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +39 -0
  179. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +216 -0
  180. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +45 -0
  181. package/node_modules/pi-agent-text-editor/src/core/apply/queue.ts +25 -0
  182. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +324 -0
  183. package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +133 -0
  184. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +112 -0
  185. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +132 -0
  186. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +205 -0
  187. package/node_modules/pi-agent-text-editor/src/core/extension.ts +6 -0
  188. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +76 -0
  189. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +153 -0
  190. package/node_modules/pi-agent-text-editor/src/core/mutation-result/diff.ts +5 -2
  191. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -0
  192. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +6 -1
  193. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +73 -0
  194. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +10 -2
  195. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +17 -0
  196. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +212 -51
  197. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +273 -11
  198. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +1 -1
  199. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +1 -1
  200. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  201. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +1 -1
  202. package/node_modules/pi-agent-text-editor-renderer/index.ts +88 -1
  203. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  204. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +42 -25
  205. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +20 -12
  206. package/node_modules/pi-agent-text-editor-renderer/src/status-summary.ts +33 -0
  207. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  208. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  209. package/node_modules/pi-agent-tool-call-interception/runtime/entry-73.js +1 -0
  210. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  211. package/node_modules/pi-agent-web/package.json +7 -7
  212. package/node_modules/pi-agent-web/runtime/entry-75.js +2 -0
  213. package/node_modules/pi-agent-web/src/browser-loader.ts +1 -0
  214. package/node_modules/pi-agent-web-html/package.json +3 -3
  215. package/node_modules/pi-agent-web-image/package.json +4 -4
  216. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  217. package/node_modules/pi-agent-web-text/package.json +4 -4
  218. package/package.json +41 -38
  219. package/src/api/plugin-protocol.ts +10 -2
  220. package/src/api/tool-config.ts +73 -2
  221. package/src/code-view/diagnostic-view.ts +22 -3
  222. package/src/composite/builtin-extensions.ts +10 -15
  223. package/src/composite/extensions-config.ts +59 -0
  224. package/src/composite/feature-flags.ts +32 -0
  225. package/src/composite/module-labels.ts +59 -0
  226. package/src/composite/module-settings-store.ts +60 -0
  227. package/src/composite/module-settings.ts +162 -0
  228. package/src/composite/preferences.ts +26 -0
  229. package/src/composite/selection.ts +4 -4
  230. package/src/composite/settings-panel.ts +103 -0
  231. package/src/core/diagnostic-delivery.ts +29 -0
  232. package/src/core/diagnostic-entry.ts +51 -3
  233. package/src/core/diagnostic-store.ts +56 -5
  234. package/src/core/extension.ts +34 -33
  235. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  236. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  237. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  238. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  239. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  240. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  241. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-76.js +2 -0
  242. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  243. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  244. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  245. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-75.js +2 -0
  246. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/browser-loader.ts +1 -0
  247. package/src/extensions/pi-agent-read/package.json +6 -6
  248. package/src/extensions/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  249. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +29 -0
  250. package/src/extensions/pi-agent-read/src/api/tools/read.ts +73 -1
  251. package/src/extensions/pi-agent-read/src/core/read-core.ts +26 -2
  252. package/src/extensions/pi-agent-read/src/core/tools/read/output-truncation.ts +1 -1
  253. package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +113 -0
  254. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +64 -14
  255. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +15 -0
  256. package/src/extensions/pi-agent-read/src/core/tools/read/temp-resource-store.ts +35 -126
  257. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +73 -44
  258. package/src/extensions/pi-agent-search/package.json +3 -3
  259. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +44 -4
  260. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
  261. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +65 -25
  262. package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  263. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +25 -0
  264. package/src/extensions/pi-agent-search/src/api/search.ts +55 -1
  265. package/src/extensions/pi-agent-search/src/core/extension.ts +2 -23
  266. package/src/extensions/pi-agent-search/src/core/search-core.ts +28 -3
  267. package/src/extensions/pi-agent-text-editor/index.ts +1 -3
  268. package/src/extensions/pi-agent-text-editor/package.json +34 -24
  269. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  270. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  271. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  272. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/src/read-handler.ts +1 -0
  273. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +88 -1
  274. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  275. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +42 -25
  276. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +20 -12
  277. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/status-summary.ts +33 -0
  278. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  279. package/src/extensions/pi-agent-text-editor/runtime/entry-69.js +0 -1
  280. package/src/extensions/pi-agent-text-editor/runtime/entry-70.js +2 -0
  281. package/src/extensions/pi-agent-text-editor/src/api/apply-renderer.ts +3 -0
  282. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  283. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +15 -0
  284. package/src/extensions/pi-agent-text-editor/src/api/last-resolved-resource.ts +5 -0
  285. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +15 -1
  286. package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +3 -0
  287. package/src/extensions/pi-agent-text-editor/src/api/tool-renderer.ts +3 -0
  288. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +237 -0
  289. package/src/extensions/pi-agent-text-editor/src/core/apply/final-mutations.ts +50 -0
  290. package/src/extensions/pi-agent-text-editor/src/core/apply/format-source.ts +11 -0
  291. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +208 -0
  292. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +39 -0
  293. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +216 -0
  294. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +45 -0
  295. package/src/extensions/pi-agent-text-editor/src/core/apply/queue.ts +25 -0
  296. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +324 -0
  297. package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +133 -0
  298. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +112 -0
  299. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +132 -0
  300. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +205 -0
  301. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +6 -0
  302. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +76 -0
  303. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +153 -0
  304. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/diff.ts +5 -2
  305. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -0
  306. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +6 -1
  307. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +73 -0
  308. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +10 -2
  309. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +17 -0
  310. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +212 -51
  311. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +273 -11
  312. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +1 -1
  313. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +1 -1
  314. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  315. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +1 -1
  316. package/src/pi-agent-ide.ts +43 -8
  317. package/src/plugins/pi-agent-ide-ast/package.json +9 -9
  318. package/src/plugins/pi-agent-ide-ast/src/extension.ts +4 -3
  319. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +68 -45
  320. package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +8 -1
  321. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +83 -5
  322. package/src/plugins/pi-agent-ide-changes/index.ts +21 -5
  323. package/src/plugins/pi-agent-ide-changes/package.json +6 -6
  324. package/src/plugins/pi-agent-ide-changes/src/last-text-transaction-store.ts +10 -0
  325. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +4 -2
  326. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +62 -11
  327. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  328. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +26 -8
  329. package/src/plugins/pi-agent-ide-formatter/src/registry.ts +9 -1
  330. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  331. package/src/plugins/pi-agent-ide-lint/index.ts +46 -17
  332. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  333. package/src/plugins/pi-agent-ide-lint/src/registry.ts +9 -1
  334. package/src/plugins/pi-agent-ide-lsp/index.ts +126 -8
  335. package/src/plugins/pi-agent-ide-lsp/package.json +9 -8
  336. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +61 -0
  337. package/src/plugins/pi-agent-ide-lsp/src/diagnostic-source.ts +18 -3
  338. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +4 -0
  339. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +40 -0
  340. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +21 -32
  341. package/src/plugins/pi-agent-ide-lsp/src/lsp/registry.ts +15 -2
  342. package/src/plugins/pi-agent-ide-lsp/src/lsp/rename.ts +1 -1
  343. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +32 -5
  344. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +138 -0
  345. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +9 -2
  346. package/src/plugins/pi-agent-ide-terminal/index.ts +34 -0
  347. package/src/plugins/pi-agent-ide-terminal/src/renderer.ts +238 -0
  348. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +461 -0
  349. package/src/plugins/pi-agent-ide-terminal/src/screen-image.ts +127 -0
  350. package/src/plugins/pi-agent-ide-terminal/src/search.ts +159 -0
  351. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +529 -0
  352. package/src/plugins/pi-agent-ide-terminal/src/shell-profile.ts +56 -0
  353. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +157 -0
  354. package/src/plugins/pi-agent-ide-terminal/src/types.ts +66 -0
  355. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +336 -0
  356. package/src/post-edit/gate.ts +15 -2
  357. package/dist/chunk-4U6KGABH.js +0 -1
  358. package/dist/chunk-6ACQQBUY.js +0 -7
  359. package/dist/chunk-GFWDXTOB.js +0 -4
  360. package/dist/chunk-JASLOB2X.js +0 -1
  361. package/dist/chunk-JJVXUL5U.js +0 -2
  362. package/dist/chunk-KCEOTU5Z.js +0 -3
  363. package/dist/chunk-KVGQG43U.js +0 -1
  364. package/dist/chunk-QJFRAMK7.js +0 -2
  365. package/dist/chunk-RAZOACDD.js +0 -2
  366. package/dist/chunk-RIGRP3FD.js +0 -1
  367. package/dist/chunk-VCCMVQXU.js +0 -1
  368. package/dist/chunk-X6MPU7UO.js +0 -3
  369. package/dist/chunk-YPHXLAQF.js +0 -1
  370. package/dist/entry-80.js +0 -1
  371. package/node_modules/pi-agent-text-editor/src/core/tool-description.ts +0 -14
  372. package/node_modules/pi-agent-text-editor-argument-order/index.ts +0 -26
  373. package/node_modules/pi-agent-text-editor-argument-order/package.json +0 -16
  374. package/node_modules/pi-agent-text-editor-argument-order/src/argument-order-guard.ts +0 -100
  375. package/node_modules/pi-agent-text-editor-overwrite/index.ts +0 -365
  376. package/node_modules/pi-agent-text-editor-overwrite/package.json +0 -17
  377. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +0 -2
  378. package/node_modules/pi-agent-tool-ui/runtime/entry-75.js +0 -1
  379. package/node_modules/pi-agent-web-text/runtime/entry-80.js +0 -2
  380. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-80.js +0 -2
  381. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +0 -2
  382. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/index.ts +0 -26
  383. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/package.json +0 -16
  384. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/runtime/entry-70.js +0 -2
  385. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/src/argument-order-guard.ts +0 -100
  386. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/index.ts +0 -365
  387. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/package.json +0 -17
  388. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +0 -2
  389. package/src/extensions/pi-agent-text-editor/src/core/tool-description.ts +0 -14
  390. /package/dist/{chunk-3H2EU7VQ.js → chunk-4U2GUKNJ.js} +0 -0
  391. /package/node_modules/{pi-agent-text-editor-argument-order → pi-agent-text-editor}/runtime/entry-70.js +0 -0
  392. /package/node_modules/{pi-agent-text-editor-overwrite → pi-agent-text-editor-renderer}/runtime/entry-71.js +0 -0
  393. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-72.js +0 -0
  394. /package/node_modules/{pi-agent-tool-call-interception → pi-agent-tool-ui}/runtime/entry-74.js +0 -0
  395. /package/node_modules/{pi-agent-web → pi-agent-web-html}/runtime/entry-76.js +0 -0
  396. /package/node_modules/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-77.js +0 -0
  397. /package/node_modules/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-78.js +0 -0
  398. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-79.js +0 -0
  399. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-77.js +0 -0
  400. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-78.js +0 -0
  401. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-79.js +0 -0
  402. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-overwrite → pi-agent-text-editor-renderer}/runtime/entry-71.js +0 -0
  403. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-72.js +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 — 2026-09-11
4
+
5
+ ### Terminal sessions
6
+
7
+ - Add a cross-platform `run` tool for synchronous and background commands. It uses Bash on Linux, PowerShell on Windows, and the system shell on macOS, with platform-specific guidance for the agent.
8
+ - Keep every run as an addressable `shell:` resource. Agents can read its output, send text or key chords, search retained output, batch input through `apply`, stop it with `delete`, and request a terminal screenshot.
9
+ - Let agents choose the virtual terminal width and height for full-screen and interactive programs.
10
+ - Deliver background completion automatically and wake the agent. Short jobs produce one completed card; longer jobs keep an initial card and add one completion card when they finish.
11
+
12
+ ### Terminal interface
13
+
14
+ - Show themed terminal cards with the shell, working directory, execution mode, command, output, elapsed time, and exit status without exposing internal session IDs.
15
+ - Stream a bounded initial preview for background runs, then keep later output available through terminal reads.
16
+ - Show compact text around the changed terminal region after input. Image-capable models also receive a cropped terminal image.
17
+ - Add a `/terminals` overlay for active and recent sessions, plus detailed, compact, and hidden activity modes.
18
+
19
+ ### Settings
20
+
21
+ - Add the terminal as an independently configurable feature that is enabled by default.
22
+ - Rework Agent IDE settings into a bordered panel with separate Features, Behavior, and UI tabs.
23
+
24
+ ## 0.3.0 — 2026-09-10
25
+
26
+ ### Composable IDE tools
27
+
28
+ - Add `apply`, a JavaScript scratchpad for combining reads, searches, diffs, guarded text edits, whole-file operations, and Git change operations in one call. Calls run in order, return structured data, and keep completed changes when a later operation fails.
29
+ - Add standalone `diff`, `copy_file`, `move_file`, and `delete_file` tools. The same operations are available inside `apply`.
30
+ - Let `apply` reuse search selections, text anchors, AST matches, inherited sources, formatter hooks, and explicitly requested diagnostics from the existing IDE tools.
31
+ - Add safe symbol operations backed by language servers. Tools can resolve declarations and rename a symbol with native reference updates when the server supports it.
32
+ - Add `raw:` reads for inspecting original file bytes without text decoding or conversion.
33
+
34
+ ### Editing and post-processing
35
+
36
+ - Keep formatter, linter, and language-server discovery local to the project that owns each edited file. Files outside the active project no longer inherit its toolchain.
37
+ - Preserve successful effects, explicit results, preview arguments, and recovery details across mixed `apply` scripts. Keep empty-file creation and formatted results visible and reusable.
38
+ - Run only explicitly requested diagnostics inline. Automatic post-edit checks remain asynchronous and no longer break otherwise successful reads or edits.
39
+ - Reuse resolved search and AST selections across guarded operations, including exact replacements and multi-file scripts.
40
+
41
+ ### Interface and settings
42
+
43
+ - Add incremental previews for mixed `apply` scripts, with syntax-coloured calls, results, diffs, formatting status, and grouped diagnostic feedback.
44
+ - Add settings for enabling `apply`, choosing its preview style, and managing IDE modules and feature groups from named settings tabs.
45
+ - Show ordinary read windows as line ranges, while keeping anchor-relative reads and tail reads explicit.
46
+ - Show whole-file operation names as `copy file`, `move file`, and `delete file` in tool cards and results.
47
+ - Tighten compact spacing and keep explicit output visible when reads, edits, and Git operations share one preview.
48
+
3
49
  ## 0.2.2 — 2026-09-08
4
50
 
5
51
  ### Agent guidance
package/README.md CHANGED
@@ -23,15 +23,20 @@ The current focus is measurement. The project is being compared with vanilla Pi
23
23
 
24
24
  ## What it does
25
25
 
26
- Pi Agent IDE provides a small set of tools with more specialized behavior behind them:
26
+ Pi Agent IDE gives the agent a focused set of tools that work together:
27
27
 
28
- - `read` handles files, web pages, images, PDFs, code views, and diagnostics;
29
- - `search` routes text and structural searches;
30
- - `write`, `replace`, `insert`, `delete`, `copy`, and `move` cover common text mutations; range-based edits can target snapshot and semantic anchors instead of reproducing the `oldText` block required by Pi's built-in `edit` tool;
31
- - optional plugins add AST, LSP, formatting, linting, and Git-aware behavior;
32
- - `/pi-agent-ide-doctor` detects project languages and lets each loaded plugin check or configure its own scope.
28
+ - `read` handles text files, original bytes, web pages, images, PDFs, code views, and diagnostics;
29
+ - `run` starts synchronous or background commands in the user's configured shell; returned `shell:` sessions can be read, controlled, deleted, and viewed in `/terminals`;
30
+ - `search` finds files, text, symbols, and syntax-tree patterns;
31
+ - `write`, `replace`, `insert`, `delete`, `copy`, and `move` edit text with exact matches, line anchors, search results, AST matches, and language-server symbols;
32
+ - `diff` compares readable sources, while `copy_file`, `move_file`, and `delete_file` handle whole files;
33
+ - `apply` combines reads, searches, diffs, edits, whole-file operations, and Git change operations in one JavaScript call;
34
+ - formatting and diagnostics run after edits and stay local to the project that owns each file;
35
+ - `/pi-agent-ide-doctor` checks the languages and tools available in the current project.
33
36
 
34
- The public interface is intentionally small. Resources, resolvers, anchors, renderers, and toolchain integrations are connected through versioned plugin protocols. The npm package loads as one Pi extension, while its built-ins remain separate modules that can be replaced or extended.
37
+ The tools share the same resources and safeguards. An `apply` script can reuse a search result or anchor from an earlier call, and completed edits remain visible if a later call fails. Formatting, diagnostics, previews, and safe undo work the same way for standalone tools and composed operations.
38
+
39
+ The npm package loads as one Pi extension. Its built-in modules can be enabled, disabled, replaced, or extended through versioned plugin protocols.
35
40
 
36
41
  ## Installation
37
42
 
@@ -45,7 +50,7 @@ Pi packages run with your full system permissions. Review the package before ins
45
50
 
46
51
  ## Check project tools
47
52
 
48
- Pi Agent IDE includes formatter, linter, and LSP mappings. It runs their external commands through your current `PATH`, so projects work without copied IDE config files when those commands are installed.
53
+ Pi Agent IDE includes formatter, linter, and LSP mappings. It finds each tool from the project that owns the file, including project-local binaries and commands on your `PATH`. Settings from one project do not leak into another.
49
54
 
50
55
  Start Pi in your project directory, then run:
51
56
 
@@ -0,0 +1,3 @@
1
+ import{c as M}from"./chunk-YHUTTZC6.js";import{i as b,o as k,t as w,u as T}from"./chunk-5VSE5X5R.js";import{a as R}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";function me(e,n){let{lines:t,truncation:r,...i}=e,o=t?.map(d=>{let l=[d.lineNumber,w(d.content,n),d.lineEnding];return(d.presentation!==void 0||d.metadata!==void 0)&&l.push(d.presentation),d.metadata!==void 0&&l.push(d.metadata),l}),{content:s,...u}=r??{};return{...i,...o===void 0?{}:{storedLines:o},...r===void 0?{}:{truncation:u,truncatedText:w(s??"",n)}}}a(me,"compactReadDetails");function P(e,n){let t=e;if(t.storedLines===void 0&&t.truncatedText===void 0)return e;let{storedLines:r,truncatedText:i,truncation:o,...s}=t;return{...s,...r===void 0?{}:{lines:r.map(([u,d,l,c,m])=>({lineNumber:u,content:T(d,n),lineEnding:l,...c==null?{}:{presentation:c},...m==null?{}:{metadata:m}}))},...o===void 0?{}:{truncation:{...o,content:T(i??"",n)}}}}a(P,"restoreReadDetails");import f from"node:path";import{homedir as I}from"node:os";import{createReadToolDefinition as V,getReadmePath as J}from"@earendil-works/pi-coding-agent";import{Text as Z}from"@earendil-works/pi-tui";var S=V(process.cwd()),K=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function v(e,n=process.cwd()){if(typeof e!="object"||e===null)return;let t=e,r=t.path;if(typeof r!="string"||r.length===0||r.includes("#")||!f.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||t.views!==void 0&&(!Array.isArray(t.views)||t.views.length>0)||t.offset!==void 0&&(typeof t.offset!="number"||!Number.isInteger(t.offset)||t.offset<1)||t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1))return;let i=r.startsWith("~/")?f.join(I(),r.slice(2)):r,o=f.resolve(n,i),s=f.basename(o),u=f.relative(f.dirname(J()),o),d=!f.isAbsolute(u)&&(u==="README.md"||u.startsWith(`docs${f.sep}`)||u.startsWith(`examples${f.sep}`));if(!(s!=="SKILL.md"&&!K.has(s)&&!d))return{path:r,...t.offset===void 0?{}:{offset:t.offset},...t.limit===void 0?{}:{limit:t.limit}}}a(v,"nativeReadArguments");function L(e,n){return{...e,args:n,lastComponent:e.lastComponent instanceof Z?e.lastComponent:void 0}}a(L,"nativeReadContext");import{getLanguageFromPath as q,getMarkdownTheme as X,highlightCode as z,keyHint as Y}from"@earendil-works/pi-coding-agent";import{Container as g,Markdown as Q,Text as _,truncateToWidth as h,visibleWidth as p,wrapTextWithAnsi as N}from"@earendil-works/pi-tui";var E=12;function ee(e,n,t){let r=typeof n=="number"?n:void 0,i=typeof t=="number"?t:void 0;if(r===void 0&&i===void 0)return{pathSuffix:"",qualifiers:[],details:[]};if(e==="inherited source"||e.includes("#")){let d=r??1,l=i===void 0?String(d):`${d}-${d+i-1}`;return{pathSuffix:"",qualifiers:[{text:`relative lines ${l}`}],details:[{label:"relative lines",value:l}]}}if(r!==void 0&&r<0)return{pathSuffix:"",qualifiers:[{text:`tail ${Math.abs(r)}`},...i===void 0?[]:[{text:`limit ${i}`}]],details:[{label:"tail",value:String(Math.abs(r))},...i===void 0?[]:[{label:"limit",value:String(i)}]]};let s=Math.max(1,r??1),u=i===void 0?String(s):`${s}-${s+i-1}`;return{pathSuffix:`:${u}`,qualifiers:[],details:[{label:"lines",value:u}]}}a(ee,"readWindowPresentation");function ke(e,n,t){let r=v(e,t.cwd);if(r!==void 0)return R(S.renderCall)(r,n,L(t,r));if(typeof e.path=="string"&&e.path.startsWith("shell:"))return new g;let i=typeof e.path=="string"?e.path:"inherited source",o=ee(i,e.offset,e.limit),s=Array.isArray(e.views)?e.views.filter(l=>typeof l=="string"):[],u=[...o.qualifiers,...s.length===0?[]:[{text:`views ${s.join(",")}`}]],d=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...o.details,...s.length===0?[]:[{label:"views",value:s.join(",")}]];return M(t.lastComponent,{tool:"read",primary:{text:`${i}${o.pathSuffix}`,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:u,details:d,expanded:t.expanded},n)}a(ke,"renderReadCall");function Me(e){let n=new WeakMap;return(t,r,i,o)=>{let s=e.nativeResources?v(o.args,o.cwd):void 0;if(s!==void 0&&!r.isPartial)return R(S.renderResult)({...t,details:{truncation:$(t.details).truncation}},r,i,L(o,s));if(r.isPartial||o.isError){let m=D(t),H=o.isError?"error":"dim";return new _(i.fg(H,m),0,0)}let u=$(t.details).diagnosticCheck;if(u?.complete&&u.count===0)return new g;if(!de(t))return o.lastComponent instanceof g?o.lastComponent:new g;let d=n.get(t);d===void 0&&(d=P($(t.details),D(t)),n.set(t,d));let c=(o.lastComponent instanceof x?o.lastComponent:void 0)??new x({result:t,details:d,options:e,expanded:r.expanded,theme:i});return c.update({result:t,details:d,options:e,expanded:r.expanded,theme:i}),c}}a(Me,"createReadResultRenderer");var x=class{constructor(n){this.state=n}static{a(this,"ReadResultPanel")}cached;update(n){this.state.result===n.result&&this.state.details===n.details&&this.state.options===n.options&&this.state.expanded===n.expanded&&this.state.theme===n.theme||(this.state=n,this.invalidate())}render(n){if(this.cached?.width===n)return this.cached.lines;if(n<8){let l=[h(B(this.state,n),Math.max(1,n))];return this.cached={width:n,lines:l},l}let t=n-2,r=Math.max(1,t-2),i=ne(this.state,r).flatMap(l=>N(l,r)),o=re(i,this.state.expanded,this.state.theme),s=[ie(this.state,t,this.state.theme)];for(let l of o)for(let c of N(l,r))s.push(W(c,t,this.state.theme));let u=ae(this.state.details,this.state.theme);u!==void 0&&s.push(W(u,t,this.state.theme)),s.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(t)}\u256F`));let d=s.map(l=>h(l,n));return this.cached={width:n,lines:d},d}invalidate(){this.cached=void 0}};function ne(e,n){let t=G(e.details),r=se(e.result,t,e.details,!e.expanded);if(e.options.kind==="markdown"||ue(e.details,t,e.options.kind)){let u=new Q(r,0,0,X());return C(u.render(n),e.theme)}if(e.options.kind==="code-view"){let u=t===void 0||j(t)?O(r).map(d=>U(d,e.theme,!1)):te(t,e.theme);return C(u,e.theme)}let i=t===void 0||j(t)?O(r).map(y):t.map(({content:u})=>y(u)),o=A(e.details,t),s=o===void 0?i.map(u=>e.theme.fg("toolOutput",u)):z(i.join(`
2
+ `),o);return C(s,e.theme)}a(ne,"renderContentRows");function te(e,n){return e.map(t=>{let r=b(t);if(r===void 0)return U(t.content,n);let i=q(r.source),o=y(F(t.content));return i===void 0?n.fg("toolOutput",o):z(o,i)[0]??n.fg("toolOutput",o)})}a(te,"renderCodeViewLines");function F(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}a(F,"stripScopeMarkers");function U(e,n,t=!0){let r=y(t?F(e):e);return/^#{2,3}\s/u.test(r)?n.fg("mdHeading",n.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?n.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?n.fg("accent",n.bold(r)):/^\s*[-*]\s/u.test(r)?n.fg("mdListBullet",r):n.fg("toolOutput",r)}a(U,"renderCodeViewLabel");function re(e,n,t){if(n||e.length<=E)return e;let r=e.slice(0,E-1),i=e.length-r.length;return[...r,`${t.fg("dim",`\u2026 ${String(i)} more ${i===1?"row":"rows"} \xB7 `)}${Y("app.tools.expand","to expand")}`]}a(re,"compactRows");function ie(e,n,t){let r=a(s=>t.fg("borderMuted",s),"frame"),i=h(` ${B(e,Math.max(1,n-1))} `,Math.max(0,n-1),""),o="\u2500".repeat(Math.max(0,n-p(i)-1));return`${r("\u256D\u2500")}${i}${r(`${o}\u256E`)}`}a(ie,"renderTopBorder");function B(e,n){let t=e.options.label??fe(A(e.details,G(e.details))),r=e.details.source??"read result",i=oe(e.details),o=e.theme.fg("accent",e.theme.bold(t)),s=i===void 0?"":e.theme.fg("dim",` \xB7 ${i}`),u=Math.max(1,n-p(o)-p(s)-2),d=ce(r,u);return`${o} ${e.theme.fg("muted",d)}${s}`}a(B,"readTitle");function oe(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(oe,"sourceRange");function ae(e,n){let t=e.truncation;if(t?.firstLineExceedsLimit===!0)return n.fg("warning","First source line is larger than the saved read limit");if(t?.truncated===!0)return n.fg("warning",`Saved result contains ${String(t.outputLines)} of ${String(t.totalLines)} rendered rows`)}a(ae,"readStatus");function W(e,n,t){let r=Math.max(0,n-2),i=h(e,r),o=` ${i}${" ".repeat(Math.max(0,r-p(i)))} `,s=t.fg("borderMuted","\u2502");return`${s}${o}${s}`}a(W,"framed");function se(e,n,t,r){if(n!==void 0)return k({source:t.source??"",content:"",lines:n},{compact:r});let i=D(e);return t.truncation===void 0&&!(t.totalLines!==void 0&&t.endLine!==void 0&&t.endLine<t.totalLines)?i:i.replace(/\n\n\[(?:Showing lines|Output truncated|\d+ more lines in source)[\s\S]*\]$/u,"")}a(se,"cleanText");function j(e){return e.some(n=>n.presentation!==void 0)}a(j,"hasPresentation");function O(e){let n=e.split(/\r\n|\r|\n/u);return n.at(-1)===""&&/(?:\r\n|\r|\n)$/u.test(e)&&n.pop(),n}a(O,"splitTextRows");function D(e){return e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
3
+ `)}a(D,"textBlocks");function G(e){return e.lines}a(G,"readLines");function $(e){return typeof e=="object"&&e!==null?e:{}}a($,"readDetails");function de(e){return e.content.some(n=>n.type==="text")}a(de,"hasTextContent");function A(e,n){let r=n?.map(b).find(i=>i!==void 0)?.source??e.source;return r===void 0?void 0:q(le(r))}a(A,"languageFor");function ue(e,n,t){return t==="source"&&A(e,n)==="markdown"}a(ue,"isMarkdownSource");function le(e){try{let n=new URL(e);return n.protocol==="file:"?n.pathname:`${n.pathname}${n.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}a(le,"normalizeSourcePath");function y(e){let n="";for(let t of e.replaceAll(" "," ".repeat(4))){let r=R(t.codePointAt(0));n+=r<32||r===127?"\uFFFD":t}return n}a(y,"normalizeText");function fe(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(fe,"languageLabel");function C(e,n){return e.length===0?[n.fg("dim","Empty content")]:[...e]}a(C,"nonEmptyRows");function ce(e,n){return p(e)<=n?e:n<=1?"\u2026":`\u2026${e.slice(-(n-1))}`}a(ce,"truncateFromStart");export{me as a,E as b,ke as c,Me as d};
@@ -0,0 +1 @@
1
+ import{d as s}from"./chunk-S3ZPXWX7.js";import{a as o}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";import{Type as n}from"typebox";var l=n.Object({path:n.Optional(n.String({description:"What to read: a file or directory path, URL, returned temp: or SEARCH# reference, or one of the source forms listed in the description. Supply a path; an empty call cannot select a source."})),offset:n.Optional(n.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor or a SEARCH selection, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier."})),limit:n.Optional(n.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read."})),views:n.Optional(n.Array(n.String(),{description:`Optional additions to the returned text. Use the views listed in the tool description. Combine views when needed, for example ["anchors", "ast"] for source text with editable line references and scope boundaries. Omit for the source's default presentation.`}))});var a=e.Function([],e.Unknown()),u=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number()),renderResult:e.Optional(a),preserveTruncatedOutput:e.Optional(e.Boolean())}),R=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),p=e.Object({id:e.String({pattern:"\\S"}),priority:e.Optional(e.Number()),resolve:a}),y=e.Object({view:e.String({pattern:"\\S"}),includes:e.Optional(e.Array(e.String({pattern:"\\S"}))),presenter:e.Object({id:e.String(),present:a}),priority:e.Optional(e.Number())}),c=e.Object({resolvedBy:e.String({pattern:"\\S"}),contentKind:e.Union([e.Literal("text"),e.Literal("any")])}),g=e.Union([e.Object({stage:e.Literal("pre-read"),handler:a}),e.Object({stage:e.Literal("read"),when:c,handler:a}),e.Object({stage:e.Literal("post-read"),handler:a})]);function h(t){if(!i.Check(R,t))return!1;let r=t,d=r.resolver;return typeof d.id=="string"&&d.id.length>0&&typeof d.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}o(h,"isTextTargetResolverRegistration");function S(t){if(!i.Check(u,t))return!1;let r=t;return s(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}o(S,"isResourceResolverRegistration");function O(t){return i.Check(g,t)}o(O,"isReadHandlerRegistration");function k(t){return i.Check(y,t)}o(k,"isReadViewRegistration");function L(t){return i.Check(p,t)}o(L,"isFragmentResolverRegistration");function P(t){return m(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}o(P,"isReadFragmentResolution");function m(t){return typeof t=="object"&&t!==null}o(m,"isRecord");export{l as a,h as b,S as c,O as d,k as e,L as f,P as g};
@@ -0,0 +1,2 @@
1
+ import{a as o}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";import{Value as C}from"typebox/value";var f=Symbol.for("pi-agent-text/TextAnchor"),u=class{constructor(n,r){this.value=n;this.lineNumber=r;if(n.length===0)throw new TypeError("Text anchor value must be non-empty");if(!Number.isSafeInteger(r)||r<1)throw new RangeError("Text anchor line number must be a positive safe integer")}static{o(this,"TextAnchor")}[f]=!0;static is(n){if(typeof n!="object"||n===null)return!1;try{let r=n;return r[f]===!0&&typeof r.value=="string"&&Number.isSafeInteger(r.lineNumber)&&r.lineNumber>=1}catch{return!1}}toString(){return this.value}},x=new WeakMap;function w(e,n,r){x.set(e,{renderer:n,resolverId:r})}o(w,"attachTextAnchorRenderer");function S(e){return x.get(e)?.renderer}o(S,"getTextAnchorRenderer");function P(e,n,r){let i=x.get(e);if(i===void 0)throw new Error(`No renderer is attached to text anchor "${n}"`);return{...i.renderer,resolverId:i.resolverId,full:i.renderer.renderFull(n,r),compact:i.renderer.renderCompact(n,r)}}o(P,"renderTextAnchor");var a={additionalProperties:!0},l=t.Function([],t.Unknown()),g=t.Object({lineNumber:t.Integer({minimum:1}),column:t.Integer({minimum:0})},a),j=t.Object({rank:t.Integer({minimum:1}),range:t.Object({start:g,end:g},a)},a),L=t.Object({id:t.String({minLength:1}),description:t.Union([t.String(),l]),normalize:t.Optional(l),renderFull:l,renderCompact:l,tryResolve:l,recover:t.Optional(l)},a),O=t.Object({code:t.Union([t.Literal("invalid"),t.Literal("stale"),t.Literal("missing"),t.Literal("ambiguous")]),reason:t.String(),contextRange:t.Optional(t.Object({offset:t.Number(),limit:t.Number()}))}),E=t.Union([t.Object({kind:t.Literal("not-handled")},a),t.Object({kind:t.Literal("resolved"),anchor:t.Unknown()},a),t.Object({kind:t.Literal("rejected"),rejection:O},a),t.Object({kind:t.Literal("failed"),error:t.Unknown()},a)]),N=t.Union([t.Object({kind:t.Literal("unavailable")},a),t.Object({kind:t.Literal("candidates"),candidates:t.Array(j),total:t.Integer({minimum:0})},a),t.Object({kind:t.Literal("timed-out")},a),t.Object({kind:t.Literal("failed"),error:t.Unknown()},a)]);function D(e){return p(L,e)&&y(()=>e.id.trim().length>0)}o(D,"isTextAnchorResolver");function I(e){return p(E,e)&&y(()=>{let n=e;return n.kind!=="resolved"||u.is(n.anchor)})}o(I,"isTextAnchorResolutionAttempt");function M(e){return p(N,e)}o(M,"isTextAnchorRecoveryOutcome");function p(e,n){return y(()=>C.Check(e,n))}o(p,"safeCheck");function y(e){try{return e()}catch{return!1}}o(y,"safeEvaluate");function T(e){if(!e.some(i=>i.marker!==void 0))return e.map(i=>`${i.prefix??""}${i.content}${i.suffix??""}`);let r=Math.max(0,...e.map(i=>i.prefix?.length??0));return e.map(i=>`${i.marker??" "}|${(i.prefix??"").padStart(r," ")}${i.content}${i.suffix??""}`)}o(T,"renderPresentedTextRows");var h="pi-agent-text/source-line";function $(e){let n=e.metadata?.[h];if(F(n))return n}o($,"getTextSourceLine");function U(e,n){return{...e,metadata:{...e.metadata,[h]:n}}}o(U,"withTextSourceLine");function F(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.source=="string"&&n.source.length>0&&typeof n.lineNumber=="number"&&Number.isInteger(n.lineNumber)&&n.lineNumber>0&&typeof n.content=="string"}o(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 V(e){return A(R,e)}o(V,"isTextLinePresenter");function _(e){return A(B,e)}o(_,"isTextPresenterRegistration");function z(e,n){return{source:e,content:n,lines:H(n)}}o(z,"createTextDocument");function K(e){return e.lines.map(n=>`${n.content}${n.lineEnding}`).join("")}o(K,"renderTextDocument");function Y(e,n={}){let r=e.lines.flatMap(s=>[...s.presentation?.before??[],G(s,n.compact===!0),...s.presentation?.after??[]]),i=T(r),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("")}o(Y,"renderPresentedTextDocument");function G(e,n){let r=n&&e.presentation?.compactPrefix!==void 0?e.presentation.compactPrefix:e.presentation?.prefix,i=n&&e.presentation?.compactSuffix!==void 0?e.presentation.compactSuffix:e.presentation?.suffix;return{content:e.content,...r!==void 0&&{prefix:r},...i!==void 0&&{suffix:i},...e.presentation?.marker!==void 0&&{marker:e.presentation.marker}}}o(G,"presentedRowFor");function H(e){if(e.length===0)return[];let n=[],r=/([^\r\n]*)(\r\n|\r|\n|$)/gu,i;for(;(i=r.exec(e))!==null&&i[0].length!==0;)n.push({lineNumber:n.length+1,content:i[1]??"",lineEnding:i[2]??""});return n}o(H,"splitTextLines");function A(e,n){try{return W.Check(e,n)}catch{return!1}}o(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,n){return Promise.resolve(X(e,n))}}}o(Q,"createTextContentConverter");function X(e,n){let r=ee(n.signal);if(r!==void 0)return{kind:"failed",error:r};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"}}}o(X,"convertText");function b(e){if(e===void 0)return!1;let n=e.split(";",1)[0]?.trim().toLowerCase()??"";return n.startsWith("text/")||J.has(n)||n.endsWith("+json")||n.endsWith("+xml")}o(b,"isTextualMediaType");function Z(e){let n=e[0];if(e.length!==1||n.type!=="text")throw new TypeError("Text resources require exactly one text block");return n.text}o(Z,"textFromAgentContent");function ee(e){if(e?.aborted===!0)return e.reason instanceof Error?e.reason:ne()}o(ee,"cancellationError");function ne(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(ne,"abortError");function te(e){if(e===null||typeof e!="object")return!1;let n=e;if(n.kind==="not-handled")return!0;if(n.kind==="failed")return"error"in n;if(n.kind==="rejected"){let r=n.rejection;return r!==null&&typeof r=="object"&&["invalid","stale","missing","ambiguous"].includes(r.code)&&typeof r.reason=="string"}return n.kind!=="resolved"||!Array.isArray(n.targets)||n.targets.length===0?!1:n.targets.every(r=>{if(r===null||typeof r!="object")return!1;let i=r.source,c=r.ranges;return typeof i=="string"&&i.length>0&&(r.expectedContent===void 0||typeof r.expectedContent=="string")&&(c===void 0||Array.isArray(c)&&c.every(re))})}o(te,"isTextTargetResolutionAttempt");function re(e){if(e===null||typeof e!="object")return!1;let n=e;return v(n.start)&&v(n.end)&&(n.linewise===void 0||typeof n.linewise=="boolean")}o(re,"isTextSelectionRange");function v(e){if(e===null||typeof e!="object")return!1;let n=e;return Number.isInteger(n.lineNumber)&&n.lineNumber>=1&&Number.isInteger(n.column)&&n.column>=0}o(v,"isTextSelectionPosition");function oe(e,n){if(e.length<16)return e;let r=n.indexOf(e);return r<0?e:[r,e.length]}o(oe,"storeText");function ie(e,n){return typeof e=="string"?e:n.slice(e[0],e[0]+e[1])}o(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,V as k,_ as l,z as m,K as n,Y as o,Q as p,b as q,Z as r,te as s,oe as t,ie as u};
@@ -0,0 +1,4 @@
1
+ import{a as j,l as M}from"./chunk-DQF5QMJ2.js";import{a as _}from"./chunk-TI5GMJ7Q.js";import{a as N,b as O}from"./chunk-Y7ZMR4LT.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import{a as C,b as R,c as A,d as $,g as F}from"./chunk-Z3VC3S2T.js";import{a as k}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";var h=[],y=[],P=[];function b(n,t,e){if(t.some(i=>i.name===e))throw new Error(`[pi-agent-ide] ${n} "${e}" is already registered. Use a unique name.`)}c(b,"assertUniqueName");function q(n){let t=new Set;for(let e of n){let i=`${e.kind}:${e.name}`;if(t.has(i))throw new Error(`[pi-agent-ide] ${e.kind} "${e.name}" is registered twice by one plugin.`);switch(t.add(i),e.kind){case"compiler":{b(e.kind,y,e.name);break}case"formatter":{b(e.kind,h,e.name);break}case"linter":{b(e.kind,P,e.name);break}}}for(let e of n)switch(e.kind){case"compiler":{y.push(e);break}case"formatter":{h.push(e);break}case"linter":{P.push(e);break}}}c(q,"registerTools");async function L(n,t){let e=[];for(let i of n)try{await i.detect(t)&&e.push(i)}catch(o){console.error(`[pi-agent-ide] detect failed for "${i.name}":`,o)}return e.sort((i,o)=>o.priority-i.priority),H(e),e}c(L,"filterActive");function H(n){let t=new Map;for(let e of n)for(let i of e.extensions){let o=`${i}@${e.priority}`,a=t.get(o);if(a!==void 0)throw new Error(`[pi-agent-ide] priority conflict: tools "${a}" and "${e.name}" both claim "${i}" at priority ${e.priority}.`);t.set(o,e.name)}}c(H,"assertNoPriorityConflicts");async function G(n){let[t,e]=await Promise.all([L(h,n),L(y.filter(i=>i.syntaxOnly===!0),n)]);return{ctx:n,formatters:t,compilers:e,linters:[]}}c(G,"warmupFormatting");function T(){h.length=0,y.length=0,P.length=0}c(T,"resetRegistry");import{readFile as D}from"node:fs/promises";import g from"node:path";var v=class{constructor(t,e={}){this.sources=t;this.options=e}static{c(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:i}){this.disposed||this.ensure(t,e,i)}async read(t,{cwd:e,mode:i,signal:o}){o?.throwIfAborted(),this.assertActive();let a=g.resolve(e,t),s=await D(a,"utf8");this.assertActive();let r=this.ensure(a,s,e);i==="complete"?await this.waitComplete(r,o):i!=="snapshot"&&await K(Promise.all(r.jobs),this.options.readWaitMs??5e3),o?.throwIfAborted(),this.assertActive();let d=await D(a,"utf8");this.assertActive();let l=this.ensure(a,d,e);if(i==="complete"&&l!==r)throw Object.assign(new Error("File changed during diagnostics"),{code:"DIAGNOSTICS_STALE"});return{filePath:a,content:l.content,results:[...l.results.values()]}}async waitComplete(t,e){let i=e?AbortSignal.any([e,t.controller.signal]):t.controller.signal;i.throwIfAborted();let o=[];await new Promise((a,s)=>{let r=c(m=>s(Object.assign(new Error(m),{code:m,details:[...t.results.values()]})),"fail"),d=c(()=>{let m=[...t.results.values()];m.some(w=>w.status==="unavailable")?r("DIAGNOSTICS_UNAVAILABLE"):m.every(w=>w.status==="ready")&&a()},"check"),l=c(()=>s(i.reason),"abort"),f=this.onDidChange(d),u=setTimeout(()=>r("DIAGNOSTICS_TIMEOUT"),this.options.checkTimeoutMs??3e4);i.addEventListener("abort",l,{once:!0});let p=c(()=>{clearTimeout(u),f(),i.removeEventListener("abort",l)},"cleanup");Promise.resolve().then(d),o.push(p)}).finally(()=>{for(let a of o)a()})}async takeNotifications(t){let e=[];for(let i of[...this.dirty]){if(i.cwd!==g.resolve(t)||(this.dirty.delete(i),!await this.isCurrent(i)))continue;let o=[...i.results.values()].filter(d=>d.status!=="pending"&&d.status!=="unavailable"&&d.diagnostics.length>0),a=this.key(i.filePath,i.cwd),s=JSON.stringify(o);if(this.sent.get(a)===s||(this.sent.set(a,s),o.length===0))continue;let r=o.map(d=>{let l=["error","warning","info","hint"].flatMap(f=>{let u=d.diagnostics.filter(p=>p.severity===f).length;return u>0?[`${u} ${f}`]:[]});return`${d.source} ${l.join(", ")}${d.status==="snapshot"?" (snapshot; completion unknown)":d.status==="unversioned"?" (unversioned)":""}`}).join("; ");e.push({filePath:g.relative(t,i.filePath),results:o,text:`${JSON.stringify(g.relative(t,i.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,i){let o=this.key(t,i),a=this.files.get(o);if(a?.content===e)return a;a?.controller.abort(),a&&this.dirty.delete(a);let s={cwd:g.resolve(i),filePath:g.resolve(i,t),content:e,controller:new AbortController,results:new Map,jobs:[],publications:new Map};this.files.set(o,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 d=new Promise(l=>{this.queue.push(async()=>{try{await this.check(s,r)}finally{l()}})});s.jobs.push(d)}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 D(t.filePath,"utf8").catch(()=>{});return this.active(t)&&e===t.content}async publish(t,e,i){let o=(t.publications.get(e)??0)+1;if(t.publications.set(e,o),!await this.isCurrent(t)||t.publications.get(e)!==o)return;let a={...i,source:i.source??e};if(JSON.stringify(t.results.get(e))===JSON.stringify(a))return;t.results.set(e,a),this.dirty.add(t);let s=[...t.results.values()].some(r=>r.status!=="pending"&&r.status!=="unavailable"&&r.diagnostics.length>0);s||this.sent.delete(this.key(t.filePath,t.cwd));for(let r of this.changeListeners)r(t.cwd,s)}async check(t,e){if(!await this.isCurrent(t))return;let i=new AbortController,o=AbortSignal.any([i.signal,t.controller.signal]);if(o.aborted)return;let a,s;try{let r=new Promise((l,f)=>{s=c(()=>f(o.reason),"onAbort"),o.addEventListener("abort",s,{once:!0}),a=setTimeout(()=>i.abort(new Error("Diagnostic check timed out")),this.options.checkTimeoutMs??3e4)}),d=await Promise.race([e.diagnose(t.filePath,{cwd:t.cwd,content:t.content,signal:o,publish:c(l=>{o.aborted||this.publish(t,e.id,l)},"publish")}),r]);await this.publish(t,e.id,d)}catch(r){await this.publish(t,e.id,{status:"unavailable",diagnostics:[],reason:r instanceof Error?r.message:String(r)})}finally{clearTimeout(a),s&&o.removeEventListener("abort",s)}}};async function K(n,t){let e;try{await Promise.race([n,new Promise(i=>{e=setTimeout(i,t)})])}finally{clearTimeout(e)}}c(K,"waitAtMost");function V(){let n=new Map,t=[],e=new v(t),i=Promise.resolve();return{diagnostics:e,registerPlugin(o){if(o.id.trim().length===0)return Promise.reject(new Error("Plugin ID must not be empty"));let a=n.get(o.id);if(a!==void 0)return a;let s=i.then(async()=>{let r=[],d=[],l=!0,f={addTool(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);Z(u),r.push(u)},addDiagnosticSource(u){if(!l)throw new Error(`Plugin ${o.id} setup is already complete`);tt(u),d.push(u)},readDiagnostics(u,p){return e.read(u,p)}};try{await o.setup(f)}catch(u){throw l=!1,u}l=!1,Q(t,d),q(r),t.push(...d)});return n.set(o.id,s),i=s.catch(()=>{}),s.catch(()=>{n.delete(o.id)}),s},async waitForPendingPlugins(){await Promise.all(n.values())}}}c(V,"createIdeCore");function Q(n,t){let e=new Set(n.map(i=>i.id));for(let i of t){if(e.has(i.id))throw new Error(`Diagnostic source ${i.id} is already registered`);e.add(i.id)}}c(Q,"assertUniqueDiagnosticSources");function Z(n){if(!U(n))throw new TypeError("IDE tool must be an object");let t=n.kind,e=t==="compiler"?n.compile:t==="formatter"?n.format:t==="linter"?n.lint:void 0;if(e===void 0||typeof e!="function"||typeof n.detect!="function"||typeof n.name!="string"||n.name.trim().length===0||typeof n.priority!="number"||!Number.isFinite(n.priority)||!Array.isArray(n.extensions)||n.extensions.length===0||n.extensions.some(i=>typeof i!="string"||i.length===0))throw new TypeError("Invalid pi-agent-ide tool contribution")}c(Z,"assertIdeTool");function tt(n){if(!U(n)||typeof n.id!="string"||n.id.trim().length===0||typeof n.diagnose!="function")throw new TypeError("Invalid pi-agent-ide diagnostic source contribution")}c(tt,"assertDiagnosticSource");function U(n){return typeof n=="object"&&n!==null}c(U,"isRecord");function J(n,t,e=console.error){let i=new Map,o=!1,a=Promise.resolve();return{schedule(s){if(o||i.has(s))return;let r=setTimeout(()=>{i.delete(s),a=a.then(async()=>{o||await n(s)}).catch(e)},t);i.set(s,r)},dispose(){o=!0;for(let s of i.values())clearTimeout(s);i.clear()}}}c(J,"createDiagnosticDelivery");import{Text as Y}from"@earendil-works/pi-tui";var S="ide-diagnostic-summary";function W(n){return{filePath:n.filePath,sources:n.results.map(t=>{let e={error:0,warning:0,info:0,hint:0};for(let i of t.diagnostics)e[i.severity]++;return{source:t.source,status:t.status,counts:e}})}}c(W,"diagnosticEntryData");function E(n,t,e=!1){return{render(i){let o=n.sources.filter(r=>r.status!=="pending"&&r.status!=="unavailable"&&Object.values(r.counts).some(d=>d>0));if(o.length===0)return[];let a=o.map(r=>`${x(r.counts,t)} ${t.fg("dim",`(${I(r.source)})`)}`+(r.status==="ready"?"":` \xB7 ${t.fg("dim",r.status)}`)).join(" \xB7 "),s=[`${t.fg("accent","Diagnostics")} ${t.fg("toolTitle",I(n.filePath))} \xB7 ${a}`];if(e)for(let r of o)s.push(` ${t.fg("dim",I(r.source))} \xB7 ${x(r.counts,t)} \xB7 ${t.fg("dim",r.status)}`);return new Y(s.join(`
2
+ `),0,0).render(i)},invalidate(){}}}c(E,"renderDiagnosticEntry");function B(n){n.registerEntryRenderer(S,(t,e,i)=>{let o=k(t.data);return"files"in o?et(o.files,i,e.expanded):E(o,i,e.expanded)})}c(B,"registerDiagnosticEntryRenderer");function et(n,t,e=!1){return{render(i){let o=n.filter(d=>d.sources.some(l=>l.status!=="pending"&&l.status!=="unavailable"&&Object.values(l.counts).some(f=>f>0)));if(o.length===1&&o[0])return E(o[0],t,e).render(i);if(o.length===0)return[];let a={error:0,warning:0,info:0,hint:0},s=new Set;for(let d of o)for(let l of d.sources)if(!(l.status==="pending"||l.status==="unavailable")){s.add(l.source);for(let f of["error","warning","info","hint"])a[f]+=l.counts[f]}let r=new Y(`${t.fg("accent","Diagnostics")} \xB7 ${o.length} files \xB7 ${x(a,t)} \xB7 ${s.size} tools`,0,0).render(i);return e?[...r,...o.flatMap(d=>E(d,t,!0).render(i))]:r},invalidate(){}}}c(et,"renderDiagnosticBatch");function x(n,t){return["error","warning","info","hint"].filter(e=>n[e]>0).map(e=>{let i=n[e],o=e==="info"||i===1?e:`${e}s`,a=i>0&&(e==="error"||e==="warning")?e:"muted";return t.fg(a,`${i} ${o}`)}).join(", ")}c(x,"renderCounts");function I(n){return n.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}c(I,"plain");import X from"node:path";async function z(n){if(!X.isAbsolute(n.resourceSource))return{formatting:{status:"unavailable"}};let t;try{let e=await G({cwd:n.cwd}),i=X.extname(n.resourceSource).toLowerCase(),o=c(d=>d.extensions.includes(i)||d.extensions.includes("*"),"matches"),a=e.compilers.find(o);if(a&&(await a.compile({filePath:n.resourceSource},e.ctx)).syntaxErrors.length>0)return{formatting:{status:"skipped-syntax"}};let s=e.formatters.find(o);if(!s)return{formatting:{status:"unavailable"}};t=s.name;let r=await s.format({filePath:n.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",formatter:t}]}:{diffStatuses:[{text:`Formatting failed (${t})`,tone:"error"}]}})}catch{return{diffStatuses:[{text:"Formatting failed",tone:"error"}],formatting:{status:"failed",...t===void 0?{}:{formatter:t}}}}}c(z,"runIdePostEditGate");import it from"node:path";async function nt(n){T();let t=V();B(n);let e=n.events.on($,s=>{if(!F(s))throw new Error("Invalid pi-agent-ide plugin registration request");s.accept(t.registerPlugin(s.plugin))});n.on("session_shutdown",()=>{e(),t.diagnostics.dispose(),T()}),M(n,{id:"pi-agent-ide",handler:c(s=>n.getFlag("pi-agent-ide-no-post-processing")===!0?Promise.resolve({formatting:{status:"disabled"}}):z(s),"handler")}),n.events.emit(A,{protocol:C,apiVersion:4}),await _(n,{protocol:N,apiVersion:O,id:"ide-diagnostics",setup(s){s.onDidEdit(r=>{n.getFlag("pi-agent-ide-no-post-processing")===!0||r.postProcessing==="deferred"||it.isAbsolute(r.resourceSource)&&j(()=>t.diagnostics.schedule(r.resourceSource,r.after.content,{cwd:r.cwd}))})}});let i=!1,o=J(async s=>{let r=await t.diagnostics.takeNotifications(s);i||r.length===0||(n.sendMessage({customType:"ide-diagnostics",display:!1,content:`File diagnostics:
3
+ ${r.map(d=>d.text).join(`
4
+ `)}`},{triggerTurn:!0,deliverAs:"steer"}),n.appendEntry(S,{files:r.map(W)}))},n.getFlag("pi-agent-ide-no-diagnostic-buffer")===!0?0:5e3),a=t.diagnostics.onDidChange((s,r)=>{r&&o.schedule(s)});n.on("session_shutdown",()=>{i=!0,o.dispose(),a()}),await t.waitForPendingPlugins()}c(nt,"registerPiAgentIde");export{nt as default};
File without changes
@@ -1 +1 @@
1
- import{c as a,d as u,e as c}from"./chunk-JASLOB2X.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
1
+ import{c as a,d as u,e as c}from"./chunk-KAB3AYA2.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
@@ -0,0 +1,14 @@
1
+ import{a as b,d as A}from"./chunk-ITSNK5YG.js";import{a as v}from"./chunk-5MSNYFDE.js";import{d as M}from"./chunk-3SE372WC.js";import{f as C}from"./chunk-YHUTTZC6.js";import{a as p}from"./chunk-EI7MMDWY.js";import F from"node:path";import{truncateHead as $,DEFAULT_MAX_BYTES as W,DEFAULT_MAX_LINES as Z}from"@earendil-works/pi-coding-agent";import{Text as S}from"@earendil-works/pi-tui";import{Type as T}from"typebox";import{Value as Q}from"typebox/value";var N=T.Union([T.String({minLength:1}),v]),_=T.Object({before:N,after:N},{additionalProperties:!1});async function ee(e,l,f){if(!Q.Check(_,l))throw Object.assign(new Error("Use before and after source strings or read request objects"),{code:"INVALID_ARGUMENTS"});let n=l,r=p(async s=>{let t=typeof s=="string"?{path:s}:s,c=await e.read(t,f,"script");if(c.isError||c.details.failure)throw Object.assign(new Error(c.details.failure?.message??"Comparison read failed"),{code:c.details.failure?.code??"READ_FAILED",details:c.details.failure});if(c.script===void 0)throw Object.assign(new Error("Source has no comparable text data"),{code:"UNSUPPORTED_CONTENT"});return L(c.script,t.path??"source")},"resolve"),i=await r(n.before),a=await r(n.after),o=b(i.source,i.content,a.content,a.source);return{kind:"diff",ok:!0,equal:i.content===a.content,before:i,after:a,...o}}p(ee,"executeDiff");function L(e,l){if(e.kind==="text")return{source:e.source,sources:[e.source],content:e.content};if(e.kind==="resources"){let f=e.resources.map(n=>L(n,l));return{source:e.source??l,sources:f.flatMap(n=>n.sources),content:f.map(n=>n.content).join(`
2
+ `)}}if(e.kind==="bytes")throw Object.assign(new Error(`Byte sources are not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});if(e.blocks.length===0||e.blocks.some(f=>f.type!=="text"))throw Object.assign(new Error(`Source is not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});return{source:e.source,sources:[e.source],content:e.blocks.flatMap(f=>f.type==="text"?[f.text]:[]).join(`
3
+ `)}}p(L,"comparisonText");function R(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="diff"&&"ok"in e&&e.ok===!0}p(R,"isDiffOutcome");function D(e,l=process.cwd()){let f=p(r=>F.isAbsolute(r)?F.relative(l,r)||".":r,"displaySource"),n=`Diff: ${f(e.before.source)} \u2192 ${f(e.after.source)}`;return{results:[new A({ok:!0,path:n,beforeContentMap:{[n]:e.before.content},afterContent:e.after.content,diffs:[e.diff]})]}}p(D,"diffPresentation");function O(e){return e.equal?`No differences: ${e.before.source} \u2192 ${e.after.source}`:e.diff}p(O,"diffText");function Se(e){return{content:[{type:"text",text:O(e)}],details:{}}}p(Se,"diffReadResult");function Te(e,l,f){e.registerTool({name:"diff",label:"Diff",parameters:_,promptSnippet:"Compare two text-readable sources without changing them",description:"Use diff to compare two sources without modifying them. before and after accept a source string or a read request {path, offset?, limit?, views?}. Use any source that read can resolve as text. Omit limit to compare complete resolved text; read presentation limits do not clip comparison inputs. Multiple resolved resources are joined with one newline separator in resolver order. Diff line numbers are relative to each selected text, not the original file when a window is selected. Native non-text content is rejected. Output uses the existing text diff and a shared output budget; oversized output has a full temporary reference. The same diff function is available inside Apply.",renderCall(n,r){return new S(r.fg("toolTitle",r.bold("Diff")),0,0)},renderResult(n,r,i,a){let o=n.details;if(o?.comparison?.equal)return new S(O(o.comparison),0,0);let s=l.getToolRenderer("diff")?.renderResult;return s?s(n,r,i,a):new S(n.content.filter(t=>t.type==="text").map(t=>t.text).join(`
4
+ `),0,0)},async execute(n,r,i,a,o){let s=f();if(s===void 0)throw new Error("Diff requires the read extension");let t=await ee(s,r,{cwd:o.cwd,signal:i}),c=O(t),y=$(c).truncated?await s.saveTemporary(c):void 0,d=y===void 0?"":`
5
+ Full diff: ${y}`;return{content:[{type:"text",text:y===void 0?c:$(c,{maxLines:Z-2,maxBytes:W-Buffer.byteLength(d)}).content+d}],details:{...D(t,o.cwd),comparison:t,temporarySource:y}}}})}p(Te,"registerDiff");import{parser as B}from"@lezer/javascript";import{TreeFragment as I}from"@lezer/common";var te=new Set(["read","search","diff","write","replace","insert","remove","copy","move","undo","stage","unstage","delete_file","copy_file","move_file"]);function q(e,l=B.parse(e)){let f=[];l.iterate({enter(r){if(r.name==="AssignmentExpression"){let t=r.node.firstChild;t?.name==="VariableName"&&f.push({name:e.slice(t.from,t.to),from:0,to:e.length})}if(r.name!=="VariableDefinition")return;let i=r.node.parent;for(;i?.parent&&!["VariableDeclaration","ParamList","Block","Script"].includes(i.name);)i=i.parent;let a=i?.name==="VariableDeclaration"&&i.firstChild?.name==="var",o=new Set(["Script","FunctionDeclaration","FunctionExpression","ArrowFunction",...a?[]:["Block"]]),s=r.node.parent;for(s?.name==="FunctionDeclaration"&&(s=s.parent);s?.parent&&!o.has(s.name);)s=s.parent;f.push({name:e.slice(r.from,r.to),from:s?.from??0,to:s?.to??e.length})}});let n=[];return l.iterate({enter(r){if(r.name!=="CallExpression")return;let i=r.node.firstChild;if(i?.name!=="VariableName")return;let a=e.slice(i.from,i.to);if(!te.has(a)||f.some(t=>t.name===a&&t.from<=r.from&&t.to>=r.to))return;let o=r.node.getChild("ArgList")?.getChild("ObjectExpression"),s=Object.create(null);if(!o){let t=r.node.getChild("ArgList"),c=t?e.slice(t.from+1,t.to).replace(/\)$/,""):"";c&&(s.arguments={text:c.length>160?c.slice(0,120)+"\u2026":c,literal:!1})}for(let t of o?.getChildren("Property")??[]){let c=t.firstChild,y=(c?e.slice(c.from,c.to):"").replace(/^["']|["']$/g,"");if(!/^[a-zA-Z_$][\w$]*$/.test(y)){for(let K of["path","query","target","before","after"])delete s[K];let w=e.slice(t.from,t.to);s[`argument@${t.from}`]={text:w.length>160?w.slice(0,160)+"\u2026":w,literal:!1};continue}let d=t.lastChild;if(!d||d.type.isError||d.name===":")continue;let m=e.slice(d.from,d.to),u=m.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),h=/^(?:["'])(?:\d+#[0-9A-F]+|CHANGE#[0-9A-F]+|begin|end|scope-(?:begin|end)-[^"']+)["']$/.test(m);s[y]={text:u.length>160&&!h?`${u.slice(0,100)}\u2026${u.slice(-40)} (${m.length} source chars)`:u,literal:["String","Number","BooleanLiteral","Null"].includes(d.name)&&d.lastChild?.type.isError!==!0}}return n.push({name:a,from:r.from,to:r.to,path:s.path,query:s.query,target:s.target,before:s.before,after:s.after,arguments:s}),!1}}),n}p(q,"parseApplyCalls");function re(e,l=q(e),f,n=r=>r){let r=0,i=[],a=p(o=>n(o.split(`
6
+ `).map(s=>s.length>200?s.slice(0,200)+"\u2026":s).join(`
7
+ `)),"codePreview");for(let o of l)i.push(a(e.slice(r,o.from))),i.push(f?.(o)??`${o.name}(${o.path?o.path.literal?o.path.text:`\u2039${o.path.text}\u203A`:"\u2026"})`),r=o.to;return i.push(a(e.slice(r))),i.join("")}p(re,"compactApplySource");function U(e,l){let f="",n="",r=[];return i=>{if(i===f)return n;let a=0;for(;a<f.length&&a<i.length&&f[a]===i[a];)a++;r=I.applyChanges(r,[{fromA:a,toA:f.length,fromB:a,toB:i.length}]);let o=B.parse(i,r);return r=I.addTree(o),n=re(i,q(i,o),e,l),f=i,n}}p(U,"createApplySourceProjection");import{lstat as z,unlink as ne}from"node:fs/promises";import V from"node:path";import J from"fs-extra";import{Type as x}from"typebox";import{Value as oe}from"typebox/value";var Ne=["delete_file","move_file","copy_file"],E=x.String({minLength:1,description:"Local regular file path, relative to cwd or absolute."}),ie=x.Object({path:E},{additionalProperties:!1}),ae=x.Object({path:E,target:E,overwrite:x.Optional(x.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))},{additionalProperties:!1});function k(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="file-operation"}p(k,"isFileOperationResult");function P(e){return[`${e.operation}: ${e.effect}`,e.path,e.target===void 0?void 0:`Target: ${e.target}`,e.error===void 0?void 0:`${e.error.code}: ${e.error.message}`].filter(l=>l!==void 0).join(`
8
+ `)}p(P,"formatFileOperation");async function _e(e,l,f,n){let r=!1,i,a;try{let o=e==="delete_file"?ie:ae;if(!oe.Check(o,l))throw Object.assign(new Error("Invalid file operation arguments"),{code:"INVALID_ARGUMENTS"});let s=l;i=V.resolve(f,s.path),a=s.target===void 0?void 0:V.resolve(f,s.target),n?.throwIfAborted();let t=await se(i);if(a!==void 0){let c=await le(a);if(c!==void 0){if(!c.isFile()||c.isSymbolicLink())throw Object.assign(new Error("Target must be a regular file"),{code:"INVALID_FILE_TYPE"});if(i===a||t.ino===c.ino&&t.dev===c.dev)throw Object.assign(new Error("Source and target are the same file"),{code:"SAME_FILE"});if(s.overwrite!==!0)throw Object.assign(new Error("Target exists; use overwrite: true to replace it"),{code:"EEXIST"})}}return n?.throwIfAborted(),r=!0,e==="delete_file"?await ne(i):a!==void 0&&(e==="copy_file"?await J.copy(i,a,{overwrite:s.overwrite===!0,errorOnExist:!0}):await J.move(i,a,{overwrite:s.overwrite===!0})),{kind:"file-operation",operation:e,ok:!0,effect:"applied",path:i,...a===void 0?{}:{target:a}}}catch(o){return{kind:"file-operation",operation:e,ok:!1,effect:r?"unknown":"not-applied",...i===void 0?{}:{path:i},...a===void 0?{}:{target:a},error:{code:o!==null&&typeof o=="object"&&"code"in o?String(o.code):"FILE_OPERATION_FAILED",message:o instanceof Error?o.message:String(o)}}}}p(_e,"executeFileOperation");async function se(e){let l=await z(e);if(!l.isFile()||l.isSymbolicLink())throw Object.assign(new Error("Source must be a regular file"),{code:"INVALID_FILE_TYPE"});return l}p(se,"regularFile");async function le(e){try{return await z(e)}catch(l){if(l!==null&&typeof l=="object"&&"code"in l&&l.code==="ENOENT")return;throw l}}p(le,"optionalStat");import{Text as fe}from"@earendil-works/pi-tui";function G(e){let l=e.select(),f=e.mutationValues().filter(ce);return l.files.map(n=>{let r=f.flatMap(o=>o.files.filter(s=>s.source===n.source).map(s=>({outcome:o,changed:s}))),i=e.mutationPresentation(n.source)?.data,a=i?.afterContent===n.after?i:void 0;return new A({ok:!0,path:n.source,files:[{path:n.source,action:n.before===null?"created":"edited"}],snapshot:{content:n.before??""},beforeContentMap:{[n.source]:n.before},afterContent:n.after??"",afterDocument:a?.afterDocument,resultPresentation:a?.resultPresentation,scopeMarkers:a?.scopeMarkers,hints:a?.hints,warnings:a?.warnings,diffStatuses:a?.diffStatuses,diffs:[b(n.source,n.before??"",n.after??"").diff],operations:r.map(({outcome:o,changed:s})=>({operation:o.operation==="remove"?"delete":o.operation,changes:s.changes.length})),formatting:a?.formatting??r.at(-1)?.changed.formatting})})}p(G,"finalApplyMutations");function ce(e){return e!==null&&typeof e=="object"&&"operation"in e&&"files"in e&&Array.isArray(e.files)&&"effect"in e}p(ce,"isMutation");import{highlightCode as H}from"@earendil-works/pi-coding-agent";import{wrapTextWithAnsi as X,visibleWidth as Y,truncateToWidth as pe}from"@earendil-works/pi-tui";function Qe(e,l,f,n=process.cwd()){let r=e.select(),i=[...r.automatic,...r.explicit.filter(t=>t.kind==="operation")].filter(t=>R(t.value)&&!t.value.equal),a=i.flatMap(t=>R(t.value)?[D(t.value,n)]:[]),o=new Set(i.flatMap(t=>t.presentation?.content??[]));if(r.files.length===0){let t=[...r.automatic.map(c=>c.presentation),...r.explicit.map(c=>c.kind==="operation"?c.presentation:void 0)].filter(c=>c!==void 0);return{comparisons:a,cwd:n,blocks:l.content.filter(c=>!o.has(c)).flatMap(c=>c.type==="text"?[{text:c.text,read:t.find(g=>g.content.includes(c))}]:[])}}let s=G(e);return{...s.length>0?{mutations:{results:s}}:{},comparisons:a,cwd:n,blocks:[...r.explicit.flatMap(t=>t.kind==="operation"&&R(t.value)&&!t.value.equal?[]:k(t.value)?[{text:P(t.value)}]:t.kind==="operation"?t.presentation?.content.flatMap(c=>c.type==="text"?[{text:c.text,read:t.presentation}]:[])??[]:[{text:typeof t.value=="string"?t.value:t.value===void 0?"undefined":JSON.stringify(t.value,null,2)}]),...r.automatic.flatMap(({value:t,presentation:c})=>k(t)?[{text:P(t)}]:t!==null&&typeof t=="object"&&"kind"in t&&t.kind==="index-operation"?c?.content.flatMap(g=>g.type==="text"?[{text:g.text}]:[])??[]:t===null||typeof t!="object"||!("errors"in t)||!Array.isArray(t.errors)?[]:t.errors.flatMap(g=>g!==null&&typeof g=="object"&&"message"in g&&typeof g.message=="string"?[{text:g.message}]:[])),...f===void 0?[]:[{text:f instanceof Error?f.message:JSON.stringify(f)}]]}}p(Qe,"createApplyDisplay");function j(e,l,f,n,r,i,a=!1){let o=Math.max(1,f);if(o<5)return e.split(`
9
+ `).flatMap(u=>X(u,o));let s=o-4,t=p(u=>l.fg("borderMuted",u),"border"),g=pe(` ${n==="call"?"Apply \xB7 JavaScript":"Result"} `,o-4,""),y=[t(`${n==="call"?"\u256D":"\u251C"}\u2500`)+l.fg(a?"error":"accent",g)+t(`${"\u2500".repeat(Math.max(0,o-Y(g)-3))}${n==="call"?"\u256E":"\u2524"}`)],d=`${t("\u2502")}${" ".repeat(o-2)}${t("\u2502")}`;for(let u of e.split(`
10
+ `)){let h=i==="diff"?l.fg(u.startsWith("+")?"toolDiffAdded":u.startsWith("-")?"toolDiffRemoved":"toolDiffContext",u):i?H(u,i).join(`
11
+ `):l.fg("toolOutput",u);for(let w of X(h,s))y.push(`${t("\u2502")} ${w}${" ".repeat(Math.max(0,s-Y(w)))} ${t("\u2502")}`)}n==="call"&&y.push(d),r&&y.push(t(`\u2570${"\u2500".repeat(o-2)}\u256F`));let m=l.getBgAnsi("toolPendingBg");return y.map(u=>m+C(u,m)+"\x1B[0m")}p(j,"applyFrameRows");function ue(e){return(l,f,n)=>{let r=n.state,i=r.projectSource??=U(e?o=>e(o,f):void 0,e?o=>H(o,"javascript").join(`
12
+ `):void 0),a=l!==null&&typeof l=="object"&&"source"in l&&typeof l.source=="string"?l.source:"";return{invalidate(){},render(o){return j(r.codeView||n.expanded?r.displaySource??a:i(r.displaySource??a),f,o,"call",!r.applyResultReady,r.codeView||n.expanded||!e?"javascript":void 0)}}}}p(ue,"createApplyCallRenderer");var et=ue();function de(e){return(l,f,n,r)=>{r.state.applyResultReady=!0;let i=l.details;r.state.displaySource=i?.displaySource;let a=i?.display,o=a?.blocks??[{text:r.isError?"Apply failed":"Apply finished"}],s=M({kind:"source"}),t=o.map(d=>s(d.read??{content:[{type:"text",text:d.text}],details:me(d.text)},f,n,{...r,isError:!1,lastComponent:void 0})),c=a?.mutations,g=(a?.comparisons??[]).flatMap(d=>[e?.(d,n,f.expanded,a?.cwd??process.cwd())??new fe((d.results??[]).flatMap(u=>u.data.diffs??[]).join(`
13
+ `),0,0)]),y=c===void 0?void 0:e?.(c,n,f.expanded,a?.cwd??process.cwd());return{invalidate(){y?.invalidate();for(let d of g)d.invalidate()},render(d){let m=[];for(let u of t){let h=u.render(Math.max(1,d-4));h.length!==0&&(m.length>0&&m.push(""),m.push(...h))}for(let u of g)m.length>0&&m.push(""),m.push(...u.render(Math.max(1,d-4)));if(y!==void 0){let u=y.render(Math.max(1,d-4));m.length>0&&u.length>0&&m.push(""),m.push(...u)}else c!==void 0&&m.push(...(c.results??[]).map(u=>u.path??"Changed file"));return m.length===0&&o.length>0&&o.every(u=>u.read?.details.diagnosticCheck?.complete&&u.read.details.diagnosticCheck.count===0)?j("",n,d,"result",!0).slice(-1):j(m.length===0?"No output":m.join(`
14
+ `),n,d,"result",!0,void 0,r.isError)}}}}p(de,"createApplyResultRenderer");function me(e){try{let l=JSON.parse(e);return l!==null&&typeof l=="object"?{source:"result.json"}:{}}catch{return{}}}p(me,"jsonDetails");var tt=de();export{ee as a,Se as b,Te as c,Ne as d,ie as e,ae as f,_e as g,G as h,Qe as i,ue as j,et as k,de as l,tt as m};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as n}from"typebox/value";var t="pi-agent-search",i=1,S="pi-agent-search/core/ready",R="pi-agent-search/plugin/register",a=e.Unsafe({type:"Function"}),s=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(i)}),c=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(i),id:e.String({minLength:1}),setup:a}),p=e.Object({plugin:c,accept:a});function g(r){return n.Check(s,r)}o(g,"isSearchCoreReady");function h(r){return n.Check(c,r)}o(h,"isSearchPlugin");function y(r){return n.Check(p,r)}o(y,"isSearchPluginRegistrationRequest");export{t as a,i as b,S as c,R as d,g as e,h as f,y as g};
1
+ import{a as o}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as n}from"typebox/value";var t="pi-agent-search",i=3,S="pi-agent-search/core/ready",R="pi-agent-search/plugin/register",a=e.Unsafe({type:"Function"}),s=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(i)}),c=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(i),id:e.String({minLength:1}),setup:a}),p=e.Object({plugin:c,accept:a});function g(r){return n.Check(s,r)}o(g,"isSearchCoreReady");function h(r){return n.Check(c,r)}o(h,"isSearchPlugin");function y(r){return n.Check(p,r)}o(y,"isSearchPluginRegistrationRequest");export{t as a,i as b,S as c,R as d,g as e,h as f,y as g};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var t=e.Function([],e.Unknown()),d=e.Union([e.Object({stage:e.Literal("text-pre-edit"),handler:t}),e.Object({stage:e.Literal("text-edit"),handler:t}),e.Object({stage:e.Literal("text-post-edit"),handler:t})]);function l(r){return i.Check(d,r)}n(l,"isTextEditHandlerRegistration");export{l as a};
1
+ import{a as n}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as d}from"typebox/value";var t=e.Function([],e.Unknown()),i=e.Union([e.Object({stage:e.Literal("text-pre-edit"),handler:t}),e.Object({stage:e.Literal("text-edit"),handler:t}),e.Object({stage:e.Literal("text-post-edit"),handler:t})]);function l(r){return d.Check(i,r)}n(l,"isTextEditHandlerRegistration");export{l as a};
@@ -1,3 +1,3 @@
1
- import{a as w}from"./chunk-RAZOACDD.js";import{a as u}from"./chunk-EI7MMDWY.js";import{createHash as T}from"node:crypto";import{createRequire as P}from"node:module";import L from"node:path";import*as h from"web-tree-sitter";var F=P(new URL("../src/plugins/pi-agent-ide-ast/src/ast/manager.ts",import.meta.url).href),j=new Set(["program","module"]),y=new Set(["body","consequence","alternative","handler","finalizer"]),S,x=new Map;function E(c){switch(c){case".ts":case".tsx":return"tree-sitter-typescript/tree-sitter-typescript.wasm";case".js":case".jsx":case".mjs":case".cjs":return"tree-sitter-javascript/tree-sitter-javascript.wasm";case".py":return"tree-sitter-python/tree-sitter-python.wasm";case".rs":return"tree-sitter-rust/tree-sitter-rust.wasm";case".c":case".cc":case".hh":case".hxx":case".cpp":case".cxx":case".h":case".hpp":return"tree-sitter-cpp/tree-sitter-cpp.wasm";case".json":case".jsonc":return"tree-sitter-json/tree-sitter-json.wasm";case".yaml":case".yml":return"@tree-sitter-grammars/tree-sitter-yaml/tree-sitter-yaml.wasm";case".toml":return"@tree-sitter-grammars/tree-sitter-toml/tree-sitter-toml.wasm";default:return}}u(E,"grammarWasmPath");async function B(c){let n=E(c);if(!n)return;S??=h.Parser.init(),await S;let t=x.get(n);if(t===void 0){let o=F.resolve(n);t=h.Language.load(o),x.set(n,t)}let s=await t,i=new h.Parser;return i.setLanguage(s),i}u(B,"ensureParser");async function W(c,n,t){if(t.length===0)return;let s=L.isAbsolute(c)?c:L.resolve(n,c),i=await B(L.extname(s).toLowerCase());if(i)return i.parse(t.join(`
1
+ import{a as w}from"./chunk-5VSE5X5R.js";import{a as u}from"./chunk-EI7MMDWY.js";import{createHash as T}from"node:crypto";import{createRequire as P}from"node:module";import L from"node:path";import*as h from"web-tree-sitter";var F=P(new URL("../src/plugins/pi-agent-ide-ast/src/ast/manager.ts",import.meta.url).href),j=new Set(["program","module"]),y=new Set(["body","consequence","alternative","handler","finalizer"]),S,x=new Map;function E(c){switch(c){case".ts":case".tsx":return"tree-sitter-typescript/tree-sitter-typescript.wasm";case".js":case".jsx":case".mjs":case".cjs":return"tree-sitter-javascript/tree-sitter-javascript.wasm";case".py":return"tree-sitter-python/tree-sitter-python.wasm";case".rs":return"tree-sitter-rust/tree-sitter-rust.wasm";case".c":case".cc":case".hh":case".hxx":case".cpp":case".cxx":case".h":case".hpp":return"tree-sitter-cpp/tree-sitter-cpp.wasm";case".json":case".jsonc":return"tree-sitter-json/tree-sitter-json.wasm";case".yaml":case".yml":return"@tree-sitter-grammars/tree-sitter-yaml/tree-sitter-yaml.wasm";case".toml":return"@tree-sitter-grammars/tree-sitter-toml/tree-sitter-toml.wasm";default:return}}u(E,"grammarWasmPath");async function B(c){let n=E(c);if(!n)return;S??=h.Parser.init(),await S;let t=x.get(n);if(t===void 0){let o=F.resolve(n);t=h.Language.load(o),x.set(n,t)}let s=await t,i=new h.Parser;return i.setLanguage(s),i}u(B,"ensureParser");async function W(c,n,t){if(t.length===0)return;let s=L.isAbsolute(c)?c:L.resolve(n,c),i=await B(L.extname(s).toLowerCase());if(i)return i.parse(t.join(`
2
2
  `))??void 0}u(W,"parseDocument");function A(c,n,t){let s=c.slice(Math.max(0,n-1),Math.max(0,t)).join(`
3
3
  `);return T("sha1").update(s).digest("hex").slice(0,4).toUpperCase()}u(A,"hashScope");var b=class extends w{static{u(this,"AstScopeTextAnchor")}constructor(n,t,s,i){super(`scope-${n}-${t}${i===void 0?"":`-${i}`}`,s)}};function g(c,n,t,s){return new b(c,n,t,s)}u(g,"createScopeAnchor");var C=class{static{u(this,"AstScopeManager")}async getDocumentScopes(n,t,s){if(s.length===0)return[];let i=await W(n,t,s);if(!i)return[];let o=[];return this.collectCandidates(i.rootNode,o),this.buildEntries(o,s)}collectCandidates(n,t,s=0,i=!1){if(s>100||!n.isNamed)return;let o=n.type;if(!o||j.has(o)){for(let a of n.namedChildren)this.collectCandidates(a,t,s+1);return}for(let a of y){let e=n.childForFieldName(a);if(!e?.isNamed)continue;let r=e.startPosition.row+1,l=e.endPosition.row+1,f=l-r>=3,d=[...y].some(m=>e.childForFieldName(m)!==null);f&&!d&&t.push({startLine:r,endLine:l,kind:`${o}.${a}`,fromBodyField:!0}),this.collectCandidates(e,t,s+1,!0)}if(![...y].some(a=>n.childForFieldName(a)!==null)&&!i){let a=n.startPosition.row+1,e=n.endPosition.row+1;e-a>=3&&n.namedChildren.length>0&&t.push({startLine:a,endLine:e,kind:o,fromBodyField:!1})}for(let a of n.namedChildren)this.collectCandidates(a,t,s+1)}buildEntries(n,t){let s=new Map;for(let e of n){let r=s.get(e.startLine);(!r||e.endLine>r.endLine||e.endLine===r.endLine&&e.fromBodyField&&!r.fromBodyField)&&s.set(e.startLine,e)}let i=[...s.values()].sort((e,r)=>e.startLine-r.startLine||r.endLine-e.endLine),o=[];for(let e of i)o.some(l=>l.startLine<e.startLine&&l.endLine===e.endLine)||o.push(e);let p=new Map;for(let e of o){let r=A(t,e.startLine,e.endLine);p.set(r,(p.get(r)??0)+1)}let a=new Map;return o.map(e=>{let r=A(t,e.startLine,e.endLine),l=p.get(r)??1,f=(a.get(r)??0)+1;a.set(r,f);let d=l>1?f:void 0;return{name:e.kind,kind:e.kind,startLine:e.startLine,endLine:e.endLine,depth:o.filter(m=>m!==e&&m.startLine<=e.startLine&&m.endLine>=e.endLine&&(m.startLine<e.startLine||m.endLine>e.endLine)).length,hash:r,blockHash:r,...d!==void 0&&{occurrence:d},beginAnchor:g("begin",r,e.startLine,d),endScopeAnchor:g("end",r,e.endLine,d),scopeBeginAnchor:g("begin",r,e.startLine,d),scopeEndAnchor:g("end",r,e.endLine,d)}})}};export{W as a,C as b};
@@ -0,0 +1 @@
1
+ import{a as p,e as f,k as g}from"./chunk-Y7ZMR4LT.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as m}from"node:async_hooks";var l=new m,u=new m;function E(t){let e=u.getStore();e?e.push(t):t()}o(E,"afterPostEditScope");async function T(t){if(u.getStore())return t();let e=[];try{return await u.run(e,t)}finally{for(let r of e)r()}}o(T,"collectPostEditNotifications");function b(t,e){let r=l.getStore();return r?(r.set(t,e),!0):!1}o(b,"deferPostEdit");function h(t){return l.getStore()?.has(t)??!1}o(h,"hasDeferredPostEdit");function v(){let t=new Map;return{run(e){return l.run(t,e)},forget(e){t.delete(e)},async finish(e){let r=[...t.values()];t.clear();let d=[],i=[];if(await T(async()=>{for(let a of r)try{let s=await a();d.push(s),e?.(s)}catch(s){i.push(s)}}),i.length>0)throw new AggregateError(i,`Some final post-processing failed; completed edits remain applied. ${i.map(a=>a instanceof Error?a.message:String(a)).join("; ")}`);return d}}}o(v,"createPostEditScope");import{Type as n}from"typebox";import{Value as c}from"typebox/value";var w=`${p}/post-edit/register`;function A(t){return c.Check(n.Object({formatting:n.Object({status:n.Union(["disabled","unavailable","skipped-syntax","unchanged","changed","failed","not-reported","deferred"].map(e=>n.Literal(e))),formatter:n.Optional(n.String())})}),t)}o(A,"isFormattingContribution");function M(t){return c.Check(n.Object({diffStatuses:n.Array(n.Object({text:n.String({minLength:1}),formatter:n.Optional(n.String()),tone:n.Optional(n.Union(["muted","success","warning","error"].map(e=>n.Literal(e))))}))}),t)}o(M,"isDiffStatusContribution");var x=n.Function([],n.Unknown()),y=n.Object({id:n.String({minLength:1}),handler:x}),P=n.Object({registration:y,accept:x});function S(t){return c.Check(y,t)}o(S,"isTextPostEditHandlerRegistration");function _(t){return c.Check(P,t)}o(_,"isTextPostEditHandlerRegistrationRequest");function j(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.hints)&&typeof e.scopeMarkers=="object"&&e.scopeMarkers!==null&&Array.isArray(e.warnings)}o(j,"isTextMutationResultContributionData");function I(t,e){if(!S(e))throw new TypeError("Invalid text editor post-edit handler registration");let r,d=o(()=>{let a={registration:e,accept(s){if(r!==void 0)throw new Error(`Post-edit handler ${e.id} was accepted more than once`);r=s}};return t.events.emit(w,a),r!==void 0},"announce"),i=o(()=>{},"unsubscribeReady");i=t.events.on(f,a=>{if(!g(a))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()}),t.on("session_shutdown",()=>{i(),r?.()}),d()&&i()}o(I,"connectTextEditorPostEditHandler");export{E as a,T as b,b as c,h as d,v as e,w as f,A as g,M as h,S as i,_ as j,j as k,I as l};
@@ -0,0 +1 @@
1
+ import{a as s}from"./chunk-EI7MMDWY.js";import{readFile as b}from"node:fs/promises";import p from"node:os";import i from"node:path";function I(n=process.env,o=p.homedir(),e=process.cwd()){let r=n.PI_CODING_AGENT_DIR?.trim(),t=r===void 0||r.length===0?i.join(o,".pi","agent"):i.resolve(r);return{globalPath:i.join(t,"pi-agent-ide","extensions.json"),projectPath:i.resolve(e,".pi","pi-agent-ide","extensions.json")}}s(I,"resolvePiAgentIdeExtensionsConfigPaths");async function $(n){let o=await g(n.globalPath),e=await g(n.projectPath);return{disabled:[...new Set([...o.disabled,...e.disabled])],enabled:[...new Set([...o.enabled,...e.enabled])],...o.flags===void 0&&e.flags===void 0?{}:{flags:{...c(o),...c(e)}},...o.preferences===void 0&&e.preferences===void 0?{}:{preferences:{...o.preferences,...e.preferences}},noAnimations:e.noAnimations??o.noAnimations??!1,noPostProcessing:e.noPostProcessing??o.noPostProcessing??!1}}s($,"readPiAgentIdeExtensionsConfig");function c(n){return{...n.noAnimations===void 0?{}:{"pi-agent-ide-no-animations":n.noAnimations},...n.noPostProcessing===void 0?{}:{"pi-agent-ide-no-post-processing":n.noPostProcessing},...n.flags}}s(c,"configuredFeatureFlags");async function h(n){return g(n)}s(h,"readExtensionSettingsScope");async function g(n){let o;try{o=await b(n,"utf8")}catch(r){if(y(r))return{disabled:[],enabled:[]};throw new Error(`Cannot read Pi Agent IDE extension config at ${n}: ${u(r)}`,{cause:r})}let e;try{e=JSON.parse(o)}catch(r){throw new Error(`Invalid JSON in Pi Agent IDE extension config at ${n}: ${u(r)}`,{cause:r})}if(!a(e))throw new Error(`Pi Agent IDE extension config at ${n} must be a JSON object`);return{disabled:f(e,"disabled",n),enabled:f(e,"enabled",n),...e.flags===void 0?{}:{flags:m(e.flags,n)},...e.preferences===void 0?{}:{preferences:w(e.preferences,n)},...e.noAnimations===void 0?{}:{noAnimations:l(e,"noAnimations",n)},...e.noPostProcessing===void 0?{}:{noPostProcessing:l(e,"noPostProcessing",n)}}}s(g,"readConfigExtensionIds");function w(n,o){if(!a(n))throw new Error(`preferences in ${o} must be an object`);let e={};for(let[r,t]of Object.entries(n)){if(typeof t!="string"||t.length===0)throw new Error(`Preference ${r} in ${o} must be a non-empty string`);e[r]=t}return e}s(w,"readPreferences");function m(n,o){if(!a(n))throw new Error(`flags in ${o} must be an object`);let e={};for(let[r,t]of Object.entries(n)){if(typeof t!="boolean")throw new Error(`Flag ${r} in ${o} must be a boolean`);e[r]=t}return e}s(m,"readFlags");function l(n,o,e){let r=n[o];if(typeof r!="boolean")throw new Error(`${o} in ${e} must be a boolean`);return r}s(l,"readBoolean");function f(n,o,e){let r=n[o];if(r===void 0)return[];if(!Array.isArray(r))throw new Error(`${o} in ${e} must be an array of non-empty strings`);let t=r.filter(d=>typeof d=="string");if(t.length!==r.length||t.some(d=>d.length===0))throw new Error(`${o} in ${e} must be an array of non-empty strings`);if(new Set(t).size!==t.length)throw new Error(`${o} in ${e} must not contain duplicate IDs`);return t}s(f,"readIdField");function y(n){return a(n)&&n.code==="ENOENT"}s(y,"isMissingFile");function a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(a,"isRecord");function u(n){return n instanceof Error?n.message:String(n)}s(u,"errorMessage");export{I as a,$ as b,c,h as d};
@@ -0,0 +1,2 @@
1
+ import"./chunk-NNCZYO4Q.js";import{d as N}from"./chunk-3SE372WC.js";import"./chunk-YHUTTZC6.js";import{a as E}from"./chunk-72EEL2DW.js";import{a as A,b}from"./chunk-KAB3AYA2.js";import{d as O}from"./chunk-DQF5QMJ2.js";import"./chunk-Y7ZMR4LT.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as D,g as w,h as k,i as P,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-HKMBQLEK.js";import{a as y,b as I}from"./chunk-Z3VC3S2T.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import S from"node:path";var T="diagnostics",V=N({kind:"code-view",label:"Diagnostics"});async function q(c){let n,t=l((o,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(o,{cwd:f,...e})},"collect"),i={protocol:y,apiVersion:4,id:"diagnostics",setup(o){n=o.readDiagnostics}},r=new WeakMap,s=new WeakMap,a=new WeakMap,d=new WeakMap,M={protocol:A,apiVersion:b,id:"diagnostics",setup(o){o.addResolver({resolver:W(t,s),renderResult:V});let f=v();o.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),o.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=s.get(g);return u&&r.set(e.request,u),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),o.addHandler({stage:"post-read",handler(e){let g=r.get(e.request);if(g&&e.result)return{kind:"continue",context:{...e,result:{...e.result,details:{...e.result.details,diagnosticCheck:g}}}};let u=a.get(e.request),h=u&&d.get(u),p=e.result,R=p?.content[0];return!h||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${h}
2
+ ${R.text}`},...p.content.slice(1)]}}}}}),o.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 after the notification buffer (five seconds by default); 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.'),o.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([C(c,i),E(c,M)])}l(q,"registerDiagnostics");function W(c,n){return{id:"diagnostics",tryResolve(t,i){return Promise.resolve(_(t,i.cwd,c,n,{signal:i.signal,...i.audience==="script"&&{mode:"complete"}}))}}}l(W,"createDiagnosticResolver");function _(c,n,t,i,r){let s;try{s=m(c,T,n)}catch(a){return{kind:"failed",error:a}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:D(T,s),async read(){let a=await t(s,n,r),d=w(s,a.content,a.results);return i.set(d,d.diagnosticCheck),[d]}}}}l(_,"resolveDiagnosticSource");function j(c,n){return{id:"diagnostics",async present(t,i){if(i.purpose!=="read"||!S.isAbsolute(t.source))return t;let r=i.audience==="script"&&!i.requestedViews?.includes("diagnostics");if(r&&O(t.source))return t;let s=await c(t.source,i.cwd,{signal:i.signal,...i.audience==="script"&&{mode:r?"snapshot":"complete"}}).catch(a=>{if(i.signal?.throwIfAborted(),!r)throw a});if(s===void 0||r&&s.content!==t.content)return t;if(s.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,P(s.results)),k(t,s.results)}}}l(j,"createDiagnosticPresenter");export{q as default};
@@ -1 +1 @@
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};
1
+ import{a as c}from"./chunk-5VSE5X5R.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{Type as e}from"typebox";var o=e.Object({query:e.String({minLength:1,description:"Text to find, a Boolean expression, or a prefixed query described below, such as files:*.ts. Quote text to keep it literal, or use regex:<pattern> for regular-expression matching."}),path:e.Optional(e.String({description:"Optional file or directory scope for local search"})),include:e.Optional(e.String({description:"Optional include glob for local search"})),exclude:e.Optional(e.String({description:"Optional exclude glob for local search"})),caseSensitive:e.Optional(e.Boolean({description:"Match letter case in local search"})),wholeWord:e.Optional(e.Boolean({description:"Match complete words in local search"})),limit:e.Optional(e.Integer({minimum:1,maximum:1e3,description:"Maximum results (default 100)"}))},{additionalProperties:!1});export{o as a};
@@ -1 +1 @@
1
- import{c as u,d as a,e as c}from"./chunk-KZBAJFCV.js";import{a as t}from"./chunk-EI7MMDWY.js";function f(o,r){let s=t(()=>{let e,i={plugin:r,accept(g){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=g}};return o.events.emit(a,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(u,e=>{if(!c(e))throw new Error("Invalid pi-agent-ide core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-ide core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(f,"connectIdePlugin");export{f as a};
1
+ import{c as u,d as a,e as c}from"./chunk-Z3VC3S2T.js";import{a as t}from"./chunk-EI7MMDWY.js";function f(o,r){let s=t(()=>{let e,i={plugin:r,accept(g){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=g}};return o.events.emit(a,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(u,e=>{if(!c(e))throw new Error("Invalid pi-agent-ide core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-ide core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(f,"connectIdePlugin");export{f as a};
@@ -0,0 +1,7 @@
1
+ import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createTwoFilesPatch as m,diffLines as g}from"diff";function y(i,e,n,r=i){return{diff:m(i,r,e,n,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:p(e,n)}}s(y,"createUnifiedDiff");function p(i,e){let n=0,r=0;for(let t of g(i,e)){let a=l(t.value);t.removed&&(n+=a),t.added&&(r+=a)}return{removed:n,added:r}}s(p,"computeStats");function l(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
2
+ `,`
3
+ `);return e.endsWith(`
4
+ `)?e.slice(0,-1).split(`
5
+ `).length:e.split(`
6
+ `).length}s(l,"countDiffLines");function x(i,e){let n=g(i,e),r=[],t=0;for(let a of n){let o=l(a.value);o!==0&&(a.removed||(a.added&&r.push({start:t+1,end:t+o}),t+=o))}return E(r)}s(x,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,t)=>r.start-t.start),n=[d(e[0])];for(let r=1;r<e.length;r++){let t=d(n.at(-1)),a=d(e[r]);a.start<=t.end+1?t.end=Math.max(t.end,a.end):n.push(a)}return n}s(E,"mergeAdjacentRanges");var f=class i{static{s(this,"FileRange")}start;end;constructor(e,n=e){n.lineNumber<e.lineNumber&&([e,n]=[n,e]),this.start=e,this.end=n}static fromLines(e,n){let r=n??e;return new i({lineNumber:e},{lineNumber:r})}},c=class i{static{s(this,"FileMutationResult")}data;constructor(e){this.data=e??{}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,n=e?.[0];if(n?.range){let r=n.range.start,a=d(e).at(-1)?.range?.end??r;return new f(r,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let n of this.files)e.add(n.path);for(let n of this.errors)n.path&&e.add(n.path);for(let n of this.warnings)n.file&&e.add(n.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let t=this.errors[0];return t?`Failed: ${t.code??"ERROR"}${t.reason?` \u2014 ${t.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let t=this.appliedPaths;return t&&t.length>0?`${t.length} path${t.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,n=this.overwrittenFiles.length,r=[];if(e>0&&r.push(`Created ${e} ${e===1?"file":"files"}`),n>0&&r.push(`Edited ${n} ${n===1?"file":"files"}`),this.diffs.length>0){let t=0,a=0;for(let o of this.diffs)for(let u of o.split(`
7
+ `))u.startsWith("+")&&!u.startsWith("+++")?t++:u.startsWith("-")&&!u.startsWith("---")&&a++;(t>0||a>0)&&r.push(`+${t}/-${a} lines`)}return r.join(", ")}getFileChange(e){return this.files.find(n=>n.path===e)}getDiffFor(e){let n=h(e);for(let r of this.diffs){let t=r.match(/^---\s+(.+)$/m);if(t&&(h(d(t[1]))===n||t[1]===e))return r}}getErrorsFor(e){return this.errors.filter(n=>n.path===e)}getWarningsFor(e){return this.warnings.filter(n=>n.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let n=e;return n.data&&typeof n.data=="object"?(Object.setPrototypeOf(n,i.prototype),n):new i(n)}return new i}};function h(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(h,"normalisePath");export{y as a,x as b,f as c,c as d};
@@ -0,0 +1 @@
1
+ import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as n}from"typebox/value";var t=e.Function([],e.Unknown()),l=e.Object({tool:e.String({pattern:"\\S"}),fallback:e.Optional(e.Boolean()),matches:e.Optional(t),renderCall:e.Optional(t),renderResult:e.Optional(t),renderShell:e.Optional(e.Union([e.Literal("default"),e.Literal("self")]))});function d(o){return n.Check(l,o)?o.renderCall!==void 0||o.renderResult!==void 0:!1}r(d,"isTextEditorToolRendererRegistration");export{d as a};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as n}from"typebox/value";var t="pi-agent-read",r=11,c=`${t}/core/ready`,s=`${t}/plugin/register`,a=e.Function([],e.Unknown()),p=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(r)}),R=e.Object({protocol:e.Literal(t),apiVersion:e.Literal(r),id:e.String(),setup:a}),l=e.Object({plugin:R,accept:a});function g(o){return n.Check(p,o)}i(g,"isReadCoreReady");function P(o){return n.Check(R,o)}i(P,"isReadPlugin");function y(o){return n.Check(l,o)}i(y,"isReadPluginRegistrationRequest");export{t as a,r as b,c,s as d,g as e,P as f,y as g};
@@ -1,7 +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(`
1
+ import"./chunk-3YK4XMWB.js";import{a as J,b as V,c as U,d as q,f as z}from"./chunk-VFBLX4TG.js";import{d as L,e as h}from"./chunk-M5MJP7Z2.js";import{a as E}from"./chunk-WZI4YC2O.js";import{d as N}from"./chunk-N34ATN52.js";import{a as O}from"./chunk-ZC65Z3CK.js";import{a as _,b as F,c as M}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(L(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 E(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 N(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
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
4
+ `)}c(te,"buildDoctorAgentPrompt");import{createHash as me}from"node:crypto";var he="doctor",x=3;function ne(n,t){let e=_(n,ye(t));e!==void 0&&e.catch(()=>{})}c(ne,"registerDoctorTipProvider");function ye(n){return{protocol:F,apiVersion:M,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(q,i=>{if(!z(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
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};
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(U,{protocol:J,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 @@
1
+ import{a as R}from"./chunk-WZI4YC2O.js";import{b as v,c as j,d as $}from"./chunk-N34ATN52.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a as i}from"./chunk-EI7MMDWY.js";import M from"cross-spawn";import{access as D,readFile as w,writeFile as N}from"node:fs/promises";import _ from"node:os";import a from"node:path";import{fileURLToPath as G}from"node:url";var L=1;function ie(e){return a.win32.basename(y(e[0]))}i(ie,"configuredExecutableName");async function se(e,n,o,t){let r=a.resolve(e),l=a.resolve(r,n),s=t.filter(d=>W(d,l));if(Q(r,l))return r;let c=a.dirname(l);for(;;){if(await H(F(c,o))||[...(await R(c,s)).values()].some(u=>u.score>0))return c;let f=a.dirname(c);if(f===c)return;c=f}}i(se,"resolveExternalToolProjectRoot");function J(e){return a.join(e,".pi","pi-agent-ide")}i(J,"projectIdeConfigDirectory");function F(e,n){return a.join(J(e),`${n}.json`)}i(F,"projectIdeConfigPath");function B(e,n,o={}){let r=(o.environment??process.env).PI_CODING_AGENT_DIR?.trim(),l=r===void 0||r.length===0?a.join(o.homeDirectory??_.homedir(),".pi","agent"):a.resolve(r);return{project:F(e,n),global:a.join(l,"extensions","pi-agent-ide",`${n}.json`),builtIn:G(new URL(`tool-config/${n}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}i(B,"resolveToolConfigPaths");async function ae(e,n,o,t={}){let r=B(e,n,t),l=[{layer:"project",sourcePath:r.project,optional:!0},...t.includeGlobal===!1?[]:[{layer:"global",sourcePath:r.global,optional:!0}],{layer:"built-in",sourcePath:r.builtIn,optional:!1}],s=[],c=new Set;for(let d of l){let f=await U(d,n,o);for(let[u,C]of Object.entries(f))c.has(u)||(c.add(u),s.push({id:u,config:C,layer:d.layer,sourcePath:d.sourcePath}))}return{entries:s,paths:r}}i(ae,"loadLayeredToolConfig");function V(e,n,o){let t=a.extname(n).toLowerCase();if(e.extensions.every(s=>!(S(s)===t||s==="*"))&&!e.fileNames?.some(s=>process.platform==="win32"?s.toLowerCase()===a.basename(n).toLowerCase():s===a.basename(n)))return!1;let r=a.relative(o,n).split(a.sep).join("/"),l=i(s=>s?.some(c=>a.matchesGlob(r,c))??!1,"matches");return(e.include===void 0||l(e.include))&&!l(e.exclude)}i(V,"matchesConfiguredFile");function le(e,n,o,t,r){let l=a.resolve(r,t),s=e.filter(f=>V(f.config,l,r)),c=s.find(f=>f.layer!=="built-in");if(c!==void 0)return c;let d=Math.max(0,...s.map(f=>o.get(f.id)?.score??0));return s.find(f=>n.has(f.id)&&(o.get(f.id)?.score??0)===d)}i(le,"selectConfiguredEntry");async function ce(e,n,o=process.env){h(e,"process");let t=y(e.command[0]).replaceAll("{project}",n),r=A(e,n,o);return $(t,n,r)}i(ce,"hasConfiguredExecutable");async function q(e,n){h(e,"process");let o=e.command.map(d=>K(d,n)),t=y(o[0]),r=o.slice(1),l=e.cwd==="file"?a.dirname(n.filePath):n.projectRoot,s=e.successExitCodes??[0],c=A(e,n.projectRoot,n.env??process.env);return new Promise((d,f)=>{let u=M(t,r,{cwd:l,env:c,signal:n.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),C="",P="",b=y(u.stdout),x=y(u.stderr),E=!1,T=setTimeout(()=>{E=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);b.setEncoding("utf8"),x.setEncoding("utf8"),b.on("data",g=>{C+=g}),x.on("data",g=>{P+=g}),u.on("error",g=>{clearTimeout(T),f(g)}),u.on("close",g=>{clearTimeout(T),d({ok:!E&&g!==null&&s.includes(g),exitCode:g,stdout:C,stderr:P})})})}i(q,"runConfiguredProcess");async function fe(e,n){let o=await w(n.filePath,"utf8"),t=await q(e.run,n);if(!t.ok)return e.output==="in-place"&&await w(n.filePath,"utf8")!==o&&await N(n.filePath,o,"utf8"),{ok:!1,changed:!1};e.output==="stdout"&&t.stdout!==o&&await N(n.filePath,t.stdout,"utf8");let r=await w(n.filePath,"utf8");return{ok:!0,changed:o!==r}}i(fe,"runConfiguredFormatter");function de(e){let n=O(e,"formatters");for(let[o,t]of Object.entries(n.entries)){let r=m(t,`formatter ${o}`);if(I(r,`formatter ${o}`),h(r.run,`formatter ${o}.run`),r.output!=="in-place"&&r.output!=="stdout")throw new Error(`formatter ${o}.output must be in-place or stdout`)}return e}i(de,"parseFormattersConfig");function ue(e){let n=O(e,"linters"),o=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[t,r]of Object.entries(n.entries)){let l=m(r,`linter ${t}`);I(l,`linter ${t}`),h(l.check,`linter ${t}.check`),l.fix!==void 0&&h(l.fix,`linter ${t}.fix`);let s=m(l.diagnostics,`linter ${t}.diagnostics`);if(!o.has(String(s.format)))throw new Error(`linter ${t} has an unsupported diagnostics format`);if(s.columnBase!==void 0&&(s.format!=="regex"||s.columnBase!==0&&s.columnBase!==1))throw new Error(`linter ${t} columnBase must be 0 or 1 for regex diagnostics`);if(s.format==="regex"&&typeof s.pattern!="string")throw new Error(`linter ${t} regex diagnostics require pattern`)}return e}i(ue,"parseLintersConfig");function O(e,n){let o=m(e,"tool config");if(o.version!==L)throw new Error(`tool config version must be ${L}`);return{entries:m(o[n],n)}}i(O,"configRoot");function I(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(I,"assertMatcher");function h(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(t=>!Number.isInteger(t))))throw new Error(`${n}.successExitCodes must contain integers`);if(o.env!==void 0){let t=m(o.env,`${n}.env`);if(Object.values(t).some(r=>typeof r!="string"))throw new Error(`${n}.env values must be strings`)}}i(h,"assertProcessConfig");function p(e,n,o){if(!Array.isArray(e)||!o&&e.length===0||e.some(t=>typeof t!="string"||t.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 S(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}i(S,"normalizeExtension");async function U(e,n,o){let t;try{t=await w(e.sourcePath,"utf8")}catch(r){if(e.optional&&z(r))return{};throw new Error(`Cannot read ${e.layer} ${n} config at ${e.sourcePath}: ${k(r)}`,{cause:r})}try{return o(JSON.parse(t))}catch(r){throw new Error(`Invalid ${e.layer} ${n} config at ${e.sourcePath}: ${k(r)}`,{cause:r})}}i(U,"readToolConfigLayer");function z(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}i(z,"isMissingFile");function k(e){return e instanceof Error?e.message:String(e)}i(k,"errorMessage");function A(e,n,o){return j(n,{...v(o),...v(e.env??{})})}i(A,"createConfiguredProcessEnvironment");function K(e,n){let o=a.relative(n.projectRoot,n.filePath);return e.replaceAll("{project}",n.projectRoot).replaceAll("{fileDir}",a.dirname(n.filePath)).replaceAll("{relativeFile}",o).replaceAll("{file}",n.filePath)}i(K,"expandPlaceholders");function W(e,n){let o=a.extname(n).toLowerCase(),t=a.basename(n),r=i((l,s=[])=>l.some(c=>S(c)===o)||s.some(c=>c===t),"matches");return e.formatter?r(e.formatter.extensions,e.formatter.fileNames):e.linter?r(e.linter.extensions,e.linter.fileNames):e.lsp?r(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}i(W,"recipeMatchesFile");async function H(e){try{return await D(e),!0}catch{return!1}}i(H,"fileExists");function Q(e,n){let o=a.relative(e,n);return o===""||o!==".."&&!o.startsWith(`..${a.sep}`)&&!a.isAbsolute(o)}i(Q,"isPathInside");export{L as a,ie as b,se as c,J as d,F as e,B as f,ae as g,V as h,le as i,ce as j,q as k,fe as l,de as m,ue as n,A as o};
@@ -0,0 +1,2 @@
1
+ import{a as j}from"./chunk-GUTQ3PWL.js";import{m as b}from"./chunk-5VSE5X5R.js";import{a as S}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{createHash as ue}from"node:crypto";import{readFile as q}from"node:fs/promises";import h from"node:path";import{spawn as ee}from"node:child_process";import D from"node:path";import{createInterface as te}from"node:readline";import{existsSync as Y}from"node:fs";import Z from"node:os";import H from"node:path";function F(e=process.env.PI_CODING_AGENT_DIR??H.join(Z.homedir(),".pi","agent"),t=process.platform){let n=H.join(e,"bin",t==="win32"?"rg.exe":"rg");return Y(n)?n:"rg"}a(F,"resolveRipgrepExecutable");async function A(e,t,n){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=D.resolve(t,oe(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,n);try{return await R(["--engine","auto",...s],r,n)}catch(i){if(!ne(i))throw i;return R(["--engine","default",...s],r,n)}}a(A,"searchText");function R(e,t,n){return new Promise((r,o)=>{let s=ee(F(),e,{stdio:["ignore","pipe","pipe"]}),i=te({input:s.stdout}),c=[],l="",u=!1,d,g=a(()=>{s.kill()},"abort"),m=a(()=>{n?.removeEventListener("abort",g),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 p=JSON.parse(f);if(p.type!=="match")return;for(let X of re(p)){if(c.length===t){u=!0,s.kill();return}c.push(X)}}catch(p){d=p,s.kill()}}),s.once("error",f=>{m(),o(f)}),s.once("close",f=>{if(m(),n?.aborted===!0){let p=new Error("Search was aborted.");p.name="AbortError",o(p);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}c.sort(ie),r({matches:c,complete:!u})}),n?.addEventListener("abort",g,{once:!0}),n?.aborted===!0&&g()})}a(R,"runRipgrep");function ne(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}a(ne,"isPcre2MatchLimitError");function re(e){let t=e.data.path.text,n=e.data.lines.text;if(t===void 0||n===void 0||!Number.isSafeInteger(e.data.line_number))return[];let r=n.replace(/(?:\r\n|\n)$/u,""),o=Buffer.from(n),s=[];for(let i of e.data.submatches){if(i.start<0||i.end<=i.start||i.end>o.length)continue;let c=o.subarray(0,i.start).toString("utf8").length,l=o.subarray(0,i.end).toString("utf8").length;s.push({source:D.resolve(t),lineNumber:e.data.line_number,startColumn:c,endColumn:l,matchedText:r.slice(c,l),lineText:r})}return s}a(re,"matchesFromEvent");function O(e){if(e===void 0)return[];let t=[],n=0,r="";for(let o of e){if(o==="{"?n+=1:o==="}"&&(n=Math.max(0,n-1)),n===0&&(o===","||/\s/u.test(o))){r.length>0&&(t.push(r),r="");continue}r+=o}return r.length>0&&t.push(r),t}a(O,"splitGlobList");function oe(e){return e.startsWith("@")?e.slice(1):e}a(oe,"stripFilePrefix");function ie(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}a(ie,"compareMatches");function N(e,t=!1){let n=M(e);if(!C(n))return t?e:B(e);let r=E(new v(e,n).parse(),t);return`^${r.condition}.*?\\K(${r.match})`}a(N,"compileSearchQuery");function _(e){if(C(M(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(B).join("|")})`:void 0}a(_,"compileSearchFallbackQuery");function C(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}a(C,"containsBooleanSyntax");var v=class{static{a(this,"BooleanQueryParser")}#t;#r;#i=0;constructor(t,n){this.#t=t,this.#r=n}parse(){let t=this.#s(),n=this.#e();if(n.type!=="end"){let r=n.type==="right"?"unexpected ')'.":`unexpected ${ae(n)}.`;throw y(n.offset,r)}return t}#s(){let t=this.#n();for(;this.#e().type==="or";){let n=this.#o(),r=this.#c(`after ${n.value}`);t={kind:"or",left:t,right:this.#a(r)}}return t}#n(){return this.#a(this.#c())}#a(t){let n=t;for(;;){let r=this.#e();if(r.type==="and"||r.type==="not"){this.#o();let o=this.#c(`after ${r.value}`);n={kind:r.type,left:n,right:o};continue}if(r.type==="term"||r.type==="left"){n={kind:"and",left:n,right:this.#c()};continue}return n}}#c(t){let n=this.#e();if(n.type==="term")return this.#o(),{kind:"term",value:n.value,quoted:n.quoted};if(n.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(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw y(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw y(n.offset,`expected a term${r}.`)}#e(){return this.#r[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function M(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&se(e,n)){t.push({type:"left",value:r,offset:n}),n+=1;continue}if(r===")"){t.push({type:"right",value:r,offset:n}),n+=1;continue}if(W(e,n)){let i=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+i),offset:n}),n+=i;continue}if(r==="'"||r==='"'){let i=n,c=r,l="";for(n+=1;n<e.length&&e.charAt(n)!==c;)e.charAt(n)==="\\"&&(e.charAt(n+1)===c||e.charAt(n+1)==="\\")&&(n+=1),l+=e.charAt(n++);if(n>=e.length)throw y(i,`unterminated ${c==="'"?"single":"double"}-quoted term.`);if(n+=1,l.length===0)throw y(i,"quoted terms must not be empty.");t.push({type:"term",value:l,offset:i,quoted:!0});continue}let o=n;for(;n<e.length;){let i=e.charAt(n);if(/\s/u.test(i)||i===")"||W(e,n))break;i==="\\"&&n+1<e.length?n+=2:i==="["||i==="("?n=$(e,n)??n+1:n+=1}let s=e.slice(o,n);t.push({type:ce(s),value:s,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}a(M,"tokenize");function W(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}a(W,"isBooleanPipe");function $(e,t){let n=e.charAt(t)==="["?"]":")",r=t+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===n)return r+1;if(n===")"&&(o==="("||o==="[")){let s=$(e,r);if(s===void 0)return;r=s}else r+=1}}}a($,"regexBlockEnd");function se(e,t){let n=$(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:C(M(r))}a(se,"isBooleanGroup");function ce(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}a(ce,"operatorType");function ae(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}a(ae,"quoteToken");function y(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(y,"syntaxError");function E(e,t){if(e.kind==="term"){let o=t&&!e.quoted?e.value:B(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let n=E(e.left,t),r=E(e.right,t);return e.kind==="or"?{condition:`(?:${n.condition}|${r.condition})`,match:`(?:${n.match}|${r.match})`}:e.kind==="not"?{condition:`${n.condition}(?!${r.condition})`,match:n.match}:{condition:`${n.condition}${r.condition}`,match:`(?:${n.match}|${r.match})`}}a(E,"compileExpression");function B(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}a(B,"escapeRegex");function Be(e){let t=N(e.query),n=N(e.query,!0),r=_(e.query),o=[];return n!==t&&o.push({query:n,mode:"regex"}),r!==void 0&&r!==t&&r!==n&&o.push({query:r,mode:"words"}),{...e,query:t,regex:!0,fallbacks:o}}a(Be,"createSearchRecipe");async function P(e,t,n){let r=e.query,o=await A(e,t,n),s=[];for(let i of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await A({...e,query:i.query,regex:!0},t,n),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(c){if(i.mode!=="regex"||!le(c)||n?.aborted)throw c;s.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:s}}a(P,"runSearchRecipe");function le(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}a(le,"isRegexSyntaxError");var de=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,z=4;function _e(e,t,n,r){return U(e,t,n,r).slice(0,z)}a(_e,"createSearchSessionId");function U(e,t,n,r){let o=n===void 0?pe(t.map(c=>c.source)):h.resolve(n),s=t.map(c=>({match:c,source:h.relative(o,h.resolve(c.source))})).sort((c,l)=>c.source.localeCompare(l.source)||L(c.match,l.match)).map(({match:c,source:l})=>[l,c.lineNumber,c.startColumn,c.endLineNumber??c.lineNumber,c.endColumn,c.matchedText,c.lineText]),i=K(r??{query:e,regex:!0},o);return ue("sha256").update(JSON.stringify([e,o,i,s])).digest("hex").toUpperCase()}a(U,"createSearchSessionIdentity");function he(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let n=z;n<=e.length;n+=1){let r=e.slice(0,n);if(!t.has(r))return r}throw new Error("Could not allocate a unique search session id.")}a(he,"allocateSearchSessionId");function K(e,t){return{query:e.query,path:h.resolve(t,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??[]}}a(K,"normalizeRecipe");var Q=class{constructor(t=U){this.createIdentity=t}static{a(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(t,n,r,o,s,i={query:t,regex:!0},c){let l=n.map(p=>({...p,source:h.resolve(p.source)})).sort(L),u=await J(l,s),d=this.createIdentity(t,l,o,i),m=this.#r.get(d)??he(d,new Set(this.#t.keys())),f={id:m,query:t,matches:l,complete:r,contentBySource:u,recipe:i,...c!==void 0&&{refresh:c},cwd:h.resolve(o)};return this.#r.set(d,m),this.#t.set(m,f),f}async observeAfterEdit(t,n){let r=new Set(t.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 c={sessionId:s,query:i.recipe.originalQuery??i.query,scope:K(i.recipe,i.cwd)};try{let l=i.refresh===void 0?await P(i.recipe,i.cwd,n):await i.refresh(n);o.push({...c,matches:l.matches.length,complete:l.complete,notices:l.notices})}catch(l){o.push({...c,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(t){return t},renderCompact(t){let n=T(t);return n===void 0?"selected result":n.selector==="all"?n.mode==="match"?"all matches":"all lines":n.mode==="match"?`match ${String(n.selector)}`:`line ${String(n.selector)}`},tryResolve:a((t,n)=>this.#i(t,n.source,n.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:a((t,n)=>this.#s(t,n.cwd),"tryResolve")}}async#i(t,n,r){let o=T(t);if(o===void 0)return{kind:"not-handled"};let s=this.#t.get(o.id);if(s===void 0)return w();if(o.selector==="all"&&!s.complete)return x();let i=h.resolve(n),c=s;if(o.selector==="all"){if(s.refreshedComplete?.complete===!0)c=s.refreshedComplete;else if(s.refreshedComplete!==void 0&&(c=await this.#n(s,r),!c.complete))return x()}let l=k(c,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 w(S(u[0]).lineNumber);if(o.selector==="all"&&d!==c.contentBySource.get(i)){if(c=await this.#n(s,r),!c.complete)return x();l=k(c,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 w(S(u[0]).lineNumber);let g=b(i,d);return{kind:"resolved",anchor:new j(t,i,u.map(m=>G(g,m,o.mode)))}}async#s(t,n){let r=T(t);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return w();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 w(i[0]?.lineNumber)}let c=new Map;for(let u of i){let d=c.get(u.source)??[];d.push(G(b(u.source,s.contentBySource.get(u.source)??u.lineText),u,r.mode)),c.set(u.source,d)}let l=[...c].map(([u,d])=>({source:u,ranges:d,expectedContent:s.contentBySource.get(u)}));return l.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:l}}async#n(t,n){let r=t.refresh===void 0?await P(t.recipe,t.cwd,n):await t.refresh(n),o=r.matches.map(i=>({...i,source:h.resolve(i.source)})).sort(L),s={matches:o,complete:r.complete,contentBySource:await J(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:s}),s}};function T(e){let t=de.exec(e);if(t!==null)return{id:S(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}a(T,"parseSearchAnchor");function k(e,t,n){let r=t==="all"?e.matches:[e.matches[t-1]].filter(fe);if(n==="match"||t!=="all")return r;let o=new Set;return r.flatMap(s=>{let i=b(s.source,e.contentBySource.get(s.source)??s.lineText),c=V(s);return i.lines.slice(s.lineNumber-1,c).flatMap(l=>{let u=`${s.source}\0${String(l.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...s,lineNumber:l.lineNumber,endLineNumber:l.lineNumber,startColumn:0,endColumn:l.content.length,lineText:l.content,matchedText:l.content}])})})}a(k,"selectMatches");function fe(e){return e!==void 0}a(fe,"isMatch");function V(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(V,"lastContainingLine");function G(e,t,n){if(n==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let r=V(t),o=S(e.lines[r-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:r+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}a(G,"selectionRange");function me(e,t){let n=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,n).map(r=>{let o=r.lineNumber===t.lineNumber?t.startColumn:0,s=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,s)+(r.lineNumber===n?"":r.lineEnding)}).join("")}a(me,"matchedSourceText");async function J(e,t){let n=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await q(r,{encoding:"utf8",...t!==void 0&&{signal:t}}),s=b(r,o);for(let i of e.filter(c=>c.source===r))if(s.lines[i.lineNumber-1]?.content!==i.lineText||me(s,i)!==i.matchedText)throw new Error(`Search result in ${r} changed before its anchors were registered.`);n.set(r,o)}return n}a(J,"snapshotContents");async function I(e,t){try{return await q(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(I,"readCurrent");function w(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}a(w,"staleAnchor");function x(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}a(x,"missingCompleteAnchor");function pe(e){if(e.length===0)return".";let t=h.dirname(h.resolve(S(e[0])));for(let n of e.slice(1)){let r=h.resolve(n);for(;!ge(t,r);){let o=h.dirname(t);if(o===t)return t;t=o}}return t}a(pe,"commonSourceDirectory");function ge(e,t){let n=h.relative(e,t);return n!==".."&&!n.startsWith(`..${h.sep}`)&&!h.isAbsolute(n)}a(ge,"isWithin");function L(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}a(L,"compareMatches");export{F as a,Be as b,P as c,_e as d,U as e,he as f,Q as g};
@@ -0,0 +1,3 @@
1
+ import{j as $}from"./chunk-5VSE5X5R.js";import{a as x}from"./chunk-KINKBPPX.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import w from"node:path";import{fileURLToPath as C}from"node:url";function D(e,n){let t=`${n}:`;if(!e.startsWith(t))return;let o=e.slice(t.length),r=o.indexOf("#"),i=r===-1?o:o.slice(0,r);if(i.length===0)throw new TypeError(`${n}: requires a file path.`);let c=b(i,`${n}: path`),s=r===-1?void 0:o.slice(r+1);if(n==="ast"){if(s!==void 0)throw new TypeError("ast: accepts only a file path and does not accept a symbol selector.");return{scheme:n,path:c}}if(n==="symbol"&&s===void 0)throw new TypeError("symbol: requires #<symbol-selector> after the file path.");if(s===void 0)return{scheme:n,path:c};if(s.length===0)throw new TypeError(`${n}: symbol selector must not be empty.`);let u=s.split("/").map(p=>{if(p.length===0)throw new TypeError(`${n}: symbol selector contains an empty segment.`);return b(p,`${n}: symbol selector`)});return{scheme:n,path:c,selector:u}}a(D,"parseCodeViewReference");function T(e,n){return e.startsWith("file://")?C(new URL(e)):w.isAbsolute(e)?w.normalize(e):w.resolve(n,e)}a(T,"resolveCodeViewPath");function k(e,n,t){let o=n.replaceAll("%","%25").replaceAll("#","%23"),r=t===void 0?"":`#${t.map(i=>encodeURIComponent(i)).join("/")}`;return`${e}:${o}${r}`}a(k,"formatCodeViewReference");function v(e){return e.map(n=>encodeURIComponent(n)).join("/")}a(v,"formatSymbolSelector");function b(e,n){try{return decodeURIComponent(e)}catch(t){throw new TypeError(`${n} contains invalid percent encoding.`,{cause:t})}}a(b,"decodePart");import N from"node:path";function j(e,n,t){let o=`${n}:`;if(!e.startsWith(o))return;let r=e.slice(o.length);if(r.length===0)throw new Error(`${n}: requires a file path.`);return N.resolve(t,r)}a(j,"resolveDiagnosticViewPath");function M(e,n){return`${e}:${n}`}a(M,"formatDiagnosticViewSource");function O(e,n,t,o={}){let r={complete:t.length>0&&t.every(d=>d.status==="ready"),count:t.reduce((d,l)=>d+l.diagnostics.length,0),sources:t.map(d=>d.source)},i=n.split(/\r\n|\r|\n/u),c=R(t,i.length);if(c.size===0)return{type:"text",diagnosticCheck:r,text:h(t)||"No completed diagnostic checks are available.",sourceLines:{}};let s=o.contextLines??5;if(!Number.isInteger(s)||s<0)throw new TypeError("Diagnostic contextLines must be a non-negative integer.");let u=new Set;for(let d of c.keys()){let l=Math.max(1,d-s),f=Math.min(i.length,d+s);for(let g=l;g<=f;g+=1)u.add(g)}let p=h(t),m=p?[p]:[],S={};for(let d of[...u].sort((l,f)=>l-f)){let l=i[d-1]??"",f=(c.get(d)??[]).map(({diagnostic:g,source:V})=>`<!-- ${V}: ${x(g,V)} -->`).join(" ");m.push(f.length===0?l:`${l} ${f}`),S[String(m.length)]={source:e,lineNumber:d,content:l}}return{type:"text",diagnosticCheck:r,text:m.join(`
2
+ `),sourceLines:S}}a(O,"createDiagnosticViewContent");function B(e,n){let t=R(n,e.lines.length,/[\r\n]$/u.test(e.content)),o=e.lines.map(r=>{let i=t.get(r.lineNumber);if(i===void 0)return r;let c=i.map(({diagnostic:s,source:u})=>`<!-- ${u}: ${x(s,u)}${s.line===r.lineNumber?"":` @${s.line}:${s.column}`} -->`).join(" ");return{...r,presentation:{...r.presentation,suffix:`${r.presentation?.suffix??""} ${c}`}}});return{...e,lines:o}}a(B,"addDiagnosticAnnotations");function h(e){return e.length>0&&e.every(n=>n.status==="ready"&&n.diagnostics.length===0)?`Checks completed (${e.map(n=>n.source).join(", ")}); no diagnostics found at this point.`:e.filter(n=>n.status&&n.status!=="ready").map(n=>`${n.source}: ${n.status}${n.reason?` (${n.reason})`:""}.`).join(" ")}a(h,"diagnosticStatus");function R(e,n,t=!1){let o=new Map;for(let{diagnostics:r,source:i}of e)for(let c of r){let s=t&&c.line===n+1?n:c.line;if(!Number.isInteger(c.line)||s<1||s>n)continue;let u=o.get(s)??[];u.push({diagnostic:c,source:i}),o.set(s,u)}return o}a(R,"diagnosticsByValidLine");function E(e){return{text:`${e.content}${e.suffix??""}`,...e.sourceLine!==void 0&&{sourceLine:e.sourceLine}}}a(E,"renderSourceViewLine");function F(e,n){if(e.length===0)return L([{text:"<empty-result>"}]);if(e.length===1&&y(e[0]).status==="failed"&&y(e[0]).path===""){let o=y(e[0]),r=n.recovery===void 0?[]:["","Recovery:",...n.recovery],i=n.includeNoChange===!0?["","No file was changed."]:[];return L([o.code??n.failureLabel,"",`Reason: ${o.error??n.unknownFailure??"unknown failure"}`,...i,...r].map(c=>({text:c})))}let t=[];for(let[o,r]of e.entries())o>0&&t.push({text:""},{text:""}),t.push(...A(r,n));return L(t)}a(F,"formatSourceViewResults");function P(){return e=>{let n=e.state;if(n?.contentKind!=="text")return{kind:"continue",context:e};let t=I(n.content[0]);if(t===void 0)return{kind:"continue",context:e};let o=n.text.lines.map(r=>{let i=t[String(r.lineNumber)];return i===void 0?r:$(r,i)});return{kind:"continue",context:{...e,state:{...n,text:{...n.text,lines:o}}}}}}a(P,"createSourceMappedTextReadHandler");function A(e,n){if(e.status==="failed")return[...e.heading===void 0?[`## file: ${e.path||"<unknown>"}`]:[`## ${e.heading}`,...e.details??[]],`${n.failureLabel} | ${e.error??n.unknownFailure??"unknown failure"}`].map(c=>({text:c}));let t=e.heading===void 0?[`## file: ${e.path}`]:[`## ${e.heading}`,...e.details??[]],o=e.continuation??"",r=e.warning===void 0?[]:[{text:""},{text:e.warning}];return[...t.map(i=>({text:i})),{text:`Lines: ${e.startLine}-${e.endLine} of ${e.totalLines}${o}`},{text:""},...e.renderedLines,...r]}a(A,"formatSourceViewBlock");function L(e){let n={};for(let[t,o]of e.entries())o.sourceLine!==void 0&&(n[String(t+1)]=o.sourceLine);return{type:"text",text:e.map(t=>t.text).join(`
3
+ `),sourceLines:n}}a(L,"sourceMappedContent");function I(e){if(typeof e!="object"||e===null||!("sourceLines"in e))return;let n=e.sourceLines;if(!(typeof n!="object"||n===null)){for(let t of Object.values(n))if(!q(t))return;return n}}a(I,"sourceLineMap");function q(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.source=="string"&&n.source.length>0&&Number.isInteger(n.lineNumber)&&(n.lineNumber??0)>0&&typeof n.content=="string"}a(q,"isTextSourceLine");export{D as a,T as b,k as c,v as d,j as e,M as f,O as g,B as h,h as i,E as j,F as k,P as l};
@@ -1 +1 @@
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};
1
+ import{a as m}from"./chunk-5VSE5X5R.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};
File without changes