pi-agent-ide 0.6.2 → 0.6.4

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 (366) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +8 -1
  3. package/dist/chunk-2P2OGO3G.js +2 -0
  4. package/dist/{chunk-5QQABP47.js → chunk-3BBJZSMS.js} +1 -1
  5. package/dist/chunk-5J43L2RL.js +11 -0
  6. package/dist/{chunk-ITSNK5YG.js → chunk-7AVXUV4A.js} +2 -2
  7. package/dist/chunk-BAYETTZZ.js +16 -0
  8. package/dist/{chunk-VCTK4JSN.js → chunk-BSICWXMH.js} +1 -1
  9. package/dist/chunk-BVK5A7ED.js +28 -0
  10. package/dist/{chunk-ZM4L5AGN.js → chunk-EDURPQAV.js} +3 -2
  11. package/dist/{chunk-L7JMDDSD.js → chunk-FBOW7XOV.js} +1 -1
  12. package/dist/{chunk-25CZ5ZIU.js → chunk-FUG2TEKI.js} +1 -1
  13. package/dist/chunk-FZBCKIJJ.js +1 -0
  14. package/dist/chunk-HPUAIWIH.js +25 -0
  15. package/dist/chunk-I5JLCFUX.js +1 -0
  16. package/dist/chunk-KUPHNMUK.js +2 -0
  17. package/dist/{chunk-NTYXZ3EL.js → chunk-KVHDMIZS.js} +1 -1
  18. package/dist/{chunk-QDST6VIU.js → chunk-KZC7TI5M.js} +1 -1
  19. package/dist/chunk-MIZAFRDR.js +1 -0
  20. package/dist/chunk-PJPA5EEE.js +2 -0
  21. package/dist/{chunk-GUTQ3PWL.js → chunk-PLKYHUNT.js} +1 -1
  22. package/dist/chunk-QEJGED4V.js +28 -0
  23. package/dist/chunk-SILJ3OL4.js +9 -0
  24. package/dist/{chunk-VXD6FZP5.js → chunk-TQZBVOTT.js} +3 -3
  25. package/dist/chunk-VBICI5YA.js +1 -0
  26. package/dist/chunk-VWW3RLUX.js +12 -0
  27. package/dist/{chunk-O6LE42GK.js → chunk-WJTHY6AG.js} +1 -1
  28. package/dist/chunk-YGGKGZO2.js +1 -0
  29. package/dist/chunk-ZODCBFBL.js +2 -0
  30. package/dist/chunk-ZPT5D4VP.js +2 -0
  31. package/dist/entry-0.js +1 -1
  32. package/dist/entry-11.js +1 -1
  33. package/dist/entry-13.js +1 -1
  34. package/dist/entry-14.js +1 -1
  35. package/dist/entry-15.js +1 -1
  36. package/dist/entry-16.js +1 -1
  37. package/dist/entry-17.js +1 -1
  38. package/dist/entry-25.js +2 -2
  39. package/dist/entry-26.js +1 -1
  40. package/dist/entry-27.js +1 -1
  41. package/dist/entry-28.js +1 -1
  42. package/dist/entry-29.js +1 -1
  43. package/dist/entry-30.js +1 -1
  44. package/dist/entry-31.js +11 -11
  45. package/dist/entry-33.js +1 -1
  46. package/dist/entry-37.js +2 -2
  47. package/dist/entry-42.js +1 -1
  48. package/dist/entry-44.js +1 -1
  49. package/dist/entry-45.js +13 -12
  50. package/dist/entry-46.js +1 -1
  51. package/dist/entry-49.js +1 -1
  52. package/dist/entry-50.js +4 -4
  53. package/dist/entry-51.js +9 -9
  54. package/dist/entry-52.js +1 -1
  55. package/dist/entry-53.js +1 -1
  56. package/dist/entry-55.js +1 -1
  57. package/dist/entry-56.js +1 -1
  58. package/dist/entry-57.js +1 -1
  59. package/dist/entry-58.js +1 -1
  60. package/dist/entry-59.js +1 -1
  61. package/dist/entry-60.js +1 -1
  62. package/dist/entry-61.js +1 -1
  63. package/dist/entry-63.js +1 -1
  64. package/dist/entry-66.js +1 -1
  65. package/dist/entry-68.js +1 -1
  66. package/dist/entry-69.js +1 -1
  67. package/dist/entry-70.js +1 -1
  68. package/dist/entry-71.js +1 -0
  69. package/dist/entry-72.js +0 -1
  70. package/dist/entry-73.js +1 -0
  71. package/dist/entry-74.js +0 -1
  72. package/dist/entry-75.js +1 -1
  73. package/dist/entry-76.js +1 -1
  74. package/dist/entry-77.js +1 -315
  75. package/dist/entry-78.js +324 -25
  76. package/dist/entry-79.js +18 -2
  77. package/dist/entry-80.js +2 -1
  78. package/dist/entry-81.js +1 -1
  79. package/dist/entry-82.js +1 -3
  80. package/dist/entry-83.js +5 -3
  81. package/dist/entry-84.js +3 -1
  82. package/dist/entry-85.js +1 -1
  83. package/dist/entry-86.js +1 -1
  84. package/dist/entry-87.js +1 -0
  85. package/dist/pi-agent-ide.js +15 -3
  86. package/docs/agent-guides/apply.md +1 -1
  87. package/docs/agent-guides/editing.md +16 -0
  88. package/docs/agent-guides/json-reading.md +19 -3
  89. package/docs/agent-guides/read-resources.md +6 -0
  90. package/docs/agent-guides/search-code.md +5 -1
  91. package/docs/agent-guides/terminal.md +1 -1
  92. package/docs/code-review.md +99 -0
  93. package/docs/configuration.md +34 -0
  94. package/docs/development.md +15 -19
  95. package/docs/nightly.md +7 -0
  96. package/docs/releases.md +42 -0
  97. package/docs/research/native-codemode-batch-decision.md +27 -0
  98. package/docs/research/native-codemode-batching.md +65 -0
  99. package/docs/structured-results.md +59 -0
  100. package/docs/tools.md +18 -2
  101. package/node_modules/pi-agent-doctor/package.json +1 -1
  102. package/node_modules/pi-agent-documentation/package.json +1 -1
  103. package/node_modules/pi-agent-documentation/src/index.ts +1 -1
  104. package/node_modules/pi-agent-filesystem/index.ts +6 -1
  105. package/node_modules/pi-agent-filesystem/package.json +7 -6
  106. package/node_modules/pi-agent-filesystem/src/path-recovery.ts +109 -0
  107. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  108. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  109. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  110. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  111. package/node_modules/pi-agent-ide-ast/package.json +10 -10
  112. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +6 -1
  113. package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +6 -2
  114. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +17 -0
  115. package/node_modules/pi-agent-ide-changes/index.ts +3 -9
  116. package/node_modules/pi-agent-ide-changes/package.json +8 -7
  117. package/node_modules/pi-agent-ide-changes/src/current-change-presenter.ts +5 -0
  118. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +125 -47
  119. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  120. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  121. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  122. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  123. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +19 -0
  124. package/node_modules/pi-agent-image/package.json +2 -2
  125. package/node_modules/pi-agent-invariant/package.json +1 -1
  126. package/node_modules/pi-agent-pdf/package.json +2 -2
  127. package/node_modules/pi-agent-read/package.json +7 -7
  128. package/node_modules/pi-agent-read/src/api/tools/read.ts +31 -2
  129. package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +9 -10
  130. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +28 -15
  131. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +216 -0
  132. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +119 -72
  133. package/node_modules/pi-agent-resource/package.json +1 -1
  134. package/node_modules/pi-agent-resource/src/index.ts +12 -0
  135. package/node_modules/pi-agent-resource/src/resource-access.ts +55 -0
  136. package/node_modules/pi-agent-resource/src/resource-scheduler.ts +204 -0
  137. package/node_modules/pi-agent-resource/src/tool-result.ts +125 -0
  138. package/node_modules/pi-agent-search/package.json +5 -4
  139. package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -5
  140. package/node_modules/pi-agent-search/src/api/search.ts +11 -0
  141. package/node_modules/pi-agent-search/src/api/structured-result.ts +93 -0
  142. package/node_modules/pi-agent-search/src/core/extension.ts +40 -14
  143. package/node_modules/pi-agent-search/src/core/search-core.ts +136 -77
  144. package/node_modules/pi-agent-search-text/index.ts +3 -0
  145. package/node_modules/pi-agent-search-text/package.json +6 -6
  146. package/node_modules/pi-agent-search-text/src/resolvers.ts +17 -0
  147. package/node_modules/pi-agent-search-text/src/search-backend.ts +104 -8
  148. package/node_modules/pi-agent-search-text/src/search-query.ts +42 -34
  149. package/node_modules/pi-agent-search-text/src/search-recipe.ts +18 -4
  150. package/node_modules/pi-agent-search-text/src/search-renderer.ts +37 -3
  151. package/node_modules/pi-agent-search-text/src/search-session.ts +21 -13
  152. package/node_modules/pi-agent-text/package.json +2 -2
  153. package/node_modules/pi-agent-text/src/text-document.ts +15 -10
  154. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  155. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  156. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +4 -3
  157. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  158. package/node_modules/pi-agent-text-editor/index.ts +4 -2
  159. package/node_modules/pi-agent-text-editor/package.json +21 -17
  160. package/node_modules/pi-agent-text-editor/runtime/entry-77.js +0 -1
  161. package/node_modules/pi-agent-text-editor/src/api/mutation-preview.ts +2 -0
  162. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +6 -0
  163. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +12 -0
  164. package/node_modules/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +4 -0
  165. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +95 -34
  166. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +1 -1
  167. package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +4 -0
  168. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +20 -11
  169. package/node_modules/pi-agent-text-editor/src/core/apply/structured-result.ts +251 -0
  170. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +32 -12
  171. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +154 -132
  172. package/node_modules/pi-agent-text-editor/src/core/builtin-edit.ts +16 -0
  173. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +74 -18
  174. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +8 -0
  175. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +6 -0
  176. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  177. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +640 -0
  178. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +20 -6
  179. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +314 -0
  180. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +52 -11
  181. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +143 -138
  182. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +2 -0
  183. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +242 -116
  184. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +109 -47
  185. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +25 -5
  186. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +8 -4
  187. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +7 -4
  188. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +24 -3
  189. package/node_modules/pi-agent-text-editor-renderer/index.ts +8 -1
  190. package/node_modules/pi-agent-text-editor-renderer/package.json +7 -6
  191. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +262 -129
  192. package/node_modules/pi-agent-text-editor-renderer/src/diff-renderer.ts +36 -2
  193. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +28 -2
  194. package/node_modules/pi-agent-text-editor-renderer/src/mutation-projection.ts +40 -10
  195. package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +16 -1
  196. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  197. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +2 -0
  198. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  199. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  200. package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +1 -0
  201. package/node_modules/pi-agent-web/index.ts +20 -0
  202. package/node_modules/pi-agent-web/package.json +8 -7
  203. package/node_modules/pi-agent-web/src/search.ts +112 -0
  204. package/node_modules/pi-agent-web-html/package.json +3 -3
  205. package/node_modules/pi-agent-web-image/package.json +4 -4
  206. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  207. package/node_modules/pi-agent-web-text/package.json +4 -4
  208. package/node_modules/pi-agent-web-text/runtime/entry-87.js +2 -0
  209. package/package.json +42 -36
  210. package/skills/capture-code-review-rule/SKILL.md +60 -0
  211. package/src/code-review/config.ts +68 -0
  212. package/src/code-review/extension.ts +105 -0
  213. package/src/code-review/fragments.ts +26 -0
  214. package/src/code-review/reviewer.ts +198 -0
  215. package/src/composite/host-version.ts +13 -0
  216. package/src/composite/nested-tool-rendering.ts +298 -0
  217. package/src/composite/tool-availability.ts +90 -0
  218. package/src/core/extension.ts +2 -0
  219. package/src/documentation/extension.ts +81 -145
  220. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +6 -1
  221. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -6
  222. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  223. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  224. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  225. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  226. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/src/path-recovery.ts +109 -0
  227. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +20 -0
  228. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -7
  229. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  230. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  231. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  232. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  233. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +2 -0
  234. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +2 -0
  235. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +112 -0
  236. package/src/extensions/pi-agent-read/package.json +7 -7
  237. package/src/extensions/pi-agent-read/src/api/tools/read.ts +31 -2
  238. package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +9 -10
  239. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +28 -15
  240. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +216 -0
  241. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +119 -72
  242. package/src/extensions/pi-agent-search/package.json +5 -4
  243. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +3 -0
  244. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
  245. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +17 -0
  246. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +104 -8
  247. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-query.ts +42 -34
  248. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +18 -4
  249. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +37 -3
  250. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +21 -13
  251. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -5
  252. package/src/extensions/pi-agent-search/src/api/search.ts +11 -0
  253. package/src/extensions/pi-agent-search/src/api/structured-result.ts +93 -0
  254. package/src/extensions/pi-agent-search/src/core/extension.ts +40 -14
  255. package/src/extensions/pi-agent-search/src/core/search-core.ts +136 -77
  256. package/src/extensions/pi-agent-text-editor/index.ts +4 -2
  257. package/src/extensions/pi-agent-text-editor/package.json +21 -17
  258. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  259. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  260. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +4 -3
  261. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  262. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +8 -1
  263. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +7 -6
  264. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +262 -129
  265. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-renderer.ts +36 -2
  266. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +28 -2
  267. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-projection.ts +40 -10
  268. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +16 -1
  269. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  270. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +2 -0
  271. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +0 -1
  272. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +2 -0
  273. package/src/extensions/pi-agent-text-editor/src/api/mutation-preview.ts +2 -0
  274. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +6 -0
  275. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +12 -0
  276. package/src/extensions/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +4 -0
  277. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +95 -34
  278. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +1 -1
  279. package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +4 -0
  280. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +20 -11
  281. package/src/extensions/pi-agent-text-editor/src/core/apply/structured-result.ts +251 -0
  282. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +32 -12
  283. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +154 -132
  284. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit.ts +16 -0
  285. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +74 -18
  286. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +8 -0
  287. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +6 -0
  288. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  289. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +640 -0
  290. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +20 -6
  291. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +314 -0
  292. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +52 -11
  293. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +143 -138
  294. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +2 -0
  295. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +242 -116
  296. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +109 -47
  297. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +25 -5
  298. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +8 -4
  299. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +7 -4
  300. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +24 -3
  301. package/src/pi-agent-ide.ts +61 -2
  302. package/src/plugins/pi-agent-ide-ast/package.json +10 -10
  303. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +6 -1
  304. package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +6 -2
  305. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +17 -0
  306. package/src/plugins/pi-agent-ide-changes/index.ts +3 -9
  307. package/src/plugins/pi-agent-ide-changes/package.json +8 -7
  308. package/src/plugins/pi-agent-ide-changes/src/current-change-presenter.ts +5 -0
  309. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +125 -47
  310. package/src/plugins/pi-agent-ide-debugger/index.ts +63 -17
  311. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +18 -2
  312. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +24 -4
  313. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +68 -2
  314. package/src/plugins/pi-agent-ide-debugger/src/java-runtime.ts +357 -0
  315. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -3
  316. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +13 -13
  317. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  318. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  319. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  320. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  321. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +19 -0
  322. package/src/plugins/pi-agent-ide-terminal/index.ts +12 -2
  323. package/src/plugins/pi-agent-ide-terminal/src/output-limits.ts +1 -1
  324. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +65 -30
  325. package/src/plugins/pi-agent-ide-terminal/src/search.ts +13 -8
  326. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +1 -0
  327. package/src/plugins/pi-agent-ide-terminal/src/shell-result.ts +100 -0
  328. package/src/plugins/pi-agent-ide-terminal/src/steering.ts +62 -0
  329. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +97 -45
  330. package/src/plugins/pi-agent-ide-terminal/src/types.ts +3 -1
  331. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +15 -6
  332. package/src/plugins/pi-agent-ide-vision/index.ts +16 -1
  333. package/dist/chunk-3E2NTWCN.js +0 -2
  334. package/dist/chunk-4LUW26BX.js +0 -10
  335. package/dist/chunk-5VSE5X5R.js +0 -2
  336. package/dist/chunk-CEX3VOJ7.js +0 -2
  337. package/dist/chunk-FA6BKC5Y.js +0 -1
  338. package/dist/chunk-FEDVTZJG.js +0 -1
  339. package/dist/chunk-HMLH43ZS.js +0 -4
  340. package/dist/chunk-KII2JQC5.js +0 -1
  341. package/dist/chunk-LVWMWWWF.js +0 -28
  342. package/dist/chunk-P7XO5CIP.js +0 -2
  343. package/dist/chunk-PZFOOHY2.js +0 -15
  344. package/dist/chunk-S3ZPXWX7.js +0 -2
  345. package/dist/chunk-T7CZIACQ.js +0 -27
  346. package/dist/chunk-YT42LKFV.js +0 -16
  347. package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +0 -52
  348. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +0 -1
  349. package/node_modules/pi-agent-web/runtime/entry-82.js +0 -2
  350. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +0 -2
  351. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +0 -2
  352. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +0 -2
  353. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +0 -52
  354. /package/dist/{chunk-4U2GUKNJ.js → chunk-F7NVAC4Q.js} +0 -0
  355. /package/dist/{chunk-ROXXK6TW.js → chunk-PXWDDBBC.js} +0 -0
  356. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-78.js +0 -0
  357. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-79.js +0 -0
  358. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-81.js +0 -0
  359. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-83.js +0 -0
  360. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-84.js +0 -0
  361. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-85.js +0 -0
  362. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-86.js +0 -0
  363. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-84.js +0 -0
  364. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-85.js +0 -0
  365. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-86.js +0 -0
  366. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-79.js +0 -0
@@ -141,6 +141,17 @@ export default async function registerVision(
141
141
  priority: -100,
142
142
  resolver: {
143
143
  id: "processes",
144
+ readResources: (request) => (/^process:/iu.test(request.query) ? undefined : []),
145
+ toScriptData(payload) {
146
+ const processes = payload as Awaited<ReturnType<typeof listProcesses>>;
147
+ return {
148
+ kind: "custom",
149
+ resolverId: "processes",
150
+ value: {
151
+ processes: processes.map((item) => ({ pid: item.pid, command: item.command })),
152
+ },
153
+ };
154
+ },
144
155
  async tryResolve(request) {
145
156
  const match = /^process:(.*)$/isu.exec(request.query);
146
157
  if (match === null) return { kind: "not-handled" as const };
@@ -203,7 +214,11 @@ function requestsScreenshot(request: ReadRequest): boolean {
203
214
  function returned(source: string, content: ReadToolResult["content"]) {
204
215
  return {
205
216
  kind: "return" as const,
206
- result: { content, details: { source, resolvedBy: "vision" } },
217
+ result: {
218
+ content,
219
+ script: { kind: "native" as const, source, blocks: content },
220
+ details: { source, resolvedBy: "vision" },
221
+ },
207
222
  };
208
223
  }
209
224
  function failed(source: string, message: string) {
@@ -1,2 +0,0 @@
1
- import{e as A,f as E}from"./chunk-T7I2VX3J.js";import{d as q}from"./chunk-FEDVTZJG.js";import"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as T}from"./chunk-VCTK4JSN.js";import"./chunk-YHUTTZC6.js";import{a as O}from"./chunk-6CZO43OH.js";import{a as b,b as N}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as h,g as w,h as P,i as k,l as y}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-QDLTO5PH.js";import{a as I,b as v}from"./chunk-QIK2E64R.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import W from"node:path";var M="diagnostics",_=T({kind:"code-view",label:"Diagnostics"});async function S(r){E(r,[await A({id:"diagnostics",description:"Diagnostic resources, readiness, and verification",triggers:[{tool:"read",resourcePrefixes:["diagnostics:"]}]})]);let n,t=l((c,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(c,{cwd:f,...e})},"collect"),s={protocol:I,apiVersion:4,id:"diagnostics",setup(c){n=c.readDiagnostics}},o=new WeakMap,i=new WeakMap,a=new WeakMap,d=new WeakMap,V={protocol:b,apiVersion:N,id:"diagnostics",setup(c){c.addResolver({resolver:H(t,i),renderResult:_});let f=y();c.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),c.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=i.get(g);return u&&o.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}}}),c.addHandler({stage:"post-read",handler(e){let g=o.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),D=u&&d.get(u),p=e.result,R=p?.content[0];return!D||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${D}
2
- ${R.text}`},...p.content.slice(1)]}}}}}),c.describe('diagnostics:<path> \u2014 lint and language-server diagnostics. views: ["diagnostics"] \u2014 diagnostics alongside source text. Results identify their reporting tool and readiness; pending results and snapshots are not completed checks.')}};await Promise.all([C(r,s),O(r,V)])}l(S,"registerDiagnostics");function H(r,n){return{id:"diagnostics",tryResolve(t,s){return Promise.resolve(L(t,s.cwd,r,n,{signal:s.signal,...s.audience==="script"&&{mode:"complete"}}))}}}l(H,"createDiagnosticResolver");function L(r,n,t,s,o){let i;try{i=m(r,M,n)}catch(a){return{kind:"failed",error:a}}return i===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:h(M,i),async read(){let a=await t(i,n,o),d=w(i,a.content,a.results);return s.set(d,d.diagnosticCheck),[d]}}}}l(L,"resolveDiagnosticSource");function j(r,n){return{id:"diagnostics",async present(t,s){if(s.purpose!=="read"||!W.isAbsolute(t.source))return t;let o=s.audience==="script"&&!s.requestedViews?.includes("diagnostics");if(o&&q(t.source))return t;let i=await r(t.source,s.cwd,{signal:s.signal,...s.audience==="script"&&{mode:o?"snapshot":"complete"}}).catch(a=>{if(s.signal?.throwIfAborted(),!o)throw a});if(i===void 0||o&&i.content!==t.content)return t;if(i.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,k(i.results)),P(t,i.results)}}}l(j,"createDiagnosticPresenter");export{S as default};
@@ -1,10 +0,0 @@
1
- import{d as w,h as P}from"./chunk-GIRAEVUJ.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as _}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as D,parse as z}from"partial-json";function B(o,e=D.ALL){if(!(!o||o.trim().length===0))try{let t=z(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(B,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),s=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),i=e.filterEntries?.(s,t)??s,d=new Set(i.map(c=>c.index));for(let c of s)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of i)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as L}from"@earendil-works/pi-ai";var M=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function N(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((s,i)=>{if(!s)return;let d=i.modelRegistry.getProvider(s.provider);if(!d)return;let u=r.get(s.provider);if(u){if(u.subscribers.add(a),u.api===s.api&&d.streamSimple===u.wrapper)return;u.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:u.wrapper});return}let m=d.streamSimple[M];if(m){if(m.subscribers.add(a),r.set(s.provider,m),m.api===s.api)return;m.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>F(c,p,v,C,g),"wrapper"),E={api:s.api,delegate:c,wrapper:b,subscribers:g};b[M]=E;let f=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...f,api:s.api,streamSimple:b}),r.set(s.provider,E)},"install");o.on("before_provider_request",(s,i)=>{a.context=i,l(i.model,i)}),o.on("turn_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("agent_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("session_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("model_select",(s,i)=>{a.context=i,l(s.model,i)}),o.on("session_shutdown",()=>{for(let[s,i]of r)i.subscribers.delete(a),i.subscribers.size===0&&o.unregisterProvider(s);r.clear(),a.context=void 0})}y(N,"registerStreamingInterceptorProvider");function F(o,e,t,n,r){let a=L(),l=new AbortController,s=n?.signal,i=!1,d=Q(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(f=>{for(let p of r)p.markStreamEventProcessed(f)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return s&&(s.aborted?l.abort():s.addEventListener("abort",E,{once:!0})),(async()=>{try{let f=o(e,t,{...n,signal:l.signal});for await(let p of f){if(i)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),H(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),W(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);i=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};U(a,b,I,u,m,c,g);let{errorMessage:T,...j}=I;a.push({type:"done",reason:"toolUse",message:{...j,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(f){if(i)return;let p=d,v=s?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:f instanceof Error?f.message:String(f)};a.push({type:"error",reason:v,error:C}),a.end()}finally{s?.removeEventListener("abort",E)}})(),a}y(F,"wrapStream");function H(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(H,"rememberStartEvent");function W(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(W,"rememberEndEvent");function U(o,e,t,n,r,a,l){for(let[s,i]of t.content.entries())if(n.has(s)){if(i.type==="text"&&!r.has(s)){let d={type:"text_end",contentIndex:s,content:i.text,partial:t};e(d),o.push(d)}else if(i.type==="thinking"&&!a.has(s)){let d={type:"thinking_end",contentIndex:s,content:i.thinking,partial:t};e(d),o.push(d)}else if(i.type==="toolCall"&&!l.has(s)){let d={type:"toolcall_end",contentIndex:s,toolCall:i,partial:t};e(d),o.push(d)}}}y(U,"emitMissingEndEvents");function Q(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Q,"emptyAssistantMessage");var V="agentic-ide-partial-tool-recovery",$="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
- `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r)return{content:r.content,details:r.details,isError:!0}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=B(a,_.OBJ|_.ARR)??{},s=J(a),i=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:i,toolName:n,args:l,complete:s!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!s&&Object.keys(l).length===0)return;let u=s!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=s??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:i,batchEntries:this.getBatchEntries(i),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let s=!this.completeArgumentContentIndices.has(e.contentIndex),i;s&&(this.completeArgumentContentIndices.add(e.contentIndex),i=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),i}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=O(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=O(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit($,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=Y(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let s={content:[{type:"text",text:e.message.content}],details:w(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:s,...r&&{blockExecution:!0}}),s}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,i=(h.IsObjectNotArray(l)&&h.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(i))for(let d of i)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,s=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],i=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:s,blockedToolCallIds:i,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?ee(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function O(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(O,"toolStreamEventKey");function Y(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(Y,"abortReason");function J(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}y(J,"parseCompleteArguments");function Z(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(i=>h.IsObjectNotArray(i.data)?i.data:i),a=n===void 0?r:r.filter(i=>i.path===n),s=(a.length>0?a:r).flatMap(i=>{let d=i.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(s)]}y(Z,"freshAnchorsAfterRecovery");function X(o,e){let n=o.indexOf(`
3
-
4
- Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
5
-
6
- Current nearby anchors:
7
- ${e.map(a=>` ${a}`).join(`
8
- `)}`}y(X,"replaceCurrentAnchors");function ee(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(u=>`${u.index} (${u.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=Z(e),s=l.length>0&&h.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,i=l.length>0?X(o.message.content,l):o.message.content,d=l.length>0&&h.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:V,content:`${i}
9
-
10
- [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:s,recovery:d}}}}y(ee,"makeRecoveryResult");var K=new WeakMap;function G(o){let e=K.get(o);if(e)return e;let t=new k(o);return K.set(o,t),N(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(G,"coordinatorFor");function te(o,e){G(o).register(e)}y(te,"registerToolCallInterceptor");function ne(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on($,n=>{!h.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!P(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(ne,"registerToolCallAnnotationSink");function fe(o,e){G(o).registerBlockedCallSink(e)}y(fe,"registerBlockedToolCallSink");export{te as a,ne as b,fe as c};
@@ -1,2 +0,0 @@
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};
@@ -1,2 +0,0 @@
1
- import{c as R}from"./chunk-7WCZOO5I.js";import{t as y,u as T}from"./chunk-5VSE5X5R.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import L from"node:path";import{keyText as D}from"@earendil-works/pi-coding-agent";import{Text as F,truncateToWidth as f,visibleWidth as u,wrapTextWithAnsi as O}from"@earendil-works/pi-tui";function $(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}l($,"sourceText");function w(e,t){let{files:r,...n}=e,a=$(t);return{...n,storedFiles:r.map(({lines:s,...o})=>({...o,lines:s.map(i=>{let d=[i.lineNumber,y(i.text,a),i.ranges];return i.logicalMatchIds===void 0?d:[...d,i.logicalMatchIds]})}))}}l(w,"compactSearchDetails");function C(e,t){if("files"in e)return e;let{storedFiles:r,...n}=e,a=$(t);return{...n,files:r.map(({lines:s,...o})=>({...o,lines:s.map(([i,d,c,m])=>({lineNumber:i,text:T(d,a),ranges:c,matchCount:c.length,...m===void 0?{}:{logicalMatchIds:m}}))}))}}l(C,"restoreSearchDetails");var M=new WeakMap,g=12,W={".ts":{label:"TS",color:"accent"},".tsx":{label:"TX",color:"accent"},".js":{label:"JS",color:"warning"},".jsx":{label:"JX",color:"warning"},".json":{label:"{}",color:"warning"},".md":{label:"MD",color:"mdHeading"},".py":{label:"PY",color:"accent"},".rs":{label:"RS",color:"accent"},".go":{label:"GO",color:"accent"},".css":{label:"CS",color:"accent"},".html":{label:"<>",color:"accent"}};function Z(e,t,r,n){if(typeof e.details=="object"){let o=M.get(e.details);o===void 0&&(o=C(e.details,e.content.flatMap(i=>i.type==="text"?[i.text]:[]).join(`
2
- `)),M.set(e.details,o)),e={...e,details:o}}if(t.isPartial||n.isError||!R(e.details)){let o=e.content[0],i=o?.type==="text"?o.text:"",d=n.isError?"error":t.isPartial?"dim":"toolOutput";return new F(r.fg(d,i),0,0)}let s=(n.lastComponent instanceof S?n.lastComponent:void 0)??new S(e.details,r,t.expanded);return s.update(e.details,r,t.expanded),s}l(Z,"renderSearchResult");var S=class{constructor(t,r,n){this.details=t;this.theme=r;this.expanded=n}static{l(this,"SearchResultPanel")}cached;update(t,r,n){this.details===t&&this.theme===r&&this.expanded===n||(this.details=t,this.theme=r,this.expanded=n,this.invalidate())}render(t){if(this.cached?.width===t)return this.cached.lines;if(t<4){let c=[f(k(this.details),Math.max(1,t))];return this.cached={width:t,lines:c},c}let r=t-2,n=v(this.details,this.expanded),a=G(this.details.files),s=n.flatMap(c=>A(c,r,a,this.theme)),o=P(s,this.expanded,r,this.theme),i=[I(this.details,r,this.theme),...o];i.push(this.theme.fg("borderMuted",`\u2570${"\u2500".repeat(r)}\u256F`));let d=i.map(c=>f(c,t));return this.cached={width:t,lines:d},d}invalidate(){this.cached=void 0}};function v(e,t){let r=e.files.length===0?[{kind:"empty"}]:e.files.flatMap(o=>[{kind:"file",file:o},...o.uniqueLineCount===void 0?o.lines.map(i=>({kind:"line",file:o,line:i})):[{kind:"summary",text:`${String(o.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(o.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(t||r.length<=g)return r;let n=r.slice(0,g-1);for(;n.at(-1)?.kind==="file";)n.pop();let a=new Set(n.flatMap(o=>o.kind==="line"?o.line.logicalMatchIds??[]:[])),s=a.size>0?a.size:n.reduce((o,i)=>o+(i.kind==="line"?i.line.matchCount:0),0);return[...n,{kind:"omitted",matches:Math.max(0,e.matchCount-s)}]}l(v,"searchViewport");function P(e,t,r,n){if(t||e.length<=g)return e;let a=`${D("app.tools.expand")} to expand`,s=h(n.fg("dim",` \u2026 output truncated \xB7 ${a}`),r,n);return[...e.slice(0,g-1),s]}l(P,"compactRenderedRows");function A(e,t,r,n){if(e.kind==="file")return[h(B(e.file,t,n),t,n,!0)];if(e.kind==="line")return j(e.line,t,r,n);if(e.kind==="summary")return[h(n.fg("dim",` ${p(e.text)}`),t,n)];if(e.kind==="omitted"){let a=`${D("app.tools.expand")} to expand`;return[h(n.fg("dim",` \u2026 ${String(e.matches)} more ${b(e.matches,"match","matches")} \xB7 ${a}`),t,n)]}return[h(n.fg("dim"," No matches found"),t,n)]}l(A,"renderPanelRow");function B(e,t,r){let n=N(e.path,r),a=r.fg("accent",r.bold(String(e.matchCount))),s=u(n)+u(a)+4,o=Math.max(1,t-s),i=H(e.path,o),d=q(i,e.link,r),c=` ${n} ${d}`,m=" ".repeat(Math.max(1,t-u(c)-u(a)-1));return f(`${c}${m}${a} `,t)}l(B,"renderFileHeader");function j(e,t,r,n){let a=String(e.lineNumber).padStart(r),s=` ${n.fg("dim",a)} ${n.fg("borderMuted","\u2502")} `,o=Math.max(1,t-u(s)-1),i=O(E(e,n),o),d=" ".repeat(u(s));return i.map((c,m)=>h(`${m===0?s:d}${c}`,t,n))}l(j,"renderMatchLine");function E(e,t){let r="",n=0;for(let a of e.ranges){a.from>n&&(r+=t.fg("toolOutput",p(e.text.slice(n,a.from))));let s=p(e.text.slice(a.from,a.to));r+=t.bg("selectedBg",t.fg("accent",t.bold(s))),n=a.to}return n<e.text.length&&(r+=t.fg("toolOutput",p(e.text.slice(n)))),r}l(E,"renderHighlightedLine");function I(e,t,r){let n=l(o=>r.fg("borderMuted",o),"frame"),a=f(` ${k(e)} `,Math.max(0,t-1),""),s="\u2500".repeat(Math.max(0,t-u(a)-1));return`${n("\u256D\u2500")}${r.fg("accent",a)}${n(`${s}\u256E`)}`}l(I,"renderTopBorder");function k(e){return e.matchCount===0?"No matches":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${b(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${b(e.fileCount,"file","files")}`}l(k,"searchSummary");function h(e,t,r,n=!1){let a=f(e,t),s=`${a}${" ".repeat(Math.max(0,t-u(a)))}`,o=n?r.bg("selectedBg",s):s,i=r.fg("borderMuted","\u2502");return`${i}${o}${i}`}l(h,"framed");function N(e,t){let r=L.extname(e).toLowerCase(),n=W[r]??{label:"\u25C7 ",color:r.length===0?"muted":"accent"};return t.fg(n.color,t.bold(n.label))}l(N,"fileBadge");function q(e,t,r){let n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),a=n===-1?"":e.slice(0,n+1),s=n===-1?e:e.slice(n+1),o=r.fg("muted",a)+r.underline(r.fg("accent",s));return t.includes("\x07")||t.includes("\x1B")?o:`\x1B]8;;${t}\x07${o}\x1B]8;;\x07`}l(q,"fileLink");function H(e,t){return u(e)<=t?e:t<=1?"\u2026":`\u2026${e.slice(-(t-1))}`}l(H,"truncatePath");function p(e){let t="";for(let r of e){if(r===" "){t+=" ".repeat(4);continue}let n=x(r.codePointAt(0));t+=n<32||n===127?"\uFFFD":r}return t}l(p,"safeText");function G(e){let t=1;for(let r of e)for(let n of r.lines)t=Math.max(t,n.lineNumber);return Math.max(3,String(t).length)}l(G,"maximumLineNumberWidth");function b(e,t,r){return e===1?t:r}l(b,"plural");export{w as a,Z as b,S as c};
@@ -1 +0,0 @@
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 supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# reference, or registered protocol source. 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. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),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. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:n.Optional(n.Array(n.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))});var a=e.Function([],e.Unknown()),u=e.Object({resolver:e.Unknown(),matchesCall:e.Optional(a),renderCall:e.Optional(a),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())}),c=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())}),p=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:p,handler:a}),e.Object({stage:e.Literal("post-read"),handler:a})]);function h(r){if(!i.Check(R,r))return!1;let t=r,d=t.resolver;return typeof d.id=="string"&&d.id.length>0&&typeof d.tryResolve=="function"&&(!("priority"in t)||typeof t.priority=="number")}o(h,"isTextTargetResolverRegistration");function O(r){if(!i.Check(u,r))return!1;let t=r;return s(t.resolver)?t.resolver.id!=="any"&&(!("priority"in t)||typeof t.priority=="number")&&(!("matchesCall"in t)||typeof t.matchesCall=="function")&&(!("renderCall"in t)||typeof t.renderCall=="function")&&"matchesCall"in t=="renderCall"in t&&(!("renderResult"in t)||typeof t.renderResult=="function"):!1}o(O,"isResourceResolverRegistration");function S(r){return i.Check(g,r)}o(S,"isReadHandlerRegistration");function C(r){return i.Check(y,r)}o(C,"isReadViewRegistration");function k(r){return i.Check(c,r)}o(k,"isFragmentResolverRegistration");function P(r){return m(r)?r.kind==="not-handled"?!0:r.kind==="failed"?typeof r.message=="string"&&r.message.length>0:r.kind==="resolved"&&typeof r.originLine=="number":!1}o(P,"isReadFragmentResolution");function m(r){return typeof r=="object"&&r!==null}o(m,"isRecord");export{l as a,h as b,O as c,S as d,C as e,k as f,P as g};
@@ -1 +0,0 @@
1
- import{a as p,e as f,k as g}from"./chunk-O6LE42GK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as m}from"node:async_hooks";var c=new m,l=new m;function E(t){let e=l.getStore();e?e.push(t):t()}o(E,"afterPostEditScope");async function T(t){if(l.getStore())return t();let e=[];try{return await l.run(e,t)}finally{for(let r of e)r()}}o(T,"collectPostEditNotifications");function b(t,e){let r=c.getStore();return r?(r.set(t,e),!0):!1}o(b,"deferPostEdit");function h(t){return c.getStore()?.has(t)??!1}o(h,"hasDeferredPostEdit");function v(t){c.getStore()?.delete(t)}o(v,"forgetDeferredPostEdit");function k(){let t=new Map;return{run(e){return c.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(k,"createPostEditScope");import{Type as n}from"typebox";import{Value as u}from"typebox/value";var w=`${p}/post-edit/register`;function M(t){return u.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(M,"isFormattingContribution");function _(t){return u.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(_,"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 u.Check(y,t)}o(S,"isTextPostEditHandlerRegistration");function j(t){return u.Check(P,t)}o(j,"isTextPostEditHandlerRegistrationRequest");function I(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(I,"isTextMutationResultContributionData");function F(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(F,"connectTextEditorPostEditHandler");export{E as a,T as b,b as c,h as d,v as e,k as f,w as g,M as h,_ as i,S as j,j as k,I as l,F as m};
@@ -1,4 +0,0 @@
1
- import{a as j,m as M}from"./chunk-FEDVTZJG.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as N,b as O}from"./chunk-O6LE42GK.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-QIK2E64R.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};
@@ -1 +0,0 @@
1
- import{Type as e}from"typebox";var t=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 detailed results returned to the agent (default 50)"}))},{additionalProperties:!1});export{t as a};
@@ -1,28 +0,0 @@
1
- import{a as se,b as ae,c as le}from"./chunk-ESPNEJHK.js";import{a as oe}from"./chunk-M5IVSCR2.js";import{e as Y,f as K}from"./chunk-T7I2VX3J.js";import{a as te}from"./chunk-L7JMDDSD.js";import{a as Q,b as ee}from"./chunk-O6LE42GK.js";import{b as E}from"./chunk-VCTK4JSN.js";import"./chunk-YHUTTZC6.js";import{a as Z}from"./chunk-6CZO43OH.js";import{a as z,b as J}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as ie}from"./chunk-ZTYWHL2F.js";import{a as ne,b as re}from"./chunk-7UGNGK7Y.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import Be from"node:path";import{stripVTControlCharacters as qe}from"node:util";import{truncateLine as Ve}from"@earendil-works/pi-coding-agent";import{Text as S}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as ue,DEFAULT_MAX_LINES as ce,formatSize as He,truncateTail as Ge}from"@earendil-works/pi-coding-agent";function D(t){return Ge(t,{maxBytes:ue-4096,maxLines:ce-32})}l(D,"terminalOutputTail");function $(t){let e=D(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
- `)}
3
- output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${ce} line output budget`:`${He(ue)} output budget`,s=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
- `)}
6
- output:
7
- ${s}${r.length===0?"":`
8
- ${r}`}`}l($,"formatAgentTerminalSnapshot");var Xe=500;function de(t,e,n,r,i){let s=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${k(n)} \xB7 ${s}`)}`;return new S(`${o}
9
- ${i.fg("accent",N(r.family))} ${t}`,0,0)}l(de,"renderRunCall");function me(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new S(r.join(`
10
- `),0,0)}l(me,"renderTerminalActionResult");function C(t,e,n,r,i){let s=[ze(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(o=>` ${i.fg("dim",o)}`)),new S(s.join(`
11
- `),0,0)}l(C,"renderTerminalAction");function x(t,e,n,r){let i=ge(t,E,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new S(i.join(`
12
- `),0,0)}l(x,"renderTerminalResult");function pe(t,e,n){if(e===!0?e="full":e===!1&&(e="compact"),e==="disabled"){if(!(t.status!==void 0&&!["running","completed"].includes(t.status)||t.exitCode!==void 0&&t.exitCode!==0||t.error!==void 0))return new S(P(t,(u,c)=>n.fg(u,c)),0,0);let o=A(t.output??"",E),a=[...o.omission===void 0?[]:[` ${n.fg("muted",o.omission)}`],...o.lines.map(u=>` ${n.fg("dim",u)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],P(t,(u,c)=>n.fg(u,c))];return new S(a.join(`
13
- `),0,0)}if(e==="full"){let s=ge(t,Number.POSITIVE_INFINITY,n).slice(2);return new S(s.join(`
14
- `),0,0)}let r=A(t.output??"",E),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(s=>` ${n.fg("dim",s)}`)];return i.push(P(t,(s,o)=>n.fg(s,o))),new S(i.join(`
15
- `),0,0)}l(pe,"renderRunResult");function fe(t,e){let n=l((o,a)=>e?.fg(o,a)??a,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${k(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",N(t.shellFamily))} ${O(t.command,84)}`],s=Ye(t.output,2);return s.length>0&&i.push(...s.map(o=>` ${n("dim",O(o,90))}`)),i.push(P(t,n)),i.join(`
16
- `)}l(fe,"renderActiveTerminal");function ge(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":k(t.cwd),o=t.shellFamily??"posix",a=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",N(o))} ${t.command??""}`],u=A(t.output??"",e);return u.omission!==void 0&&a.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&a.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),a.push(P(t,(c,d)=>n.fg(c,d))),a}l(ge,"terminalCardLines");function Ye(t,e){return A(t,e).lines}l(Ye,"outputTail");function A(t,e){let n=D(qe(t).replaceAll("\r","")),r=n.content.split(`
17
- `).map(u=>Ve(u.trimEnd(),Xe).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),a=s+o;return{lines:r.slice(s),...n.truncated||a>0?{omission:a>0?`\u2026 ${a} earlier lines`:"\u2026 earlier output omitted"}:{}}}l(A,"outputWindow");function P(t,e){let n=t.status??"running",r=Ke(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,Je(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}l(P,"statusLine");function Ke(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}l(Ke,"statusIcon");function N(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}l(N,"promptMarker");function ze(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":k(t.cwd),i=t.background===!0?"background":"wait",s=O(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}l(ze,"terminalIdentity");function k(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Be.sep}`))?`~${t.slice(e.length)}`:t}l(k,"shortCwd");function O(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}l(O,"oneLine");function Je(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(Je,"formatElapsed");function he(t){return{id:"terminal",onDidChange:l(e=>t.onDidChange(e),"onDidChange"),list:l(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:l(n=>fe(e,n).split(`
18
- `),"renderSummary"),renderDetail:l(n=>x(e,!0,n),"renderDetail"),sendInput:l(n=>t.write(e.source,n),"sendInput"),stop:l(()=>t.delete(e.source),"stop")})),"list")}}l(he,"terminalProcessProvider");import{setTimeout as nt}from"node:timers/promises";var Ze="#d8dee9",W="#111418",Qe=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function F(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:s}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),a=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),u=i.cols*9+24,c=a*18+24,d=s(Math.max(1,Math.round(u*r)),Math.max(1,Math.round(c*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=W,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,f=Math.max(0,p.baseY);for(let g=0;g<a;g+=1){let b=p.getLine(f+o+g);if(b!==void 0)for(let w=0;w<i.cols;w+=1){let v=b.getCell(w);v===void 0||v.getWidth()===0||et(m,v,w,g)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+a&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}l(F,"renderTerminalScreen");function et(t,e,n,r){let i=ye(e,"foreground"),s=ye(e,"background");e.isInverse()&&([i,s]=[s,i]);let o=12+n*9,a=12+r*18;s!==W&&(t.fillStyle=s,t.fillRect(o,a,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,o,a),e.isUnderline()&&t.fillRect(o,a+18-2,9*Math.max(1,e.getWidth()),1))}l(et,"drawCell");function ye(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ze:W;let i=n?t.isFgRGB():t.isBgRGB(),s=n?t.getFgColor():t.getBgColor();return i?`#${s.toString(16).padStart(6,"0")}`:tt(s)}l(ye,"cellColor");function tt(t){let e=Qe[t];if(e!==void 0)return e;if(t>=232){let a=8+(t-232)*10;return we(a,a,a)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),s=n%6,o=l(a=>a===0?0:55+a*40,"channel");return we(o(r),o(i),o(s))}l(tt,"ansiColor");function we(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}l(we,"rgb");var j="\0pi-terminal-write\0",H="\0pi-terminal-keys\0";function rt(t){let e=t?.find(u=>u==="image"||u==="sequence"||u.startsWith("image:")||u.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let u of e.slice(n+1).split(",")){let[c,d,m]=u.split("=");if(c===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${u}`);if(c!=="duration"&&c!=="interval"&&c!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${c}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${c} must be a number`);i.set(c,p)}let s=i.get("duration")??2,o=i.get("interval")??.5,a=i.get("scale")??1;if(!(a>0&&a<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(s>0&&s<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(s/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:s,interval:o,scale:a}}l(rt,"parseTerminalVisualView");async function xe(t,e){let n=new Map,r=new Map,i={protocol:z,apiVersion:J,id:"terminal",setup(o){o.addResolver({resolver:it(e),preserveTruncatedOutput:!0,renderResult(a,u,c){let d=a.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return x(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
- `)},u.expanded,c,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(a){let u=a.request.path;if(u===void 0||!y(u))return{kind:"continue",context:a};let c;try{c=rt(a.request.views)}catch(m){return{kind:"return",result:U(u,m instanceof Error?m.message:String(m))}}if(c===void 0)return{kind:"continue",context:a};let d=e.get(u);if(d===void 0)return{kind:"return",result:U(u,`Unknown terminal session ${u}`)};try{e.markInspected(u);let m=c.mode==="image"?1:Math.floor(c.duration/c.interval)+1,p=[];for(let f=0;f<m;f+=1){a.resolverContext.signal?.throwIfAborted(),f>0&&await nt(c.interval*1e3,void 0,{signal:a.resolverContext.signal});let g=await F(e,u,void 0,c.scale);p.push({type:"image",data:g,mimeType:"image/png"})}return{kind:"return",result:{content:p,details:{source:d.source,resolvedBy:"terminal",frames:m,mode:c.mode}}}}catch(m){return{kind:"return",result:U(u,m instanceof Error?m.message:String(m))}}}}),o.describe("shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated. image and parameterized sequence views return the virtual terminal screen as ordered PNG frames.")}},s={protocol:Q,apiVersion:ee,id:"terminal",setup(o){o.addResolver({resolver:ot(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:l(async a=>(Se(a.input,e,n),await Te(a.input,e,r),st(a,j)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:l(async a=>(await Te(a.input,e,r),Se(a.input,e,n),at(a)),"handler")});for(let a of["write","insert","delete"])o.addToolRenderer({tool:a,matches:l((u,c)=>dt(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),C(f.snapshot??{},a,be(a,m),[],c)},renderResult(u,c,d){let m=ct(u.details);return me(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([Z(t,i),te(t,s)]),t.on("tool_result",async(o,a)=>{if(!T(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:o.details,isError:!0};if(o.toolName==="delete"&&typeof u=="string"&&y(u)){let X=e.get(u);if(X===void 0)return;let je=e.snapshot(X);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:je,action:"delete",input:"session",changedLines:[]},isError:!1}),_=>({content:[{type:"text",text:_ instanceof Error?_.message:String(_)}],details:{source:u,deleted:!1},isError:!0}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),g=o.toolName,b=be(g,o.input),w=e.screenChangeRegion(d,m,6),v=[{type:"text",text:`Sent ${b} to ${d.source}.`}];return a.model?.input.includes("image")===!0&&v.push({type:"image",data:await F(e,c,{start:w.startRow,count:w.lines.length}),mimeType:"image/png"}),{content:v,details:{source:d.source,action:g,status:d.status,snapshot:f,input:b,changedLines:w.lines},isError:o.isError}})}l(xe,"registerTerminalResources");function it(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:lt(r)}]}}}}}}l(it,"createReadResolver");function ot(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=ut(r),s=i.indexOf(j),o=i.indexOf(H);if(s>=0){t.write(n.source,i.slice(s+j.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+H.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}l(ot,"createInputResolver");function st(t,e){return!T(t.input)||!Re(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}l(st,"transformWriteInput");function at(t){if(!T(t.input)||!Re(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${H}${typeof t.input.text=="string"?t.input.text:""}`}}}l(at,"transformInsertInput");function lt(t){return $(t)}l(lt,"formatSnapshot");function ut(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}l(ut,"singleText");function U(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}l(U,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}l(y,"isShellSource");function Re(t){return typeof t=="string"&&y(t)}l(Re,"isShellSourceValue");function ct(t){if(!T(t)||!T(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}l(ct,"terminalActionDetails");async function Te(t,e,n){if(!T(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}l(Te,"rememberScreen");function Se(t,e,n){if(!T(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}l(Se,"rememberOutputEnd");function be(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}l(be,"terminalInputLabel");function dt(t,e){if(!T(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return T(n)&&typeof n.source=="string"&&y(n.source)}l(dt,"isTerminalRenderValue");function T(t){return typeof t=="object"&&t!==null}l(T,"isRecord");async function Ee(t,e){await ie(t,{protocol:ne,apiVersion:re,id:"terminal",setup(r){r.addResolver({resolver:mt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}l(Ee,"registerTerminalSearch");function mt(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=pt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=G(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
- `)}
21
-
22
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,s=q(i)?G(i.payload):G(void 0),o=C(s.snapshot,"search",JSON.stringify(s.query),s.matches.slice(-6).map(a=>`${a.lineNumber}: ${a.lineText}`),r);return new B(o,n.expanded===!0,r)}}}l(mt,"terminalSearchResolver");var ve=12,B=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{l(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=ve)return n;let r=ve-1;return[...n.slice(0,r),this.theme.fg("muted",`\u2026 ${String(n.length-r)} visual rows omitted \xB7 ctrl+o to expand`)]}invalidate(){this.content.invalidate()}};function pt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[s,o]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let a=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=a.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||ft(a,c,d))&&r.push({source:t.source,lineNumber:s+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}l(pt,"findTerminalMatches");function ft(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}l(ft,"isWordBoundary");function G(t){if(!gt(t))throw new TypeError("Invalid terminal search result");return t}l(G,"parsePayload");function gt(t){return q(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&q(t.snapshot)&&typeof t.snapshot.source=="string"}l(gt,"isTerminalSearchPayload");function q(t){return typeof t=="object"&&t!==null}l(q,"isRecord");import{spawn as ht}from"node:child_process";import{closeSync as yt,mkdirSync as wt,openSync as Tt,rmSync as St,writeSync as bt}from"node:fs";import xt from"node:os";import Pe from"node:path";import{createRequire as Rt}from"node:module";import{randomUUID as vt}from"node:crypto";import{stripVTControlCharacters as Et}from"node:util";var Ce=Rt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),$e=1e6,Pt=100,$t=30,At=2e3,L=class{static{l(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=Lt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(It(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Wt(n);this.#i.set(n,Tt(r,"a",384));let i=e.cols??Pt,s=e.rows??$t,o=kt(i,s),a=l(p=>{},"resolveCompletion"),u=new Promise(p=>{a=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:s,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:a,completionDelivered:!1},d;try{let p=Ce("node-pty"),f={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:_t(Mt())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:Nt(p)};return this.#e.set(n,f),this.#s(n),a(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{R(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return R(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,s)=>{let o=l(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(a=>{n?.removeEventListener("abort",o),i(a)},s)})}async waitForForeground(e,n){let r=this.required(e);if(R(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(s=>{let o=!1,a,u=l(p=>{o||(p!==void 0&&R(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=l(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Ct(r)){a=void 0;return}a??=Date.now(),Date.now()-a>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,s;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=40)return;await V(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),s=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),a=-1;for(let d=0;d<=e.rows-s;d+=1){let m=0;for(let p=d;p<d+s;p+=1){let f=n[p]??"",g=i[p]??"",b=g.length>0&&!n.includes(g),w=f.length>0&&g.length===0;f!==g&&(b||w)&&(m+=1)}m>a&&(a=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+s).map((d,m)=>{if(o+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),s=[];for(let o=0;o<e.rows;o+=1){let a=r.getLine(i+o)?.translateToString(!0).trimEnd();a!==void 0&&a.length>0&&s.push(a)}return s.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Dt(n))}async stop(e,n="stopped"){let r=this.required(e);return R(r.status)||(r.status="stopping",this.#n(r),await Ae(r,!1),await Promise.race([r.completion.then(()=>!0),V(At).then(()=>!1)])||(await Ae(r,!0),await Promise.race([r.completion,V(1e3)])),R(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),St(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],s=Math.max(0,r.baseY);for(let o=s;o<s+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!R(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Et(n),i=this.#i.get(e.id);if(i!==void 0&&bt(i,r),e.output+=r,e.output.length>$e){let s=e.output.length-$e;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(yt(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Ct(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}l(Ct,"looksInteractive");function kt(t,e){let{Terminal:n}=Ce("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}l(kt,"createScreen");function Lt(){return vt().replaceAll("-","").slice(0,12)}l(Lt,"defaultSessionId");function It(t){return t.startsWith("shell:")?t.slice(6):t}l(It,"normalizeSessionId");function R(t){return t!=="running"&&t!=="stopping"}l(R,"isTerminalStatus");function Mt(){return process.env}l(Mt,"processEnvironment");function _t(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}l(_t,"cleanEnvironment");function Dt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Ot).join("")}l(Dt,"encodeTerminalKeys");function Ot(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),s=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return s?`\x1B${m}`:m}let a={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!s&&!o&&a[n]!==void 0)return a[n];if(s&&!i&&!o&&a[n]!==void 0)return`\x1B${a[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!s&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(s?2:0)+(i?4:0)}${c}`;if(s&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}l(Ot,"encodeTerminalKey");async function Ae(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=ht("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}l(Ae,"terminateProcessTree");function V(t){return new Promise(e=>setTimeout(e,t))}l(V,"delay");function Nt(t){return t instanceof Error?t.message:String(t)}l(Nt,"errorMessage");function Wt(t){let e=Pe.join(xt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return wt(e,{recursive:!0,mode:448}),Pe.join(e,`${t}.log`)}l(Wt,"createOutputLog");import Ft from"node:os";import ke from"node:path";function Le(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=ke.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:l(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:l(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Ft.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=ke.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:l(i=>["-c",i],"commandArgs")}}l(Le,"resolveShellProfile");function Ie(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}l(Ie,"shellSyntaxGuidance");import Me from"node:path";import{stripVTControlCharacters as Ut}from"node:util";import{defineTool as jt}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{Text as Ht}from"@earendil-works/pi-tui";var Gt=h.Object({command:h.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:h.Optional(h.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:h.Optional(h.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:h.Optional(h.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:h.Optional(h.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:h.Optional(h.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function _e(t,e,n,r,i="compact"){let s=process.platform==="win32"?"powershell":"bash";t.registerTool(jt({name:s,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${s} commands or scripts to edit files. Use Apply or the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${s} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions are treated as potentially stale after two minutes and wake an idle agent for inspection. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${Ie(n)}`,parameters:Gt,async execute(o,a,u,c,d){r.bind(d);let m=a.cwd===void 0?d.cwd:Me.resolve(d.cwd,a.cwd),p=e.start({command:a.command,background:a.background??!1,cwd:m,shell:n,...a.cols===void 0?{}:{cols:a.cols},...a.rows===void 0?{}:{rows:a.rows}});if(a.background===!0&&p.status!=="failed")return await Bt(e,p,c),p.status!=="running"&&(p.completionDelivered=!0),I(e.snapshot(p));if(p.status==="failed")return I(e.snapshot(p));let f=await e.waitForForeground(p.source,{signal:u,timeoutMs:(a.timeoutSeconds??60)*1e3});return f.reason==="aborted"&&r.notifyWaitTransition(f.session),I(e.snapshot(f.session))},renderCall(o,a,u){if((u.expanded?"full":i)==="disabled")return new Ht(a.fg("toolTitle",s),0,0);let d=typeof o.command=="string"?o.command:"",m=typeof o.cwd=="string"?Me.resolve(process.cwd(),o.cwd):process.cwd();return de(d,o.background===!0,m,n,a)},renderResult(o,a,u){return pe(o.details,a.expanded?"full":i,u)}}))}l(_e,"registerTerminalTools");function I(t){return{content:[{type:"text",text:$(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}l(I,"terminalResult");async function Bt(t,e,n){await new Promise(r=>{let i=!1,s,o=l(()=>{},"unsubscribe"),a=l(()=>{i||(i=!0,clearTimeout(s),o(),r())},"finish"),u=l(()=>{let c=t.snapshot(e);n?.(I(c)),(Ut(c.output).replaceAll("\r","").split(`
24
- `).filter(m=>m.length>0).length>=E||c.status!=="running")&&a()},"publish");o=t.onDidChange(c=>{c.id===e.id&&u()}),s=setTimeout(a,2e3),u()})}l(Bt,"captureInitialBackgroundPreview");import{Box as De,Container as Oe}from"@earendil-works/pi-tui";var qt=120,Vt=12e4,M=class{constructor(e,n,r=Vt){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:s},o)=>{let a=Ne(i.details)?i.details:void 0,u=new Oe;a!==void 0&&u.addChild(x(a,s,o,"stale \xB7 inspect session"));let c=new De(1,1,d=>o.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:s},o)=>{let a=new Oe;for(let c of Xt(i.details))a.addChild(x(c,s,o));let u=new De(1,1,c=>o.bg("toolSuccessBg",c));return u.addChild(a),u}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{l(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:Kt(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.#t.set(e.id,setTimeout(()=>this.#n(e),this.staleIntervalMs))}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:Yt(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},qt)))}};function Xt(t){return!Fe(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Ne)}l(Xt,"completionSnapshots");function Ne(t){return Fe(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}l(Ne,"isTerminalSessionSnapshot");function Yt(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
- ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,s=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${We(n.elapsedMs)}
26
- ${s||"(no output)"}`}).join(`
27
- `)}`}l(Yt,"formatCompletionMessage");function Kt(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${We(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}l(Kt,"formatStaleMessage");function We(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(We,"formatElapsed");function Fe(t){return typeof t=="object"&&t!==null}l(Fe,"isRecord");function Ue(t){return t==="full"||t==="disabled"?t:"compact"}l(Ue,"toolPresentation");async function zt(t,e){K(t,[await Y({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},...["read","write","insert","delete"].map(o=>({tool:o,resourcePrefixes:["shell:","process:"]}))]})]);let n=ae("terminal")??new L,r=Le(),i=new M(t,n),s=oe(t).add(he(n));await Promise.all([xe(t,n),Ee(t,n)]),_e(t,n,r,i,Ue(e?.preferences["ui.terminal"])),t.on("session_start",(o,a)=>i.bind(a)),t.on("agent_settled",(o,a)=>i.onAgentSettled(a)),t.on("session_shutdown",async o=>{if(i.dispose(),s(),o.reason!=="quit"){se("terminal",n);return}le("terminal",n),await n.dispose()})}l(zt,"registerTerminal");export{zt as default};
@@ -1,2 +0,0 @@
1
- import{a as H}from"./chunk-GUTQ3PWL.js";import{m as S}from"./chunk-5VSE5X5R.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{createHash as ue}from"node:crypto";import{readFile as z}from"node:fs/promises";import f 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 F from"node:path";function O(e=process.env.PI_CODING_AGENT_DIR??F.join(Z.homedir(),".pi","agent"),t=process.platform){let n=F.join(e,"bin",t==="win32"?"rg.exe":"rg");return Y(n)?n:"rg"}a(O,"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=D.resolve(t,oe(e.path??".")),o=["--json","--no-config","--no-ignore-parent","--color=never","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],..._(e.include).flatMap(i=>["--glob",i]),..._(e.exclude).flatMap(i=>["--glob",`!${i}`]),"--",e.query,r];if(e.regex!==!0)return k(["--fixed-strings",...o],n);try{return await k(["--engine","auto",...o],n)}catch(i){if(!ne(i))throw i;return k(["--engine","default",...o],n)}}a(A,"searchText");function k(e,t){return new Promise((n,r)=>{let o=ee(O(),e,{stdio:["ignore","pipe","pipe"]}),i=te({input:o.stdout}),s=[],l="",c,u=a(()=>{o.kill()},"abort"),d=a(()=>{t?.removeEventListener("abort",u),i.close()},"cleanup");o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{l+=m}),i.on("line",m=>{if(!(c!==void 0||m.length===0))try{let h=JSON.parse(m);if(h.type!=="match")return;for(let b of re(h))s.push(b)}catch(h){c=h,o.kill()}}),o.once("error",m=>{d(),r(m)}),o.once("close",m=>{if(d(),t?.aborted===!0){let h=new Error("Search was aborted.");h.name="AbortError",r(h);return}if(c!==void 0){r(new Error("Unable to parse ripgrep search output.",{cause:c}));return}if(m!==0&&m!==1){r(new Error(l.trim()||`ripgrep exited with code ${String(m)}.`));return}s.sort(ie),n({matches:s,complete:!0})}),t?.addEventListener("abort",u,{once:!0}),t?.aborted===!0&&u()})}a(k,"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),i=[];for(let s of e.data.submatches){if(s.start<0||s.end<=s.start||s.end>o.length)continue;let l=o.subarray(0,s.start).toString("utf8").length,c=o.subarray(0,s.end).toString("utf8").length;i.push({source:D.resolve(t),lineNumber:e.data.line_number,startColumn:l,endColumn:c,matchedText:r.slice(l,c),lineText:r})}return i}a(re,"matchesFromEvent");function _(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(_,"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 Q(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(Q,"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 p(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 p(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw p(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw p(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw p(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 s=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+s),offset:n}),n+=s;continue}if(r==="'"||r==='"'){let s=n,l=r,c="";for(n+=1;n<e.length&&e.charAt(n)!==l;)e.charAt(n)==="\\"&&(e.charAt(n+1)===l||e.charAt(n+1)==="\\")&&(n+=1),c+=e.charAt(n++);if(n>=e.length)throw p(s,`unterminated ${l==="'"?"single":"double"}-quoted term.`);if(n+=1,c.length===0)throw p(s,"quoted terms must not be empty.");t.push({type:"term",value:c,offset:s,quoted:!0});continue}let o=n;for(;n<e.length;){let s=e.charAt(n);if(/\s/u.test(s)||s===")"||W(e,n))break;s==="\\"&&n+1<e.length?n+=2:s==="["||s==="("?n=$(e,n)??n+1:n+=1}let i=e.slice(o,n);t.push({type:ce(i),value:i,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 i=$(e,r);if(i===void 0)return;r=i}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 p(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(p,"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=Q(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),i=[];for(let s of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await A({...e,query:s.query,regex:!0},t,n),r=s.query,i.push(s.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(l){if(s.mode!=="regex"||!le(l)||n?.aborted)throw l;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:i}}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,U=4;function We(e,t,n,r){return K(e,t,n,r).slice(0,U)}a(We,"createSearchSessionId");function K(e,t,n,r){let o=n===void 0?pe(t.map(c=>c.source)):f.resolve(n),i=t.map(c=>({match:c,source:f.relative(o,f.resolve(c.source))})).sort((c,u)=>c.source.localeCompare(u.source)||L(c.match,u.match)).map(({match:c,source:u})=>[u,c.lineNumber,c.startColumn,c.endLineNumber??c.lineNumber,c.endColumn,c.matchedText,c.lineText]),{limit:s,...l}=V(r??{query:e,regex:!0},o);return ue("sha256").update(JSON.stringify([e,o,l,i])).digest("hex").toUpperCase()}a(K,"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=U;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 V(e,t){return{query:e.query,path:f.resolve(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,fallbacks:e.fallbacks??[]}}a(V,"normalizeRecipe");var R=class extends Error{static{a(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},q=class{constructor(t=K){this.createIdentity=t}static{a(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(t,n,r,o,i,s={query:t,regex:!0},l){let c=n.map(j=>({...j,source:f.resolve(j.source)})).sort(L),u=await J(c,i),d=this.createIdentity(t,c,o,s),h=this.#r.get(d)??he(d,new Set(this.#t.keys())),b={id:h,query:t,matches:c,complete:r,contentBySource:u,recipe:s,...l!==void 0&&{refresh:l},cwd:f.resolve(o)};return this.#r.set(d,h),this.#t.set(h,b),b}async registerIfCurrent(t,n,r,o,i,s,l){try{return await this.register(t,n,r,o,i,s,l)}catch(c){if(c instanceof R)return;throw c}}async observeAfterEdit(t,n){let r=new Set(t.flatMap(i=>{let s=typeof i=="string"?w(i):void 0;return s===void 0?[]:[s.id]})),o=[];for(let i of r){let s=this.#t.get(i);if(s===void 0)continue;let l={sessionId:i,query:s.recipe.originalQuery??s.query,scope:V(s.recipe,s.cwd)};try{let c=s.refresh===void 0?await P(s.recipe,s.cwd,n):await s.refresh(n);o.push({...l,matches:c.matches.length,complete:c.complete,notices:c.notices})}catch(c){o.push({...l,error:c instanceof Error?c.message:String(c)})}}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=w(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=w(t);if(o===void 0)return{kind:"not-handled"};let i=this.#t.get(o.id);if(i===void 0)return x();if(o.selector==="all"&&!i.complete)return y();let s=f.resolve(n),l=i;if(o.selector==="all"){if(i.refreshedComplete?.complete===!0)l=i.refreshedComplete;else if(i.refreshedComplete!==void 0&&(l=await this.#n(i,r),!l.complete))return y()}let c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await I(s,r);if(d===void 0)return x(g(u[0]).lineNumber);if(o.selector==="all"&&d!==l.contentBySource.get(s)){if(l=await this.#n(i,r),!l.complete)return y();c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==i.contentBySource.get(s))return x(g(u[0]).lineNumber);let m=S(s,d);return{kind:"resolved",anchor:new H(t,s,u.map(h=>G(m,h,o.mode)))}}async#s(t,n){let r=w(t);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return x();if(r.selector==="all"&&!o.complete)return y();let i=o;if(r.selector==="all"){if(o.refreshedComplete?.complete===!0)i=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(i=await this.#n(o),!i.complete))return y();let u=new Set(T(i,r.selector,r.mode).map(d=>d.source));for(let d of u)if(await I(d)!==i.contentBySource.get(d)){if(i=await this.#n(o),!i.complete)return y();break}}let s=T(i,r.selector,r.mode);if(r.selector!=="all"){let u=s[0]?.source;if(u!==void 0&&await I(u)!==i.contentBySource.get(u))return x(s[0]?.lineNumber)}let l=new Map;for(let u of s){let d=l.get(u.source)??[];d.push(G(S(u.source,i.contentBySource.get(u.source)??u.lineText),u,r.mode)),l.set(u.source,d)}let c=[...l].map(([u,d])=>({source:u,ranges:d,expectedContent:i.contentBySource.get(u)}));return c.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:c}}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(s=>({...s,source:f.resolve(s.source)})).sort(L),i={matches:o,complete:r.complete,contentBySource:await J(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:i}),i}};function w(e){let t=de.exec(e);if(t!==null)return{id:g(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}a(w,"parseSearchAnchor");function T(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(i=>{let s=S(i.source,e.contentBySource.get(i.source)??i.lineText),l=X(i);return s.lines.slice(i.lineNumber-1,l).flatMap(c=>{let u=`${i.source}\0${String(c.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...i,lineNumber:c.lineNumber,endLineNumber:c.lineNumber,startColumn:0,endColumn:c.content.length,lineText:c.content,matchedText:c.content}])})})}a(T,"selectMatches");function fe(e){return e!==void 0}a(fe,"isMatch");function X(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(X,"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=X(t),o=g(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,i=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,i)+(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 z(r,{encoding:"utf8",...t!==void 0&&{signal:t}}),i=S(r,o);for(let s of e.filter(l=>l.source===r))if(i.lines[s.lineNumber-1]?.content!==s.lineText||me(i,s)!==s.matchedText)throw new R(r);n.set(r,o)}return n}a(J,"snapshotContents");async function I(e,t){try{return await z(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(I,"readCurrent");function x(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}a(x,"staleAnchor");function y(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}a(y,"missingCompleteAnchor");function pe(e){if(e.length===0)return".";let t=f.dirname(f.resolve(g(e[0])));for(let n of e.slice(1)){let r=f.resolve(n);for(;!ge(t,r);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}a(pe,"commonSourceDirectory");function ge(e,t){let n=f.relative(e,t);return n!==".."&&!n.startsWith(`..${f.sep}`)&&!f.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{O as a,Be as b,P as c,We as d,K as e,he as f,R as g,q as h};
@@ -1,15 +0,0 @@
1
- import{a as p}from"./chunk-4LUW26BX.js";import"./chunk-GIRAEVUJ.js";import"./chunk-MPT3R4BL.js";import{a as E,b as I,c as k,d as P}from"./chunk-T7I2VX3J.js";import"./chunk-YHUTTZC6.js";import{a as R}from"./chunk-6CZO43OH.js";import{a as T,b as _}from"./chunk-OBNING2A.js";import{a}from"./chunk-EI7MMDWY.js";var G=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/,h=class{static{a(this,"AgentDocumentationRegistry")}#e=new Map;register(n){let o=new Set(this.#e.keys());for(let s of n)b(s,o),o.add(s.id);for(let s of n)this.#e.set(s.id,x(s))}list(){return[...this.#e.values()].sort((n,o)=>n.id.localeCompare(o.id))}get(n){return this.#e.get(n)}matching(n,o){let s=M(o);return s?.startsWith("docs:")===!0?[]:this.list().filter(u=>u.triggers.some(i=>{if(i.tool!==n)return!1;let g=i.resourcePrefixes===void 0||s!==void 0&&i.resourcePrefixes.some(r=>s.startsWith(r)),t=i.viewPrefixes===void 0||S(o).some(r=>i.viewPrefixes?.some(d=>r.startsWith(d)));return g&&t}))}};function b(e,n){if(!G.test(e.id))throw new Error(`Invalid documentation ID: ${e.id}`);if(e.description.trim().length===0)throw new Error(`Documentation ${e.id} has no description`);if(e.markdown.trim().length===0)throw new Error(`Documentation ${e.id} has no Markdown content`);if(e.triggers.length===0||e.triggers.some(o=>o.tool.trim().length===0||o.resourcePrefixes?.some(s=>s.length===0)===!0||o.viewPrefixes?.some(s=>s.length===0)===!0))throw new Error(`Documentation ${e.id} has no valid triggers`);if(n.has(e.id))throw new Error(`Documentation ${e.id} is already registered`)}a(b,"validateDocument");function x(e){return Object.freeze({...e,triggers:Object.freeze(e.triggers.map(n=>Object.freeze({...n,...n.resourcePrefixes===void 0?{}:{resourcePrefixes:Object.freeze([...n.resourcePrefixes])},...n.viewPrefixes===void 0?{}:{viewPrefixes:Object.freeze([...n.viewPrefixes])}})))})}a(x,"freezeDocument");function S(e){if(typeof e!="object"||e===null)return[];let n=e.views;return Array.isArray(n)?n.filter(o=>typeof o=="string"):[]}a(S,"readViews");function M(e){if(typeof e!="object"||e===null)return;let n=e.path;return typeof n=="string"?n:void 0}a(M,"readPath");async function $(e){let n=new h,o=new Set,s=new Map,u=[],i={name:"agent-documentation-first-use",blockExecution:!0,toolNames:u,intercept(t){if(process.env.PI_AGENT_IDE_TEST_SKIP_GUIDE_GATE==="1"||t.toolCall.id.includes("-preflight-"))return;let r=N(n,o,t.toolCall.name,t.partialArgs??t.args);if(r.length!==0)return s.set(t.toolCall.id,r),C(e,r),U(r)}};p(e,i);let g=e.events.on(P,t=>{if(!q(t))throw new Error("Invalid agent documentation registration");n.register(t.documents),u.splice(0,u.length,...new Set(n.list().flatMap(r=>r.triggers.map(d=>d.tool)))),p(e,i)});e.on("session_shutdown",g),await R(e,{protocol:T,apiVersion:_,id:"agent-documentation",setup(t){t.addResolver({resolver:{id:"agent-documentation",tryResolve(r){if(!r.startsWith("docs:"))return Promise.resolve({kind:"not-handled"});let d=r.slice(5),m=d.length===0?void 0:n.get(d),f=d.length===0?z(n.list()):m?.markdown;return f===void 0?Promise.resolve({kind:"failed",error:new Error(`Unknown documentation ID: ${d}`)}):Promise.resolve({kind:"resolved",resource:{source:r,read:a(()=>Promise.resolve([{type:"text",text:f}]),"read")}})}}}),t.describe(()=>n.list().length===0?void 0:"docs: and docs:<id> \u2014 list or read packaged agent guidance."),t.addPromptGuideline(()=>V(n.list()))}}),e.on("session_start",(t,r)=>{y(r.sessionManager.getBranch(),n,o)}),e.on("tool_call",(t,r)=>{if(process.env.PI_AGENT_IDE_TEST_SKIP_GUIDE_GATE==="1"||t.toolCallId.includes("-preflight-"))return;y(r.sessionManager.getBranch(),n,o);let d=N(n,o,t.toolName,t.input);if(d.length!==0)return s.set(t.toolCallId,d),C(e,d),{block:!0,reason:w(d)}}),e.on("tool_result",(t,r)=>{if(t.toolCallId.includes("-preflight-"))return;let d=s.get(t.toolCallId);if(d!==void 0)return s.delete(t.toolCallId),{content:[{type:"text",text:w(d)}],details:A(d),isError:!0};y(r.sessionManager.getBranch(),n,o,t.toolCallId);let m=W(t.input);if(m!==void 0){let l=m.slice(5),O=n.list(),D=l.length===0||n.get(l)!==void 0;return l.length>0&&D&&o.add(l),{content:t.content,details:{...c(t.details)?t.details:{},documentation:D?l.length===0?{kind:"list",ids:O.map(v=>v.id)}:{kind:"document",id:l}:{kind:"error",code:"UNKNOWN_DOCUMENTATION",id:l}},isError:t.isError}}if(process.env.PI_AGENT_IDE_TEST_SKIP_GUIDE_GATE==="1")return;let f=n.matching(t.toolName,t.input).filter(l=>!o.has(l.id));if(f.length!==0){for(let l of f)o.add(l.id);return{content:[...t.content,...f.map(l=>({type:"text",text:`
2
-
3
- ---
4
-
5
- # Guide: ${l.id}
6
-
7
- ${l.markdown.trim()}`}))],details:{...c(t.details)?t.details:{},documentation:{kind:"attachment",ids:f.map(l=>l.id)}},isError:t.isError}}}),e.events.emit(k,{protocol:E,apiVersion:I})}a($,"registerProgressiveDocumentation");function N(e,n,o,s){let u=e.matching(o,s).filter(i=>!n.has(i.id));for(let i of u)n.add(i.id);return u}a(N,"claimMatchingGuides");function j(e){return["[SYSTEM] Read the attached guide before using this tool. Repeat the tool call after reading it.",...e.map(n=>`
8
-
9
- ---
10
-
11
- # Guide: ${n.id}
12
-
13
- ${n.markdown.trim()}`)].join("")}a(j,"renderGuideGate");function w(e){return`Guide sent to agent: ${e.map(n=>n.id).join(", ")}. Repeat the tool call.`}a(w,"guideNotice");function C(e,n){e.sendMessage({customType:"agent-documentation-first-use",content:j(n),display:!1,details:A(n)})}a(C,"sendGuideToAgent");function A(e){return{documentation:{kind:"gate",ids:e.map(n=>n.id)}}}a(A,"documentationGateDetails");function U(e){return{annotation:{kind:"blocked",reason:"Read the first-use guide, then retry."},message:{customType:"agent-documentation-first-use",content:w(e),display:!1,details:A(e)}}}a(U,"guideGateResult");function z(e){return e.length===0?"No agent documentation is currently available.":["# Available agent documentation","",...e.map(n=>`- \`${n.id}\` \u2014 ${n.description}`)].join(`
14
- `)}a(z,"renderListing");function V(e){if(e.length!==0)return["Read docs:<id> for detailed packaged guidance when needed. Available documents:",...e.map(n=>` - ${n.id} \u2014 ${n.description}`)].join(`
15
- `)}a(V,"renderPromptGuideline");function y(e,n,o,s){for(let u of e){if(!c(u)||u.type!=="message"||!c(u.message))continue;let i=u.message;if(i.toolCallId===s||typeof i.toolCallId=="string"&&i.toolCallId.includes("-preflight-")||i.role!=="toolResult"||typeof i.toolName!="string")continue;if(c(i.details)&&c(i.details.documentation)){let t=i.details.documentation,r=t.ids;if(Array.isArray(r)){for(let d of r)typeof d=="string"&&n.get(d)!==void 0&&o.add(d);continue}if(t.kind==="document"&&typeof t.id=="string"&&n.get(t.id)!==void 0){o.add(t.id);continue}}let g=i.input??K(i.details);for(let t of n.matching(i.toolName,g))o.add(t.id)}}a(y,"restoreClaims");function W(e){if(!(!c(e)||typeof e.path!="string"||!e.path.startsWith("docs:")))return e.path}a(W,"documentationSource");function K(e){if(!(!c(e)||typeof e.source!="string"))return{path:e.source}}a(K,"sourceInput");function q(e){return c(e)&&Array.isArray(e.documents)}a(q,"isRegistrationRequest");function c(e){return typeof e=="object"&&e!==null}a(c,"isRecord");export{$ as default};
@@ -1,2 +0,0 @@
1
- import{a as o}from"./chunk-EI7MMDWY.js";function G(t,e){if(e.length===0)return;let c=t.trim();if(c.length===0||/[\r\n]/u.test(c))throw new TypeError("Content provider summary must be one non-empty line");return[c,...e.map(({description:a})=>a)].join(`
2
- `)}o(G,"renderContentDescription");import{Type as i}from"typebox";import{Value as tt}from"typebox/value";import{Type as n}from"typebox";import{Value as W}from"typebox/value";var C={additionalProperties:!0},E=n.Function([],n.Unknown()),u=n.String({minLength:1}),Y=n.Object({type:n.Literal("text"),text:n.String(),textSignature:n.Optional(n.String())},C),B=n.Object({type:n.Literal("image"),data:n.String(),mimeType:n.String()},C),z=n.Object({type:n.Literal("custom"),kind:u,data:n.Unknown()},C),J=n.Array(n.Union([Y,B,z]),{minItems:1}),$=n.Union([n.Object({source:u,link:n.Optional(u),read:E,write:n.Optional(n.Never())},C),n.Object({source:u,link:n.Optional(u),read:n.Optional(n.Never()),write:E},C),n.Object({source:u,link:n.Optional(u),read:E,write:E},C)]),M=n.Object({id:u,tryResolve:E},C),Q=n.Union([n.Object({kind:n.Literal("not-handled")},C),n.Object({kind:n.Literal("resolved"),resource:$},C),n.Object({kind:n.Literal("failed"),error:n.Unknown()},C)]);function A(t){return x(J,t)?b(()=>t.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}o(A,"isAgentContent");function H(t){return x($,t)?b(()=>{let e=t,c=!("read"in e)||typeof e.read=="function",a=!("write"in e)||typeof e.write=="function";return c&&a}):!1}o(H,"isResource");function X(t){return x(M,t)}o(X,"isResourceResolver");function Z(t){return x(Q,t)?b(()=>{let e=t;return e.kind!=="resolved"||H(e.resource)}):!1}o(Z,"isResourceResolutionAttempt");function x(t,e){return b(()=>W.Check(t,e))}o(x,"safeCheck");function b(t){try{return t()}catch{return!1}}o(b,"safeEvaluate");var d={additionalProperties:!0},et=i.Function([],i.Unknown()),k=i.String({minLength:1}),nt=i.Object({provider:k,capability:i.Union([i.Literal("read"),i.Literal("write")])},d),ot=i.Object({source:k,bytes:i.Unknown(),mediaType:i.Optional(i.String())},d),rt=i.Object({signal:i.Optional(i.Unknown())},d),it=i.Object({id:k,description:k,tryConvert:et},d),st=i.Union([i.Object({kind:i.Literal("not-handled")},d),i.Object({kind:i.Literal("converted"),content:i.Unknown()},d),i.Object({kind:i.Literal("failed"),error:i.Unknown()},d)]),ct=i.Object({target:i.Unknown(),converter:i.Unknown(),priority:i.Optional(i.Number())},d);function f(t){return g(nt,t)&&v(()=>t.provider.trim().length>0)}o(f,"isContentTarget");function j(t){return g(ot,t)?v(()=>{let e=t;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}o(j,"isContentInput");function I(t){return g(rt,t)?v(()=>{let e=t;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}o(I,"isContentConversionContext");function q(t){return g(it,t)?v(()=>{let e=t;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}o(q,"isContentConverter");function _(t){return g(st,t)?v(()=>{let e=t;return e.kind!=="converted"||A(e.content)}):!1}o(_,"isContentConversionAttempt");function l(t){return g(ct,t)?v(()=>{let e=t;return f(e.target)&&q(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}o(l,"isContentConverterRegistration");function g(t,e){return v(()=>tt.Check(t,e))}o(g,"safeCheck");function v(t){try{return t()}catch{return!1}}o(v,"safeEvaluate");var N=class extends Error{static{o(this,"UnsupportedContentError")}source;target;constructor(e,c){super(`No content converter for ${e} in ${c.provider}/${c.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=c}};function V(t){if(!f(t))throw new TypeError("Invalid content target");let e={...t},c=[],a=o(()=>[...c].sort((r,s)=>r.priority-s.priority||r.order-s.order),"snapshotConverters");return{target:e,register(r){if(!l(r))throw new TypeError("Invalid content converter registration");if(!R(e,r.target))throw new Error(`Content converter ${r.converter.id} targets ${r.target.provider}/${r.target.capability}, not ${e.provider}/${e.capability}`);if(c.some(({converter:s})=>s.id===r.converter.id))throw new Error(`Content converter ${r.converter.id} is already registered for ${e.provider}/${e.capability}`);c.push({converter:r.converter,priority:r.priority??0,order:c.length})},listDescriptions(){return a().map(({converter:r})=>({id:r.id,description:r.description}))},async convert(r,s){if(!j(r))throw new TypeError("Invalid content input");if(!I(s))throw new TypeError("Invalid content conversion context");P(s.signal);let p=a();for(let{converter:O}of p){P(s.signal);let T=await O.tryConvert(r,s);if(P(s.signal),!_(T))throw new TypeError(`Content converter ${O.id} returned an invalid outcome`);if(T.kind!=="not-handled"){if(T.kind==="failed")throw T.error;return T.content}}throw new N(r.source,e)}}}o(V,"createContentRunner");function R(t,e){return t.provider===e.provider&&t.capability===e.capability}o(R,"targetsEqual");function P(t){t?.throwIfAborted()}o(P,"throwIfAborted");import{Type as m}from"typebox";import{Value as at}from"typebox/value";var y="pi-agent-resource/content-conversion",S=2,w=`${y}/host/ready`,h=`${y}/converter/register`,K={additionalProperties:!0},pt=m.Function([],m.Unknown()),Ct=m.Object({protocol:m.Literal(y),apiVersion:m.Literal(S),target:m.Unknown()},K),ut=m.Object({registration:m.Unknown(),accept:pt},K);function D(t){return F(Ct,t)&&L(()=>f(t.target))}o(D,"isContentHostReady");function U(t){return F(ut,t)&&L(()=>l(t.registration))}o(U,"isContentConverterRegistrationRequest");function F(t,e){return L(()=>at.Check(t,e))}o(F,"safeCheck");function L(t){try{return t()}catch{return!1}}o(L,"safeEvaluate");function dt(t,e){let c=V(e),a=t.events.on(h,r=>{if(!U(r))throw new Error("Invalid content converter registration request");if(!R(c.target,r.registration.target))return;let s;try{c.register(r.registration),s=Promise.resolve()}catch(p){s=Promise.reject(p instanceof Error?p:new Error("Content converter registration failed",{cause:p}))}r.accept(s)});return t.on("session_shutdown",a),t.events.emit(w,{protocol:y,apiVersion:S,target:c.target}),{target:c.target,listDescriptions(){return c.listDescriptions()},convert(r,s){return c.convert(r,s)}}}o(dt,"createContentHost");function mt(t,e){if(!l(e))throw new TypeError("Invalid content converter registration");let c=o(()=>{let s,p={registration:e,accept(O){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=O}};return t.events.emit(h,p),s},"announce"),a=o(()=>{},"unsubscribe");a=t.events.on(w,s=>{if(!D(s))throw new Error("Invalid content conversion host readiness event");if(!R(e.target,s.target))return;let p=c();if(p===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);a(),p.catch(()=>{})}),t.on("session_shutdown",a);let r=c();if(r!==void 0)return a(),r}o(mt,"connectContentConverter");export{G as a,A as b,H as c,X as d,Z as e,f,j as g,I as h,q as i,_ as j,l as k,N as l,V as m,R as n,y as o,S as p,w as q,h as r,D as s,U as t,dt as u,mt as v};