pi-agent-ide 0.6.4 → 0.7.1

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 (431) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +2 -2
  3. package/dist/{chunk-AWXVJ5AC.js → chunk-2RTCSZB3.js} +1 -1
  4. package/dist/chunk-2TRHFMCZ.js +11 -0
  5. package/dist/{chunk-WJTHY6AG.js → chunk-4GCWGE2C.js} +1 -1
  6. package/dist/chunk-4XMY4H4V.js +1 -0
  7. package/dist/{chunk-BSICWXMH.js → chunk-64M3SQPG.js} +1 -1
  8. package/dist/{chunk-QEJGED4V.js → chunk-76ZK5ODR.js} +2 -2
  9. package/dist/{chunk-3BBJZSMS.js → chunk-7LD2OQH3.js} +1 -1
  10. package/dist/{chunk-6CZO43OH.js → chunk-BU7IZLKB.js} +1 -1
  11. package/dist/chunk-CWD4O5PM.js +3 -0
  12. package/dist/chunk-D3WTDA6V.js +2 -0
  13. package/dist/chunk-EAZGN5ND.js +7 -0
  14. package/dist/chunk-GXEGY7GV.js +1 -0
  15. package/dist/chunk-HZEY4GT4.js +2 -0
  16. package/dist/chunk-LEEQIQ7D.js +28 -0
  17. package/dist/chunk-NRZO5KJT.js +9 -0
  18. package/dist/chunk-OMVRLWMX.js +5 -0
  19. package/dist/{chunk-VBICI5YA.js → chunk-PGIVHICI.js} +1 -1
  20. package/dist/{chunk-FBOW7XOV.js → chunk-PKKDDIWW.js} +1 -1
  21. package/dist/chunk-PNU3E7IO.js +3 -0
  22. package/dist/chunk-PS2B6THP.js +3 -0
  23. package/dist/{chunk-FUG2TEKI.js → chunk-QFTBY67N.js} +2 -2
  24. package/dist/{chunk-EDURPQAV.js → chunk-QRJLIV6P.js} +6 -6
  25. package/dist/{chunk-OBNING2A.js → chunk-S5PL5DFQ.js} +1 -1
  26. package/dist/chunk-VMTR74FF.js +2 -0
  27. package/dist/{chunk-HPUAIWIH.js → chunk-WMO6RNE2.js} +1 -1
  28. package/dist/chunk-WU6ZK6YD.js +1 -0
  29. package/dist/{chunk-GIRAEVUJ.js → chunk-XH5WN5XA.js} +1 -1
  30. package/dist/chunk-XYS4FSCC.js +12 -0
  31. package/dist/chunk-YP46DVVP.js +2 -0
  32. package/dist/entry-11.js +1 -1
  33. package/dist/entry-13.js +1 -1
  34. package/dist/entry-14.js +1 -1
  35. package/dist/entry-15.js +1 -1
  36. package/dist/entry-17.js +1 -1
  37. package/dist/entry-25.js +2 -2
  38. package/dist/entry-26.js +1 -1
  39. package/dist/entry-27.js +2 -2
  40. package/dist/entry-28.js +1 -1
  41. package/dist/entry-29.js +1 -1
  42. package/dist/entry-30.js +1 -1
  43. package/dist/entry-31.js +12 -9
  44. package/dist/entry-33.js +1 -1
  45. package/dist/entry-37.js +6 -6
  46. package/dist/entry-41.js +1 -1
  47. package/dist/entry-42.js +1 -1
  48. package/dist/entry-43.js +1 -1
  49. package/dist/entry-44.js +1 -1
  50. package/dist/entry-45.js +13 -14
  51. package/dist/entry-46.js +1 -1
  52. package/dist/entry-49.js +1 -1
  53. package/dist/entry-50.js +3 -6
  54. package/dist/entry-51.js +11 -9
  55. package/dist/entry-52.js +1 -1
  56. package/dist/entry-53.js +1 -1
  57. package/dist/entry-54.js +1 -1
  58. package/dist/entry-56.js +1 -1
  59. package/dist/entry-57.js +1 -1
  60. package/dist/entry-58.js +1 -1
  61. package/dist/entry-60.js +1 -1
  62. package/dist/entry-61.js +0 -1
  63. package/dist/entry-62.js +1 -0
  64. package/dist/entry-63.js +0 -1
  65. package/dist/entry-64.js +1 -0
  66. package/dist/entry-65.js +1 -1
  67. package/dist/entry-66.js +1 -1
  68. package/dist/entry-67.js +1 -1
  69. package/dist/entry-68.js +1 -1
  70. package/dist/entry-69.js +1 -1
  71. package/dist/entry-70.js +1 -1
  72. package/dist/entry-71.js +0 -1
  73. package/dist/entry-72.js +1 -0
  74. package/dist/entry-73.js +0 -1
  75. package/dist/entry-74.js +1 -0
  76. package/dist/entry-75.js +1 -1
  77. package/dist/entry-76.js +1 -1
  78. package/dist/entry-77.js +66 -1
  79. package/dist/entry-78.js +14 -325
  80. package/dist/entry-79.js +2 -18
  81. package/dist/entry-80.js +1 -2
  82. package/dist/entry-81.js +1 -1
  83. package/dist/entry-82.js +5 -1
  84. package/dist/entry-83.js +3 -5
  85. package/dist/entry-84.js +1 -3
  86. package/dist/entry-85.js +1 -1
  87. package/dist/entry-86.js +1 -1
  88. package/dist/pi-agent-ide.js +14 -9
  89. package/docs/agent-guides/editing.md +38 -33
  90. package/docs/agent-guides/git-changes.md +1 -1
  91. package/docs/agent-guides/read-resources.md +8 -4
  92. package/docs/agent-guides/search-code.md +34 -2
  93. package/docs/agent-guides/select-code.md +115 -0
  94. package/docs/configuration.md +12 -17
  95. package/docs/development.md +2 -1
  96. package/docs/releases.md +1 -1
  97. package/docs/research/apply-native-capability-matrix.md +174 -0
  98. package/docs/research/apply-read-latency.md +2 -0
  99. package/docs/research/lpt-393-fuzzy-results/file.json +152 -0
  100. package/docs/research/lpt-393-fuzzy-results/repo.json +122 -0
  101. package/docs/research/lpt-393-search-fuzzy-fallback.md +97 -0
  102. package/docs/research/native-codemode-batch-decision.md +2 -0
  103. package/docs/research/native-codemode-batching.md +1 -1
  104. package/docs/structured-results.md +30 -38
  105. package/docs/tools.md +11 -11
  106. package/docs/user-hooks.md +1 -1
  107. package/node_modules/pi-agent-doctor/package.json +1 -1
  108. package/node_modules/pi-agent-documentation/package.json +1 -1
  109. package/node_modules/pi-agent-filesystem/index.ts +7 -6
  110. package/node_modules/pi-agent-filesystem/package.json +7 -7
  111. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  112. package/node_modules/pi-agent-filesystem-jq/index.ts +4 -3
  113. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  114. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  115. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  116. package/node_modules/pi-agent-ide-ast/package.json +15 -10
  117. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
  118. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
  119. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +5 -1
  120. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +204 -0
  121. package/node_modules/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
  122. package/node_modules/pi-agent-ide-ast/src/extension.ts +10 -5
  123. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
  124. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +142 -27
  125. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +104 -0
  126. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +384 -0
  127. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +41 -0
  128. package/node_modules/pi-agent-ide-ast/src/source-text.ts +92 -0
  129. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +214 -0
  130. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +268 -0
  131. package/node_modules/pi-agent-ide-changes/index.ts +6 -21
  132. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  133. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
  134. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
  135. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  136. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  137. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  138. package/node_modules/pi-agent-ide-lsp/index.ts +5 -5
  139. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  140. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
  141. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
  142. package/node_modules/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
  143. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
  144. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
  145. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +92 -45
  146. package/node_modules/pi-agent-image/package.json +2 -2
  147. package/node_modules/pi-agent-invariant/package.json +1 -1
  148. package/node_modules/pi-agent-pdf/package.json +2 -2
  149. package/node_modules/pi-agent-read/package.json +7 -7
  150. package/node_modules/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  151. package/node_modules/pi-agent-read/src/api/read-parameters.ts +40 -3
  152. package/node_modules/pi-agent-read/src/api/tools/read.ts +11 -1
  153. package/node_modules/pi-agent-read/src/core/extension.ts +18 -1
  154. package/node_modules/pi-agent-read/src/core/read-core.ts +50 -35
  155. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
  156. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +5 -3
  157. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +17 -3
  158. package/node_modules/pi-agent-resource/package.json +1 -1
  159. package/node_modules/pi-agent-resource/src/index.ts +10 -0
  160. package/node_modules/pi-agent-resource/src/result-targets.ts +407 -0
  161. package/node_modules/pi-agent-resource/src/tool-result.ts +13 -1
  162. package/node_modules/pi-agent-search/package.json +5 -5
  163. package/node_modules/pi-agent-search/src/api/fuzzy.ts +208 -0
  164. package/node_modules/pi-agent-search/src/api/presentation.ts +68 -0
  165. package/node_modules/pi-agent-search/src/api/search-parameters.ts +9 -3
  166. package/node_modules/pi-agent-search/src/api/search-scope.ts +22 -0
  167. package/node_modules/pi-agent-search/src/api/search.ts +28 -0
  168. package/node_modules/pi-agent-search/src/api/structured-result.ts +69 -14
  169. package/node_modules/pi-agent-search/src/core/extension.ts +56 -16
  170. package/node_modules/pi-agent-search/src/core/search-core.ts +9 -1
  171. package/node_modules/pi-agent-search-text/index.ts +3 -1
  172. package/node_modules/pi-agent-search-text/package.json +7 -6
  173. package/node_modules/pi-agent-search-text/src/fuzzy-search.ts +164 -0
  174. package/node_modules/pi-agent-search-text/src/resolvers.ts +161 -30
  175. package/node_modules/pi-agent-search-text/src/scoped-search.ts +103 -0
  176. package/node_modules/pi-agent-search-text/src/search-backend.ts +104 -17
  177. package/node_modules/pi-agent-search-text/src/search-renderer.ts +89 -292
  178. package/node_modules/pi-agent-search-text/src/search-result.ts +77 -0
  179. package/node_modules/pi-agent-search-text/src/search-session.ts +96 -11
  180. package/node_modules/pi-agent-text/package.json +2 -2
  181. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  182. package/node_modules/pi-agent-text-anchor-exact/index.ts +65 -4
  183. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  184. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  185. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +4 -3
  186. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  187. package/node_modules/pi-agent-text-editor/index.ts +0 -5
  188. package/node_modules/pi-agent-text-editor/package.json +26 -31
  189. package/node_modules/pi-agent-text-editor/runtime/entry-77.js +1 -0
  190. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +3 -1
  191. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
  192. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
  193. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
  194. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
  195. package/node_modules/pi-agent-text-editor/src/core/extension.ts +22 -5
  196. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
  197. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +4 -14
  198. package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
  199. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
  200. package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
  201. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +217 -30
  202. package/node_modules/pi-agent-text-editor/src/core/result-input.ts +22 -0
  203. package/node_modules/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
  204. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
  205. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +86 -154
  206. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
  207. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
  208. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +238 -244
  209. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  210. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -11
  211. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
  212. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
  213. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
  214. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
  215. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
  216. package/node_modules/pi-agent-text-editor-renderer/index.ts +1 -72
  217. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  218. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
  219. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
  220. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  221. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  222. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +1 -0
  223. package/node_modules/pi-agent-tool-call-interception/src/index.ts +3 -0
  224. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  225. package/node_modules/pi-agent-tool-ui/src/index.ts +7 -0
  226. package/node_modules/pi-agent-tool-ui/src/result-panel.ts +298 -0
  227. package/node_modules/pi-agent-web/index.ts +7 -3
  228. package/node_modules/pi-agent-web/package.json +8 -8
  229. package/node_modules/pi-agent-web/runtime/entry-82.js +2 -0
  230. package/node_modules/pi-agent-web/src/search.ts +111 -2
  231. package/node_modules/pi-agent-web-html/package.json +3 -3
  232. package/node_modules/pi-agent-web-image/package.json +4 -4
  233. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  234. package/node_modules/pi-agent-web-text/package.json +4 -4
  235. package/package.json +35 -36
  236. package/src/composite/module-labels.ts +1 -1
  237. package/src/composite/preferences.ts +0 -5
  238. package/src/composite/text-results.ts +221 -0
  239. package/src/documentation/extension.ts +11 -9
  240. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +7 -6
  241. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  242. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  243. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +4 -3
  244. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  245. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  246. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  247. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +7 -3
  248. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  249. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  250. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +2 -0
  251. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  252. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  253. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  254. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +2 -0
  255. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +111 -2
  256. package/src/extensions/pi-agent-read/package.json +7 -7
  257. package/src/extensions/pi-agent-read/src/api/plugin-protocol.ts +1 -1
  258. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +40 -3
  259. package/src/extensions/pi-agent-read/src/api/tools/read.ts +11 -1
  260. package/src/extensions/pi-agent-read/src/core/extension.ts +18 -1
  261. package/src/extensions/pi-agent-read/src/core/read-core.ts +50 -35
  262. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
  263. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +5 -3
  264. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +17 -3
  265. package/src/extensions/pi-agent-search/package.json +5 -5
  266. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +3 -1
  267. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -6
  268. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/fuzzy-search.ts +164 -0
  269. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +161 -30
  270. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +103 -0
  271. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +104 -17
  272. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +89 -292
  273. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +77 -0
  274. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +96 -11
  275. package/src/extensions/pi-agent-search/src/api/fuzzy.ts +208 -0
  276. package/src/extensions/pi-agent-search/src/api/presentation.ts +68 -0
  277. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +9 -3
  278. package/src/extensions/pi-agent-search/src/api/search-scope.ts +22 -0
  279. package/src/extensions/pi-agent-search/src/api/search.ts +28 -0
  280. package/src/extensions/pi-agent-search/src/api/structured-result.ts +69 -14
  281. package/src/extensions/pi-agent-search/src/core/extension.ts +56 -16
  282. package/src/extensions/pi-agent-search/src/core/search-core.ts +9 -1
  283. package/src/extensions/pi-agent-text-editor/index.ts +0 -5
  284. package/src/extensions/pi-agent-text-editor/package.json +26 -31
  285. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +65 -4
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +12 -2
  289. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +4 -3
  290. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  291. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +1 -72
  292. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  293. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  294. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
  295. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
  296. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  297. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +1 -0
  298. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +3 -1
  299. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
  300. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
  301. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
  302. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
  303. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +22 -5
  304. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
  305. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +4 -14
  306. package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
  307. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
  308. package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
  309. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +217 -30
  310. package/src/extensions/pi-agent-text-editor/src/core/result-input.ts +22 -0
  311. package/src/extensions/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
  312. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
  313. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +86 -154
  314. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
  315. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
  316. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +238 -244
  317. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +1 -1
  318. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -11
  319. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
  320. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
  321. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
  322. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
  323. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
  324. package/src/pi-agent-ide.ts +4 -7
  325. package/src/plugins/pi-agent-ide-ast/package.json +15 -10
  326. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
  327. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
  328. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +5 -1
  329. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +204 -0
  330. package/src/plugins/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
  331. package/src/plugins/pi-agent-ide-ast/src/extension.ts +10 -5
  332. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
  333. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +142 -27
  334. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +104 -0
  335. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +384 -0
  336. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +41 -0
  337. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +92 -0
  338. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +214 -0
  339. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +268 -0
  340. package/src/plugins/pi-agent-ide-changes/index.ts +6 -21
  341. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  342. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
  343. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
  344. package/src/plugins/pi-agent-ide-debugger/index.ts +5 -3
  345. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +5 -3
  346. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  347. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  348. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  349. package/src/plugins/pi-agent-ide-lsp/index.ts +5 -5
  350. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  351. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
  352. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
  353. package/src/plugins/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
  354. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
  355. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
  356. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +92 -45
  357. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +8 -6
  358. package/src/plugins/pi-agent-ide-terminal/src/search.ts +10 -36
  359. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -1
  360. package/src/plugins/pi-agent-ide-vision/index.ts +31 -4
  361. package/dist/chunk-2P2OGO3G.js +0 -2
  362. package/dist/chunk-5J43L2RL.js +0 -11
  363. package/dist/chunk-6EYWFBNG.js +0 -0
  364. package/dist/chunk-7AVXUV4A.js +0 -7
  365. package/dist/chunk-7WCZOO5I.js +0 -1
  366. package/dist/chunk-BAYETTZZ.js +0 -16
  367. package/dist/chunk-BVK5A7ED.js +0 -28
  368. package/dist/chunk-F7NVAC4Q.js +0 -0
  369. package/dist/chunk-FZBCKIJJ.js +0 -1
  370. package/dist/chunk-I5JLCFUX.js +0 -1
  371. package/dist/chunk-KUPHNMUK.js +0 -2
  372. package/dist/chunk-MIZAFRDR.js +0 -1
  373. package/dist/chunk-PJPA5EEE.js +0 -2
  374. package/dist/chunk-PXWDDBBC.js +0 -0
  375. package/dist/chunk-SILJ3OL4.js +0 -9
  376. package/dist/chunk-TQZBVOTT.js +0 -5
  377. package/dist/chunk-VWW3RLUX.js +0 -12
  378. package/dist/chunk-YHUTTZC6.js +0 -2
  379. package/dist/chunk-ZODCBFBL.js +0 -2
  380. package/dist/entry-87.js +0 -1
  381. package/docs/agent-guides/apply.md +0 -333
  382. package/node_modules/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
  383. package/node_modules/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
  384. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
  385. package/node_modules/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
  386. package/node_modules/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
  387. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
  388. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
  389. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +0 -276
  390. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
  391. package/node_modules/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
  392. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
  393. package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +0 -137
  394. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
  395. package/node_modules/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
  396. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
  397. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
  398. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  399. package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +0 -1
  400. package/node_modules/pi-agent-web-text/runtime/entry-87.js +0 -2
  401. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +0 -2
  402. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +0 -2
  403. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  404. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +0 -2
  405. package/src/extensions/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
  406. package/src/extensions/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
  407. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
  408. package/src/extensions/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
  409. package/src/extensions/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
  410. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
  411. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
  412. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +0 -276
  413. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
  414. package/src/extensions/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
  415. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
  416. package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +0 -137
  417. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
  418. package/src/extensions/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
  419. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
  420. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
  421. /package/node_modules/{pi-agent-text-editor → pi-agent-text-editor-renderer}/runtime/entry-78.js +0 -0
  422. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
  423. /package/node_modules/{pi-agent-tool-call-interception → pi-agent-tool-ui}/runtime/entry-81.js +0 -0
  424. /package/node_modules/{pi-agent-web → pi-agent-web-html}/runtime/entry-83.js +0 -0
  425. /package/node_modules/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
  426. /package/node_modules/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
  427. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
  428. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
  429. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
  430. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
  431. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,50 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.1 — 2026-10-05
4
+
5
+ - Reduced prompt size by keeping internal result structures out of agent-facing tool schemas.
6
+ - Restored readable string results for agents. Structured records stay internal because exposing their layout made tool use more complicated.
7
+ - Preserved tool composition, including Read, Search, Select, editing and Codemode store/load. Results carry registered references instead of exposing internal fields.
8
+ - Made Copy and Move replace existing destination files without a separate overwrite flag.
9
+
10
+ ## 0.7.0 — 2026-10-05
11
+
12
+ ### Native tool composition
13
+
14
+ - Compose Read, Search, Select and editing tools through source-backed results and exact snapshot targets, including sparse and multi-file selections. Reject stale or incomplete inputs without widening their scope.
15
+ - Search within returned Read and mutation targets. Keep mutation change records and destination targets available for follow-up work, with explicit reasons when a text target cannot be returned.
16
+ - Expose AST captures as source targets and LSP symbol identity and definition/reference roles. Follow references outside a seed scope only when explicitly requested.
17
+ - Remove Apply, its grouped undo receipts and preview settings. Use ordinary tools through native Codemode; per-file text undo and Git change undo remain. Native copy/move pairs selections rather than concatenating and broadcasting them.
18
+ - Fix empty-file creation so successful native writes report truthful applied effects and return usable targets.
19
+
20
+ ### Select
21
+
22
+ - Add guarded text boundaries, marker pairs, slices, trimming, splitting, line expansion and exact insertion positions, preserving UTF-16 and CRLF boundaries.
23
+ - Add source-local range operations: containment, intersection, subtraction and explicit merging, without filling gaps between selections.
24
+ - Add JavaScript and TypeScript AST enclosing constructs, navigation and named parts. Select call arguments and function parameters with owned separators; refuse ambiguous neighboring comments instead of guessing or repairing syntax.
25
+
26
+ ### Search and presentation
27
+
28
+ - Suggest bounded possible identifier names after eligible zero-result searches, with separate exact candidate scopes. Keep quoted, Boolean and explicit-protocol queries exact.
29
+ - Unify structural and text search panels and keep agent guidance out of fuzzy user cards.
30
+ - Skip LSP providers that do not support workspace symbols instead of sending unsupported requests.
31
+
32
+ ### Mutation diffs
33
+
34
+ - Keep whole replacements visible when old and new blocks share no trimmed line. Avoid unnecessary character refinement while preserving the existing time, pairing and size limits, precise small-edit highlights and truthful unavailable state for unfinished comparisons.
35
+
36
+ ### Packaging
37
+
38
+ - Fix a documentation link to excluded tests so public package validation succeeds.
39
+
40
+ ### Verification
41
+
42
+ - Run the full integration suite in four standalone CI shards with separate reports and retained logs, without raising timeouts or skipping tests. Close each scenario's Pi process instead of accumulating shared fixture hosts.
43
+ - Check that each final file is formatted once without requiring independent files to finish in a fixed order.
44
+ - Make the shell-result scenario independent of background completion timing while keeping separate completion-delivery coverage.
45
+ - Run Windows source and installed-package checks without a retained shared harness workspace, avoiding locks on the shared cleanup directory.
46
+ - Retry transient Windows test-workspace removal locks a bounded number of times after the Pi process tree exits; persistent locks still fail. Retain Windows host traces on failure without changing test timeouts or assertions.
47
+
3
48
  ## 0.6.4 — 2026-10-03
4
49
 
5
50
  ### Native Pi integration
package/README.md CHANGED
@@ -76,9 +76,9 @@ Editing uses direct semantic operations:
76
76
  - `insert` adds text around a selection;
77
77
  - `delete` removes selected text or a resource;
78
78
  - `copy` and `move` duplicate or relocate text and files;
79
- - `undo` restores an edit or a complete transaction.
79
+ - `undo` restores the last text edit or a selected Git change.
80
80
 
81
- Independent edits can be submitted together as a tool-call batch. Conditional and multi-file work uses Apply, a code mode that exposes the same guarded operations through transactional JavaScript. Diffing and staging are first-class tools too.
81
+ Independent edits can be submitted together as a tool-call batch. For conditional or dependent work, native Codemode composes the same guarded tools with Read, Search and Select results. Check each operation's status and final effects; a script error does not roll back accepted edits. Diffing and staging are first-class tools too.
82
82
 
83
83
  <div align="center">
84
84
 
@@ -1 +1 @@
1
- import{a as r}from"./chunk-EI7MMDWY.js";function l(t,n){return typeof n=="string"&&n.length>0&&t.nonAnchorValues?.includes(n)!==!0}r(l,"isMutationAnchorValue");function u(t){if(typeof t.name!="string"||t.name.trim().length===0)throw new TypeError("Mutation tool name must be a non-empty string");if(typeof t.description!="string"||typeof t.mutate!="function")throw new TypeError(`Mutation tool ${t.name} has an invalid description or operation`);if(t.direct!==void 0&&(typeof t.direct.matches!="function"||typeof t.direct.execute!="function"))throw new TypeError(`Mutation tool ${t.name} has an invalid direct operation`);let n=t.intent;if(n!==void 0&&n!=="edit"&&n!=="restore")throw new TypeError(`Mutation tool ${t.name} has an invalid intent`);let o=d(t.parameters,t.name);c(o,t.source.field,`${t.name} primary source`);let a=new Set([t.source.field]);for(let e of t.source.targets??[]){if(c(o,e.field,`${t.name} target source`),!a.has(e.fallbackTo))throw new TypeError(`Mutation tool ${t.name} target ${e.field} has an unknown fallback ${e.fallbackTo}`);a.add(e.field)}let s=new Set;for(let e of t.anchors??[]){if(c(o,e.field,`${t.name} anchor`),!a.has(e.sourceField))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} has an unknown source ${e.sourceField}`);if(!Array.isArray(e.kinds)||e.kinds.length===0||e.kinds.some(i=>typeof i!="string"||i.trim().length===0))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must accept non-empty kinds`);if(new Set(e.kinds).size!==e.kinds.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate kinds`);if(e.nonAnchorValues!==void 0&&(e.nonAnchorValues.length===0||e.nonAnchorValues.some(i=>typeof i!="string"||i.length===0)))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must declare non-empty non-anchor values`);if(e.nonAnchorValues!==void 0&&new Set(e.nonAnchorValues).size!==e.nonAnchorValues.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate non-anchor values`);if(s.has(e.field))throw new TypeError(`Mutation tool ${t.name} declares anchor ${e.field} more than once`);s.add(e.field)}for(let e of t.pair??[])if(!s.has(e))throw new TypeError(`Mutation tool ${t.name} pair field ${e} is not an anchor`)}r(u,"assertTextMutationToolRegistration");function p(t,n){let o=n[t.source.field];return typeof o=="string"?o:""}r(p,"mutationSource");function d(t,n){let o=t.properties;if(typeof o!="object"||o===null)throw new TypeError(`Mutation tool ${n} parameters must be an object schema`);return o}r(d,"schemaProperties");function c(t,n,o){if(typeof n!="string"||n.length===0||!(n in t))throw new TypeError(`${o} field ${n} is not declared by its schema`)}r(c,"assertProperty");export{l as a,u as b,p as c};
1
+ import{a as r}from"./chunk-EI7MMDWY.js";function l(t,n){return typeof n=="string"&&n.length>0&&t.nonAnchorValues?.includes(n)!==!0}r(l,"isMutationAnchorValue");function u(t){if(typeof t.name!="string"||t.name.trim().length===0)throw new TypeError("Mutation tool name must be a non-empty string");if(typeof t.description!="string"||typeof t.mutate!="function")throw new TypeError(`Mutation tool ${t.name} has an invalid description or operation`);if(t.direct!==void 0&&(typeof t.direct.matches!="function"||typeof t.direct.execute!="function"))throw new TypeError(`Mutation tool ${t.name} has an invalid direct operation`);let n=t.intent;if(n!==void 0&&n!=="edit"&&n!=="restore")throw new TypeError(`Mutation tool ${t.name} has an invalid intent`);let o=d(t.parameters,t.name);c(o,t.source.field,`${t.name} primary source`);let a=new Set([t.source.field]);for(let e of t.source.targets??[]){if(c(o,e.field,`${t.name} target source`),!a.has(e.fallbackTo))throw new TypeError(`Mutation tool ${t.name} target ${e.field} has an unknown fallback ${e.fallbackTo}`);a.add(e.field)}let s=new Set;for(let e of t.anchors??[]){if(c(o,e.field,`${t.name} anchor`),!a.has(e.sourceField))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} has an unknown source ${e.sourceField}`);if(!Array.isArray(e.kinds)||e.kinds.length===0||e.kinds.some(i=>typeof i!="string"||i.trim().length===0))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must accept non-empty kinds`);if(new Set(e.kinds).size!==e.kinds.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate kinds`);if(e.nonAnchorValues!==void 0&&(e.nonAnchorValues.length===0||e.nonAnchorValues.some(i=>typeof i!="string"||i.length===0)))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must declare non-empty non-anchor values`);if(e.nonAnchorValues!==void 0&&new Set(e.nonAnchorValues).size!==e.nonAnchorValues.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate non-anchor values`);if(s.has(e.field))throw new TypeError(`Mutation tool ${t.name} declares anchor ${e.field} more than once`);s.add(e.field)}for(let e of t.pair??[])if(!s.has(e))throw new TypeError(`Mutation tool ${t.name} pair field ${e} is not an anchor`)}r(u,"assertTextMutationToolRegistration");function y(t,n){let o=n[t.source.field];return typeof o=="string"?o:""}r(y,"mutationSource");function d(t,n){let o=t.properties;if(typeof o!="object"||o===null)throw new TypeError(`Mutation tool ${n} parameters must be an object schema`);return o}r(d,"schemaProperties");function c(t,n,o){if(typeof n!="string"||n.length===0||!(n in t))throw new TypeError(`${o} field ${n} is not declared by its schema`)}r(c,"assertProperty");export{l as a,u as b,y as c};
@@ -0,0 +1,11 @@
1
+ import{d as B,h as M}from"./chunk-XH5WN5XA.js";import{a as N}from"./chunk-4XMY4H4V.js";import{h as w,i as P}from"./chunk-CWD4O5PM.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(t.toolName),{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 +1 @@
1
- import{m as c}from"./chunk-2P2OGO3G.js";import{e as a}from"./chunk-ZPT5D4VP.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var n="pi-agent-text-editor",p=22,P="pi-agent-text-editor/position",S="pi-agent-text-editor/search",I=`${n}/core/ready`,b=`${n}/plugin/register`,s=e.Function([],e.Unknown()),u=e.Object({tryResolve:s},{additionalProperties:!0}),l=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),T=e.Object({start:l,end:l,linewise:e.Optional(e.Boolean())}),x=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(T))}),R=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(x,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),g=e.String({pattern:"\\S"}),m=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),y=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),v=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p)}),d=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p),id:e.String(),setup:s}),E=e.Object({plugin:d,accept:s});function k(t){return i.Check(g,t)}r(k,"isTextEditorToolId");function _(t){if(!i.Check(m,t))return!1;let o=t;return c(o.resolver)&&(!("priority"in o)||typeof o.priority=="number")}r(_,"isResourceResolverRegistration");function C(t){if(!i.Check(y,t))return!1;let o=t;return a(o.resolver)&&(!("resources"in o)||i.Check(u,o.resources))&&(!("priority"in o)||typeof o.priority=="number")}r(C,"isTextAnchorResolverRegistration");function j(t){return i.Check(R,t)}r(j,"isTextAnchorResourceResolutionAttempt");function w(t){return i.Check(v,t)}r(w,"isTextEditorCoreReady");function L(t){return i.Check(d,t)}r(L,"isTextEditorPlugin");function N(t){return i.Check(E,t)}r(N,"isTextEditorPluginRegistrationRequest");export{n as a,p as b,P as c,S as d,I as e,b as f,k as g,_ as h,C as i,j,w as k,L as l,N as m};
1
+ import{m as c}from"./chunk-CWD4O5PM.js";import{e as a}from"./chunk-ZPT5D4VP.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var n="pi-agent-text-editor",p=23,P="pi-agent-text-editor/position",I="pi-agent-text-editor/search",b=`${n}/core/ready`,S=`${n}/plugin/register`,s=e.Function([],e.Unknown()),d=e.Object({tryResolve:s},{additionalProperties:!0}),l=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),T=e.Object({start:l,end:l,linewise:e.Optional(e.Boolean())}),R=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(T))}),x=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(R,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),g=e.String({pattern:"\\S"}),m=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),y=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),v=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p)}),u=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p),id:e.String(),setup:s}),E=e.Object({plugin:u,accept:s});function k(t){return i.Check(g,t)}r(k,"isTextEditorToolId");function _(t){if(!i.Check(m,t))return!1;let o=t;return c(o.resolver)&&(!("priority"in o)||typeof o.priority=="number")}r(_,"isResourceResolverRegistration");function j(t){if(!i.Check(y,t))return!1;let o=t;return a(o.resolver)&&(!("resources"in o)||i.Check(d,o.resources))&&(!("priority"in o)||typeof o.priority=="number")}r(j,"isTextAnchorResolverRegistration");function C(t){return i.Check(x,t)}r(C,"isTextAnchorResourceResolutionAttempt");function L(t){return i.Check(v,t)}r(L,"isTextEditorCoreReady");function w(t){return i.Check(u,t)}r(w,"isTextEditorPlugin");function N(t){return i.Check(E,t)}r(N,"isTextEditorPluginRegistrationRequest");export{n as a,p as b,P as c,I as d,b as e,S as f,k as g,_ as h,j as i,C as j,L as k,w as l,N as m};
@@ -0,0 +1 @@
1
+ import{d as k,e as S,h as m,i as M}from"./chunk-CWD4O5PM.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var T=t.Union([t.Literal("pending"),t.Literal("applied"),t.Literal("not-applied"),t.Literal("unknown")]),b=t.Object({source:t.String(),effect:T,state:t.Optional(t.Union([t.Literal("present"),t.Literal("absent"),t.Literal("unknown")]))},{additionalProperties:!1}),O={effect:T,files:t.Array(b)};function R(s){return t.Object({operation:t.Literal(s),...O,operationId:t.Optional(t.String()),...s==="delete"||s==="flush"?{}:{target:t.Optional(t.String()),targetUnavailable:t.Optional(t.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function N(s){return S(R(s))}p(N,"mutationResultSchema");var U=t.Object({id:t.String(),operation:t.String(),effect:T,errors:t.Array(k)},{additionalProperties:!1}),D=t.Object({operation:t.Literal("flush"),...O,operations:t.Array(U)},{additionalProperties:!1}),_=S(D);function u(s){return typeof s=="object"&&s!==null}p(u,"record");function F(s,i,h=[]){let r=s.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:i,effect:"pending",...i!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(e=>e.resourceSource)),n=[],f=[],E=r.results;for(let e of E??[]){let o=e.data,y=[...new Set([...(o.files??[]).map(c=>c.path),...o.path?[o.path]:[]])];for(let c of y)f.push({source:c,...g.has(c)?{state:"present"}:{},effect:g.has(c)||o.ok===!0&&o.files?.some(L=>L.path===c)?"applied":r.effect??"unknown"});for(let c of o.errors??[])n.push({code:c.code??"MUTATION_FAILED",message:c.reason??"Mutation failed",source:c.path});o.ok===!1&&(o.errors?.length??0)===0&&n.push({code:"MUTATION_FAILED",message:"Mutation failed",...o.path?{source:o.path}:{}})}for(let e of g)f.some(o=>o.source===e)||f.push({source:e,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let e=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",o=typeof a.source=="string"?a.source:void 0;o&&f.push({source:o,...a.kind==="file-operation"&&a.ok===!0?{state:i==="delete"||i==="move"?"absent":"present"}:{},effect:i==="copy"&&typeof a.target=="string"&&a.target!==o?"not-applied":e}),typeof a.target=="string"&&f.push({source:a.target,effect:e,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&n.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",o)),typeof a.postProcessingError=="string"&&n.push(m(a.postProcessingError,"POST_EDIT_FAILED",o)),a.ok===!1&&n.length===0&&n.push(m("Resource operation failed","MUTATION_FAILED",o))}let d=[...new Map(f.map(e=>[e.source,e])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let e of r.metadata.resultFileStates){if(!u(e))continue;let o=d.find(y=>y.source===e.source);o&&(e.state==="present"||e.state==="absent")&&(o.state=e.state)}let A=d.some(e=>e.effect==="applied");s.isError&&n.length===0&&n.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(E?.length??0)===0&&!a&&g.size===0&&n.length===0&&r.effect!=="not-applied"&&n.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=d.some(e=>e.effect==="unknown")||n.some(e=>e.code==="UNKNOWN_RESULT")?"unknown":A?"applied":"not-applied";return{status:n.length===0?"success":!a&&A&&d.some(e=>e.effect!=="applied")?"partial":"error",data:{operation:i,effect:w,files:d,...i!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...i!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:n}}p(F,"mutationOutcome");function j(s,i,h=[],r){let l=F(s,i,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(s,R(i),l)}p(j,"structuredMutation");export{R as a,N as b,D as c,_ as d,F as e,j as f};
@@ -1,3 +1,3 @@
1
- import{c as j}from"./chunk-YHUTTZC6.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(`
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
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
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,4 +1,4 @@
1
- import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-FBOW7XOV.js";import{a as he,b as ve}from"./chunk-WJTHY6AG.js";import{a as C}from"./chunk-K5G4FDXD.js";import{c as be}from"./chunk-YHUTTZC6.js";import{a as ge}from"./chunk-6CZO43OH.js";import{a as ce,b as pe}from"./chunk-OBNING2A.js";import{e as fe,h as me,i as Y}from"./chunk-2P2OGO3G.js";import"./chunk-ZPT5D4VP.js";import{d as S,e as w}from"./chunk-N34ATN52.js";import{a as s}from"./chunk-EI7MMDWY.js";import A from"node:path";import{access as Lt}from"node:fs/promises";import{StringEnum as Bt}from"@earendil-works/pi-ai";import{defineTool as Ht}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{access as B}from"node:fs/promises";async function j(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}s(j,"resolvePythonDebuggerCommand");import Qe from"cross-spawn";import{cp as et,mkdtemp as tt,readdir as rt,rm as nt,stat as O}from"node:fs/promises";import{tmpdir as at}from"node:os";import ot from"node:net";import P from"node:path";import{pathToFileURL as it}from"node:url";import{createMessageConnection as st,StreamMessageReader as dt,StreamMessageWriter as ut}from"vscode-jsonrpc/node";import Ke from"cross-spawn";import Xe from"node:net";var Ye=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),Ze=128,k=class r{static{s(this,"DapClient")}#t;#o;#u;#r=new Map;#n=[];#i=new Set;#c=new Set;#a=Buffer.alloc(0);#g=1;#l;#f;#p;constructor(e,t,n){this.#t=e,this.#o=t,this.#u=n,e.on("data",o=>this.#b(o)),e.once("error",o=>this.#e(o)),e.once("close",()=>this.#e(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#e(o)),n.once("exit",(o,a)=>{this.#e(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Ke(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#g=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Xe.createConnection({port:e,host:t}),i=s(d=>o(d),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),n(new r(a,a))})})}onReverseRequest(e){this.#f=e}onEvent(e){return this.#c.add(e),()=>this.#c.delete(e)}request(e,t,n={}){if(this.#l!==void 0)return Promise.reject(this.#l);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#p=void 0);let o=this.#g++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((d,u)=>{let b,l=s(()=>{b!==void 0&&clearTimeout(b),n.signal?.removeEventListener("abort",p)},"cleanup"),p=s(()=>{this.#r.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(b=setTimeout(()=>{this.#r.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#r.set(o,{resolve:s(m=>d(m),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),i}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#n.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#n.splice(a,1)[0]):this.#l!==void 0?Promise.reject(this.#l):new Promise((i,d)=>{let u={events:o,resolve:s(l=>{clearTimeout(u.timer),this.#i.delete(u),i(l)},"resolve"),reject:s(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let b=s(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?b():n?.addEventListener("abort",b,{once:!0})})}close(){this.#t.destroy(),this.#o.destroy(),this.#u!==void 0&&!this.#u.killed&&this.#u.kill(),this.#e(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#o.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
1
+ import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-PKKDDIWW.js";import{a as he,b as ve}from"./chunk-4GCWGE2C.js";import{a as C}from"./chunk-K5G4FDXD.js";import{a as ge}from"./chunk-BU7IZLKB.js";import{a as ce,b as pe}from"./chunk-S5PL5DFQ.js";import{e as be}from"./chunk-PS2B6THP.js";import{e as fe,h as me,i as Y}from"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.js";import{d as S,e as w}from"./chunk-N34ATN52.js";import{a as s}from"./chunk-EI7MMDWY.js";import A from"node:path";import{access as Lt}from"node:fs/promises";import{StringEnum as Bt}from"@earendil-works/pi-ai";import{defineTool as Ht}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{access as B}from"node:fs/promises";async function j(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}s(j,"resolvePythonDebuggerCommand");import Qe from"cross-spawn";import{cp as et,mkdtemp as tt,readdir as rt,rm as nt,stat as O}from"node:fs/promises";import{tmpdir as at}from"node:os";import ot from"node:net";import P from"node:path";import{pathToFileURL as it}from"node:url";import{createMessageConnection as st,StreamMessageReader as dt,StreamMessageWriter as ut}from"vscode-jsonrpc/node";import Ke from"cross-spawn";import Xe from"node:net";var Ye=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),Ze=128,k=class r{static{s(this,"DapClient")}#t;#o;#u;#r=new Map;#n=[];#i=new Set;#c=new Set;#a=Buffer.alloc(0);#g=1;#l;#f;#p;constructor(e,t,n){this.#t=e,this.#o=t,this.#u=n,e.on("data",o=>this.#b(o)),e.once("error",o=>this.#e(o)),e.once("close",()=>this.#e(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#e(o)),n.once("exit",(o,a)=>{this.#e(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Ke(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#g=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Xe.createConnection({port:e,host:t}),i=s(d=>o(d),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),n(new r(a,a))})})}onReverseRequest(e){this.#f=e}onEvent(e){return this.#c.add(e),()=>this.#c.delete(e)}request(e,t,n={}){if(this.#l!==void 0)return Promise.reject(this.#l);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#p=void 0);let o=this.#g++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((d,u)=>{let b,l=s(()=>{b!==void 0&&clearTimeout(b),n.signal?.removeEventListener("abort",p)},"cleanup"),p=s(()=>{this.#r.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(b=setTimeout(()=>{this.#r.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#r.set(o,{resolve:s(m=>d(m),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),i}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#n.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#n.splice(a,1)[0]):this.#l!==void 0?Promise.reject(this.#l):new Promise((i,d)=>{let u={events:o,resolve:s(l=>{clearTimeout(u.timer),this.#i.delete(u),i(l)},"resolve"),reject:s(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let b=s(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?b():n?.addEventListener("abort",b,{once:!0})})}close(){this.#t.destroy(),this.#o.destroy(),this.#u!==void 0&&!this.#u.killed&&this.#u.kill(),this.#e(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#o.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
2
2
  \r
3
3
  `),t]))}#b(e){for(this.#a=Buffer.concat([this.#a,e]);;){let t=this.#a.indexOf(`\r
4
4
  \r
@@ -17,7 +17,7 @@ ${t.fg("accent",Et(e))}`,0,0)}s($e,"renderDebugActionCall");function N(r,e,t,n){
17
17
  \r
18
18
  ${e}`}s(It,"dapFrame");function re(r,e,t){return r.request("initialize",{clientID:"pi-agent-ide",adapterID:e,pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0,supportsVariableType:!0,supportsVariablePaging:!0,supportsRunInTerminalRequest:!1,supportsStartDebuggingRequest:!0},{signal:t})}s(re,"initializeClient");function V(){return new Promise((r,e)=>{let t=Ve.createServer();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let n=t.address();if(n===null||typeof n=="string"){t.close(),e(new Error("Could not allocate a debug adapter port"));return}t.close(o=>o===void 0?r(n.port):e(o))})})}s(V,"availablePort");function ne(r,e){if(process.env.PI_DEBUG_DAP_TRACE==="1"){process.stderr.write(`[${e}] pid=${String(r.pid)}
19
19
  `),r.once("exit",(t,n)=>process.stderr.write(`[${e}] exit code=${String(t)} signal=${String(n)}
20
- `));for(let t of[r.stdout,r.stderr])t?.on("data",n=>process.stderr.write(`[${e}] ${n.toString("utf8")}`))}}s(ne,"traceAdapterProcess");function $t(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),i=s(()=>{clearTimeout(a),e.off("error",d),e.off("exit",u)},"cleanup"),d=s(b=>{i(),t.close(),e.killed||e.kill(),o(b)},"fail"),u=s(b=>d(new Error(`vscDebugger exited with code ${String(b)} before connecting`)),"onExit");e.once("error",d),e.once("exit",u),r.then(b=>{i(),n(b)},d)})}s($t,"waitForRAdapterConnection");function Je(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(b=>b!==null),i=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=s(()=>{clearTimeout(i);for(let b of a)b.off("data",u)},"cleanup"),u=s(b=>{b.toString("utf8").includes(e)&&(d(),n())},"onData");for(let b of a)b.on("data",u);r.once("error",b=>{d(),o(b)}),r.once("exit",b=>{d(),o(new Error(`${t} server exited with code ${String(b)}`))})})}s(Je,"waitForAdapterReady");function Ct(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=s(i=>{i.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",i=>t(new Error(`js-debug server exited with code ${i}`)))})}s(Ct,"waitForJsDebugReady");async function Ue(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await k.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}s(Ue,"connectWithRetry");async function ae(r){r.adapterTemporaryDirectory!==void 0&&(await xt(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}s(ae,"removeAdapterTemporaryDirectory");async function Me(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=H("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}s(Me,"terminateOwnedAdapterProcess");async function jt(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await j(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:y.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:y.dirname(y.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:r.cwd}};if(r.adapter==="shell"){let n=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??y.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:y.join(n,"bashdb_dir/bashdb"),pathBashdbLib:y.join(n,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(r.adapter==="powershell"){let n=process.env.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";if(e===void 0)throw new Error("PowerShell debugger temporary directory was not created");return{command:process.env.PI_PWSH_PATH??"pwsh",args:["-NoLogo","-NoProfile","-Command",`& '${y.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${y.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${y.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${n.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:r.program,createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}return{command:process.execPath,args:[],adapterID:"pwa-node",request:"launch",launch:{...t,type:"pwa-node",console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(r.program),"**","*.js")]}}}s(jt,"adapterRecipe");var oe=h.Object({source:h.String(),sourceResource:h.String(),breakpointsResource:h.String(),adapter:h.String(),program:h.String(),cwd:h.String(),status:h.String(),breakpoints:h.Array(h.Object({source:h.String(),file:h.String(),line:h.Integer(),verified:h.Boolean()},{additionalProperties:!1}))},{additionalProperties:!1}),qt=fe(oe),Nt=h.Object({adapter:Bt(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed DAP adapter for Dart, Python, Go, Java, Elixir, Julia, Kotlin, C, C++, Rust, Swift, Zig, Lua, C#, JavaScript, TypeScript, PHP, PowerShell, R, Ruby, or shell scripts."}),program:h.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:h.Optional(h.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:h.Optional(h.Array(h.String(),{description:"Arguments passed to the debugged program."})),mainClass:h.Optional(h.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:h.Optional(h.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function Ot(r){ue(r,[await de({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(l=>({tool:l,resourcePrefixes:["debug:"]}))]})]);let e=Pe("debugger"),t=e!==void 0&&typeof e.evaluate=="function"?e:new W,n=new Map,o=We(t,"debugger-source"),a=We(t,"debugger-input"),i=ye(r).add(Oe(t)),d=Ie(t),u={protocol:ce,apiVersion:pe,id:"debugger",setup(l){l.addResolver({resolver:o,matchesCall:s(p=>t.sourceFile(p)!==void 0,"matchesCall"),renderCall(p,m,c){let g=$(p)?p:{},f=typeof g.path=="string"?g.path:"",D=t.get(f),v=t.sourceFile(f);if(D===void 0||v===void 0)throw new Error("Debugger source header lost its session");let E=A.relative(D.options.cwd,v),_=Array.isArray(g.views)?g.views.filter(X=>typeof X=="string"):[],R=typeof g.offset=="number"?g.offset:1,I=typeof g.limit=="number"?g.limit:void 0,K=I===void 0?String(R):`${R}-${R+I-1}`;return be(c.lastComponent,{tool:"debug file",primary:{text:`${E}:${K}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:c.expanded},m)}}),l.addView({view:"breakpoints",presenter:d}),l.describe('views: ["breakpoints"] \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped. debug:<session> \u2014 debugger state.')}},b={protocol:he,apiVersion:ve,id:"debugger",setup(l){l.addResolver({resolver:a}),l.tool("insert").addSemanticHandler({matches:s(p=>Ft(p,t),"matches"),execute:s(async(p,m)=>{let c=m,g=ze(t,c.path);if(t.sourceFile(c.path)!==void 0){if(c.text!=="breakpoint"||c.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let D=await p.resolveAnchor("anchor"),v=await t.addBreakpoint(c.path,D.lineNumber,p.signal);return{source:v.source,summary:`Breakpoint ${v.source} created at ${A.relative(g.options.cwd,v.file)}:${v.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:v.file,line:v.line,verified:v.verified,snapshot:t.snapshot(g)}}}if(c.path!==g.source||c.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let f=await Ut(t,g,c.text,p.signal);return{source:g.source,summary:f===void 0?z(g):`${f.expression} = ${f.result}${f.type===void 0?"":` (${f.type})`}`,data:Gt(t,g,c.text,f)}},"execute")}),l.tool("delete").addSemanticHandler({matches:s(p=>Jt(p,t),"matches"),execute:s(async(p,m)=>{let c=m.path,g=ze(t,c),f=t.snapshot(g);n.set(c,f);let D=c.includes("/breakpoint/");await t.delete(c,p.signal);let v=D?t.snapshot(g):{...f,status:"terminated"};return{source:c,summary:`Deleted ${c}.`,data:{kind:D?"debug-breakpoint":"debug-session",deleted:!0,snapshot:v}}},"execute")}),l.describe('For debug:<session> resources, insert performs debugger actions without changing source text. On a debug source, insert "breakpoint" at an anchor. On the session, insert start, continue, step over, step into, step out, or evaluate <expression>. Delete removes a breakpoint or terminates the session.');for(let p of["insert","delete"])l.addToolRenderer({tool:p,matches(m,c){return c==="call"?$(m)&&typeof m.path=="string"&&(t.get(m.path)!==void 0||n.has(m.path)):te($(m)&&"details"in m?m.details:m)!==void 0},renderCall(m,c,g){let f=m,D=f.path===void 0?void 0:t.get(f.path),v=f.path===void 0?void 0:n.get(f.path),E=g.state;D!==void 0?E.snapshot=t.snapshot(D):v!==void 0&&(E.snapshot=v);let _=E.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:t.breakpoint(f.path)??_.breakpoints.find(X=>X.source===f.path),I=f.path===void 0?void 0:t.sourceFile(f.path),K=p==="delete"?R===void 0?"delete-session":`delete-breakpoint ${A.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&I!==void 0?`breakpoint ${A.basename(I)}:${Wt(f)}`:f.text??"debug action";return $e(_,K,c)},renderResult(m,c,g){let f=te(m.details);if(f===void 0)throw new Error("Debugger result is missing its session");let D=qe(m.details);return N(f,c.expanded,g,D)}})}};await Promise.all([le(r,Ae),ge(r,u)]),await we(r,b),r.registerTool(Ht({name:"debug",exposure:"deferred",namespace:{name:"ide_debug",description:"Create local debugger sessions and inspect debug resources."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:Nt,outputSchema:qt,async execute(l,p,m,c,g){let f=A.resolve(g.cwd,p.cwd??"."),D=A.resolve(f,p.program);try{await Lt(D);let v=t.create({adapter:p.adapter,program:D,sourceFile:A.resolve(f,p.source??p.program),args:p.args??[],cwd:f,...p.mainClass===void 0?{}:{mainClass:p.mainClass}}),E=Mt(t,v),{snapshot:_,stop:R,...I}=E;return Y({content:[{type:"text",text:`${z(v)}
20
+ `));for(let t of[r.stdout,r.stderr])t?.on("data",n=>process.stderr.write(`[${e}] ${n.toString("utf8")}`))}}s(ne,"traceAdapterProcess");function $t(r,e,t){return new Promise((n,o)=>{let a=setTimeout(()=>d(new Error("Timed out starting vscDebugger")),5e3),i=s(()=>{clearTimeout(a),e.off("error",d),e.off("exit",u)},"cleanup"),d=s(b=>{i(),t.close(),e.killed||e.kill(),o(b)},"fail"),u=s(b=>d(new Error(`vscDebugger exited with code ${String(b)} before connecting`)),"onExit");e.once("error",d),e.once("exit",u),r.then(b=>{i(),n(b)},d)})}s($t,"waitForRAdapterConnection");function Je(r,e,t){return new Promise((n,o)=>{let a=[r.stdout,r.stderr].filter(b=>b!==null),i=setTimeout(()=>o(new Error(`Timed out starting ${t} server`)),process.platform==="win32"?15e3:5e3),d=s(()=>{clearTimeout(i);for(let b of a)b.off("data",u)},"cleanup"),u=s(b=>{b.toString("utf8").includes(e)&&(d(),n())},"onData");for(let b of a)b.on("data",u);r.once("error",b=>{d(),o(b)}),r.once("exit",b=>{d(),o(new Error(`${t} server exited with code ${String(b)}`))})})}s(Je,"waitForAdapterReady");function Ct(r){return new Promise((e,t)=>{let n=r.stdout;if(n===null){t(new Error("js-debug server stdout is unavailable"));return}let o=setTimeout(()=>t(new Error("Timed out starting js-debug server")),5e3),a=s(i=>{i.toString("utf8").includes("Debug server listening")&&(clearTimeout(o),n.off("data",a),e())},"onData");n.on("data",a),r.once("error",t),r.once("exit",i=>t(new Error(`js-debug server exited with code ${i}`)))})}s(Ct,"waitForJsDebugReady");async function Ue(r,e="js-debug"){let t;for(let n=0;n<100;n++)try{return await k.connect(r)}catch(o){t=o,await new Promise(a=>setTimeout(a,25))}throw t instanceof Error?t:new Error(`Could not connect to ${e}`)}s(Ue,"connectWithRetry");async function ae(r){r.adapterTemporaryDirectory!==void 0&&(await xt(r.adapterTemporaryDirectory,{recursive:!0,force:!0,maxRetries:process.platform==="win32"?10:0,retryDelay:100}),r.adapterTemporaryDirectory=void 0)}s(ae,"removeAdapterTemporaryDirectory");async function Me(r){if(!(r===void 0||r.exitCode!==null||r.signalCode!==null)){if(process.platform!=="win32"||r.pid===void 0){r.kill();return}await new Promise(e=>{let t=H("taskkill.exe",["/pid",String(r.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0});t.once("error",()=>{r.kill(),e()}),t.once("exit",()=>e())})}}s(Me,"terminateOwnedAdapterProcess");async function jt(r,e){let t={name:"Pi Agent IDE debug session",request:"launch",program:r.program,cwd:r.cwd,args:[...r.args]};if(r.adapter==="dart")return{command:process.env.PI_DART_PATH??"dart",args:["debug_adapter"],adapterID:"dart",request:"launch",launch:{...t,type:"dart",debugSdkLibraries:!1,debugExternalPackageLibraries:!1,stopOnEntry:!0,vmAdditionalArgs:["--pause-isolates-on-start"]}};if(r.adapter==="debugpy"){let n=await j(r.cwd);return{command:n.command,args:[...n.args,"-m","debugpy.adapter"],adapterID:"debugpy",request:"launch",launch:{...t,type:"python",console:"internalConsole",justMyCode:!1}}}if(r.adapter==="kotlin"){if(r.mainClass===void 0)throw new Error("Java and Kotlin debug sessions require mainClass");return{command:process.env.PI_KOTLIN_DEBUG_ADAPTER_PATH??"kotlin-debug-adapter",args:[],adapterID:r.adapter,request:"launch",launch:{...t,type:"kotlin",mainClass:r.mainClass,projectRoot:r.cwd,stopOnEntry:!0}}}if(r.adapter==="netcoredbg")return{command:process.env.PI_NETCOREDBG_PATH??"netcoredbg",args:["--interpreter=vscode"],adapterID:"coreclr",request:"launch",launch:{...t,type:"coreclr",console:"internalConsole"}};if(r.adapter==="elixir")return{command:process.env.PI_ELIXIR_LS_DEBUG_PATH??(process.platform==="win32"?"debug_adapter.bat":"/opt/pi-debug-adapters/elixir-ls/debug_adapter.sh"),args:[],adapterID:"mix_task",request:"launch",launch:{name:t.name,request:"launch",type:"mix_task",task:"run",taskArgs:[r.program,...r.args],projectDir:r.cwd,startApps:!0,exitAfterTaskReturns:!0}};if(r.adapter==="julia")return{command:process.env.PI_JULIA_PATH??"julia",args:[],adapterID:"julia",request:"launch",launch:{...t,type:"julia",stopOnEntry:!1}};if(r.adapter==="lldb-dap")return{command:y.extname(r.sourceFile).toLowerCase()===".swift"?process.env.PI_SWIFT_LLDB_DAP_PATH??process.env.PI_LLDB_DAP_PATH??"lldb-dap":process.env.PI_LLDB_DAP_PATH??(process.platform==="win32"?"lldb-dap":"lldb-dap-18"),args:[],adapterID:"lldb-dap",request:"launch",launch:{...t,type:"lldb-dap"}};if(r.adapter==="delve")return{command:process.env.PI_DELVE_PATH??"dlv",args:[],adapterID:"go",request:"launch",launch:{...t,type:"go",mode:"debug"}};if(r.adapter==="r")return{command:process.env.PI_R_PATH??"R",args:[],adapterID:"R-Debugger",request:"launch",launch:{name:t.name,request:"launch",type:"R-Debugger",debugMode:"file",file:r.program,workingDirectory:r.cwd,commandLineArgs:[...r.args],allowGlobalDebugging:!1,loadPackages:[],supportsStdoutReading:!0,supportsWriteToStdinEvent:!0,overwriteHelp:!1}};if(r.adapter==="ruby")return{command:process.env.PI_RUBY_DEBUG_PATH??"rdbg",args:[],adapterID:"rdbg",request:"launch",launch:{...t,type:"rdbg"}};if(r.adapter==="php")return{command:process.execPath,args:[process.env.PI_PHP_DEBUG_PATH??"/opt/pi-debug-adapters/php-debug/extension/out/phpDebug.js"],adapterID:"php",request:"launch",launch:{...t,type:"php",runtimeExecutable:process.env.PI_PHP_PATH??"php",runtimeArgs:["-dxdebug.start_with_request=yes"],console:"internalConsole",port:0,env:{XDEBUG_MODE:"debug,develop",XDEBUG_CONFIG:"client_port=${port}"}}};if(r.adapter==="lua")return{command:process.execPath,args:[process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js"],adapterID:"lua-local",request:"launch",launch:{...t,type:"lua-local",program:{lua:process.env.PI_LUA_PATH??"lua",file:r.program},extensionPath:y.dirname(y.dirname(process.env.PI_LUA_DEBUG_PATH??"/opt/pi-debug-adapters/lua-debug/extension/extension/debugAdapter.js")),workspacePath:r.cwd}};if(r.adapter==="shell"){let n=process.env.PI_BASH_DEBUG_ROOT??"/opt/pi-debug-adapters/bash-debug/extension";return{command:process.execPath,args:[process.env.PI_BASH_DEBUG_PATH??y.join(n,"out/bashDebug.js")],adapterID:"bashdb",request:"launch",launch:{...t,type:"bashdb",pathBash:process.env.PI_BASH_PATH??"/usr/bin/bash",pathBashdb:y.join(n,"bashdb_dir/bashdb"),pathBashdbLib:y.join(n,"bashdb_dir"),pathCat:"/usr/bin/cat",pathMkfifo:"/usr/bin/mkfifo",pathPkill:"/usr/bin/pkill",terminalKind:"debugConsole",argsString:"",env:{},showDebugOutput:!1,trace:!1}}}if(r.adapter==="powershell"){let n=process.env.PI_POWERSHELL_EDITOR_SERVICES_PATH??"/opt/pi-debug-adapters/powershell-editor-services";if(e===void 0)throw new Error("PowerShell debugger temporary directory was not created");return{command:process.env.PI_PWSH_PATH??"pwsh",args:["-NoLogo","-NoProfile","-Command",`& '${y.join(n,"PowerShellEditorServices/Start-EditorServices.ps1").replaceAll("'","''")}' -LogPath '${y.join(e,"logs").replaceAll("'","''")}' -LogLevel Warning -SessionDetailsPath '${y.join(e,"session.json").replaceAll("'","''")}' -FeatureFlags @() -AdditionalModules @() -HostName 'Pi Agent IDE' -HostProfileId 'pi-agent-ide' -HostVersion '1.0.0' -BundledModulesPath '${n.replaceAll("'","''")}' -Stdio -DebugServiceOnly`],adapterID:"PowerShell",request:"launch",launch:{...t,script:r.program,createTemporaryIntegratedConsole:!1,executeMode:"Call"}}}return{command:process.execPath,args:[],adapterID:"pwa-node",request:"launch",launch:{...t,type:"pwa-node",console:"internalConsole",autoAttachChildProcesses:!1,stopOnEntry:!0,sourceMaps:!0,pauseForSourceMap:!0,outFiles:[y.join(y.dirname(r.program),"**","*.js")]}}}s(jt,"adapterRecipe");var oe=h.Object({source:h.String(),sourceResource:h.String(),breakpointsResource:h.String(),adapter:h.String(),program:h.String(),cwd:h.String(),status:h.String(),breakpoints:h.Array(h.Object({source:h.String(),file:h.String(),line:h.Integer(),verified:h.Boolean()},{additionalProperties:!1}))},{additionalProperties:!1}),qt=fe(oe),Nt=h.Object({adapter:Bt(["dart","debugpy","delve","java","elixir","julia","kotlin","lldb-dap","lua","netcoredbg","node","php","powershell","r","ruby","shell"],{description:"Select an installed DAP adapter for Dart, Python, Go, Java, Elixir, Julia, Kotlin, C, C++, Rust, Swift, Zig, Lua, C#, JavaScript, TypeScript, PHP, PowerShell, R, Ruby, or shell scripts."}),program:h.String({minLength:1,description:"Source file or executable to launch. Relative paths resolve from cwd."}),source:h.Optional(h.String({description:"Source file used for anchored breakpoints. Defaults to program."})),args:h.Optional(h.Array(h.String(),{description:"Arguments passed to the debugged program."})),mainClass:h.Optional(h.String({minLength:1,description:"Fully qualified JVM main class. Required by Java and Kotlin adapters."})),cwd:h.Optional(h.String({description:"Working directory. Relative paths resolve from the workspace."}))},{additionalProperties:!1});async function Ot(r){ue(r,[await de({id:"debugger",description:"Debugger sessions, breakpoints, stepping, and cleanup",triggers:[{tool:"debug"},...["read","insert","delete"].map(l=>({tool:l,resourcePrefixes:["debug:"]}))]})]);let e=Pe("debugger"),t=e!==void 0&&typeof e.evaluate=="function"?e:new W,n=new Map,o=We(t,"debugger-source"),a=We(t,"debugger-input"),i=ye(r).add(Oe(t)),d=Ie(t),u={protocol:ce,apiVersion:pe,id:"debugger",setup(l){l.addResolver({resolver:o,matchesCall:s(p=>t.sourceFile(p)!==void 0,"matchesCall"),renderCall(p,m,c){let g=$(p)?p:{},f=typeof g.path=="string"?g.path:"",D=t.get(f),v=t.sourceFile(f);if(D===void 0||v===void 0)throw new Error("Debugger source header lost its session");let E=A.relative(D.options.cwd,v),_=Array.isArray(g.views)?g.views.filter(X=>typeof X=="string"):[],R=typeof g.offset=="number"?g.offset:1,I=typeof g.limit=="number"?g.limit:void 0,K=I===void 0?String(R):`${R}-${R+I-1}`;return be(c.lastComponent,{tool:"debug file",primary:{text:`${E}:${K}`,color:"accent",underline:!0},qualifiers:_.length===0?[]:[{text:`views ${_.join(",")}`}],details:[{label:"source",value:f},{label:"file",value:v},..._.length===0?[]:[{label:"views",value:_.join(",")}]],expanded:c.expanded},m)}}),l.addView({view:"breakpoints",presenter:d}),l.describe({path:"debug:<session> \u2014 debugger state.",views:"breakpoints \u2014 current debugger breakpoints beside source lines. Normal files include every current session; debug sources are session-scoped."})}},b={protocol:he,apiVersion:ve,id:"debugger",setup(l){l.addResolver({resolver:a}),l.tool("insert").addSemanticHandler({matches:s(p=>Ft(p,t),"matches"),execute:s(async(p,m)=>{let c=m,g=ze(t,c.path);if(t.sourceFile(c.path)!==void 0){if(c.text!=="breakpoint"||c.anchor===void 0)throw new Error('A debug source accepts text "breakpoint" with one anchor');let D=await p.resolveAnchor("anchor"),v=await t.addBreakpoint(c.path,D.lineNumber,p.signal);return{source:v.source,summary:`Breakpoint ${v.source} created at ${A.relative(g.options.cwd,v.file)}:${v.line}.`,data:{kind:"debug-breakpoint",session:g.source,file:v.file,line:v.line,verified:v.verified,snapshot:t.snapshot(g)}}}if(c.path!==g.source||c.anchor!==void 0)throw new Error("Debug commands target the session resource without an anchor");let f=await Ut(t,g,c.text,p.signal);return{source:g.source,summary:f===void 0?z(g):`${f.expression} = ${f.result}${f.type===void 0?"":` (${f.type})`}`,data:Gt(t,g,c.text,f)}},"execute")}),l.tool("delete").addSemanticHandler({matches:s(p=>Jt(p,t),"matches"),execute:s(async(p,m)=>{let c=m.path,g=ze(t,c),f=t.snapshot(g);n.set(c,f);let D=c.includes("/breakpoint/");await t.delete(c,p.signal);let v=D?t.snapshot(g):{...f,status:"terminated"};return{source:c,summary:`Deleted ${c}.`,data:{kind:D?"debug-breakpoint":"debug-session",deleted:!0,snapshot:v}}},"execute")}),l.describe('For debug:<session> resources, insert performs debugger actions without changing source text. On a debug source, insert "breakpoint" at an anchor. On the session, insert start, continue, step over, step into, step out, or evaluate <expression>. Delete removes a breakpoint or terminates the session.');for(let p of["insert","delete"])l.addToolRenderer({tool:p,matches(m,c){return c==="call"?$(m)&&typeof m.path=="string"&&(t.get(m.path)!==void 0||n.has(m.path)):te($(m)&&"details"in m?m.details:m)!==void 0},renderCall(m,c,g){let f=m,D=f.path===void 0?void 0:t.get(f.path),v=f.path===void 0?void 0:n.get(f.path),E=g.state;D!==void 0?E.snapshot=t.snapshot(D):v!==void 0&&(E.snapshot=v);let _=E.snapshot;if(_===void 0)throw new Error("Debugger renderer lost its session");let R=f.path===void 0?void 0:t.breakpoint(f.path)??_.breakpoints.find(X=>X.source===f.path),I=f.path===void 0?void 0:t.sourceFile(f.path),K=p==="delete"?R===void 0?"delete-session":`delete-breakpoint ${A.basename(R.file)}:${R.line}`:f.text==="breakpoint"&&I!==void 0?`breakpoint ${A.basename(I)}:${Wt(f)}`:f.text??"debug action";return $e(_,K,c)},renderResult(m,c,g){let f=te(m.details);if(f===void 0)throw new Error("Debugger result is missing its session");let D=qe(m.details);return N(f,c.expanded,g,D)}})}};await Promise.all([le(r,Ae),ge(r,u)]),await we(r,b),r.registerTool(Ht({name:"debug",exposure:"deferred",namespace:{name:"ide_debug",description:"Create local debugger sessions and inspect debug resources."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},label:"Debug session",promptSnippet:"Create a local DAP debug session before setting anchored breakpoints",description:"Use debug to create a configured local debugger session. This does not launch the program yet. The returned debug: resource survives extension reloads.",parameters:Nt,outputSchema:qt,async execute(l,p,m,c,g){let f=A.resolve(g.cwd,p.cwd??"."),D=A.resolve(f,p.program);try{await Lt(D);let v=t.create({adapter:p.adapter,program:D,sourceFile:A.resolve(f,p.source??p.program),args:p.args??[],cwd:f,...p.mainClass===void 0?{}:{mainClass:p.mainClass}}),E=Mt(t,v),{snapshot:_,stop:R,...I}=E;return Y({content:[{type:"text",text:`${z(v)}
21
21
  Source: ${E.sourceResource}
22
22
  Breakpoints: ${E.breakpointsResource}
23
23
 
@@ -1,4 +1,4 @@
1
- import{a as k,b as I,c as A}from"./chunk-FUG2TEKI.js";import{j as E,k as S}from"./chunk-KVHDMIZS.js";import"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as K}from"node:fs/promises";import W from"node:path";async function T(e){let n=[],t=await K(e,{withFileTypes:!0});for(let i of t){let o=W.join(e,i.name);i.isDirectory()?n.push(...await T(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}s(T,"collectFiles");import{readFile as X}from"node:fs/promises";var v=256*1024;async function w(e){let n=await X(e);if(n.byteLength>v)throw new Error(`File exceeds the ${v}-byte AST outline limit: ${e}`);if(n.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${e}`);let t=n.toString("utf8").replaceAll(`\r
1
+ import{a as k,b as I,c as A}from"./chunk-QFTBY67N.js";import{j as E,k as S}from"./chunk-KVHDMIZS.js";import"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as K}from"node:fs/promises";import W from"node:path";async function T(e){let n=[],t=await K(e,{withFileTypes:!0});for(let i of t){let o=W.join(e,i.name);i.isDirectory()?n.push(...await T(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}s(T,"collectFiles");import{readFile as X}from"node:fs/promises";var v=256*1024;async function w(e){let n=await X(e);if(n.byteLength>v)throw new Error(`File exceeds the ${v}-byte AST outline limit: ${e}`);if(n.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${e}`);let t=n.toString("utf8").replaceAll(`\r
2
2
  `,`
3
3
  `),i=t.endsWith(`
4
4
  `)?t.slice(0,-1):t,o=i.length===0?[]:i.split(`
@@ -1 +1 @@
1
- import{c as a,d as u,e as c}from"./chunk-OBNING2A.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
1
+ import{c as a,d as u,e as c}from"./chunk-S5PL5DFQ.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(o,r){let s=t(()=>{let e,i={plugin:r,accept(R){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=R}};return o.events.emit(u,i),e},"announce"),n=t(()=>{},"unsubscribe");n=o.events.on(a,e=>{if(!c(e))throw new Error("Invalid pi-agent-read core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-read core announced readiness without accepting the plugin");n(),i.catch(()=>{})}),o.on("session_shutdown",n);let d=s();if(d!==void 0)return n(),d}t(E,"connectReadPlugin");export{E as a};
@@ -0,0 +1,3 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";function oe(){return{pending:new Set,active:new Ce}}i(oe,"createSchedulerState");function ve(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(ve,"conflicts");function Re(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===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=>r.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(Re,"coveredAccess");async function we(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(we,"waitForDependencies");var U=class r{constructor(e=oe()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(b=>{if(n?.throwIfAborted(),!Re(a.accesses,b,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 b});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],u=s.catch(()=>{}),p,f=new Promise(m=>{p=m}),h={accesses:u,done:f};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await we(s.then(async b=>(await Promise.all(d.map(q=>Promise.race([q.done,q.accesses.then(ye=>ve(b,ye)?q.done:void 0)]))),b)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Te=Symbol.for("pi-agent-resource.resource-scheduler-state"),be=globalThis,Ee=be[Te]??=oe(),Se=new U(Ee);import{realpath as xe,stat as Ae}from"node:fs/promises";import j from"node:path";import{fileURLToPath as Oe}from"node:url";async function se(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=j.resolve(e,r.startsWith("file:")?Oe(r):r),[o,s]=await Promise.allSettled([xe(n),Ae(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let f=o.reason;if(!(f instanceof Error)||!("code"in f)||f.code!=="ENOENT")throw f;let h=j.dirname(n);if(h===n)a=n;else{let y=(await se(h,e,t)).find(b=>b.resource.startsWith("file:"));a=j.join(y?.resource.slice(5)??h,j.basename(n))}}let d=a.split(j.sep).join("/"),u=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:u,group:u,mode:t}];if(s.status==="fulfilled"){let f=s.value;f.isDirectory()&&(p[0]={resource:u,group:u,mode:t,recursive:!0}),f.ino!==0n&&p.push({resource:`inode:${f.dev}:${f.ino}`,group:u,mode:t,recursive:f.isDirectory()})}else{let f=s.reason;if(!(f instanceof Error)||!("code"in f)||f.code!=="ENOENT")throw f}return p}i(se,"resourceAccesses");import{Type as g}from"typebox";import{Value as ke}from"typebox/value";var D=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ie(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(D,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(D,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(D)},required:["status","errors"],additionalProperties:!1}}i(ie,"structuredResultSchema");var ae=1024*1024;function z(r){let e=new Set,t=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))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>ae)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(z,"assertJsonData");function ce(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(ce,"resultError");function Ne(r,e,t){try{if(z(t),!ke.Check(ie(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=ce(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return z(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Ne,"withStructuredResult");function je(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(je,"renderContentDescription");import{Type as l}from"typebox";import{Value as He}from"typebox/value";import{Type as c}from"typebox";import{Value as Pe}from"typebox/value";var C={additionalProperties:!0},P=c.Function([],c.Unknown()),v=c.String({minLength:1}),Ie=c.Object({type:c.Literal("text"),text:c.String(),textSignature:c.Optional(c.String())},C),_e=c.Object({type:c.Literal("image"),data:c.String(),mimeType:c.String()},C),Ue=c.Object({type:c.Literal("custom"),kind:v,data:c.Unknown()},C),De=c.Array(c.Union([Ie,_e,Ue]),{minItems:1}),ue=c.Union([c.Object({source:v,link:c.Optional(v),read:P,write:c.Optional(c.Never())},C),c.Object({source:v,link:c.Optional(v),read:c.Optional(c.Never()),write:P},C),c.Object({source:v,link:c.Optional(v),read:P,write:P},C)]),Le=c.Object({id:v,tryResolve:P},C),$e=c.Union([c.Object({kind:c.Literal("not-handled")},C),c.Object({kind:c.Literal("resolved"),resource:ue},C),c.Object({kind:c.Literal("failed"),error:c.Unknown()},C)]);function J(r){return L(De,r)?$(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(J,"isAgentContent");function le(r){return L(ue,r)?$(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function";return t&&n}):!1}i(le,"isResource");function We(r){return L(Le,r)}i(We,"isResourceResolver");function Ve(r){return L($e,r)?$(()=>{let e=r;return e.kind!=="resolved"||le(e.resource)}):!1}i(Ve,"isResourceResolutionAttempt");function L(r,e){return $(()=>Pe.Check(r,e))}i(L,"safeCheck");function $(r){try{return r()}catch{return!1}}i($,"safeEvaluate");var R={additionalProperties:!0},Me=l.Function([],l.Unknown()),W=l.String({minLength:1}),Fe=l.Object({provider:W,capability:l.Union([l.Literal("read"),l.Literal("write")])},R),Ke=l.Object({source:W,bytes:l.Unknown(),mediaType:l.Optional(l.String())},R),qe=l.Object({signal:l.Optional(l.Unknown())},R),ze=l.Object({id:W,description:W,tryConvert:Me},R),Je=l.Union([l.Object({kind:l.Literal("not-handled")},R),l.Object({kind:l.Literal("converted"),content:l.Unknown()},R),l.Object({kind:l.Literal("failed"),error:l.Unknown()},R)]),Be=l.Object({target:l.Unknown(),converter:l.Unknown(),priority:l.Optional(l.Number())},R);function A(r){return O(Fe,r)&&S(()=>r.provider.trim().length>0)}i(A,"isContentTarget");function B(r){return O(Ke,r)?S(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(B,"isContentInput");function Y(r){return O(qe,r)?S(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(Y,"isContentConversionContext");function de(r){return O(ze,r)?S(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(de,"isContentConverter");function G(r){return O(Je,r)?S(()=>{let e=r;return e.kind!=="converted"||J(e.content)}):!1}i(G,"isContentConversionAttempt");function E(r){return O(Be,r)?S(()=>{let e=r;return A(e.target)&&de(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(E,"isContentConverterRegistration");function O(r,e){return S(()=>He.Check(r,e))}i(O,"safeCheck");function S(r){try{return r()}catch{return!1}}i(S,"safeEvaluate");var V=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function Q(r){if(!A(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!E(o))throw new TypeError("Invalid content converter registration");if(!k(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.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(!Y(s))throw new TypeError("Invalid content conversion context");X(s.signal);let a=n();for(let{converter:d}of a){X(s.signal);let u=await d.tryConvert(o,s);if(X(s.signal),!G(u))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(u.kind!=="not-handled"){if(u.kind==="failed")throw u.error;return u.content}}throw new V(o.source,e)}}}i(Q,"createContentRunner");function k(r,e){return r.provider===e.provider&&r.capability===e.capability}i(k,"targetsEqual");function X(r){r?.throwIfAborted()}i(X,"throwIfAborted");import{Type as w}from"typebox";import{Value as Ye}from"typebox/value";var N="pi-agent-resource/content-conversion",H=2,I=`${N}/host/ready`,_=`${N}/converter/register`,fe={additionalProperties:!0},Ge=w.Function([],w.Unknown()),Xe=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(H),target:w.Unknown()},fe),Qe=w.Object({registration:w.Unknown(),accept:Ge},fe);function Z(r){return pe(Xe,r)&&te(()=>A(r.target))}i(Z,"isContentHostReady");function ee(r){return pe(Qe,r)&&te(()=>E(r.registration))}i(ee,"isContentConverterRegistrationRequest");function pe(r,e){return te(()=>Ye.Check(r,e))}i(pe,"safeCheck");function te(r){try{return r()}catch{return!1}}i(te,"safeEvaluate");function Ze(r,e){let t=Q(e),n=r.events.on(_,o=>{if(!ee(o))throw new Error("Invalid content converter registration request");if(!k(t.target,o.registration.target))return;let s;try{t.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 r.on("session_shutdown",n),r.events.emit(I,{protocol:N,apiVersion:H,target:t.target}),{target:t.target,listDescriptions(){return t.listDescriptions()},convert(o,s){return t.convert(o,s)}}}i(Ze,"createContentHost");function et(r,e){if(!E(e))throw new TypeError("Invalid content converter registration");let t=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 r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!Z(s))throw new Error("Invalid content conversion host readiness event");if(!k(e.target,s.target))return;let a=t();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(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(et,"connectContentConverter");import{createHash as ge,randomUUID as re}from"node:crypto";import{statSync as tt}from"node:fs";import{readFile as rt}from"node:fs/promises";import T from"node:path";import{fileURLToPath as nt}from"node:url";import{Type as M}from"typebox";var ot=M.Union([M.String(),M.Array(M.String())]),x="RESULT#",he="pi-agent-resource:result-targets",K=class{static{i(this,"ResultTargetStore")}#e=new Map;#o=new Map;#n=new Map;#t=new Map;clear(){this.#e.clear(),this.#o.clear(),this.#n.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${x}${re()}`;return this.#e.set(o,{state:"ready",targets:ne(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${x}${re()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:ne(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(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!==T.resolve(t))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);for(let u of d.targets)this.refresh(u.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:ne(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let u of d.ranges){let p=JSON.stringify([d.source,u]);s.has(p)||(s.add(p),o.push({...d,ranges:[u]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await me(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}publish(e,t,n,o=[]){let s=re();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,u=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(u&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let f=p.matches;for(let h of f){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#o.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ge("sha256").update(d).digest("hex"),consumable:u,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(f=>this.source(f,t,n));if(typeof e!="string")return e;let o=this.#o.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(x)?e.slice(x.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let u=this.#t.get(a);if(!u&&!s&&e.startsWith(x)&&this.#e.has(e))return e;if(!u)throw new Error("Result reference expired or unknown; repeat the source tool.");if(u.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ge("sha256").update(e).digest("hex")!==u.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let f of u.resources)this.refresh(f,t);if(!this.#t.has(a))throw new Error("Result reference expired; repeat the source tool.");if(!u.consumable)throw new Error("Only successful source results can be consumed.");for(let f of u.references)if(!this.#e.has(f))throw this.#t.delete(a),new Error("Result reference expired; repeat the source tool.");if(u.references.length===1)return u.references[0];if(u.references.length>1)return u.references;let p=u.resources.length===1?u.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>F(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>F(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=F(e,t),o=JSON.stringify([T.resolve(t),n]),s=st(e,t),a=this.#n.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#n.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#n.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(x))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(x))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function F(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(t.startsWith("file:"))try{return nt(t)}catch{}return T.resolve(e,t)}i(F,"sourcePath");function st(r,e){try{let t=tt(F(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(st,"fileStamp");async function me(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=await rt(n.source,{encoding:"utf8",signal:e}),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(me,"verifyResultTargets");function ne(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...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(ne,"combineTargets");function it(r){let e;if(r.events.emit(he,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new K,n=r.events.on(he,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(it,"connectResultTargets");export{U as a,Se as b,se as c,D as d,ie as e,ae as f,z as g,ce as h,Ne as i,je as j,J as k,le as l,We as m,Ve as n,A as o,B as p,Y as q,de as r,G as s,E as t,V as u,Q as v,k as w,N as x,H as y,I as z,_ as A,Z as B,ee as C,Ze as D,et as E,ot as F,K as G,me as H,it as I};
@@ -0,0 +1,2 @@
1
+ import{e as m,i as g,m as x}from"./chunk-CWD4O5PM.js";import{a as i}from"./chunk-EI7MMDWY.js";import{Type as n}from"typebox";import{Value as y}from"typebox/value";import{Type as d}from"typebox";var c=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.`}))}),O={path:"What to read: a resource path, unchanged source result or its UUID. Pass the whole result to compose tools. Supply a source; an empty call cannot select one. temp:<id> reads saved complete output until this runtime is disposed. raw:<local-file> reads original bytes from a regular file (relative, absolute or file:// path); raw: does not accept views.",offset:"For raw: sources, a zero-based integer byte offset; negative offsets count from the file end. For text sources, the 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.",limit:"For raw: sources, a non-negative integer byte count (0 reads no bytes). For text sources, the maximum lines from the selected starting position. Omit for the bounded default read. Explicit ranges on other content require a source-specific handler; otherwise they fail.",views:"Optional source-specific presentations. Omit for the source's default presentation. Values may include settings after a colon; use the syntax below. Combine views only when their contracts allow it. Unknown views can be ignored and reported in ignoredViews; they do not add capabilities. raw: sources reject views."};function H(e){let r=i((o,u)=>({...o,description:[O[u],e[u]].filter(R=>R!==void 0).join(`
2
+ `)}),"describe");return{...c,properties:{path:r(c.properties.path,"path"),offset:r(c.properties.offset,"offset"),limit:r(c.properties.limit,"limit"),views:r(c.properties.views,"views")}}}i(H,"describeReadParameters");import{Type as t}from"typebox";var w=t.Object({value:t.String(),kind:t.String(),state:t.Optional(t.String())},{additionalProperties:!1}),k=t.Object({lineNumber:t.Integer(),content:t.String(),lineEnding:t.String(),anchors:t.Optional(t.Array(t.String()))},{additionalProperties:!1}),L=t.Object({path:t.String(),offset:t.Integer()},{additionalProperties:!1}),f={source:t.String(),truncated:t.Boolean(),continuation:t.Optional(L),fullResult:t.Optional(t.String())},h=t.Object({...f,kind:t.Literal("text"),target:t.Optional(t.String()),lines:t.Array(k),startLine:t.Integer(),endLine:t.Integer(),totalLines:t.Integer(),references:t.Optional(t.Array(w))},{additionalProperties:!1}),b=t.Object({...f,kind:t.Literal("bytes"),bytes:t.Array(t.Integer({minimum:0,maximum:255})),byteOffset:t.Integer(),byteLength:t.Integer(),totalBytes:t.Integer()},{additionalProperties:!1}),P=t.Union([t.Object({type:t.Literal("text"),text:t.String()},{additionalProperties:!1}),t.Object({type:t.Literal("image"),mimeType:t.String()},{additionalProperties:!1})]),S=t.Object({...f,kind:t.Literal("native"),blocks:t.Array(P)},{additionalProperties:!1}),p=t.Union([t.Object({kind:t.Literal("recovery"),source:t.String(),candidates:t.Array(t.Object({path:t.String()},{additionalProperties:!1}))},{additionalProperties:!1}),h,b,S,t.Object({kind:t.Literal("resources"),source:t.Optional(t.String()),resources:t.Array(t.Union([h,b,S])),truncated:t.Boolean(),fullResult:t.Optional(t.String())},{additionalProperties:!1})]),v=m(p);function C(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}i(C,"publicLine");function T(e){if(e.kind==="resources"){let a=e.resources.map(s=>T(s));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:a,truncated:a.some(s=>typeof s=="object"&&s!==null&&"truncated"in s&&s.truncated===!0)}}if(e.kind==="bytes"){let a=e.bytes.slice(0,32768),s=e.truncated===!0||a.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:a,byteOffset:e.byteOffset,byteLength:a.length,totalBytes:e.totalBytes,truncated:s,...e.byteOffset+a.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+a.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(a=>{if(a.type==="text")return{type:a.type,text:a.text};if(a.type==="image")return{type:a.type,mimeType:a.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let r=[],o=0;for(let a of e.lines){let s=C(a);if(o+=Buffer.byteLength(JSON.stringify(s)),r.length>=2e3||o>512*1024)break;r.push(s)}if(r.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 u=r.length<e.lines.length,R=r.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,lines:r,startLine:r[0]?.lineNumber??0,endLine:r.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:u,...e.target===void 0?{}:{target:e.target},...e.references===void 0?{}:{references:e.references},...u||R<e.totalLines?{continuation:{path:e.source,offset:R+1}}:{}}}i(T,"publicData");function E(e){let r=e.details.failure;if(e.isError||r!==void 0)return g(e,p,{status:"error",...r?.candidates?.length&&r.source!==void 0?{data:{kind:"recovery",source:r.source,candidates:r.candidates}}:{},errors:[{code:r?.code??"READ_FAILED",message:r?.message??"Read failed",...r?.source===void 0?{}:{source:r.source}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let o=T(e.script);return g(e,p,{status:"success",data:e.details.temporarySource!==void 0&&typeof o=="object"&&o!==null?{...o,fullResult:e.details.temporarySource}:o,errors:[]})}catch(o){return g(e,p,{status:"error",errors:[{code:o instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:o instanceof Error?o.message:String(o)}]})}}i(E,"structuredRead");var l=n.Function([],n.Unknown()),D=n.Object({resolver:n.Unknown(),matchesCall:n.Optional(l),renderCall:n.Optional(l),priority:n.Optional(n.Number()),renderResult:n.Optional(l),preserveTruncatedOutput:n.Optional(n.Boolean())}),A=n.Object({resolver:n.Unknown(),priority:n.Optional(n.Number())}),F=n.Object({id:n.String({pattern:"\\S"}),priority:n.Optional(n.Number()),resolve:l}),N=n.Object({view:n.String({pattern:"\\S"}),includes:n.Optional(n.Array(n.String({pattern:"\\S"}))),presenter:n.Object({id:n.String(),present:l}),priority:n.Optional(n.Number())}),U=n.Object({resolvedBy:n.String({pattern:"\\S"}),contentKind:n.Union([n.Literal("text"),n.Literal("any")])}),j=n.Union([n.Object({stage:n.Literal("pre-read"),handler:l}),n.Object({stage:n.Literal("read"),when:U,handler:l}),n.Object({stage:n.Literal("post-read"),handler:l})]);function J(e){if(!y.Check(A,e))return!1;let r=e,o=r.resolver;return typeof o.id=="string"&&o.id.length>0&&typeof o.tryResolve=="function"&&(!("priority"in r)||typeof r.priority=="number")}i(J,"isTextTargetResolverRegistration");function Y(e){if(!y.Check(D,e))return!1;let r=e;return x(r.resolver)?r.resolver.id!=="any"&&(!("priority"in r)||typeof r.priority=="number")&&(!("matchesCall"in r)||typeof r.matchesCall=="function")&&(!("renderCall"in r)||typeof r.renderCall=="function")&&"matchesCall"in r=="renderCall"in r&&(!("renderResult"in r)||typeof r.renderResult=="function"):!1}i(Y,"isResourceResolverRegistration");function X(e){return y.Check(j,e)}i(X,"isReadHandlerRegistration");function Z(e){return y.Check(N,e)}i(Z,"isReadViewRegistration");function $(e){return y.Check(F,e)}i($,"isFragmentResolverRegistration");function ee(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(ee,"isReadFragmentResolution");function I(e){return typeof e=="object"&&e!==null}i(I,"isRecord");export{c as a,H as b,p as c,v as d,E as e,J as f,Y as g,X as h,Z as i,$ as j,ee as k};
@@ -0,0 +1,7 @@
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};
@@ -0,0 +1 @@
1
+ import{F as d,e as c}from"./chunk-CWD4O5PM.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, unchanged Read/Search/Select/edit result, its UUID, or an array of such results. Results select only their registered ranges unless symbols: navigation follows external references."}),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})]),P=c(O);function T(o,l,r,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((n,a)=>({source:n.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:n.lineNumber,startColumn:n.startColumn,endLine:n.endLineNumber??n.lineNumber,endColumn:n.endColumn},...Buffer.byteLength(n.matchedText)<=4096?{matchedText:n.matchedText}:{textTruncated:!0},...r===void 0?{}:{references:{line:`SEARCH#${r}:${a+1}:line`,match:`SEARCH#${r}:${a+1}:match`}}})),...l&&r!==void 0?{all:{line:`SEARCH#${r}:all:line`,match:`SEARCH#${r}:all:match`}}:{}}}s(T,"selectionData");export{y as a,h as b,O as c,P as d,T as e};
@@ -0,0 +1,2 @@
1
+ import{d as R}from"./chunk-WU6ZK6YD.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as C}from"@earendil-works/pi-coding-agent";import{Text as D}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,z=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
2
+ `)),k.set(e.details,a)),e={...e,details:a}}if(r.isPartial||t.isError||!R(e.details)){let a=e.content[0],n=a?.type==="text"?a.text:"",i=t.isError?"error":r.isPartial?"dim":"toolOutput";return new D(o.fg(i,n),0,0)}let l=(t.lastComponent instanceof f?t.lastComponent:void 0)??new f(e.details,o,r.expanded);return l.updateSearch(e.details,o,r.expanded),l}c(v,"renderSearchResult");var f=class extends S{static{c(this,"SearchResultPanel")}constructor(r,o,t){super(T(r,t),o,t)}updateSearch(r,o,t){super.update(T(r,t),o,t)}};function T(e,r){let o=$(e,r).map(t=>t.kind==="file"?{kind:"source",label:t.file.path,link:t.file.link,count:t.file.matchCount}:t.kind==="line"?{kind:"line",...t.line}:t.kind==="candidate"?{kind:"note",text:t.identifier}:t.kind==="summary"?{kind:"note",text:t.text}:t.kind==="omitted"?{kind:"note",text:`\u2026 ${t.matches} more ${d(t.matches,"match","matches")} \xB7 ${C("app.tools.expand")} to expand`}:{kind:"note",text:"No matches found"});return{summary:P(e),rows:o}}c(T,"searchModel");function $(e,r){let o=e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0,t=e.files.length===0?o?[]:[{kind:"empty"}]:e.files.flatMap(n=>[{kind:"file",file:n},...n.uniqueLineCount===void 0?n.lines.map(i=>({kind:"line",file:n,line:i})):[{kind:"summary",text:`${String(n.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(n.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(e.fuzzy!==void 0&&(e.fuzzy.status==="skipped"?t.push({kind:"summary",text:"Fuzzy search unavailable"}):e.fuzzy.candidates.length>0&&t.push(...e.fuzzy.candidates.flatMap(n=>{let i=e.fuzzyPresentation?.groups.find(u=>u.identifier===n.identifier)?.files??[],h=i.reduce((u,m)=>u+m.matchCount,0);return[{kind:"candidate",identifier:n.identifier},...i.length===0?[]:[{kind:"summary",text:`Shown ${String(h)} of ${String(n.matchCount)}${n.selection.complete?"":"+"}`},...i.flatMap(u=>[{kind:"file",file:u},...u.lines.map(m=>({kind:"line",file:u,line:m}))])]]}))),e.fuzzy!==void 0||r||t.length<=z)return t;let s=t.slice(0,z-1);for(;s.at(-1)?.kind==="file";)s.pop();let l=new Set(s.flatMap(n=>n.kind==="line"?n.line.logicalMatchIds??[]:[])),a=l.size>0?l.size:s.reduce((n,i)=>n+(i.kind==="line"?i.line.matchCount:0),0);return[...s,{kind:"omitted",matches:Math.max(0,e.matchCount-a)}]}c($,"searchViewport");function P(e){if(e.matchCount===0&&e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0&&e.fuzzyPresentation!==void 0){let o=e.fuzzy.candidates.reduce((l,a)=>l+a.matchCount,0),t=e.fuzzy.candidates.every(l=>l.selection.complete)?"":"+",s=e.fuzzyPresentation.fileCount;return`0 exact \xB7 ${String(o)}${t} fuzzy ${d(o,"match","matches")} \xB7 ${String(s)}${t} ${d(s,"file","files")}`}return e.matchCount===0?e.complete?"No matches":"No matches \xB7 incomplete":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${d(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${d(e.fileCount,"file","files")}`}c(P,"searchSummary");function d(e,r,o){return e===1?r:o}c(d,"plural");export{w as a,v as b,f as c};