pi-agent-ide 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/chunk-6U5OU77O.js +3 -0
  3. package/dist/{chunk-6CZO43OH.js → chunk-BU7IZLKB.js} +1 -1
  4. package/dist/chunk-EURHXLN3.js +2 -0
  5. package/dist/{chunk-PYPPV2F5.js → chunk-F6IWZKOG.js} +6 -6
  6. package/dist/{chunk-GBLKIB6O.js → chunk-H445SHSJ.js} +2 -2
  7. package/dist/chunk-IG56UGSO.js +2 -0
  8. package/dist/chunk-IICJXZBU.js +6 -0
  9. package/dist/{chunk-XYS4FSCC.js → chunk-IM24DB3K.js} +1 -1
  10. package/dist/{chunk-YRF7OATP.js → chunk-KOVPDKSJ.js} +1 -1
  11. package/dist/chunk-MXLSGMRZ.js +3 -0
  12. package/dist/chunk-NRZO5KJT.js +9 -0
  13. package/dist/chunk-OB46OPMZ.js +1 -0
  14. package/dist/chunk-PKSQT6TC.js +1 -0
  15. package/dist/{chunk-PNU3E7IO.js → chunk-Q6CZ6GBR.js} +2 -2
  16. package/dist/{chunk-EDURPQAV.js → chunk-QRJLIV6P.js} +6 -6
  17. package/dist/chunk-QUYXINGZ.js +7 -0
  18. package/dist/{chunk-OBNING2A.js → chunk-S5PL5DFQ.js} +1 -1
  19. package/dist/chunk-SBP3ABH4.js +5 -0
  20. package/dist/{chunk-FXNKMNSJ.js → chunk-SJ4UZ4GU.js} +1 -1
  21. package/dist/chunk-SNF7PDDX.js +11 -0
  22. package/dist/{chunk-AJRIASPQ.js → chunk-STBJO3Z3.js} +1 -1
  23. package/dist/{chunk-3HYXQ4YA.js → chunk-TQGE7RH6.js} +13 -13
  24. package/dist/{chunk-S5LXX32D.js → chunk-XDG7EQRN.js} +3 -3
  25. package/dist/{chunk-F5YZG77W.js → chunk-XH5WN5XA.js} +1 -1
  26. package/dist/chunk-YWQS33DF.js +1 -0
  27. package/dist/chunk-ZIWPKIBZ.js +1 -0
  28. package/dist/entry-11.js +1 -1
  29. package/dist/entry-13.js +1 -1
  30. package/dist/entry-14.js +1 -1
  31. package/dist/entry-15.js +1 -1
  32. package/dist/entry-17.js +1 -1
  33. package/dist/entry-25.js +2 -2
  34. package/dist/entry-26.js +1 -1
  35. package/dist/entry-27.js +2 -2
  36. package/dist/entry-28.js +1 -1
  37. package/dist/entry-29.js +1 -1
  38. package/dist/entry-31.js +15 -13
  39. package/dist/entry-33.js +2 -1
  40. package/dist/entry-37.js +6 -6
  41. package/dist/entry-41.js +1 -1
  42. package/dist/entry-42.js +1 -1
  43. package/dist/entry-43.js +1 -1
  44. package/dist/entry-44.js +1 -1
  45. package/dist/entry-45.js +20 -13
  46. package/dist/entry-46.js +1 -1
  47. package/dist/entry-49.js +1 -1
  48. package/dist/entry-50.js +1 -1
  49. package/dist/entry-51.js +8 -7
  50. package/dist/entry-52.js +1 -1
  51. package/dist/entry-53.js +1 -1
  52. package/dist/entry-54.js +1 -1
  53. package/dist/entry-56.js +1 -1
  54. package/dist/entry-57.js +1 -1
  55. package/dist/entry-58.js +1 -1
  56. package/dist/entry-60.js +1 -1
  57. package/dist/entry-62.js +1 -1
  58. package/dist/entry-65.js +1 -1
  59. package/dist/entry-66.js +1 -1
  60. package/dist/entry-68.js +1 -1
  61. package/dist/entry-70.js +1 -1
  62. package/dist/entry-75.js +1 -1
  63. package/dist/entry-77.js +51 -43
  64. package/dist/entry-78.js +14 -14
  65. package/dist/entry-79.js +1 -1
  66. package/dist/entry-80.js +1 -1
  67. package/dist/entry-82.js +5 -5
  68. package/dist/entry-83.js +1 -1
  69. package/dist/entry-84.js +1 -1
  70. package/dist/entry-85.js +1 -1
  71. package/dist/entry-86.js +1 -1
  72. package/dist/pi-agent-ide.js +37 -9
  73. package/docs/agent-guides/editing.md +35 -46
  74. package/docs/agent-guides/git-changes.md +10 -0
  75. package/docs/agent-guides/read-resources.md +9 -50
  76. package/docs/agent-guides/search-code.md +18 -17
  77. package/docs/agent-guides/select-code.md +62 -140
  78. package/docs/agent-guides/terminal.md +9 -1
  79. package/docs/configuration.md +1 -1
  80. package/docs/releases.md +4 -0
  81. package/docs/research/native-codemode-batch-decision.md +2 -0
  82. package/docs/structured-results.md +27 -62
  83. package/docs/tools.md +15 -11
  84. package/node_modules/pi-agent-doctor/package.json +1 -1
  85. package/node_modules/pi-agent-documentation/package.json +1 -1
  86. package/node_modules/pi-agent-filesystem/index.ts +7 -6
  87. package/node_modules/pi-agent-filesystem/package.json +7 -7
  88. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  89. package/node_modules/pi-agent-filesystem-jq/index.ts +4 -3
  90. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  91. package/node_modules/pi-agent-filesystem-jq/src/jq.ts +4 -1
  92. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  93. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  94. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  95. package/node_modules/pi-agent-ide-ast/src/extension.ts +5 -4
  96. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  97. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +35 -9
  98. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +1 -1
  99. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +10 -8
  100. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +28 -3
  101. package/node_modules/pi-agent-ide-changes/index.ts +4 -3
  102. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  103. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +66 -4
  104. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +8 -11
  105. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  106. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  107. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  108. package/node_modules/pi-agent-ide-lsp/index.ts +3 -3
  109. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  110. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +5 -2
  111. package/node_modules/pi-agent-image/package.json +2 -2
  112. package/node_modules/pi-agent-invariant/package.json +1 -1
  113. package/node_modules/pi-agent-pdf/package.json +2 -2
  114. package/node_modules/pi-agent-read/package.json +7 -7
  115. package/node_modules/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  116. package/node_modules/pi-agent-read/src/api/read-parameters.ts +38 -1
  117. package/node_modules/pi-agent-read/src/api/tools/read.ts +18 -1
  118. package/node_modules/pi-agent-read/src/core/extension.ts +8 -2
  119. package/node_modules/pi-agent-read/src/core/read-core.ts +54 -35
  120. package/node_modules/pi-agent-read/src/core/tools/read/output-truncation.ts +91 -18
  121. package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +8 -2
  122. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +38 -1
  123. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +57 -2
  124. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +3 -3
  125. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +108 -46
  126. package/node_modules/pi-agent-resource/package.json +1 -1
  127. package/node_modules/pi-agent-resource/src/index.ts +1 -0
  128. package/node_modules/pi-agent-resource/src/result-targets.ts +186 -9
  129. package/node_modules/{pi-agent-read/src/core/tools/read → pi-agent-resource/src}/temp-resource-store.ts +17 -7
  130. package/node_modules/pi-agent-resource/src/tool-result.ts +13 -1
  131. package/node_modules/pi-agent-search/package.json +5 -5
  132. package/node_modules/pi-agent-search/src/api/fuzzy.ts +5 -1
  133. package/node_modules/pi-agent-search/src/api/search-parameters.ts +3 -3
  134. package/node_modules/pi-agent-search/src/core/extension.ts +2 -1
  135. package/node_modules/pi-agent-search/src/core/search-core.ts +13 -4
  136. package/node_modules/pi-agent-search-text/index.ts +1 -1
  137. package/node_modules/pi-agent-search-text/package.json +7 -7
  138. package/node_modules/pi-agent-search-text/src/resolvers.ts +11 -1
  139. package/node_modules/pi-agent-search-text/src/scoped-search.ts +1 -1
  140. package/node_modules/pi-agent-search-text/src/search-presentation.ts +42 -32
  141. package/node_modules/pi-agent-search-text/src/search-recipe.ts +1 -1
  142. package/node_modules/pi-agent-search-text/src/search-renderer.ts +6 -0
  143. package/node_modules/pi-agent-search-text/src/search-result.ts +17 -3
  144. package/node_modules/pi-agent-text/package.json +2 -2
  145. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  146. package/node_modules/pi-agent-text-anchor-exact/index.ts +65 -4
  147. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  148. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  149. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +4 -3
  150. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  151. package/node_modules/pi-agent-text-editor/package.json +9 -9
  152. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -2
  153. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +2 -1
  154. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +4 -0
  155. package/node_modules/pi-agent-text-editor/src/api/stale-anchor-message.ts +1 -1
  156. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +54 -12
  157. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +1 -1
  158. package/node_modules/pi-agent-text-editor/src/core/extension.ts +10 -3
  159. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +3 -13
  160. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +35 -6
  161. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +19 -1
  162. package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +132 -11
  163. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +232 -144
  164. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +34 -10
  165. package/node_modules/pi-agent-text-editor/src/core/result-input.ts +24 -4
  166. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +7 -2
  167. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +49 -214
  168. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +5 -1
  169. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +152 -22
  170. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +4 -0
  171. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +76 -32
  172. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +409 -209
  173. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  174. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +6 -9
  175. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +10 -3
  176. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +9 -4
  177. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +7 -8
  178. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  179. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  180. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +10 -4
  181. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  182. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +11 -0
  183. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +54 -5
  184. package/node_modules/pi-agent-text-editor-renderer/src/status-summary.ts +18 -3
  185. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  186. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  187. package/node_modules/pi-agent-tool-call-interception/src/index.ts +3 -0
  188. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  189. package/node_modules/pi-agent-web/index.ts +4 -3
  190. package/node_modules/pi-agent-web/package.json +7 -7
  191. package/node_modules/pi-agent-web/src/resolver.ts +11 -13
  192. package/node_modules/pi-agent-web-html/package.json +2 -2
  193. package/node_modules/pi-agent-web-image/package.json +3 -3
  194. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  195. package/node_modules/pi-agent-web-text/package.json +3 -3
  196. package/package.json +35 -35
  197. package/src/composite/nested-tool-rendering.ts +64 -6
  198. package/src/composite/output-limits.ts +125 -0
  199. package/src/composite/responses-tools.ts +25 -0
  200. package/src/composite/text-results.ts +372 -0
  201. package/src/documentation/extension.ts +11 -9
  202. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +7 -6
  203. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  204. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  205. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +4 -3
  206. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  207. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts +4 -1
  208. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  209. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  210. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +4 -3
  211. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  212. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  213. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  214. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  215. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  216. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +11 -13
  217. package/src/extensions/pi-agent-read/package.json +7 -7
  218. package/src/extensions/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  219. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +38 -1
  220. package/src/extensions/pi-agent-read/src/api/tools/read.ts +18 -1
  221. package/src/extensions/pi-agent-read/src/core/extension.ts +8 -2
  222. package/src/extensions/pi-agent-read/src/core/read-core.ts +54 -35
  223. package/src/extensions/pi-agent-read/src/core/tools/read/output-truncation.ts +91 -18
  224. package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +8 -2
  225. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +38 -1
  226. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +57 -2
  227. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +3 -3
  228. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +108 -46
  229. package/src/extensions/pi-agent-search/package.json +5 -5
  230. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +1 -1
  231. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -7
  232. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +11 -1
  233. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +1 -1
  234. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +42 -32
  235. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +1 -1
  236. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +6 -0
  237. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +17 -3
  238. package/src/extensions/pi-agent-search/src/api/fuzzy.ts +5 -1
  239. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +3 -3
  240. package/src/extensions/pi-agent-search/src/core/extension.ts +2 -1
  241. package/src/extensions/pi-agent-search/src/core/search-core.ts +13 -4
  242. package/src/extensions/pi-agent-text-editor/package.json +9 -9
  243. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  244. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +65 -4
  245. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  246. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  247. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +4 -3
  248. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  249. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  250. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +11 -0
  251. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +54 -5
  252. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/status-summary.ts +18 -3
  253. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  254. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -2
  255. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +2 -1
  256. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +4 -0
  257. package/src/extensions/pi-agent-text-editor/src/api/stale-anchor-message.ts +1 -1
  258. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +54 -12
  259. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +1 -1
  260. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +10 -3
  261. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +3 -13
  262. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +35 -6
  263. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +19 -1
  264. package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +132 -11
  265. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +232 -144
  266. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +34 -10
  267. package/src/extensions/pi-agent-text-editor/src/core/result-input.ts +24 -4
  268. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +7 -2
  269. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +49 -214
  270. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +5 -1
  271. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +152 -22
  272. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +4 -0
  273. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +76 -32
  274. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +409 -209
  275. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  276. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +6 -9
  277. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +10 -3
  278. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +9 -4
  279. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +7 -8
  280. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +1 -1
  281. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  282. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +10 -4
  283. package/src/pi-agent-ide.ts +15 -1
  284. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  285. package/src/plugins/pi-agent-ide-ast/src/extension.ts +5 -4
  286. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  287. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +35 -9
  288. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +1 -1
  289. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +10 -8
  290. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +28 -3
  291. package/src/plugins/pi-agent-ide-changes/index.ts +4 -3
  292. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  293. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +66 -4
  294. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +8 -11
  295. package/src/plugins/pi-agent-ide-debugger/index.ts +22 -10
  296. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -0
  297. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +93 -38
  298. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +6 -3
  299. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  300. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  301. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  302. package/src/plugins/pi-agent-ide-lsp/index.ts +3 -3
  303. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  304. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +5 -2
  305. package/src/plugins/pi-agent-ide-terminal/src/output-limits.ts +3 -3
  306. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +8 -6
  307. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +3 -3
  308. package/src/plugins/pi-agent-ide-vision/index.ts +13 -4
  309. package/src/post-edit/gate.ts +13 -2
  310. package/dist/chunk-3JO7QFIL.js +0 -1
  311. package/dist/chunk-4NIFBFFR.js +0 -11
  312. package/dist/chunk-64M3SQPG.js +0 -3
  313. package/dist/chunk-7LZKOHH2.js +0 -1
  314. package/dist/chunk-EAZGN5ND.js +0 -7
  315. package/dist/chunk-FK42RSF4.js +0 -1
  316. package/dist/chunk-KBP3QUDT.js +0 -2
  317. package/dist/chunk-KR36BT5E.js +0 -1
  318. package/dist/chunk-MBUXFKIW.js +0 -3
  319. package/dist/chunk-OE7QVAI2.js +0 -5
  320. package/dist/chunk-SILJ3OL4.js +0 -9
  321. package/dist/chunk-SQKAXYIR.js +0 -2
  322. package/dist/chunk-VCGNVTXQ.js +0 -1
  323. package/src/extensions/pi-agent-read/src/core/tools/read/temp-resource-store.ts +0 -105
@@ -185,9 +185,11 @@ export async function registerTerminalResources(
185
185
  }
186
186
  },
187
187
  });
188
- api.describe(
189
- "shell:<session> — 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.",
190
- );
188
+ api.describe({
189
+ path: "shell:<session> — terminal status and a bounded output tail with a full-log path when truncated.",
190
+ views:
191
+ "On shell:<session>, image[:scale=S] returns the virtual terminal screen; sequence[:duration=D,interval=I,scale=S] returns ordered PNG frames. Defaults: D=2 seconds, I=0.5 seconds, S=1. Scale satisfies 0 < S <= 1; sequences require 0 < D <= 10, I > 0, and at most 20 frames (floor(D/I)+1). Terminal captures do not support region or image grid selection; offset/limit do not crop their frames.",
192
+ });
191
193
  },
192
194
  } satisfies ReadPlugin;
193
195
 
@@ -268,7 +270,7 @@ export async function registerTerminalResources(
268
270
  content: [{ type: "text", text: message }],
269
271
  details: event.details,
270
272
  },
271
- mutationDataSchema,
273
+ mutationDataSchema(event.toolName),
272
274
  {
273
275
  status: "error",
274
276
  errors: [resultError(message, "UNSUPPORTED_OPERATION", requestedSource)],
@@ -302,7 +304,7 @@ export async function registerTerminalResources(
302
304
  changedLines: [],
303
305
  } satisfies TerminalActionDetails,
304
306
  },
305
- mutationDataSchema,
307
+ mutationDataSchema(event.toolName),
306
308
  {
307
309
  status: "success",
308
310
  errors: [],
@@ -321,7 +323,7 @@ export async function registerTerminalResources(
321
323
  ],
322
324
  details: { source: requestedSource, deleted: false },
323
325
  },
324
- mutationDataSchema,
326
+ mutationDataSchema(event.toolName),
325
327
  {
326
328
  status: "error",
327
329
  errors: [resultError(error, "TERMINAL_DELETE_FAILED", requestedSource)],
@@ -34,7 +34,7 @@ const createRunParameters = (profile: ShellProfile) =>
34
34
  background: Type.Optional(
35
35
  Type.Boolean({
36
36
  description:
37
- "Return immediately while the terminal session continues. Defaults to false.",
37
+ "Set true to return after an initial output preview instead of waiting for completion. Defaults to false.",
38
38
  }),
39
39
  ),
40
40
  timeoutSeconds: Type.Optional(
@@ -42,7 +42,7 @@ const createRunParameters = (profile: ShellProfile) =>
42
42
  minimum: 0.1,
43
43
  maximum: 86_400,
44
44
  description:
45
- "Maximum foreground wait in seconds before returning the live session as background. Defaults to 60.",
45
+ "Set the foreground wait limit in seconds. On expiry, the live session returns in background without stopping the process. Ignored when background is true. Defaults to 60.",
46
46
  }),
47
47
  ),
48
48
  cwd: Type.Optional(
@@ -91,7 +91,7 @@ export function registerTerminalTools(
91
91
  promptGuidelines: [
92
92
  `Do not use ${toolName} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`,
93
93
  ],
94
- description: `Use ${toolName} to execute a command in the user's configured ${profile.displayName} shell (${profile.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 wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. 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.`,
94
+ description: `Use ${toolName} to execute a command in the user's configured shell. Each call creates a new terminal session and returns its shell: source for inspection and interaction.`,
95
95
  parameters: runParameters,
96
96
  outputSchema: shellOutputSchema,
97
97
  async execute(_toolCallId, input, signal, onUpdate, context) {
@@ -52,6 +52,7 @@ export default async function registerVision(
52
52
  setup(api) {
53
53
  for (const view of ["image", "sequence"]) {
54
54
  api.addView({
55
+ contentKind: "any",
55
56
  view,
56
57
  presenter: { id: `vision-${view}`, present: (document) => document },
57
58
  });
@@ -127,10 +128,18 @@ export default async function registerVision(
127
128
  return { kind: "continue", context };
128
129
  },
129
130
  });
130
- const defaults = getVisionDefaults();
131
- api.describe(
132
- `Process metadata: process:PID. Visual capture: window:PID and display: or display:#N. HTTP(S) sources accept image and sequence screenshots. Use named view parameters such as sequence:duration=2,interval=0.5,scale=0.5 and image:scale=0.5,region=0.25,0.25,0.5,0.5. Duration is limited to 10 seconds and sequences to 20 frames. Defaults: duration=${defaults.durationSeconds}, interval=${defaults.intervalSeconds}, scale=${defaults.scale}. Region uses normalized x,y,width,height and runs before scaling. For captures, limit is a square grid cell size in output pixels and offset is one zero-based row-major cell index; limit without offset selects cell 0, while offset without limit is invalid. Omit both for the bounded transformed image.`,
133
- );
131
+ api.describe({
132
+ path: () =>
133
+ `process:PID — process metadata. window:PID — capture a window of an IDE-owned or allowlisted process${pi.getFlag("pi-agent-ide-vision-arbitrary-windows") === true ? "; arbitrary windows are enabled" : "; other processes require --pi-agent-ide-vision-arbitrary-windows"}. display: or display:#N — display capture with a zero-based index; ${pi.getFlag("pi-agent-ide-vision-displays") === true ? "enabled" : "requires --pi-agent-ide-vision-displays"}. HTTP(S) URLs accept image or sequence screenshots.`,
134
+ views: () => {
135
+ const defaults = getVisionDefaults();
136
+ return `image or image:scale=S,region=X,Y,W,H — one screenshot. sequence or sequence:duration=D,interval=I,scale=S,region=X,Y,W,H — timed frames. Only one image/sequence view per request. duration and interval are seconds and only valid for sequence: 0 < D <= 10, I > 0, at most 20 frames (floor(D/I)+1). Scale satisfies 0 < S <= 1. Region uses normalized x,y,width,height: x,y >= 0, width,height > 0, and the rectangle must fit in 0..1; crop runs before scaling. Settings are optional; defaults: duration=${defaults.durationSeconds}, interval=${defaults.intervalSeconds}, scale=${defaults.scale}.`;
137
+ },
138
+ offset:
139
+ "For window:, display: and HTTP(S) image/sequence captures, a non-negative integer zero-based row-major grid cell index in the transformed image. Requires limit; omit to select cell 0 when limit is set.",
140
+ limit:
141
+ "For window:, display: and HTTP(S) image/sequence captures, a positive integer square grid cell size in output pixels. Omit both offset and limit for the bounded transformed image.",
142
+ });
134
143
  },
135
144
  }),
136
145
  connectSearchPlugin(pi, {
@@ -47,13 +47,24 @@ export async function runIdePostEditGate(
47
47
  }
48
48
  : {
49
49
  diffStatuses: [
50
- { text: `Formatting failed (${formatterName})`, tone: "error" as const },
50
+ {
51
+ text: `Formatting failed (${formatterName})`,
52
+ formatter: formatterName,
53
+ tone: "error" as const,
54
+ },
51
55
  ],
52
56
  }),
53
57
  };
54
58
  } catch {
55
59
  return {
56
- diffStatuses: [{ text: "Formatting failed", tone: "error" as const }],
60
+ diffStatuses: [
61
+ {
62
+ text: "Formatting failed",
63
+ tone: "error" as const,
64
+ formattingStatus: "failed",
65
+ ...(formatterName === undefined ? {} : { formatter: formatterName }),
66
+ },
67
+ ],
57
68
  formatting: {
58
69
  status: "failed",
59
70
  ...(formatterName === undefined ? {} : { formatter: formatterName }),
@@ -1 +0,0 @@
1
- import{c as g,d as p}from"./chunk-AJRIASPQ.js";import{a as c}from"./chunk-EI7MMDWY.js";import b from"node:path";import{pathToFileURL as C}from"node:url";function S(e,r){let o=new Map;for(let n of e){let t=o.get(n.source)??[];t.push(n),o.set(n.source,t)}let i=new Set,a=e.length,s=[...o].sort(([n,t],[h,l])=>l.length-t.length||n.localeCompare(h));for(let[n,t]of s){if(a<=r)break;i.add(n),a-=t.length}return{files:[...o].sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>{if(!i.has(n))return{kind:"detailed",source:n,matches:t};let h=new Map;for(let l of t)h.set(l.lineText,(h.get(l.lineText)??0)+1);return{kind:"compacted",source:n,matchCount:t.length,uniqueLineCount:h.size,groups:o.size===1?[...h].sort(([l,d],[m,R])=>R-d||l.localeCompare(m)).slice(0,r).map(([l,d])=>({text:l,matchCount:d})):[]}})}}c(S,"planSearchPresentation");function F(e,r,o,i,a,s=50){let n=S(r,s).files.map(t=>t.kind==="detailed"?k(t.source,t.matches,i):{path:z(t.source,i),link:C(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups,lines:[]});return{...a!==void 0&&{sessionId:a},query:e,matchCount:r.length,fileCount:n.length,complete:o,files:n}}c(F,"createSearchToolDetails");function D(e,r){return{fileCount:new Set(e.flatMap(o=>o.matches.map(i=>i.source))).size,groups:e.map(o=>{let a=F(o.identifier,o.matches.slice(0,g.previewMatches),o.complete,r).files.map(s=>{let u=s.lines.map(n=>{let t=Math.max(0,(n.ranges[0]?.from??0)-64),h=Math.min(n.text.length,(n.ranges[0]?.to??0)+64),l=t>0?"\u2026":"",d=n.ranges.filter(m=>m.from>=t&&m.to<=h).map(m=>({from:m.from-t+l.length,to:m.to-t+l.length}));return{...n,text:l+n.text.slice(t,h)+(h<n.text.length?"\u2026":""),ranges:d,matchCount:d.length}});return{...s,lines:u,matchCount:u.reduce((n,t)=>n+t.matchCount,0)}});return{identifier:o.identifier,files:a}})}}c(D,"createFuzzyPresentation");function M(e){return f(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(r=>f(r)&&typeof r.identifier=="string"&&Array.isArray(r.files)&&r.files.every(x))}c(M,"isFuzzyPresentation");function G(e){if(!f(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!p(e.fuzzy)||e.fuzzyPresentation!==void 0&&!M(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(x))return!1;let r=e.files;return e.fileCount===r.length&&e.matchCount===r.reduce((o,i)=>o+i.matchCount,0)}c(G,"isSearchToolDetails");function k(e,r,o){let i=new Map;for(let s of r){let u=i.get(s.lineNumber);if(u!==void 0&&u.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let n=u??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};n.ranges.push({from:s.startColumn,to:s.endColumn}),i.set(s.lineNumber,n)}let a=[...i.values()].sort((s,u)=>s.lineNumber-u.lineNumber).map(s=>{let u=[...s.ranges].sort((n,t)=>n.from-t.from||n.to-t.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:u.length,ranges:u}});return{path:z(e,o),link:C(e).href,matchCount:r.length,lines:a}}c(k,"createSearchResultFile");function x(e){if(!f(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(w))return!1;let r=e.lines,o=e.groups,i=new Set(r.flatMap(a=>a.logicalMatchIds??[]));return(o===void 0||Array.isArray(o)&&o.every(a=>f(a)&&typeof a.text=="string"&&y(a.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(r.length===0||(i.size>0?i.size===e.matchCount:e.matchCount===r.reduce((a,s)=>a+s.matchCount,0)))}c(x,"isSearchResultFile");function w(e){return f(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(r=>typeof r=="string"))&&e.ranges.every(r=>L(r,e.text))}c(w,"isSearchResultLine");function L(e,r){return f(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=r.length}c(L,"isSearchResultRange");function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(f,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}c(y,"isCount");function z(e,r){let o=b.relative(r,e);return o.length>0&&!o.startsWith("..")&&!b.isAbsolute(o)?o:e}c(z,"displaySource");export{S as a,F as b,D as c,G as d};
@@ -1,11 +0,0 @@
1
- import{d as B,h as M}from"./chunk-F5YZG77W.js";import{a as N}from"./chunk-VCGNVTXQ.js";import{h as w,i as P}from"./chunk-SQKAXYIR.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as F,parse as H}from"partial-json";function _(o,e=F.ALL){if(!(!o||o.trim().length===0))try{let t=H(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(_,"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),i=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let 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}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of s)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 W}from"@earendil-works/pi-ai";var O=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let u=r.get(i.provider);if(u){if(u.subscribers.add(a),u.api===i.api&&d.streamSimple===u.wrapper)return;u.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:u.wrapper});return}let m=d.streamSimple[O];if(m){if(m.subscribers.add(a),r.set(i.provider,m),m.api===i.api)return;m.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>U(c,p,v,C,g),"wrapper"),E={api:i.api,delegate:c,wrapper:b,subscribers:g};b[O]=E;let h=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...h,api:i.api,streamSimple:b}),r.set(i.provider,E)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r)s.subscribers.delete(a),s.subscribers.size===0&&o.unregisterProvider(i);r.clear(),a.context=void 0})}y(K,"registerStreamingInterceptorProvider");function U(o,e,t,n,r){let a=W(),l=new AbortController,i=n?.signal,s=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),Q(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),q(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);s=!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)};V(a,b,I,u,m,c,g);let{errorMessage:T,...L}=I;a.push({type:"done",reason:"toolUse",message:{...L,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(s)return;let p=d,v=i?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:v,error:C}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}y(U,"wrapStream");function Q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(Q,"rememberStartEvent");function q(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(q,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(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(Y,"emptyAssistantMessage");var Z="agentic-ide-partial-tool-recovery",G="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){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
3
- `);return P({content:r.content,details:a},N,{status:"error",errors:[w(i,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="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=_(a,$.OBJ|$.ARR)??{},i=ee(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let u=i!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(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(G,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=X(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let i={content:[{type:"text",text:e.message.content}],details:B(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:i,...r&&{blockExecution:!0}}),i}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,s=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],s=[...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:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?re(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 j(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(j,"toolStreamEventKey");function X(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(X,"abortReason");function ee(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(ee,"parseCompleteArguments");function te(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(s=>f.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(i)]}y(te,"freshAnchorsAfterRecovery");function ne(o,e){let n=o.indexOf(`
4
-
5
- Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
-
7
- Current nearby anchors:
8
- ${e.map(a=>` ${a}`).join(`
9
- `)}`}y(ne,"replaceCurrentAnchors");function re(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=te(e),i=l.length>0&&f.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,s=l.length>0?ne(o.message.content,l):o.message.content,d=l.length>0&&f.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:Z,content:`${s}
10
-
11
- [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:i,recovery:d}}}}y(re,"makeRecoveryResult");var D=new WeakMap;function z(o){let e=D.get(o);if(e)return e;let t=new k(o);return D.set(o,t),K(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(z,"coordinatorFor");function oe(o,e){z(o).register(e)}y(oe,"registerToolCallInterceptor");function ae(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on(G,n=>{!f.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!M(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(ae,"registerToolCallAnnotationSink");function Ee(o,e){z(o).registerBlockedCallSink(e)}y(Ee,"registerBlockedToolCallSink");export{oe as a,ae as b,Ee as c};
@@ -1,3 +0,0 @@
1
- import{e as j}from"./chunk-PS2B6THP.js";import{i as T,o as m,t as L,u as C}from"./chunk-ZPT5D4VP.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function Te(e,n){let{lines:t,truncation:r,...i}=e,o=t?.map(a=>{let l=[a.lineNumber,L(a.content,n),a.lineEnding];return(a.presentation!==void 0||a.metadata!==void 0)&&l.push(a.presentation),a.metadata!==void 0&&l.push(a.metadata),l}),{content:s,...u}=r??{};return{...i,...o===void 0?{}:{storedLines:o},...r===void 0?{}:{truncation:u,truncatedText:L(s??"",n)}}}d(Te,"compactReadDetails");function H(e,n){let t=e;if(t.storedLines===void 0&&t.truncatedText===void 0)return e;let{storedLines:r,truncatedText:i,truncation:o,...s}=t;return{...s,...r===void 0?{}:{lines:r.map(([u,a,l,c,p])=>({lineNumber:u,content:C(a,n),lineEnding:l,...c==null?{}:{presentation:c},...p==null?{}:{metadata:p}}))},...o===void 0?{}:{truncation:{...o,content:C(i??"",n)}}}}d(H,"restoreReadDetails");import f from"node:path";import{homedir as G}from"node:os";import{createReadToolDefinition as X,getReadmePath as J}from"@earendil-works/pi-coding-agent";import{Text as Z}from"@earendil-works/pi-tui";var v=X(process.cwd()),K=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function $(e,n=process.cwd()){if(typeof e!="object"||e===null)return;let t=e,r=t.path;if(typeof r!="string"||r.length===0||r.includes("#")||!f.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||t.views!==void 0&&(!Array.isArray(t.views)||t.views.length>0)||t.offset!==void 0&&(typeof t.offset!="number"||!Number.isInteger(t.offset)||t.offset<1)||t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1))return;let i=r.startsWith("~/")?f.join(G(),r.slice(2)):r,o=f.resolve(n,i),s=f.basename(o),u=f.relative(f.dirname(J()),o),a=!f.isAbsolute(u)&&(u==="README.md"||u.startsWith(`docs${f.sep}`)||u.startsWith(`examples${f.sep}`));if(!(s!=="SKILL.md"&&!K.has(s)&&!a))return{path:r,...t.offset===void 0?{}:{offset:t.offset},...t.limit===void 0?{}:{limit:t.limit}}}d($,"nativeReadArguments");function A(e,n){return{...e,args:n,lastComponent:e.lastComponent instanceof Z?e.lastComponent:void 0}}d(A,"nativeReadContext");import{getLanguageFromPath as k,getMarkdownTheme as Y,highlightCode as E,keyHint as Q}from"@earendil-works/pi-coding-agent";import{Container as w,Markdown as _,Text as ee,truncateToWidth as S,visibleWidth as R,wrapTextWithAnsi as q}from"@earendil-works/pi-tui";var g=12;function ne(e,n,t){let r=typeof n=="number"?n:void 0,i=typeof t=="number"?t:void 0;if(r===void 0&&i===void 0)return{pathSuffix:"",qualifiers:[],details:[]};if(e==="inherited source"||e.includes("#")){let a=r??1,l=i===void 0?String(a):`${a}-${a+i-1}`;return{pathSuffix:"",qualifiers:[{text:`relative lines ${l}`}],details:[{label:"relative lines",value:l}]}}if(r!==void 0&&r<0)return{pathSuffix:"",qualifiers:[{text:`tail ${Math.abs(r)}`},...i===void 0?[]:[{text:`limit ${i}`}]],details:[{label:"tail",value:String(Math.abs(r))},...i===void 0?[]:[{label:"limit",value:String(i)}]]};let s=Math.max(1,r??1),u=i===void 0?String(s):`${s}-${s+i-1}`;return{pathSuffix:`:${u}`,qualifiers:[],details:[{label:"lines",value:u}]}}d(ne,"readWindowPresentation");function We(e,n,t){let r=$(e,t.cwd);if(r!==void 0)return y(v.renderCall)(r,n,A(t,r));if(typeof e.path=="string"&&e.path.startsWith("shell:"))return new w;let i=typeof e.path=="string"?e.path:"inherited source",o=ne(i,e.offset,e.limit),s=Array.isArray(e.views)?e.views.filter(l=>typeof l=="string"):[],u=[...o.qualifiers,...s.length===0?[]:[{text:`views ${s.join(",")}`}]],a=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...o.details,...s.length===0?[]:[{label:"views",value:s.join(",")}]];return j(t.lastComponent,{tool:"read",primary:{text:`${i}${o.pathSuffix}`,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:u,details:a,expanded:t.expanded},n)}d(We,"renderReadCall");function je(e){let n=new WeakMap;return(t,r,i,o)=>{let s=e.nativeResources?$(o.args,o.cwd):void 0;if(s!==void 0&&!r.isPartial)return y(v.renderResult)({...t,details:{truncation:D(t.details).truncation}},r,i,A(o,s));if(r.isPartial||o.isError){let p=P(t),B=o.isError?"error":"dim";return new ee(i.fg(B,p),0,0)}let u=D(t.details).diagnosticCheck;if(u?.complete&&u.count===0)return new w;if(!me(t))return o.lastComponent instanceof w?o.lastComponent:new w;let a=n.get(t);a===void 0&&(a=H(D(t.details),P(t)),n.set(t,a));let c=(o.lastComponent instanceof b?o.lastComponent:void 0)??new b({result:t,details:a,options:e,expanded:r.expanded,theme:i});return c.update({result:t,details:a,options:e,expanded:r.expanded,theme:i}),c}}d(je,"createReadResultRenderer");var b=class{constructor(n){this.state=n}static{d(this,"ReadResultPanel")}cached;update(n){this.state.result===n.result&&this.state.details===n.details&&this.state.options===n.options&&this.state.expanded===n.expanded&&this.state.theme===n.theme||(this.state=n,this.invalidate())}render(n){if(this.cached?.width===n)return this.cached.lines;if(n<8){let c=[S(V(this.state,n),Math.max(1,n))];return this.cached={width:n,lines:c},c}let t=n-2,r=Math.max(1,t-2),i=oe(this.state,r),o=se(i.state,r).flatMap(c=>q(c,r)),s=ue(o,this.state.expanded,this.state.theme,i.hasHiddenRows),u=[le(this.state,t,this.state.theme)];for(let c of s)for(let p of q(c,r))u.push(I(p,t,this.state.theme));let a=fe(this.state.details,this.state.theme);a!==void 0&&u.push(I(a,t,this.state.theme)),u.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(t)}\u256F`));let l=u.map(c=>S(c,n));return this.cached={width:n,lines:l},l}invalidate(){this.cached=void 0}},te=100,re=g,ie=4;function oe(e,n){if(e.expanded)return{state:e,hasHiddenRows:!1};let t=N(e.details);if(t!==void 0&&t.length>te)return{state:{...e,details:{...e.details,lines:t.slice(0,re)}},hasHiddenRows:!0};if(t!==void 0)return{state:e,hasHiddenRows:!1};let r=Math.max(g,n*g*ie),i=e.result.content.map(s=>s.type!=="text"||s.text.length<=r?s:{...s,text:s.text.slice(0,r)}),o=i.some((s,u)=>{let a=e.result.content[u];return s.type==="text"&&a?.type==="text"&&s.text.length<a.text.length});return o?{state:{...e,result:{...e.result,content:i}},hasHiddenRows:o}:{state:e,hasHiddenRows:!1}}d(oe,"compactRenderInput");function se(e,n){let t=N(e.details),r=pe(e.result,t,e.details,!e.expanded);if(e.options.kind==="markdown"||Re(e.details,t,e.options.kind)){let a=new _(r,0,0,Y());return M(a.render(n),e.theme)}if(e.options.kind==="code-view"){let a=t===void 0?h(r).map(l=>O(l,e.theme,!1)):z(t)?ae(t,!e.expanded,e.theme):de(t,e.theme);return M(a,e.theme)}let i=t!==void 0&&z(t),o=t===void 0||i?h(r).map(x):t.map(({content:a})=>x(a)),s=W(e.details,t),u=s===void 0?o.map(a=>e.theme.fg("toolOutput",a)):i?U(t,s,!e.expanded,e.theme):E(o.join(`
2
- `),s);return M(u,e.theme)}d(se,"renderContentRows");function U(e,n,t,r){return e.flatMap(i=>{let o=x(i.content),s=E(o,n)[0]??r.fg("toolOutput",o),u=!1,a=m({source:"",content:i.content,lines:[i]},{compact:t});return h(a).map(l=>{if(!u&&o.length>0){let c=l.indexOf(o);if(c>=0)return u=!0,`${r.fg("toolOutput",l.slice(0,c))}${s}${r.fg("toolOutput",l.slice(c+o.length))}`}return r.fg("toolOutput",l)})})}d(U,"renderHighlightedPresentedLines");function ae(e,n,t){return e.flatMap(r=>{let i=T(r);if(i===void 0){let s=m({source:"",content:r.content,lines:[r]},{compact:n});return h(s).map(u=>O(u,t,!1))}let o=k(i.source);if(o===void 0){let s=m({source:"",content:r.content,lines:[r]},{compact:n});return h(s).map(u=>t.fg("toolOutput",u))}return U([r],o,n,t)})}d(ae,"renderPresentedCodeViewLines");function de(e,n){return e.map(t=>{let r=T(t);if(r===void 0)return O(t.content,n);let i=k(r.source),o=x(F(t.content));return i===void 0?n.fg("toolOutput",o):E(o,i)[0]??n.fg("toolOutput",o)})}d(de,"renderCodeViewLines");function F(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}d(F,"stripScopeMarkers");function O(e,n,t=!0){let r=x(t?F(e):e);return/^#{2,3}\s/u.test(r)?n.fg("mdHeading",n.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?n.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?n.fg("accent",n.bold(r)):/^\s*[-*]\s/u.test(r)?n.fg("mdListBullet",r):n.fg("toolOutput",r)}d(O,"renderCodeViewLabel");function ue(e,n,t,r=!1){if(n||e.length<=g&&!r)return e;let i=e.slice(0,g-1),o=e.length-i.length,s=r?"more rows":`${String(o)} more ${o===1?"row":"rows"}`;return[...i,`${t.fg("dim",`\u2026 ${s} \xB7 `)}${Q("app.tools.expand","to expand")}`]}d(ue,"compactRows");function le(e,n,t){let r=d(s=>t.fg("borderMuted",s),"frame"),i=S(` ${V(e,Math.max(1,n-1))} `,Math.max(0,n-1),""),o="\u2500".repeat(Math.max(0,n-R(i)-1));return`${r("\u256D\u2500")}${i}${r(`${o}\u256E`)}`}d(le,"renderTopBorder");function V(e,n){let t=e.options.label??he(W(e.details,N(e.details))),r=e.details.source??"read result",i=ce(e.details),o=e.theme.fg("accent",e.theme.bold(t)),s=i===void 0?"":e.theme.fg("dim",` \xB7 ${i}`),u=Math.max(1,n-R(o)-R(s)-2),a=xe(r,u);return`${o} ${e.theme.fg("muted",a)}${s}`}d(V,"readTitle");function ce(e){if(!(e.startLine===void 0||e.endLine===void 0||e.totalLines===void 0||e.totalLines<=0))return`${String(e.startLine)}\u2013${String(e.endLine)} / ${String(e.totalLines)}`}d(ce,"sourceRange");function fe(e,n){let t=e.truncation;if(t?.firstLineExceedsLimit===!0)return n.fg("warning","First source line is larger than the saved read limit");if(t?.truncated===!0)return n.fg("warning",`Saved result contains ${String(t.outputLines)} of ${String(t.totalLines)} rendered rows`)}d(fe,"readStatus");function I(e,n,t){let r=Math.max(0,n-2),i=S(e,r),o=` ${i}${" ".repeat(Math.max(0,r-R(i)))} `,s=t.fg("borderMuted","\u2502");return`${s}${o}${s}`}d(I,"framed");function pe(e,n,t,r){if(n!==void 0)return m({source:t.source??"",content:"",lines:n},{compact:r});let i=P(e);return t.truncation===void 0&&!(t.totalLines!==void 0&&t.endLine!==void 0&&t.endLine<t.totalLines)?i:i.replace(/\n\n\[(?:Showing lines|Output truncated|\d+ more lines in source)[\s\S]*\]$/u,"")}d(pe,"cleanText");function z(e){return e.some(n=>n.presentation!==void 0)}d(z,"hasPresentation");function h(e){let n=e.split(/\r\n|\r|\n/u);return n.at(-1)===""&&/(?:\r\n|\r|\n)$/u.test(e)&&n.pop(),n}d(h,"splitTextRows");function P(e){return e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
3
- `)}d(P,"textBlocks");function N(e){return e.lines}d(N,"readLines");function D(e){return typeof e=="object"&&e!==null?e:{}}d(D,"readDetails");function me(e){return e.content.some(n=>n.type==="text")}d(me,"hasTextContent");function W(e,n){let r=n?.map(T).find(i=>i!==void 0)?.source??e.source;return r===void 0?void 0:k(ge(r))}d(W,"languageFor");function Re(e,n,t){return t==="source"&&W(e,n)==="markdown"}d(Re,"isMarkdownSource");function ge(e){try{let n=new URL(e);return n.protocol==="file:"?n.pathname:`${n.pathname}${n.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}d(ge,"normalizeSourcePath");function x(e){let n="";for(let t of e.replaceAll(" "," ".repeat(4))){let r=y(t.codePointAt(0));n+=r<32||r===127?"\uFFFD":t}return n}d(x,"normalizeText");function he(e){return e===void 0?"TEXT":{javascript:"JS",json:"JSON",markdown:"MD",python:"PY",rust:"RS",typescript:"TS"}[e]??e.slice(0,4).toUpperCase()}d(he,"languageLabel");function M(e,n){return e.length===0?[n.fg("dim","Empty content")]:[...e]}d(M,"nonEmptyRows");function xe(e,n){return R(e)<=n?e:n<=1?"\u2026":`\u2026${e.slice(-(n-1))}`}d(xe,"truncateFromStart");export{Te as a,g as b,We as c,je as d};
@@ -1 +0,0 @@
1
- import{e as f,i as p,m}from"./chunk-SQKAXYIR.js";import{a as i}from"./chunk-EI7MMDWY.js";import{Type as r}from"typebox";import{Value as u}from"typebox/value";import{Type as d}from"typebox";var T=d.Object({path:d.Optional(d.String({description:"What to read: a supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# or RESULT# reference, or registered protocol source. Supply a path; an empty call cannot select a source."})),offset:d.Optional(d.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor, SEARCH or RESULT# selections, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:d.Optional(d.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:d.Optional(d.Array(d.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))});import{Type as t}from"typebox";var O=t.Object({value:t.String(),kind:t.String(),state:t.Optional(t.String())},{additionalProperties:!1}),L=t.Object({lineNumber:t.Integer(),content:t.String(),lineEnding:t.String(),anchors:t.Optional(t.Array(t.String()))},{additionalProperties:!1}),k=t.Object({path:t.String(),offset:t.Integer()},{additionalProperties:!1}),y={source:t.String(),truncated:t.Boolean(),continuation:t.Optional(k),fullResult:t.Optional(t.String())},x=t.Object({...y,kind:t.Literal("text"),target:t.Optional(t.String()),lines:t.Array(L),startLine:t.Integer(),endLine:t.Integer(),totalLines:t.Integer(),references:t.Optional(t.Array(O))},{additionalProperties:!1}),b=t.Object({...y,kind:t.Literal("bytes"),bytes:t.Array(t.Integer({minimum:0,maximum:255})),byteOffset:t.Integer(),byteLength:t.Integer(),totalBytes:t.Integer()},{additionalProperties:!1}),C=t.Union([t.Object({type:t.Literal("text"),text:t.String()},{additionalProperties:!1}),t.Object({type:t.Literal("image"),data:t.String(),mimeType:t.String()},{additionalProperties:!1})]),h=t.Object({...y,kind:t.Literal("native"),blocks:t.Array(C)},{additionalProperties:!1}),c=t.Union([t.Object({kind:t.Literal("recovery"),source:t.String(),candidates:t.Array(t.Object({path:t.String()},{additionalProperties:!1}))},{additionalProperties:!1}),x,b,h,t.Object({kind:t.Literal("resources"),source:t.Optional(t.String()),resources:t.Array(t.Union([x,b,h])),truncated:t.Boolean(),fullResult:t.Optional(t.String())},{additionalProperties:!1})]),P=f(c);function w(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}i(w,"publicLine");function S(e){if(e.kind==="resources"){let o=e.resources.map(s=>S(s));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:o,truncated:o.some(s=>typeof s=="object"&&s!==null&&"truncated"in s&&s.truncated===!0)}}if(e.kind==="bytes"){let o=e.bytes.slice(0,32768),s=e.truncated===!0||o.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:o,byteOffset:e.byteOffset,byteLength:o.length,totalBytes:e.totalBytes,truncated:s,...e.byteOffset+o.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+o.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(o=>{if(o.type==="text")return{type:o.type,text:o.text};if(o.type==="image")return{type:o.type,data:o.data,mimeType:o.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let n=[],a=0;for(let o of e.lines){let s=w(o);if(a+=Buffer.byteLength(JSON.stringify(s)),n.length>=2e3||a>512*1024)break;n.push(s)}if(n.length===0&&e.lines.length>0)throw new RangeError("Selected line exceeds the structured window; use a raw byte range or a source-specific view");let R=n.length<e.lines.length,g=n.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,lines:n,startLine:n[0]?.lineNumber??0,endLine:n.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:R,...e.target===void 0?{}:{target:e.target},...e.references===void 0?{}:{references:e.references},...R||g<e.totalLines?{continuation:{path:e.source,offset:g+1}}:{}}}i(S,"publicData");function E(e){let n=e.details.failure;if(e.isError||n!==void 0)return p(e,c,{status:"error",...n?.candidates?.length&&n.source!==void 0?{data:{kind:"recovery",source:n.source,candidates:n.candidates}}:{},errors:[{code:n?.code??"READ_FAILED",message:n?.message??"Read failed",...n?.source===void 0?{}:{source:n.source}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let a=S(e.script);return p(e,c,{status:"success",data:e.details.temporarySource!==void 0&&typeof a=="object"&&a!==null?{...a,fullResult:e.details.temporarySource}:a,errors:[]})}catch(a){return p(e,c,{status:"error",errors:[{code:a instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:a instanceof Error?a.message:String(a)}]})}}i(E,"structuredRead");var l=r.Function([],r.Unknown()),v=r.Object({resolver:r.Unknown(),matchesCall:r.Optional(l),renderCall:r.Optional(l),priority:r.Optional(r.Number()),renderResult:r.Optional(l),preserveTruncatedOutput:r.Optional(r.Boolean())}),D=r.Object({resolver:r.Unknown(),priority:r.Optional(r.Number())}),A=r.Object({id:r.String({pattern:"\\S"}),priority:r.Optional(r.Number()),resolve:l}),N=r.Object({view:r.String({pattern:"\\S"}),includes:r.Optional(r.Array(r.String({pattern:"\\S"}))),presenter:r.Object({id:r.String(),present:l}),priority:r.Optional(r.Number())}),F=r.Object({resolvedBy:r.String({pattern:"\\S"}),contentKind:r.Union([r.Literal("text"),r.Literal("any")])}),U=r.Union([r.Object({stage:r.Literal("pre-read"),handler:l}),r.Object({stage:r.Literal("read"),when:F,handler:l}),r.Object({stage:r.Literal("post-read"),handler:l})]);function W(e){if(!u.Check(D,e))return!1;let n=e,a=n.resolver;return typeof a.id=="string"&&a.id.length>0&&typeof a.tryResolve=="function"&&(!("priority"in n)||typeof n.priority=="number")}i(W,"isTextTargetResolverRegistration");function M(e){if(!u.Check(v,e))return!1;let n=e;return m(n.resolver)?n.resolver.id!=="any"&&(!("priority"in n)||typeof n.priority=="number")&&(!("matchesCall"in n)||typeof n.matchesCall=="function")&&(!("renderCall"in n)||typeof n.renderCall=="function")&&"matchesCall"in n=="renderCall"in n&&(!("renderResult"in n)||typeof n.renderResult=="function"):!1}i(M,"isResourceResolverRegistration");function Q(e){return u.Check(U,e)}i(Q,"isReadHandlerRegistration");function J(e){return u.Check(N,e)}i(J,"isReadViewRegistration");function Y(e){return u.Check(A,e)}i(Y,"isFragmentResolverRegistration");function X(e){return I(e)?e.kind==="not-handled"?!0:e.kind==="failed"?typeof e.message=="string"&&e.message.length>0:e.kind==="resolved"&&typeof e.originLine=="number":!1}i(X,"isReadFragmentResolution");function I(e){return typeof e=="object"&&e!==null}i(I,"isRecord");export{T as a,c as b,P as c,E as d,W as e,M as f,Q as g,J as h,Y as i,X as j};
@@ -1,7 +0,0 @@
1
- import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";var f=class i{static{s(this,"FileRange")}start;end;constructor(e,t=e){t.lineNumber<e.lineNumber&&([e,t]=[t,e]),this.start=e,this.end=t}static fromLines(e,t){let r=t??e;return new i({lineNumber:e},{lineNumber:r})}},l=class i{static{s(this,"FileMutationResult")}data;constructor(e){this.data=e??{}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,t=e?.[0];if(t?.range){let r=t.range.start,a=d(e).at(-1)?.range?.end??r;return new f(r,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let t of this.files)e.add(t.path);for(let t of this.errors)t.path&&e.add(t.path);for(let t of this.warnings)t.file&&e.add(t.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let n=this.errors[0];return n?`Failed: ${n.code??"ERROR"}${n.reason?` \u2014 ${n.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let n=this.appliedPaths;return n&&n.length>0?`${n.length} path${n.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,t=this.overwrittenFiles.length,r=[];if(e>0&&r.push(`Created ${e} ${e===1?"file":"files"}`),t>0&&r.push(`Edited ${t} ${t===1?"file":"files"}`),this.diffs.length>0){let n=0,a=0;for(let o of this.diffs)for(let u of o.split(`
2
- `))u.startsWith("+")&&!u.startsWith("+++")?n++:u.startsWith("-")&&!u.startsWith("---")&&a++;(n>0||a>0)&&r.push(`+${n}/-${a} lines`)}return r.join(", ")}getFileChange(e){return this.files.find(t=>t.path===e)}getDiffFor(e){let t=g(e);for(let r of this.diffs){let n=r.match(/^---\s+(.+)$/m);if(n&&(g(d(n[1]))===t||n[1]===e))return r}}getErrorsFor(e){return this.errors.filter(t=>t.path===e)}getWarningsFor(e){return this.warnings.filter(t=>t.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let t=e;return t.data&&typeof t.data=="object"?(Object.setPrototypeOf(t,i.prototype),t):new i(t)}return new i}};function g(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(g,"normalisePath");import{createTwoFilesPatch as p,diffLines as c}from"diff";function D(i,e,t,r=i){return{diff:p(i,r,e,t,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:m(e,t)}}s(D,"createUnifiedDiff");function m(i,e){let t=0,r=0;for(let n of c(i,e)){let a=h(n.value);n.removed&&(t+=a),n.added&&(r+=a)}return{removed:t,added:r}}s(m,"computeStats");function h(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
3
- `,`
4
- `);return e.endsWith(`
5
- `)?e.slice(0,-1).split(`
6
- `).length:e.split(`
7
- `).length}s(h,"countDiffLines");function y(i,e){let t=c(i,e),r=[],n=0;for(let a of t){let o=h(a.value);o!==0&&(a.removed||(a.added&&r.push({start:n+1,end:n+o}),n+=o))}return E(r)}s(y,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,n)=>r.start-n.start),t=[d(e[0])];for(let r=1;r<e.length;r++){let n=d(t.at(-1)),a=d(e[r]);a.start<=n.end+1?n.end=Math.max(n.end,a.end):t.push(a)}return t}s(E,"mergeAdjacentRanges");export{f as a,l as b,D as c,y as d};
@@ -1 +0,0 @@
1
- import{F as d,e as c}from"./chunk-SQKAXYIR.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var y=t.Object({query:t.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:t.Optional({...d,description:"File, directory, URL, or a source-aware Read/Search/Select/mutation result with a live target, RESULT# reference, or array of returned targets. Result scopes search only their exact ranges unless symbols: navigation explicitly follows external references; plain preview text is not a source."}),navigation:t.Optional(t.Literal("references",{description:"Only for symbols: queries. Explicitly follow symbols represented inside path to their references outside that scope. Without navigation, all returned ranges stay inside path."})),include:t.Optional(t.String({description:"Optional include glob for local search"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local search"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum detailed results returned to the agent (default 50)"}))},{additionalProperties:!1});import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},h=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),O=e.Union([e.Object({...g,fuzzy:e.Optional(h)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),T=c(O);function P(o,l,n,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((r,a)=>({source:r.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:r.lineNumber,startColumn:r.startColumn,endLine:r.endLineNumber??r.lineNumber,endColumn:r.endColumn},...Buffer.byteLength(r.matchedText)<=4096?{matchedText:r.matchedText}:{textTruncated:!0},...n===void 0?{}:{references:{line:`SEARCH#${n}:${a+1}:line`,match:`SEARCH#${n}:${a+1}:match`}}})),...l&&n!==void 0?{all:{line:`SEARCH#${n}:all:line`,match:`SEARCH#${n}:all:match`}}:{}}}s(P,"selectionData");export{y as a,h as b,O as c,T as d,P as e};
@@ -1,2 +0,0 @@
1
- import{e as E,f as b}from"./chunk-T7I2VX3J.js";import{d as M}from"./chunk-KR36BT5E.js";import"./chunk-FXNKMNSJ.js";import"./chunk-NNCZYO4Q.js";import{d as q}from"./chunk-64M3SQPG.js";import{a as T}from"./chunk-6CZO43OH.js";import{a as N,b as O}from"./chunk-OBNING2A.js";import"./chunk-PS2B6THP.js";import"./chunk-SQKAXYIR.js";import{e as h,f as w,g as P,h as k,i as y,l as I}from"./chunk-KVHDMIZS.js";import"./chunk-ZPT5D4VP.js";import{a as A}from"./chunk-QDLTO5PH.js";import{a as v,b as C}from"./chunk-QIK2E64R.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import H from"node:path";var S="diagnostics",L=q({kind:"code-view",label:"Diagnostics"});async function V(r){b(r,[await E({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"),i={protocol:v,apiVersion:4,id:"diagnostics",setup(c){n=c.readDiagnostics}},o=new WeakMap,s=new WeakMap,a=new WeakMap,u=new WeakMap,W={protocol:N,apiVersion:O,id:"diagnostics",setup(c){c.addResolver({resolver:j(t,s),renderResult:L});let f=I();c.addView({view:"diagnostics",priority:100,presenter:B(t,u)}),c.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let p=e.state.content[0],g=s.get(p);return g&&o.set(e.request,g),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 p=o.get(e.request);if(p&&e.result)return{kind:"continue",context:e,transform:l(d=>({...d,details:{...d.details,diagnosticCheck:p}}),"transform")};let g=a.get(e.request),m=g&&u.get(g),D=e.result,_=D?.content[0];return!m||!D||_?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:e,transform(d){let R=d.content[0];return R?.type!=="text"?d:{...d,content:[{...R,text:`${m}
2
- ${R.text}`},...d.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([A(r,i),T(r,W)])}l(V,"registerDiagnostics");function j(r,n){return{id:"diagnostics",tryResolve(t,i){return Promise.resolve(x(t,i.cwd,r,n,{signal:i.signal,...i.audience==="script"&&{mode:"complete"}}))}}}l(j,"createDiagnosticResolver");function x(r,n,t,i,o){let s;try{s=h(r,S,n)}catch(a){return{kind:"failed",error:a}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:w(S,s),async read(){let a=await t(s,n,o),u=P(s,a.content,a.results);return i.set(u,u.diagnosticCheck),[u]}}}}l(x,"resolveDiagnosticSource");function B(r,n){return{id:"diagnostics",async present(t,i){if(i.purpose!=="read"||!H.isAbsolute(t.source))return t;let o=i.audience==="script"&&!i.requestedViews?.includes("diagnostics");if(o&&M(t.source))return t;let s=await r(t.source,i.cwd,{signal:i.signal,...i.audience==="script"&&{mode:o?"snapshot":"complete"}}).catch(a=>{if(i.signal?.throwIfAborted(),!o)throw a});if(s===void 0||o&&s.content!==t.content)return t;if(s.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,y(s.results)),k(t,s.results)}}}l(B,"createDiagnosticPresenter");export{V as default};
@@ -1 +0,0 @@
1
- import{a as x,e as y,k as E}from"./chunk-FXNKMNSJ.js";import{a as g,c as m}from"./chunk-SQKAXYIR.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as T}from"node:async_hooks";var u=new T,f=new T;function S(t){let e=f.getStore();e?e.push(t):t()}o(S,"afterPostEditScope");async function R(t){if(f.getStore())return t();let e=[];try{return await f.run(e,t)}finally{for(let r of e)r()}}o(R,"collectPostEditNotifications");function A(t,e){let r=u.getStore();return r?(r.set(t,e),!0):!1}o(A,"deferPostEdit");function v(t){return u.getStore()?.has(t)??!1}o(v,"hasDeferredPostEdit");function H(t){u.getStore()?.delete(t)}o(H,"forgetDeferredPostEdit");function j(t=process.cwd()){let e=new Map;return{run(r){return u.run(e,r)},forget(r){e.delete(r)},sources(){return[...e.keys()]},async finish(r){let c=[...e];e.clear();let a=[],i=[];if(await R(async()=>{let s=new g,P=await Promise.allSettled(c.map(([d,p])=>s.run(m(d,t,"write"),p)));for(let d of P){if(d.status==="rejected"){i.push(d.reason);continue}a.push(d.value);try{r?.(d.value)}catch(p){i.push(p)}}}),i.length>0)throw new AggregateError(i,`Some final post-processing failed; completed edits remain applied. ${i.map(s=>s instanceof Error?s.message:String(s)).join("; ")}`);return a}}}o(j,"createPostEditScope");import{Type as n}from"typebox";import{Value as l}from"typebox/value";var b=`${x}/post-edit/register`;function L(t){return l.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(L,"isFormattingContribution");function z(t){return l.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(z,"isDiffStatusContribution");var h=n.Function([],n.Unknown()),w=n.Object({id:n.String({minLength:1}),handler:h}),k=n.Object({registration:w,accept:h});function C(t){return l.Check(w,t)}o(C,"isTextPostEditHandlerRegistration");function N(t){return l.Check(k,t)}o(N,"isTextPostEditHandlerRegistrationRequest");function U(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(U,"isTextMutationResultContributionData");function V(t,e){if(!C(e))throw new TypeError("Invalid text editor post-edit handler registration");let r,c=o(()=>{let i={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(b,i),r!==void 0},"announce"),a=o(()=>{},"unsubscribeReady");a=t.events.on(y,i=>{if(!E(i))throw new Error("Invalid pi-agent-text-editor core readiness event");if(!c())throw new Error("pi-agent-text-editor core announced readiness without accepting the post-edit handler");a()}),t.on("session_shutdown",()=>{a(),r?.()}),c()&&a()}o(V,"connectTextEditorPostEditHandler");export{S as a,R as b,A as c,v as d,H as e,j as f,b as g,L as h,z as i,C as j,N as k,U as l,V as m};
@@ -1,3 +0,0 @@
1
- import{a as n}from"./chunk-EI7MMDWY.js";function o(e,t){let r=e.context===void 0?"":`
2
-
3
- ${e.context}`;return`[SYSTEM] ${e.toolName} blocked: ${e.field} anchor "${e.anchor}" is stale. If the required line is represented by one of the context lines below, use that anchor. Otherwise, reread only the relevant section of "${e.path}" and regenerate the anchor. (${t})${r}`}n(o,"formatStaleAnchorMessage");export{o as a};
@@ -1,5 +0,0 @@
1
- import{a as z}from"./chunk-M5IVSCR2.js";import{e as V,f as q}from"./chunk-T7I2VX3J.js";import{a as O}from"./chunk-6CZO43OH.js";import{a as k,b as T}from"./chunk-OBNING2A.js";import{a as _}from"./chunk-ZTYWHL2F.js";import{a as L,b as W}from"./chunk-7UGNGK7Y.js";import{a as U}from"./chunk-PS2B6THP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{execFile as te}from"node:child_process";import re from"node:os";import{promisify as oe}from"node:util";import{createCanvas as B,loadImage as se}from"@napi-rs/canvas";var w=oe(te),I=20*1024*1024,H={durationSeconds:2,intervalSeconds:.5,scale:.5},j=new Set;function G(e){let n=R({mode:"sequence",durationSeconds:Number(e.durationSeconds??2),intervalSeconds:Number(e.intervalSeconds??.5),scale:Number(e.scale??.5)});H={durationSeconds:n.durationSeconds,intervalSeconds:n.intervalSeconds,scale:n.scale},j=new Set((e.allowedExecutables??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}c(G,"configureVision");function y(){return H}c(y,"getVisionDefaults");function J(e){let n=e.includes("\\")?e.slice(e.lastIndexOf("\\")+1):e,r=n.trim().split(/\s+/u)[0]??"",t=r.slice(r.lastIndexOf("/")+1);return j.has((e.includes("\\")?n:t).toLowerCase())}c(J,"isExecutableAllowed");function X(e,n){let r=e?.filter(s=>/^(?:image|sequence)(?::|$)/u.test(s))??[];if(r.length===0)return;if(r.length>1)throw new Error("Use only one image or sequence view");let t=r[0],i=t.indexOf(":"),a=t.slice(0,i<0?void 0:i),o={};if(i>=0&&ie(t.slice(i+1),o),a==="image"&&(o.duration!==void 0||o.interval!==void 0))throw new Error("duration and interval are supported only by the sequence view");return R({mode:a,durationSeconds:o.duration??n.durationSeconds,intervalSeconds:o.interval??n.intervalSeconds,scale:o.scale??n.scale,...o.region===void 0?{}:{region:o.region}})}c(X,"parseVisionView");function ie(e,n){if(e.length===0)throw new Error("View parameters cannot be empty");let r=e.split(",");for(let t=0;t<r.length;t+=1){let i=r[t],a=i.indexOf("=");if(a<=0)throw new Error(`Invalid view parameter ${i}`);let o=i.slice(0,a),s=i.slice(a+1);if(o==="region"){let u=[s,r[t+1],r[t+2],r[t+3]].map(Number);if(u.some(m=>!Number.isFinite(m)))throw new Error("region requires x,y,width,height values");n.region={x:u[0],y:u[1],width:u[2],height:u[3]},t+=3;continue}if(o!=="duration"&&o!=="interval"&&o!=="scale")throw new Error(`Unknown view parameter ${o}`);let d=Number(s);if(!Number.isFinite(d))throw new Error(`View parameter ${o} must be a number`);if(n[o]!==void 0)throw new Error(`Duplicate view parameter ${o}`);n[o]=d}}c(ie,"parseViewParameters");function Y(e){if(!e.startsWith("display:"))return;if(e==="display:")return 0;let n=/^display:#(\d+)$/u.exec(e);if(n===null)throw new Error("Display sources use display: or display:#N with a zero-based index");let r=Number(n[1]);if(!Number.isSafeInteger(r))throw new Error("Display sources use display: or display:#N with a zero-based index");return r}c(Y,"parseDisplaySource");async function E(e){let n=new Map(e.list().flatMap(i=>i.pid===void 0?[]:[[i.pid,i]]));if(process.platform!=="linux"&&process.platform!=="darwin")return[...n].map(([i,a])=>({pid:i,command:a.description,owned:!0,source:a.source,host:"local"}));let{stdout:r}=await w("ps",["-eo","pid=,ppid=,lstart=,args="],{maxBuffer:4*1024*1024}),t=r.split(`
2
- `).flatMap(i=>{let a=/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/u.exec(i);if(a===null)return[];let o=Number(a[1]),s=n.get(o);return[{pid:o,parentPid:Number(a[2]),started:a[3],command:a[4]??"",owned:s!==void 0,host:"local",...s===void 0?{}:{source:s.source}}]});return S()?[...t,...await ae()]:t}c(E,"listProcesses");async function ae(){try{let{stdout:e}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command","Get-Process | Select-Object Id,ProcessName,Path,StartTime | ConvertTo-Json -Compress"],{maxBuffer:4194304}),n=JSON.parse(e);return(Array.isArray(n)?n:[n]).flatMap(t=>{if(typeof t!="object"||t===null||!("Id"in t)||typeof t.Id!="number")return[];let i="ProcessName"in t&&typeof t.ProcessName=="string"?t.ProcessName:"Windows process",a="Path"in t&&typeof t.Path=="string"?t.Path:void 0,o="StartTime"in t&&typeof t.StartTime=="string"?t.StartTime:void 0;return[{pid:t.Id,command:a??i,owned:!1,host:"windows",...o===void 0?{}:{started:o}}]})}catch{return[]}}c(ae,"listWindowsProcesses");async function A(e,n){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Process PID must be a positive integer");let r=(await E(n)).find(t=>t.pid===e);if(r===void 0)throw new Error(`Process ${e} is not running`);return r}c(A,"readProcess");function R(e){let n=e.scale??1;if(!(n>0&&n<=1))throw new Error("Image scale must be greater than 0 and at most 1");let r=e.durationSeconds??0,t=e.intervalSeconds??1;if(e.mode==="sequence"){if(!(r>0&&r<=10))throw new Error("Sequence duration must be greater than 0 and at most 10 seconds");if(!(t>0))throw new Error("Sequence interval must be greater than 0 seconds");if(Math.floor(r/t)+1>20)throw new Error("Sequence capture is limited to 20 frames")}if(e.region!==void 0){let{x:i,y:a,width:o,height:s}=e.region;if(i<0||a<0||o<=0||s<=0||i+o>1||a+s>1)throw new Error("Image region x,y,width,height must fit within normalized bounds 0..1")}if(e.cellIndex!==void 0&&e.cellSize===void 0)throw new Error("Image offset requires limit to set the square grid cell size");if(e.cellSize!==void 0&&(!Number.isSafeInteger(e.cellSize)||e.cellSize<=0))throw new Error("Image limit must be a positive integer pixel size");if(e.cellIndex!==void 0&&(!Number.isSafeInteger(e.cellIndex)||e.cellIndex<0))throw new Error("Image offset must be a zero-based cell index");return e}c(R,"validateVisionOptions");async function b(e,n,r){let t=R(n),i=t.mode==="image"?1:Math.floor(t.durationSeconds/t.intervalSeconds)+1,a=[],o=0;for(let s=0;s<i;s+=1){r?.throwIfAborted(),s>0&&await pe(t.intervalSeconds*1e3,r);let d=await e();if(o+=d.byteLength,o>I)throw new Error("Captured images exceed the 20MB aggregate limit");for(let u of await ce(d,t))a.push({type:"image",data:Buffer.from(u).toString("base64"),mimeType:"image/png"})}return a}c(b,"captureImages");async function ce(e,n){let r=await se(e),t=n.region??{x:0,y:0,width:1,height:1},i=Math.round(t.x*r.width),a=Math.round(t.y*r.height),o=Math.max(1,Math.round(t.width*r.width)),s=Math.max(1,Math.round(t.height*r.height)),d=n.scale??1,u=Math.max(1,Math.round(o*d)),m=Math.max(1,Math.round(s*d)),f=B(u,m);if(f.getContext("2d").drawImage(r,i,a,o,s,0,0,u,m),n.cellSize===void 0)return[await f.encode("png")];let l=Math.ceil(u/n.cellSize),p=Math.ceil(m/n.cellSize),h=n.cellIndex??0;if(h>=l*p)throw new Error(`Image cell offset ${h} exceeds the ${l}x${p} grid`);let ee=h%l,ne=Math.floor(h/l),C=ee*n.cellSize,M=ne*n.cellSize,P=Math.min(n.cellSize,u-C),x=Math.min(n.cellSize,m-M),$=B(P,x);return $.getContext("2d").drawImage(f,C,M,P,x,0,0,P,x),[await $.encode("png")]}c(ce,"selectImage");function de(e,n){return e&&n==="windows"}c(de,"usesWindowsHostWindowCapture");function K(){return{async captureWindow(e,n,r){if(r?.throwIfAborted(),de(S(),n))return ue(e,r);if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Window capture is unsupported on ${process.platform}`);let{Window:t}=await import("node-screenshots"),i;try{i=t.all()}catch(s){throw new Error(`Desktop window enumeration is unavailable: ${F(s)}`,{cause:s})}let a=i.find(s=>{try{return s.pid()===e}catch{return!1}});if(a===void 0)throw new Error(`No capturable desktop window belongs to PID ${e}`);let o=await a.captureImage();return r?.throwIfAborted(),new Uint8Array(await o.toPng())},async captureDisplay(e,n){if(n?.throwIfAborted(),S())return le(e,n);if(process.platform!=="linux"&&process.platform!=="darwin"&&process.platform!=="win32")throw new Error(`Display capture is unsupported on ${process.platform}`);let{Monitor:r}=await import("node-screenshots"),t;try{t=r.all()}catch(o){throw new Error(`Desktop display enumeration is unavailable: ${F(o)}`,{cause:o})}let i=t[e];if(i===void 0)throw new Error(`Display index ${e} is unavailable; found ${t.length} display(s)`);let a=await i.captureImage();return n?.throwIfAborted(),new Uint8Array(await a.toPng())},async captureUrl(e,n){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Web screenshots require an HTTP(S) URL");let{chromium:r}=await import("playwright-core"),t=await me(),i=await r.launch({executablePath:t,headless:!0,chromiumSandbox:!1,timeout:3e4}),a=c(()=>{i.close()},"abort");n?.addEventListener("abort",a,{once:!0});try{let o=await i.newPage({viewport:{width:1280,height:720}});return await o.goto(e.href,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle",{timeout:1500}).catch(()=>{}),n?.throwIfAborted(),new Uint8Array(await o.screenshot({type:"png",fullPage:!0}))}finally{n?.removeEventListener("abort",a),await i.close().catch(()=>{})}}}}c(K,"createCaptureBackend");async function ue(e,n){let r=new URL("windows-window-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await w("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-ProcessId",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(ue,"captureWslWindow");async function le(e,n){let r=new URL("windows-display-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await w("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-DisplayIndex",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(le,"captureWslDisplay");function S(){return process.platform==="linux"&&(process.env.WSL_DISTRO_NAME!==void 0||re.release().toLowerCase().includes("microsoft"))}c(S,"isWsl");async function me(){let e=process.env.PI_AGENT_IDE_BROWSER_PATH;if(e!==void 0)return e;let{stdout:n}=await w("bash",["-lc","command -v google-chrome-stable || command -v google-chrome || command -v chromium || command -v chromium-browser"]),r=n.trim();if(r.length===0)throw new Error("No Chrome or Chromium executable was found; set PI_AGENT_IDE_BROWSER_PATH");return r}c(me,"resolveBrowser");function pe(e,n){return new Promise((r,t)=>{let i=setTimeout(r,e),a=c(()=>{clearTimeout(i),t(n?.reason??new Error("Capture aborted"))},"abort");n?.addEventListener("abort",a,{once:!0}),i.unref()})}c(pe,"delay");function F(e){return e instanceof Error?e.message:String(e)}c(F,"errorMessage");async function fe(e,n){q(e,[await V({id:"vision",description:"Window, display, image, and sequence capture",triggers:[{tool:"read",resourcePrefixes:["window:","display:"]}]})]);let r=n?.preferences??{};G({durationSeconds:r["vision.sequenceDurationSeconds"],intervalSeconds:r["vision.sequenceIntervalSeconds"],scale:r["vision.imageScale"],allowedExecutables:r["vision.allowedExecutables"]});let t=z(e),i=K();await Promise.all([O(e,{protocol:k,apiVersion:T,id:"vision",setup(a){for(let s of["image","sequence"])a.addView({view:s,presenter:{id:`vision-${s}`,present:c(d=>d,"present")}});a.addHandler({stage:"pre-read",async handler(s){let d=s.request.path;if(d===void 0)return{kind:"continue",context:s};let u=Y(d);if(u!==void 0){if(e.getFlag("pi-agent-ide-vision-displays")!==!0)return g(d,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");try{let l=await b(()=>i.captureDisplay(u,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(d,l)}catch(l){return g(d,N(l))}}let m=Q(d,"process:");if(m!==void 0){let l=await A(m,t);return v(d,[{type:"text",text:Z(l)}])}let f=Q(d,"window:");if(f!==void 0){let l=await A(f,t);if(!l.owned&&!J(l.command)&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)return g(d,`Window capture for PID ${f} is denied because the process is neither Agent IDE-owned nor allowlisted by executable name. Enable --pi-agent-ide-vision-arbitrary-windows to allow it.`);try{let p=await b(()=>i.captureWindow(f,l.host,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(d,p)}catch(p){return g(d,N(p))}}if(/^https?:\/\//iu.test(d)&&we(s.request)){let l=new URL(d);try{let p=await b(()=>i.captureUrl(l,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(l.href,p)}catch(p){return g(l.href,N(p))}}return{kind:"continue",context:s}}});let o=y();a.describe(`Process metadata: process:PID. Visual capture: window:PID and display: or display:#N. HTTP(S) sources accept image and sequence screenshots. Use named view parameters such as sequence:duration=2,interval=0.5,scale=0.5 and image:scale=0.5,region=0.25,0.25,0.5,0.5. Duration is limited to 10 seconds and sequences to 20 frames. Defaults: duration=${o.durationSeconds}, interval=${o.intervalSeconds}, scale=${o.scale}. Region uses normalized x,y,width,height and runs before scaling. For captures, limit is a square grid cell size in output pixels and offset is one zero-based row-major cell index; limit without offset selects cell 0, while offset without limit is invalid. Omit both for the bounded transformed image.`)}}),_(e,{protocol:L,apiVersion:W,id:"vision-processes",setup(a){a.addResolver({priority:-100,resolver:{id:"processes",readResources:c(o=>/^process:/iu.test(o.query)?void 0:[],"readResources"),toScriptData(o){return{kind:"custom",resolverId:"processes",value:{processes:o.map(d=>({pid:d.pid,command:d.command}))}}},async tryResolve(o){let s=/^process:(.*)$/isu.exec(o.query);if(s===null)return{kind:"not-handled"};let d=(s[1]??"").trim().toLowerCase();return{kind:"resolved",payload:(await E(t)).filter(m=>d.length===0||String(m.pid)===d||m.command.toLowerCase().includes(d)).slice(0,Math.min(o.limit??50,100))}},renderResult(o,s,d){let u=o.details;return new U({summary:`${u.processes.length} processes shown`,rows:u.processes.length?u.processes.map(m=>({kind:"note",text:`${m.pid} ${m.command}`})):[{kind:"note",text:"No matching processes"}]},d,s.expanded)},format(o){let s=o;return{content:[{type:"text",text:s.length===0?"No matching processes.":s.map(Z).join(`
3
-
4
- `)}],details:{count:s.length,processes:s}}}}}),a.describe("process:<query> finds running processes by PID or command for process:PID metadata reads and guarded window:PID capture.")}})])}c(fe,"registerVision");function Q(e,n){if(!e.startsWith(n))return;let r=e.slice(n.length);if(!/^\d+$/u.test(r))throw new Error(`${n} sources require a numeric PID`);return Number(r)}c(Q,"prefixedPid");function D(e){return{...X(e.views,y())??{mode:"image",...y()},...e.limit===void 0?{}:{cellSize:e.limit},...e.offset===void 0?{}:{cellIndex:e.offset}}}c(D,"options");function we(e){return e.views?.some(n=>/^(?:image|sequence)(?::|$)/u.test(n))===!0}c(we,"requestsScreenshot");function v(e,n){return{kind:"return",result:{content:n,script:{kind:"native",source:e,blocks:n},details:{source:e,resolvedBy:"vision"}}}}c(v,"returned");function g(e,n){return{kind:"return",result:{content:[{type:"text",text:n}],details:{source:e,resolvedBy:"vision",failure:{code:"READ_FAILED",source:e,resolverId:"vision",message:n}},isError:!0}}}c(g,"failed");function N(e){return e instanceof Error?e.message:String(e)}c(N,"errorMessage");function Z(e){return[`PID: ${e.pid}`,`Command: ${e.command}`,`Owned by Agent IDE: ${e.owned?"yes":"no"}`,...e.parentPid===void 0?[]:[`Parent PID: ${e.parentPid}`],...e.started===void 0?[]:[`Started: ${e.started}`],...e.source===void 0?[]:[`Agent IDE source: ${e.source}`]].join(`
5
- `)}c(Z,"formatProcess");export{fe as default};
@@ -1,9 +0,0 @@
1
- import"./chunk-MPT3R4BL.js";import{a as y,b as A,c as D,d as k}from"./chunk-T7I2VX3J.js";import{a as I}from"./chunk-6CZO43OH.js";import{a as E,b as P}from"./chunk-OBNING2A.js";import{a}from"./chunk-EI7MMDWY.js";var N=/^[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 r of n)_(r,o),o.add(r.id);for(let r of n)this.#e.set(r.id,b(r))}list(){return[...this.#e.values()].sort((n,o)=>n.id.localeCompare(o.id))}get(n){return this.#e.get(n)}matching(n,o){let r=v(o);return r?.startsWith("docs:")===!0?[]:this.list().filter(s=>s.triggers.some(d=>{if(d.tool!==n)return!1;let l=d.resourcePrefixes===void 0||r!==void 0&&d.resourcePrefixes.some(i=>r.startsWith(i)),t=d.viewPrefixes===void 0||T(o).some(i=>d.viewPrefixes?.some(u=>i.startsWith(u)));return l&&t}))}};function _(e,n){if(!N.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(r=>r.length===0)===!0||o.viewPrefixes?.some(r=>r.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(_,"validateDocument");function b(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(b,"freezeDocument");function T(e){if(typeof e!="object"||e===null)return[];let n=e.views;return Array.isArray(n)?n.filter(o=>typeof o=="string"):[]}a(T,"readViews");function v(e){if(typeof e!="object"||e===null)return;let n=e.path;return typeof n=="string"?n:void 0}a(v,"readPath");var R="agent-documentation-read";async function M(e){let n=new h,o=new Set,r=new Map,s=new Map,d=a(t=>{let i=t.filter(u=>!o.has(u));if(i.length!==0){e.appendEntry(R,{ids:i});for(let u of i)o.add(u)}},"remember"),l=e.events.on(k,t=>{if(!z(t))throw new Error("Invalid agent documentation registration");n.register(t.documents)});e.on("session_shutdown",l),await I(e,{protocol:E,apiVersion:P,id:"agent-documentation",setup(t){t.addResolver({resolver:{id:"agent-documentation",tryResolve(i){if(!i.startsWith("docs:"))return Promise.resolve({kind:"not-handled"});let u=i.slice(5),m=u.length===0?void 0:n.get(u),g=u.length===0?$(n.list()):m?.markdown;return g===void 0?Promise.resolve({kind:"failed",error:new Error(`Unknown documentation ID: ${u}`)}):Promise.resolve({kind:"resolved",resource:{source:i,read:a(()=>Promise.resolve([{type:"text",text:g}]),"read")}})}}}),t.describe(()=>n.list().length===0?void 0:"docs: and docs:<id> \u2014 list or read packaged agent guidance."),t.addPromptGuideline(()=>j(n.list()))}}),e.on("session_start",(t,i)=>{w(i.sessionManager.getBranch(),n,o)}),e.on("session_tree",(t,i)=>{w(i.sessionManager.getBranch(),n,o)}),e.on("session_compact",(t,i)=>{w(i.sessionManager.getBranch(),n,o)}),e.on("tool_call",t=>{t.toolCallId.includes("-preflight-")||t.parentToolCallId!==void 0&&r.set(t.toolCallId,t.parentToolCallId)}),e.on("tool_result",t=>{if(t.toolCallId.includes("-preflight-"))return;let i=r.get(t.toolCallId);r.delete(t.toolCallId);let u=s.get(t.toolCallId)??[];s.delete(t.toolCallId);let m=t.toolName==="read"?S(t.input):void 0;if(m!==void 0){let c=m.slice(5),C=c.length===0||n.get(c)!==void 0,p=n.get(c);return p!==void 0&&!t.isError&&O(t.content,p)&&d([c]),{content:t.content,structuredContent:t.structuredContent,details:{...f(t.details)?t.details:{},documentation:C?c.length===0?{kind:"list",ids:n.list().map(x=>x.id)}:{kind:"document",id:c}:{kind:"error",code:"UNKNOWN_DOCUMENTATION",id:c}},isError:t.isError}}let g=[...u,...n.matching(t.toolName,t.input).filter(c=>!o.has(c.id))];if(g.length!==0)return d(g.map(c=>c.id)),i!==void 0&&t.structuredContent!==void 0&&s.set(i,[...s.get(i)??[],...g]),{content:[...t.content,...g.map(c=>({type:"text",text:`
2
-
3
- ---
4
-
5
- # Guide: ${c.id}
6
-
7
- ${c.markdown.trim()}`}))],structuredContent:t.structuredContent,details:{...f(t.details)?t.details:{},documentation:{kind:"attachment",ids:g.map(c=>c.id)}},isError:t.isError}}),e.events.emit(D,{protocol:y,apiVersion:A})}a(M,"registerProgressiveDocumentation");function $(e){return e.length===0?"No agent documentation is currently available.":["# Available agent documentation","",...e.map(n=>`- \`${n.id}\` \u2014 ${n.description}`)].join(`
8
- `)}a($,"renderListing");function j(e){if(e.length!==0)return["Read the matching docs:<id> before using any tool or feature with packaged guidance, including tools discovered later or called through Codemode. Read each guide once per branch. Tool descriptions and docs: listings do not replace the full guide.","If a result includes a Guide, read it before your next use. The call has already run: do not repeat it just to obtain documentation. Native structured child calls keep their guides on the parent result. Output readable-only child results to retain their guides; filtering those results can hide them.","Available documents:",...e.map(n=>` - ${n.id} \u2014 ${n.description}`)].join(`
9
- `)}a(j,"renderPromptGuideline");function w(e,n,o){o.clear();for(let s of e){if(!f(s))continue;if(s.type==="custom"&&s.customType===R&&f(s.data)){r(s.data.ids);continue}if(s.type!=="message"||!f(s.message))continue;let d=s.message;if(d.role!=="toolResult"||!f(d.details))continue;let l=d.details.documentation;if(f(l)&&(l.kind==="attachment"&&r(l.ids),l.kind==="document"&&!d.isError&&typeof l.id=="string")){let t=n.get(l.id);t!==void 0&&O(d.content,t)&&r([t.id])}}function r(s){if(Array.isArray(s))for(let d of s)typeof d=="string"&&n.get(d)!==void 0&&o.add(d)}a(r,"addIds")}a(w,"restoreClaims");function O(e,n){return Array.isArray(e)&&e.some(o=>f(o)&&o.type==="text"&&typeof o.text=="string"&&o.text.includes(n.markdown.trim()))}a(O,"containsFullGuide");function S(e){if(!(!f(e)||typeof e.path!="string"||!e.path.startsWith("docs:")))return e.path}a(S,"documentationSource");function z(e){return f(e)&&Array.isArray(e.documents)}a(z,"isRegistrationRequest");function f(e){return typeof e=="object"&&e!==null}a(f,"isRecord");export{M as default};
@@ -1,2 +0,0 @@
1
- import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as ye}from"node:async_hooks";function re(){return{pending:new Set,active:new ye}}i(re,"createSchedulerState");function Ce(t,e){return t===void 0||e===void 0?!0:t.some(r=>e.some(n=>(r.mode==="write"||n.mode==="write")&&(r.resource==="*"||n.resource==="*"||r.resource===n.resource||r.recursive===!0&&n.resource.startsWith(r.resource.endsWith("/")?r.resource:`${r.resource}/`)||n.recursive===!0&&r.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(Ce,"conflicts");function ve(t,e,r){if(e===void 0||!r&&e.some(o=>o.mode!=="read"))return!1;if(t===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>t.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(ve,"coveredAccess");async function Re(t,e){if(e===void 0)return await t;e.throwIfAborted();let r,n=new Promise((o,s)=>{r=i(()=>s(e.reason),"abort"),e.addEventListener("abort",r,{once:!0})});try{return await Promise.race([t,n])}finally{e.removeEventListener("abort",r)}}i(Re,"waitForDependencies");var _=class t{constructor(e=re()){this.state=e}static{i(this,"ResourceScheduler")}run(e,r,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let E=s.then(h=>{if(n?.throwIfAborted(),!ve(a.accesses,h,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return h});a.nested??=new t;let g=a.nested.run(E,r,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(g),g.then(()=>a.children.delete(g),()=>a.children.delete(g)),g}let d=[...this.state.pending],p=s.catch(()=>{}),y,l=new Promise(E=>{y=E}),S={accesses:p,done:l};return this.state.pending.add(S),(async()=>{try{n?.throwIfAborted();let E=await Re(s.then(async h=>(await Promise.all(d.map(F=>Promise.race([F.done,F.accesses.then(me=>Ce(h,me)?F.done:void 0)]))),h)),n);n?.throwIfAborted();let g={accesses:E,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(g,r)}finally{for(;g.children.size>0;)await Promise.allSettled([...g.children]);g.open=!1}}finally{this.state.pending.delete(S),y()}})()}},he=Symbol.for("pi-agent-resource.resource-scheduler-state"),we=globalThis,Te=we[he]??=re(),Se=new _(Te);import{realpath as Ee,stat as be}from"node:fs/promises";import N from"node:path";import{fileURLToPath as xe}from"node:url";async function ne(t,e,r){if(/^[a-z][a-z\d+.-]*:/iu.test(t)&&!/^[a-z]:[\\/]/iu.test(t)&&!t.startsWith("file:"))return[{resource:t,mode:r}];let n=N.resolve(e,t.startsWith("file:")?xe(t):t),[o,s]=await Promise.allSettled([Ee(n),be(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let S=N.dirname(n);if(S===n)a=n;else{let g=(await ne(S,e,r)).find(h=>h.resource.startsWith("file:"));a=N.join(g?.resource.slice(5)??S,N.basename(n))}}let d=a.split(N.sep).join("/"),p=`file:${process.platform==="win32"?d.toLowerCase():d}`,y=[{resource:p,group:p,mode:r}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(y[0]={resource:p,group:p,mode:r,recursive:!0}),l.ino!==0n&&y.push({resource:`inode:${l.dev}:${l.ino}`,group:p,mode:r,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return y}i(ne,"resourceAccesses");import{Type as f}from"typebox";import{Value as Ae}from"typebox/value";var M=f.Object({code:f.String(),message:f.String(),source:f.Optional(f.String())},{additionalProperties:!1});function oe(t){return f.Union([f.Object({status:f.Literal("success"),data:t,errors:f.Array(M,{maxItems:0})},{additionalProperties:!1}),f.Object({status:f.Union([f.Literal("error"),f.Literal("partial")]),data:f.Optional(t),errors:f.Array(M,{minItems:1})},{additionalProperties:!1})])}i(oe,"structuredResultSchema");var se=1024*1024;function q(t){let e=new Set,r=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))r(o);e.delete(n)}},"visit");if(r(t),Buffer.byteLength(JSON.stringify(t))>se)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function ie(t,e="EXECUTION_FAILED",r){return{code:typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:e,message:t instanceof Error?t.message:String(t),...r===void 0?{}:{source:r}}}i(ie,"resultError");function Oe(t,e,r){try{if(q(r),!Ae.Check(oe(e),r))throw new TypeError("Result adapter returned data outside its public schema");return{...t,structuredContent:r,isError:r.status!=="success"}}catch(n){let o=ie(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...t,content:[...t.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Oe,"withStructuredResult");function Ne(t,e){if(e.length===0)return;let r=t.trim();if(r.length===0||/[\r\n]/u.test(r))throw new TypeError("Content provider summary must be one non-empty line");return[r,...e.map(({description:n})=>n)].join(`
2
- `)}i(Ne,"renderContentDescription");import{Type as u}from"typebox";import{Value as Ve}from"typebox/value";import{Type as c}from"typebox";import{Value as ke}from"typebox/value";var m={additionalProperties:!0},k=c.Function([],c.Unknown()),C=c.String({minLength:1}),Pe=c.Object({type:c.Literal("text"),text:c.String(),textSignature:c.Optional(c.String())},m),je=c.Object({type:c.Literal("image"),data:c.String(),mimeType:c.String()},m),Ie=c.Object({type:c.Literal("custom"),kind:C,data:c.Unknown()},m),_e=c.Array(c.Union([Pe,je,Ie]),{minItems:1}),ae=c.Union([c.Object({source:C,link:c.Optional(C),read:k,write:c.Optional(c.Never())},m),c.Object({source:C,link:c.Optional(C),read:c.Optional(c.Never()),write:k},m),c.Object({source:C,link:c.Optional(C),read:k,write:k},m)]),Ue=c.Object({id:C,tryResolve:k},m),De=c.Union([c.Object({kind:c.Literal("not-handled")},m),c.Object({kind:c.Literal("resolved"),resource:ae},m),c.Object({kind:c.Literal("failed"),error:c.Unknown()},m)]);function z(t){return U(_e,t)?D(()=>t.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(z,"isAgentContent");function ce(t){return U(ae,t)?D(()=>{let e=t,r=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function";return r&&n}):!1}i(ce,"isResource");function Le(t){return U(Ue,t)}i(Le,"isResourceResolver");function $e(t){return U(De,t)?D(()=>{let e=t;return e.kind!=="resolved"||ce(e.resource)}):!1}i($e,"isResourceResolutionAttempt");function U(t,e){return D(()=>ke.Check(t,e))}i(U,"safeCheck");function D(t){try{return t()}catch{return!1}}i(D,"safeEvaluate");var v={additionalProperties:!0},We=u.Function([],u.Unknown()),L=u.String({minLength:1}),He=u.Object({provider:L,capability:u.Union([u.Literal("read"),u.Literal("write")])},v),Ke=u.Object({source:L,bytes:u.Unknown(),mediaType:u.Optional(u.String())},v),Fe=u.Object({signal:u.Optional(u.Unknown())},v),Me=u.Object({id:L,description:L,tryConvert:We},v),qe=u.Union([u.Object({kind:u.Literal("not-handled")},v),u.Object({kind:u.Literal("converted"),content:u.Unknown()},v),u.Object({kind:u.Literal("failed"),error:u.Unknown()},v)]),ze=u.Object({target:u.Unknown(),converter:u.Unknown(),priority:u.Optional(u.Number())},v);function b(t){return x(He,t)&&T(()=>t.provider.trim().length>0)}i(b,"isContentTarget");function B(t){return x(Ke,t)?T(()=>{let e=t;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(B,"isContentInput");function J(t){return x(Fe,t)?T(()=>{let e=t;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(J,"isContentConversionContext");function ue(t){return x(Me,t)?T(()=>{let e=t;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(ue,"isContentConverter");function Y(t){return x(qe,t)?T(()=>{let e=t;return e.kind!=="converted"||z(e.content)}):!1}i(Y,"isContentConversionAttempt");function w(t){return x(ze,t)?T(()=>{let e=t;return b(e.target)&&ue(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(w,"isContentConverterRegistration");function x(t,e){return T(()=>Ve.Check(t,e))}i(x,"safeCheck");function T(t){try{return t()}catch{return!1}}i(T,"safeEvaluate");var $=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,r){super(`No content converter for ${e} in ${r.provider}/${r.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=r}};function X(t){if(!b(t))throw new TypeError("Invalid content target");let e={...t},r=[],n=i(()=>[...r].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!w(o))throw new TypeError("Invalid content converter registration");if(!A(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(r.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);r.push({converter:o.converter,priority:o.priority??0,order:r.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!B(o))throw new TypeError("Invalid content input");if(!J(s))throw new TypeError("Invalid content conversion context");G(s.signal);let a=n();for(let{converter:d}of a){G(s.signal);let p=await d.tryConvert(o,s);if(G(s.signal),!Y(p))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(p.kind!=="not-handled"){if(p.kind==="failed")throw p.error;return p.content}}throw new $(o.source,e)}}}i(X,"createContentRunner");function A(t,e){return t.provider===e.provider&&t.capability===e.capability}i(A,"targetsEqual");function G(t){t?.throwIfAborted()}i(G,"throwIfAborted");import{Type as R}from"typebox";import{Value as Be}from"typebox/value";var O="pi-agent-resource/content-conversion",V=2,P=`${O}/host/ready`,j=`${O}/converter/register`,de={additionalProperties:!0},Je=R.Function([],R.Unknown()),Ye=R.Object({protocol:R.Literal(O),apiVersion:R.Literal(V),target:R.Unknown()},de),Ge=R.Object({registration:R.Unknown(),accept:Je},de);function Q(t){return le(Ye,t)&&ee(()=>b(t.target))}i(Q,"isContentHostReady");function Z(t){return le(Ge,t)&&ee(()=>w(t.registration))}i(Z,"isContentConverterRegistrationRequest");function le(t,e){return ee(()=>Be.Check(t,e))}i(le,"safeCheck");function ee(t){try{return t()}catch{return!1}}i(ee,"safeEvaluate");function Xe(t,e){let r=X(e),n=t.events.on(j,o=>{if(!Z(o))throw new Error("Invalid content converter registration request");if(!A(r.target,o.registration.target))return;let s;try{r.register(o.registration),s=Promise.resolve()}catch(a){s=Promise.reject(a instanceof Error?a:new Error("Content converter registration failed",{cause:a}))}o.accept(s)});return t.on("session_shutdown",n),t.events.emit(P,{protocol:O,apiVersion:V,target:r.target}),{target:r.target,listDescriptions(){return r.listDescriptions()},convert(o,s){return r.convert(o,s)}}}i(Xe,"createContentHost");function Qe(t,e){if(!w(e))throw new TypeError("Invalid content converter registration");let r=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return t.events.emit(j,a),s},"announce"),n=i(()=>{},"unsubscribe");n=t.events.on(P,s=>{if(!Q(s))throw new Error("Invalid content conversion host readiness event");if(!A(e.target,s.target))return;let a=r();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),t.on("session_shutdown",n);let o=r();if(o!==void 0)return n(),o}i(Qe,"connectContentConverter");import{randomUUID as pe}from"node:crypto";import{readFile as Ze}from"node:fs/promises";import W from"node:path";import{Type as I}from"typebox";var et=I.Union([I.String(),I.Object({},{additionalProperties:!0}),I.Array(I.Unknown())]),H="RESULT#",fe="pi-agent-resource:result-targets",K=class{static{i(this,"ResultTargetStore")}#e=new Map;clear(){this.#e.clear()}register(e,r,n=!0){let o=`${H}${pe()}`;return this.#e.set(o,{state:"ready",targets:te(e),complete:n,cwd:W.resolve(r)}),o}reserve(e){let r=`${H}${pe()}`;return this.#e.set(r,{state:"pending",cwd:W.resolve(e)}),r}confirm(e,r,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==W.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");this.#e.set(e,{state:"ready",cwd:o.cwd,targets:te(r),complete:!0})}reject(e,r){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:r})}resolve(e,r){let n=this.#t(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==W.resolve(r))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);s&&=d.complete,o.push(...d.targets)}return{targets:te(o),complete:s}}resolveOrdered(e,r){let n=this.resolve(e,r),o=[],s=new Set;for(let a of new Set(this.#t(e)))for(let d of this.resolve(a,r).targets)for(let p of d.ranges){let y=JSON.stringify([d.source,p]);s.has(y)||(s.add(y),o.push({...d,ranges:[p]}))}return{targets:o,complete:n.complete}}async verify(e,r){await ge(e,r)}#t(e){if(typeof e=="string"&&e.startsWith(H))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#t(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let r=e;if("status"in r){if(r.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#t(r.data)}if(typeof r.target=="string"&&r.target.startsWith(H))return[r.target];if(r.kind==="resources"&&Array.isArray(r.resources))return this.#t(r.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};async function ge(t,e){let r=new Map;for(let n of t.targets){e?.throwIfAborted();let o=r.get(n.source);if(o===void 0&&(o=await Ze(n.source,{encoding:"utf8",signal:e}),r.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(ge,"verifyResultTargets");function te(t){let e=new Map;for(let r of t){let n=e.get(r.source);if(n!==void 0&&n.expectedContent!==r.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:r.source,expectedContent:r.expectedContent,ranges:[],seen:new Set};for(let s of r.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(r.source,o)}return[...e.values()].filter(r=>r.ranges.length>0).map(({seen:r,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(te,"combineTargets");function tt(t){let e;if(t.events.emit(fe,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let r=new K,n=t.events.on(fe,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(r)});return t.on("session_start",()=>{r.clear()}),t.on("session_shutdown",()=>{r.clear(),n()}),r}i(tt,"connectResultTargets");export{_ as a,Se as b,ne as c,M as d,oe as e,se as f,q as g,ie as h,Oe as i,Ne as j,z as k,ce as l,Le as m,$e as n,b as o,B as p,J as q,ue as r,Y as s,w as t,$ as u,X as v,A as w,O as x,V as y,P as z,j as A,Q as B,Z as C,Xe as D,Qe as E,et as F,K as G,ge as H,tt as I};
@@ -1 +0,0 @@
1
- import{d as A,e as R,f as w,h as g,i as U}from"./chunk-SQKAXYIR.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as D}from"typebox/value";var k=e.Union([e.Literal("pending"),e.Literal("applied"),e.Literal("not-applied"),e.Literal("unknown")]),F=e.Object({source:e.String(),effect:k,action:e.Optional(e.String()),state:e.Optional(e.Union([e.Literal("present"),e.Literal("absent"),e.Literal("unknown")]))},{additionalProperties:!1}),j=e.Object({id:e.String(),operation:e.String(),effect:k,errors:e.Array(A),status:e.Optional(e.Union([e.Literal("success"),e.Literal("error"),e.Literal("warning"),e.Literal("unknown")])),sources:e.Optional(e.Array(e.String())),warnings:e.Optional(e.Array(A))},{additionalProperties:!1}),I=e.Object({operation:e.String(),effect:k,operationId:e.Optional(e.String()),target:e.Optional(e.String({description:"Backend-owned resulting-text scope: replace/insert text, write's whole file, copy/move destinations, or undo's whole restored files. Delete never supplies a live target. Pending handles require a confirmed commit."})),targetUnavailable:e.Optional(e.String({description:"Why a completed mutation could not provide a safe resulting-text target. The write effect is reported separately."})),files:e.Array(F),changes:e.Optional(e.Array(e.Object({source:e.String(),from:e.Integer({description:"Inclusive zero-based UTF-16 offset in the pre-edit snapshot; not a live selector."}),to:e.Integer({description:"Exclusive zero-based UTF-16 offset in the pre-edit snapshot; not a live selector."}),removedText:e.String(),insertedText:e.String()},{additionalProperties:!1}))),changesUnavailable:e.Optional(e.String({description:"Why the exact change record is omitted; applied effects remain reported."})),operations:e.Optional(e.Array(j)),parentToolCallId:e.Optional(e.String()),recovery:e.Optional(e.Array(e.Object({source:e.String(),field:e.String(),anchor:e.String(),total:e.Integer(),candidates:e.Array(e.Object({rank:e.Integer(),range:e.Object({start:e.Object({lineNumber:e.Integer(),column:e.Integer()}),end:e.Object({lineNumber:e.Integer(),column:e.Integer()})})}))}))),action:e.Optional(e.Object({source:e.String(),kind:e.Optional(e.String()),status:e.Optional(e.String()),command:e.Optional(e.String()),deleted:e.Optional(e.Boolean()),session:e.Optional(e.String()),file:e.Optional(e.String()),line:e.Optional(e.Integer()),verified:e.Optional(e.Boolean()),evaluation:e.Optional(e.Object({expression:e.String(),result:e.String(),type:e.Optional(e.String()),variablesReference:e.Integer()},{additionalProperties:!1})),breakpoints:e.Optional(e.Array(e.Object({source:e.String(),file:e.String(),line:e.Integer(),verified:e.Boolean()},{additionalProperties:!1})))},{additionalProperties:!1}))},{additionalProperties:!1}),P=R(I);function s(l){return typeof l=="object"&&l!==null}y(s,"record");function N(l,p,S=[]){let o=l.details,d=s(o)?o:{},O=s(o)&&s(o.nativeEditBatch)?o.nativeEditBatch:void 0;if(O?.state==="accepted")return{status:"success",errors:[],data:{operation:p,effect:"pending",...typeof o.metadata?.resultTarget=="string"?{target:o.metadata.resultTarget}:{},files:typeof d.source=="string"?[{source:d.source,effect:"pending"}]:[],...typeof O.parentToolCallId=="string"?{parentToolCallId:O.parentToolCallId}:{}}};let m=new Set(S.map(r=>r.resourceSource)),a=[],u=[],v=o.results;for(let r of v??[]){let n=r.data,c=[...new Set([...(n.files??[]).map(i=>i.path),...n.path?[n.path]:[]])];for(let i of c)u.push({source:i,...m.has(i)?{state:"present"}:{},effect:m.has(i)||n.ok===!0&&n.files?.some(M=>M.path===i)?"applied":o.effect??"unknown"});for(let i of n.errors??[])a.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});n.ok===!1&&(n.errors?.length??0)===0&&a.push({code:"MUTATION_FAILED",message:"Mutation failed",...n.path?{source:n.path}:{}})}for(let r of m)u.some(n=>n.source===r)||u.push({source:r,effect:"applied",state:"present"});let t=s(o.metadata)&&s(o.metadata.semanticAction)?o.metadata.semanticAction:void 0;if(t){let r=t.effect==="not-applied"||t.effect==="unknown"?t.effect:t.ok===!1?"unknown":"applied",n=typeof t.source=="string"?t.source:void 0;n&&u.push({source:n,...t.kind==="file-operation"&&t.ok===!0?{state:p==="delete"||p==="move"?"absent":"present"}:{},effect:p==="copy"&&typeof t.target=="string"&&t.target!==n?"not-applied":r}),typeof t.target=="string"&&u.push({source:t.target,effect:r,...t.kind==="file-operation"&&t.ok===!0?{state:"present"}:{}}),s(t.error)&&a.push(g(t.error.message,typeof t.error.code=="string"?t.error.code:"MUTATION_FAILED",n)),typeof t.postProcessingError=="string"&&a.push(g(t.postProcessingError,"POST_EDIT_FAILED",n)),t.ok===!1&&a.length===0&&a.push(g("Resource operation failed","MUTATION_FAILED",n))}let f=[...new Map(u.map(r=>[r.source,r])).values()];if(Array.isArray(o.metadata?.resultFileStates))for(let r of o.metadata.resultFileStates){if(!s(r))continue;let n=f.find(c=>c.source===r.source);n&&(r.state==="present"||r.state==="absent")&&(n.state=r.state)}let T=(v??[]).filter(r=>r.data.ok).flatMap(r=>{let n=r.data.path;return n===void 0?[]:(r.data.rawChanges??[]).map(c=>({source:n,from:c.fromA,to:c.toA,removedText:c.removedText,insertedText:c.insertedText}))}),x=Buffer.byteLength(JSON.stringify(T))<=w/2,E=f.some(r=>r.effect==="applied");l.isError&&a.length===0&&a.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(v?.length??0)===0&&!t&&m.size===0&&a.length===0&&o.effect!=="not-applied"&&a.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let L=f.some(r=>r.effect==="unknown")||a.some(r=>r.code==="UNKNOWN_RESULT")?"unknown":E?"applied":"not-applied",h=t&&typeof t.source=="string"?{source:t.source,...typeof t.kind=="string"?{kind:t.kind}:{},...typeof t.status=="string"?{status:t.status}:{},...typeof t.command=="string"?{command:t.command}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.session=="string"?{session:t.session}:{},...typeof t.file=="string"?{file:t.file}:{},...typeof t.line=="number"?{line:t.line}:{},...typeof t.verified=="boolean"?{verified:t.verified}:{},...s(t.evaluation)?{evaluation:{expression:t.evaluation.expression,result:t.evaluation.result,variablesReference:t.evaluation.variablesReference,...typeof t.evaluation.type=="string"?{type:t.evaluation.type}:{}}}:{},...Array.isArray(t.breakpoints)?{breakpoints:t.breakpoints.filter(s).map(r=>({source:r.source,file:r.file,line:r.line,verified:r.verified}))}:{}}:void 0,b=h&&D.Check(I.properties.action,h)?h:void 0;return h&&!b&&a.push(g("Action adapter returned invalid fields","INVALID_STRUCTURED_RESULT")),{status:a.length===0?"success":!t&&E&&f.some(r=>r.effect!=="applied")?"partial":"error",data:{operation:p,effect:L,files:f,...T.length===0?{}:x?{changes:T}:{changesUnavailable:"Exact change record exceeds the 512 KiB receipt budget; it was not clipped."},...typeof o.metadata?.resultTarget=="string"?{target:o.metadata.resultTarget}:{},...typeof o.metadata?.targetUnavailable=="string"?{targetUnavailable:o.metadata.targetUnavailable}:{},...o.anchorRecoveries===void 0?{}:{recovery:o.anchorRecoveries.map(r=>({source:r.path,field:r.field,anchor:r.anchor,total:r.total,candidates:[...r.candidates]}))},...b?{action:b}:{}},errors:a}}y(N,"mutationOutcome");function W(l,p,S=[],o){let d=N(l,p,S);return d.data&&o!==void 0&&(d.data.operationId=o),U(l,I,d)}y(W,"structuredMutation");export{I as a,P as b,N as c,W as d};
@@ -1,105 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import path from "node:path";
5
-
6
- import type { AgentContent, ResourceResolutionAttempt, ResourceResolver } from "pi-agent-resource";
7
-
8
- export interface TempResourceStoreOptions {
9
- /** Parent folder for this store's private temporary directory. */
10
- readonly parentDirectory?: string;
11
- }
12
-
13
- /** Keeps temporary text resources isolated and readable until the owning runtime disposes it. */
14
- export class TempResourceStore {
15
- readonly resolver: ResourceResolver;
16
- readonly #entries = new Map<string, string>();
17
- readonly #pendingSaves = new Set<Promise<string>>();
18
- readonly #parentDirectory: string;
19
- #directoryReady: Promise<string> | undefined;
20
- #disposal: Promise<void> | undefined;
21
-
22
- constructor(options: TempResourceStoreOptions = {}) {
23
- this.#parentDirectory = options.parentDirectory ?? tmpdir();
24
- this.resolver = {
25
- id: "temp",
26
- tryResolve: (source) => Promise.resolve(this.#resolve(source)),
27
- };
28
- }
29
-
30
- /** Saves text and returns a reference owned by this store. Rejects after disposal starts. */
31
- async save(text: string): Promise<string> {
32
- if (this.#disposal !== undefined) {
33
- throw new Error("Temporary resource store is closed");
34
- }
35
-
36
- const saving = this.#save(text);
37
- this.#pendingSaves.add(saving);
38
- try {
39
- return await saving;
40
- } finally {
41
- this.#pendingSaves.delete(saving);
42
- }
43
- }
44
-
45
- /** Closes the store, waits for pending saves, and removes its private directory. */
46
- dispose(): Promise<void> {
47
- this.#disposal ??= this.#dispose();
48
- return this.#disposal;
49
- }
50
-
51
- async #save(text: string): Promise<string> {
52
- const directory = await this.#getDirectory();
53
- const id = randomUUID();
54
- const source = `temp:${id}`;
55
- const filePath = path.join(directory, `${id}.txt`);
56
- await writeFile(filePath, text, { encoding: "utf8", flag: "wx" });
57
- this.#entries.set(source, filePath);
58
- return source;
59
- }
60
-
61
- async #dispose(): Promise<void> {
62
- await Promise.allSettled(this.#pendingSaves);
63
- this.#entries.clear();
64
- if (this.#directoryReady !== undefined) {
65
- await rm(await this.#directoryReady, { recursive: true, force: true });
66
- }
67
- }
68
-
69
- #resolve(source: string): ResourceResolutionAttempt {
70
- if (!source.startsWith("temp:")) {
71
- return { kind: "not-handled" };
72
- }
73
-
74
- if (this.#disposal !== undefined || !this.#entries.has(source)) {
75
- return {
76
- kind: "failed",
77
- error: new Error(`Temporary resource ${source} does not exist in this runtime`),
78
- };
79
- }
80
-
81
- return {
82
- kind: "resolved",
83
- resource: {
84
- source,
85
- read: () => this.#read(source),
86
- },
87
- };
88
- }
89
-
90
- async #read(source: string): Promise<AgentContent> {
91
- const filePath = this.#entries.get(source);
92
- if (this.#disposal !== undefined || filePath === undefined) {
93
- throw new Error(`Temporary resource ${source} does not exist in this runtime`);
94
- }
95
- return [{ type: "text", text: await readFile(filePath, "utf8") }];
96
- }
97
-
98
- async #getDirectory(): Promise<string> {
99
- this.#directoryReady ??= (async () => {
100
- await mkdir(this.#parentDirectory, { recursive: true });
101
- return mkdtemp(path.join(this.#parentDirectory, "pi-agent-read-"));
102
- })();
103
- return this.#directoryReady;
104
- }
105
- }