pi-agent-ide 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +10 -4
  3. package/dist/chunk-22CLOM2D.js +1 -0
  4. package/dist/{chunk-LY6U5EAD.js → chunk-2527OQ4Y.js} +1 -1
  5. package/dist/chunk-3XJ3KDPZ.js +16 -0
  6. package/dist/chunk-5JELU6RV.js +7 -0
  7. package/dist/chunk-DDKHZZDO.js +5 -0
  8. package/dist/chunk-FEDVTZJG.js +1 -0
  9. package/dist/chunk-HSM6R7IB.js +27 -0
  10. package/dist/chunk-K5G4FDXD.js +1 -0
  11. package/dist/chunk-M5IVSCR2.js +1 -0
  12. package/dist/chunk-OYWIZII6.js +1 -0
  13. package/dist/{chunk-7ALCBKCW.js → chunk-PCZH7GOX.js} +11 -11
  14. package/dist/{chunk-DQXPQOF7.js → chunk-SQ7ZTGOP.js} +1 -1
  15. package/dist/entry-10.js +1 -1
  16. package/dist/entry-11.js +1 -1
  17. package/dist/entry-12.js +1 -1
  18. package/dist/entry-13.js +1 -1
  19. package/dist/entry-14.js +1 -1
  20. package/dist/entry-15.js +1 -1
  21. package/dist/entry-16.js +1 -0
  22. package/dist/entry-18.js +1 -1
  23. package/dist/entry-19.js +1 -1
  24. package/dist/entry-20.js +1 -1
  25. package/dist/entry-21.js +1 -1
  26. package/dist/entry-22.js +1 -2
  27. package/dist/entry-23.js +2 -1
  28. package/dist/entry-24.js +1 -1
  29. package/dist/entry-25.js +1 -1
  30. package/dist/entry-26.js +1 -1
  31. package/dist/entry-27.js +1 -12
  32. package/dist/entry-28.js +12 -1
  33. package/dist/entry-29.js +1 -1
  34. package/dist/entry-30.js +1 -1
  35. package/dist/entry-31.js +1 -1
  36. package/dist/entry-32.js +1 -4
  37. package/dist/entry-33.js +3 -8
  38. package/dist/entry-34.js +9 -1
  39. package/dist/entry-35.js +1 -1
  40. package/dist/entry-36.js +1 -1
  41. package/dist/entry-37.js +1 -1
  42. package/dist/entry-38.js +1 -1
  43. package/dist/entry-39.js +1 -1
  44. package/dist/entry-40.js +1 -1
  45. package/dist/entry-41.js +1 -18
  46. package/dist/entry-42.js +18 -1
  47. package/dist/entry-43.js +1 -1
  48. package/dist/entry-44.js +1 -1
  49. package/dist/entry-45.js +1 -1
  50. package/dist/entry-46.js +1 -7
  51. package/dist/entry-47.js +7 -11
  52. package/dist/entry-48.js +11 -1
  53. package/dist/entry-49.js +1 -1
  54. package/dist/entry-50.js +1 -1
  55. package/dist/entry-51.js +1 -1
  56. package/dist/entry-52.js +1 -1
  57. package/dist/entry-53.js +1 -1
  58. package/dist/entry-54.js +1 -1
  59. package/dist/entry-55.js +1 -1
  60. package/dist/entry-56.js +1 -0
  61. package/dist/entry-57.js +0 -1
  62. package/dist/entry-58.js +1 -0
  63. package/dist/entry-59.js +0 -1
  64. package/dist/entry-60.js +1 -1
  65. package/dist/entry-61.js +1 -1
  66. package/dist/entry-62.js +1 -1
  67. package/dist/entry-63.js +1 -1
  68. package/dist/entry-64.js +1 -1
  69. package/dist/entry-65.js +1 -0
  70. package/dist/entry-66.js +0 -1
  71. package/dist/entry-67.js +1 -0
  72. package/dist/entry-68.js +0 -1
  73. package/dist/entry-69.js +1 -1
  74. package/dist/entry-70.js +1 -1
  75. package/dist/entry-71.js +1 -203
  76. package/dist/entry-72.js +254 -25
  77. package/dist/entry-73.js +30 -2
  78. package/dist/entry-74.js +2 -1
  79. package/dist/entry-75.js +1 -1
  80. package/dist/entry-76.js +1 -3
  81. package/dist/entry-77.js +3 -3
  82. package/dist/entry-78.js +3 -1
  83. package/dist/entry-79.js +1 -1
  84. package/dist/entry-80.js +1 -1
  85. package/dist/entry-81.js +1 -0
  86. package/dist/pi-agent-ide.js +3 -3
  87. package/docs/configuration.md +3 -1
  88. package/docs/tools.md +12 -0
  89. package/node_modules/pi-agent-doctor/package.json +6 -6
  90. package/node_modules/pi-agent-doctor/runtime/entry-22.js +1 -0
  91. package/node_modules/pi-agent-filesystem/package.json +7 -7
  92. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  93. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  94. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  95. package/node_modules/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  96. package/node_modules/pi-agent-ide-ast/package.json +12 -11
  97. package/node_modules/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  98. package/node_modules/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  99. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  100. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  101. package/node_modules/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  102. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  103. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  104. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  105. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +3 -1
  106. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  107. package/node_modules/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  108. package/node_modules/pi-agent-image/package.json +3 -3
  109. package/node_modules/pi-agent-invariant/package.json +2 -2
  110. package/node_modules/pi-agent-pdf/package.json +3 -3
  111. package/node_modules/pi-agent-read/package.json +11 -11
  112. package/node_modules/pi-agent-read/runtime/entry-41.js +0 -1
  113. package/node_modules/pi-agent-read/runtime/entry-42.js +2 -0
  114. package/node_modules/pi-agent-read/src/api/read-parameters.ts +2 -2
  115. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  116. package/node_modules/pi-agent-resource/package.json +2 -2
  117. package/node_modules/pi-agent-search/package.json +7 -7
  118. package/node_modules/pi-agent-search/runtime/entry-46.js +0 -1
  119. package/node_modules/pi-agent-search-text/package.json +9 -9
  120. package/node_modules/pi-agent-search-text/runtime/entry-48.js +1 -0
  121. package/node_modules/pi-agent-text/package.json +3 -3
  122. package/node_modules/pi-agent-text/runtime/entry-50.js +1 -0
  123. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  124. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  125. package/node_modules/pi-agent-text-anchor-exact/index.ts +3 -3
  126. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  127. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  128. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  129. package/node_modules/pi-agent-text-anchor-exact/src/config.ts +2 -2
  130. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  131. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  132. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  133. package/node_modules/pi-agent-text-editor/package.json +25 -25
  134. package/node_modules/pi-agent-text-editor/runtime/entry-71.js +0 -1
  135. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  136. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  137. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  138. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  139. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  140. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  141. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  142. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  143. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  144. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  145. package/node_modules/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  146. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  147. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  148. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  149. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  150. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  151. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  152. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  153. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  154. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  155. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  156. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  157. package/node_modules/pi-agent-tool-ui/runtime/entry-76.js +1 -0
  158. package/node_modules/pi-agent-web/package.json +7 -7
  159. package/node_modules/pi-agent-web-html/package.json +3 -3
  160. package/node_modules/pi-agent-web-image/package.json +4 -4
  161. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  162. package/node_modules/pi-agent-web-text/package.json +4 -4
  163. package/node_modules/pi-agent-web-text/runtime/entry-81.js +2 -0
  164. package/package.json +43 -38
  165. package/src/api/path-identity.ts +15 -0
  166. package/src/composite/builtin-extensions.ts +7 -2
  167. package/src/composite/module-labels.ts +4 -0
  168. package/src/composite/module-settings.ts +34 -14
  169. package/src/composite/preferences.ts +46 -3
  170. package/src/composite/selection.ts +5 -1
  171. package/src/doctor/inventory.ts +7 -2
  172. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  173. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  174. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  175. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  176. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-26.js +2 -0
  177. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-23.js +2 -0
  178. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  179. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  180. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  181. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  182. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  183. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-81.js +2 -0
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-77.js +2 -0
  185. package/src/extensions/pi-agent-read/package.json +11 -11
  186. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  187. package/src/extensions/pi-agent-read/runtime/entry-42.js +2 -0
  188. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
  189. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +11 -6
  190. package/src/extensions/pi-agent-search/package.json +7 -7
  191. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  192. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-48.js +1 -0
  193. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-49.js +1 -0
  194. package/src/extensions/pi-agent-search/runtime/entry-46.js +0 -1
  195. package/src/extensions/pi-agent-search/runtime/entry-47.js +2 -0
  196. package/src/extensions/pi-agent-text-editor/package.json +25 -25
  197. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  198. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-51.js +2 -0
  199. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +3 -3
  200. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  201. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -1
  202. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-53.js +2 -0
  203. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/config.ts +2 -2
  204. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  205. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-54.js +0 -1
  206. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-55.js +2 -0
  207. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  208. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  209. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-74.js +2 -0
  210. package/src/extensions/pi-agent-text-editor/runtime/entry-71.js +0 -1
  211. package/src/extensions/pi-agent-text-editor/runtime/entry-72.js +2 -0
  212. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +125 -3
  213. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  214. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  215. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +32 -3
  216. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +21 -19
  217. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +37 -0
  218. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +85 -34
  219. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +2 -3
  220. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +589 -241
  221. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  222. package/src/extensions/pi-agent-text-editor/src/core/text-editor-config.ts +3 -3
  223. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  224. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  225. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  226. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  227. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  228. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  229. package/src/pi-agent-ide.ts +15 -2
  230. package/src/plugins/pi-agent-ide-ast/package.json +12 -11
  231. package/src/plugins/pi-agent-ide-ast/runtime/entry-27.js +0 -1
  232. package/src/plugins/pi-agent-ide-ast/runtime/entry-28.js +2 -0
  233. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  234. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  235. package/src/plugins/pi-agent-ide-changes/runtime/entry-29.js +0 -1
  236. package/src/plugins/pi-agent-ide-debugger/index.ts +2 -8
  237. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +31 -0
  238. package/src/plugins/pi-agent-ide-debugger/src/breakpoint-view.ts +3 -1
  239. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +24 -23
  240. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -2
  241. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +55 -17
  242. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -22
  243. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  244. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  245. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  246. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +3 -1
  247. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  248. package/src/plugins/pi-agent-ide-lsp/runtime/entry-34.js +2 -0
  249. package/src/plugins/pi-agent-ide-processes/src/registry.ts +4 -0
  250. package/src/plugins/pi-agent-ide-processes/src/ui.ts +18 -9
  251. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +1 -0
  252. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +1 -0
  253. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
  254. package/src/plugins/pi-agent-ide-terminal/src/types.ts +1 -0
  255. package/src/plugins/pi-agent-ide-vision/index.ts +232 -0
  256. package/src/plugins/pi-agent-ide-vision/src/vision.ts +530 -0
  257. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +30 -0
  258. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +33 -0
  259. package/dist/chunk-5PLV4HLG.js +0 -1
  260. package/dist/chunk-G725MARR.js +0 -16
  261. package/dist/chunk-HKXDP2FD.js +0 -7
  262. package/dist/chunk-IRECDTJG.js +0 -27
  263. package/dist/chunk-J4RTW44E.js +0 -1
  264. package/dist/chunk-NZYDMBM6.js +0 -1
  265. package/dist/chunk-WGGIQ7IJ.js +0 -1
  266. package/dist/entry-17.js +0 -1
  267. package/node_modules/pi-agent-doctor/runtime/entry-17.js +0 -1
  268. package/node_modules/pi-agent-filesystem/runtime/entry-22.js +0 -2
  269. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  270. package/node_modules/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  271. package/node_modules/pi-agent-image/runtime/entry-34.js +0 -1
  272. package/node_modules/pi-agent-resource/runtime/entry-42.js +0 -1
  273. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  274. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  275. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  276. package/node_modules/pi-agent-text-editor/runtime/entry-55.js +0 -1
  277. package/node_modules/pi-agent-tool-call-interception/runtime/entry-74.js +0 -1
  278. package/node_modules/pi-agent-web/runtime/entry-76.js +0 -2
  279. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  280. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-22.js +0 -2
  281. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-77.js +0 -2
  282. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-76.js +0 -2
  283. package/src/extensions/pi-agent-read/runtime/entry-37.js +0 -1
  284. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +0 -2
  285. package/src/extensions/pi-agent-search/runtime/entry-43.js +0 -1
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  289. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  290. package/src/extensions/pi-agent-text-editor/runtime/entry-55.js +0 -1
  291. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  292. package/src/plugins/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  293. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-23.js +0 -0
  294. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  295. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  296. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  297. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  298. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  299. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
  300. /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-35.js +0 -0
  301. /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-36.js +0 -0
  302. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-37.js +0 -0
  303. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-43.js +0 -0
  304. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-47.js +0 -0
  305. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-49.js +0 -0
  306. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-72.js +0 -0
  307. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  308. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-75.js +0 -0
  309. /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-77.js +0 -0
  310. /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  311. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  312. /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  313. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-24.js +0 -0
  314. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-25.js +0 -0
  315. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-78.js +0 -0
  316. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-79.js +0 -0
  317. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-80.js +0 -0
  318. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-73.js +0 -0
  319. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-30.js +0 -0
  320. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-31.js +0 -0
  321. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-32.js +0 -0
  322. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-33.js +0 -0
@@ -1,26 +1,26 @@
1
- import{a as re,b as ie,c as oe}from"./chunk-ESPNEJHK.js";import{a as ne}from"./chunk-5PLV4HLG.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as K}from"./chunk-6CZO43OH.js";import{a as Y,b as V}from"./chunk-OBNING2A.js";import{a as te}from"./chunk-ZTYWHL2F.js";import{a as Q,b as ee}from"./chunk-7UGNGK7Y.js";import{a as Z}from"./chunk-L7JMDDSD.js";import{a as z,b as J}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Fe from"node:path";import{stripVTControlCharacters as je}from"node:util";import{truncateLine as Ge}from"@earendil-works/pi-coding-agent";import{Text as x}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as ae,formatSize as Ue,truncateTail as We}from"@earendil-works/pi-coding-agent";function I(t){return We(t,{maxBytes:se-4096,maxLines:ae-32})}a(I,"terminalOutputTail");function P(t){let e=I(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
1
+ import{a as re,b as ie,c as oe}from"./chunk-ESPNEJHK.js";import{a as ne}from"./chunk-M5IVSCR2.js";import{a as Z}from"./chunk-L7JMDDSD.js";import{a as z,b as J}from"./chunk-O6LE42GK.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as K}from"./chunk-6CZO43OH.js";import{a as Y,b as V}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as te}from"./chunk-ZTYWHL2F.js";import{a as Q,b as ee}from"./chunk-7UGNGK7Y.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Fe from"node:path";import{stripVTControlCharacters as je}from"node:util";import{truncateLine as Ge}from"@earendil-works/pi-coding-agent";import{Text as x}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as ae,formatSize as Ue,truncateTail as We}from"@earendil-works/pi-coding-agent";function I(t){return We(t,{maxBytes:se-4096,maxLines:ae-32})}a(I,"terminalOutputTail");function P(t){let e=I(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
2
  `)}
3
3
  output:${r.length===0?" (empty)":`
4
4
  ${r}`}`;let i=e.truncatedBy==="lines"?`${ae} line output budget`:`${Ue(se)} output budget`,s=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
5
  `)}
6
6
  output:
7
7
  ${s}${r.length===0?"":`
8
- ${r}`}`}a(P,"formatAgentTerminalSnapshot");var He=500;function le(t,e,n,r,i){let s=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${E(n)} \xB7 ${s}`)}`;return new x(`${o}
8
+ ${r}`}`}a(P,"formatAgentTerminalSnapshot");var He=500;function le(t,e,n,r,i){let s=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${$(n)} \xB7 ${s}`)}`;return new x(`${o}
9
9
  ${i.fg("accent",O(r.family))} ${t}`,0,0)}a(le,"renderRunCall");function ue(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new x(r.join(`
10
- `),0,0)}a(ue,"renderTerminalActionResult");function $(t,e,n,r,i){let s=[Ye(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(o=>` ${i.fg("dim",o)}`)),new x(s.join(`
11
- `),0,0)}a($,"renderTerminalAction");function S(t,e,n,r){let i=Be(t,R,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new x(i.join(`
10
+ `),0,0)}a(ue,"renderTerminalActionResult");function E(t,e,n,r,i){let s=[Ye(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(o=>` ${i.fg("dim",o)}`)),new x(s.join(`
11
+ `),0,0)}a(E,"renderTerminalAction");function S(t,e,n,r){let i=Be(t,R,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new x(i.join(`
12
12
  `),0,0)}a(S,"renderTerminalResult");function ce(t,e,n){if(e)return S(t,!0,n);let r=_(t.output??"",R),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(s=>` ${n.fg("dim",s)}`)];return i.push(D(t,(s,o)=>n.fg(s,o))),new x(i.join(`
13
- `),0,0)}a(ce,"renderRunResult");function de(t,e){let n=a((o,l)=>e?.fg(o,l)??l,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${E(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",O(t.shellFamily))} ${M(t.command,84)}`],s=qe(t.output,2);return s.length>0&&i.push(...s.map(o=>` ${n("dim",M(o,90))}`)),i.push(D(t,n)),i.join(`
14
- `)}a(de,"renderActiveTerminal");function Be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":E(t.cwd),o=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",O(o))} ${t.command??""}`],u=_(t.output??"",e);return u.omission!==void 0&&l.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&l.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),l.push(D(t,(c,d)=>n.fg(c,d))),l}a(Be,"terminalCardLines");function qe(t,e){return _(t,e).lines}a(qe,"outputTail");function _(t,e){let n=I(je(t).replaceAll("\r","")),r=n.content.split(`
15
- `).map(u=>Ge(u.trimEnd(),He).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),l=s+o;return{lines:r.slice(s),...n.truncated||l>0?{omission:l>0?`\u2026 ${l} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(_,"outputWindow");function D(t,e){let n=t.status??"running",r=Xe(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,Ve(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}a(D,"statusLine");function Xe(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Xe,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function Ye(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":E(t.cwd),i=t.background===!0?"background":"wait",s=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}a(Ye,"terminalIdentity");function E(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Fe.sep}`))?`~${t.slice(e.length)}`:t}a(E,"shortCwd");function M(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(M,"oneLine");function Ve(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Ve,"formatElapsed");function me(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",renderSummary:a(n=>de(e,n).split(`
13
+ `),0,0)}a(ce,"renderRunResult");function de(t,e){let n=a((o,l)=>e?.fg(o,l)??l,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${$(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",O(t.shellFamily))} ${M(t.command,84)}`],s=qe(t.output,2);return s.length>0&&i.push(...s.map(o=>` ${n("dim",M(o,90))}`)),i.push(D(t,n)),i.join(`
14
+ `)}a(de,"renderActiveTerminal");function Be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":$(t.cwd),o=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",O(o))} ${t.command??""}`],u=_(t.output??"",e);return u.omission!==void 0&&l.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&l.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),l.push(D(t,(c,d)=>n.fg(c,d))),l}a(Be,"terminalCardLines");function qe(t,e){return _(t,e).lines}a(qe,"outputTail");function _(t,e){let n=I(je(t).replaceAll("\r","")),r=n.content.split(`
15
+ `).map(u=>Ge(u.trimEnd(),He).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),l=s+o;return{lines:r.slice(s),...n.truncated||l>0?{omission:l>0?`\u2026 ${l} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(_,"outputWindow");function D(t,e){let n=t.status??"running",r=Xe(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,Ve(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}a(D,"statusLine");function Xe(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Xe,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function Ye(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":$(t.cwd),i=t.background===!0?"background":"wait",s=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}a(Ye,"terminalIdentity");function $(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Fe.sep}`))?`~${t.slice(e.length)}`:t}a($,"shortCwd");function M(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(M,"oneLine");function Ve(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Ve,"formatElapsed");function me(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:a(n=>de(e,n).split(`
16
16
  `),"renderSummary"),renderDetail:a(n=>S(e,!0,n),"renderDetail"),sendInput:a(n=>t.write(e.source,n),"sendInput"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(me,"terminalProcessProvider");var Ke="#d8dee9",N="#111418",ze=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function U(t,e,n){let r=t.get(e);if(r===void 0)throw new Error(`Unknown terminal session ${e}`);await r.screenReady;let{createCanvas:i}=await import("@napi-rs/canvas"),s=Math.max(0,Math.min(r.rows-1,n?.start??0)),o=Math.max(1,Math.min(r.rows-s,n?.count??r.rows)),l=i(r.cols*9+24,o*18+24),u=l.getContext("2d");u.fillStyle=N,u.fillRect(0,0,l.width,l.height),u.textBaseline="top";let c=r.screen.buffer.active,d=Math.max(0,c.baseY);for(let m=0;m<o;m+=1){let p=c.getLine(d+s+m);if(p!==void 0)for(let f=0;f<r.cols;f+=1){let h=p.getCell(f);h===void 0||h.getWidth()===0||Je(u,h,f,m)}}return r.status==="running"&&c.cursorY>=s&&c.cursorY<s+o&&(u.fillStyle="rgba(216, 222, 233, 0.75)",u.fillRect(12+c.cursorX*9,12+(c.cursorY-s)*18+18-2,9,2)),l.toBuffer("image/png").toString("base64")}a(U,"renderTerminalScreen");function Je(t,e,n,r){let i=pe(e,"foreground"),s=pe(e,"background");e.isInverse()&&([i,s]=[s,i]);let o=12+n*9,l=12+r*18;s!==N&&(t.fillStyle=s,t.fillRect(o,l,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,o,l),e.isUnderline()&&t.fillRect(o,l+18-2,9*Math.max(1,e.getWidth()),1))}a(Je,"drawCell");function pe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ke:N;let i=n?t.isFgRGB():t.isBgRGB(),s=n?t.getFgColor():t.getBgColor();return i?`#${s.toString(16).padStart(6,"0")}`:Ze(s)}a(pe,"cellColor");function Ze(t){let e=ze[t];if(e!==void 0)return e;if(t>=232){let l=8+(t-232)*10;return fe(l,l,l)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),s=n%6,o=a(l=>l===0?0:55+l*40,"channel");return fe(o(r),o(i),o(s))}a(Ze,"ansiColor");function fe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(fe,"rgb");var W="\0pi-terminal-write\0",F="\0pi-terminal-keys\0";async function Se(t,e){let n=new Map,r=new Map,i={protocol:Y,apiVersion:V,id:"terminal",setup(o){o.addResolver({resolver:Qe(e),preserveTruncatedOutput:!0,renderResult(l,u,c){let d=l.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return S(m===void 0?p:{...p,output:e.screenTail(m).join(`
17
- `)},u.expanded,c,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(l){let u=l.request.path;if(u===void 0||!y(u)||l.request.views?.includes("image")!==!0)return{kind:"continue",context:l};let c=e.get(u);if(c===void 0)return{kind:"return",result:ge(u,`Unknown terminal session ${u}`)};try{return e.markInspected(u),{kind:"return",result:{content:[{type:"image",data:await U(e,u),mimeType:"image/png"}],details:{source:c.source,resolvedBy:"terminal"}}}}catch(d){return{kind:"return",result:ge(u,d instanceof Error?d.message:String(d))}}}}),o.describe('shell:<session> \u2014 terminal session status and a bounded output tail with a full-log path when truncated. Use views: ["image"] to read the current virtual terminal screen as a PNG.'),o.addPromptGuideline("Use read with a returned shell:<session> source to inspect terminal status and output. Add the image view when cursor movement, ANSI layout, or a full-screen terminal interface matters.")}},s={protocol:z,apiVersion:J,id:"terminal",setup(o){o.addResolver({resolver:et(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(ye(l.input,e,n),await he(l.input,e,r),tt(l,W)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await he(l.input,e,r),ye(l.input,e,n),nt(l)),"handler")});for(let l of["write","insert","delete"])o.addToolRenderer({tool:l,matches:a((u,c)=>st(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),$(f.snapshot??{},l,we(l,m),[],c)},renderResult(u,c,d){let m=ot(u.details);return ue(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([K(t,i),Z(t,s)]),t.on("tool_result",async(o,l)=>{if(!w(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:o.details,isError:!0};if(o.toolName==="delete"&&typeof u=="string"&&y(u)){let X=e.get(u);if(X===void 0)return;let Ne=e.snapshot(X);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:Ne,action:"delete",input:"session",changedLines:[]},isError:!1}),L=>({content:[{type:"text",text:L instanceof Error?L.message:String(L)}],details:{source:u,deleted:!1},isError:!0}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,v=we(h,o.input),b=e.screenChangeRegion(d,m,6),q=[{type:"text",text:`Sent ${v} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&q.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:q,details:{source:d.source,action:h,status:d.status,snapshot:f,input:v,changedLines:b.lines},isError:o.isError}})}a(Se,"registerTerminalResources");function Qe(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:rt(r)}]}}}}}}a(Qe,"createReadResolver");function et(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=it(r),s=i.indexOf(W),o=i.indexOf(F);if(s>=0){t.write(n.source,i.slice(s+W.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(et,"createInputResolver");function tt(t,e){return!w(t.input)||!Te(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(tt,"transformWriteInput");function nt(t){if(!w(t.input)||!Te(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${F}${typeof t.input.text=="string"?t.input.text:""}`}}}a(nt,"transformInsertInput");function rt(t){return P(t)}a(rt,"formatSnapshot");function it(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(it,"singleText");function ge(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(ge,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Te(t){return typeof t=="string"&&y(t)}a(Te,"isShellSourceValue");function ot(t){if(!w(t)||!w(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(ot,"terminalActionDetails");async function he(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(he,"rememberScreen");function ye(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(ye,"rememberOutputEnd");function we(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(we,"terminalInputLabel");function st(t,e){if(!w(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return w(n)&&typeof n.source=="string"&&y(n.source)}a(st,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Re(t,e){await te(t,{protocol:Q,apiVersion:ee,id:"terminal",setup(r){r.addResolver({resolver:at(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."),r.addPromptGuideline("Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.")}})}a(Re,"registerTerminalSearch");function at(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=lt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=j(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
17
+ `)},u.expanded,c,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(l){let u=l.request.path;if(u===void 0||!y(u)||l.request.views?.includes("image")!==!0)return{kind:"continue",context:l};let c=e.get(u);if(c===void 0)return{kind:"return",result:ge(u,`Unknown terminal session ${u}`)};try{return e.markInspected(u),{kind:"return",result:{content:[{type:"image",data:await U(e,u),mimeType:"image/png"}],details:{source:c.source,resolvedBy:"terminal"}}}}catch(d){return{kind:"return",result:ge(u,d instanceof Error?d.message:String(d))}}}}),o.describe('shell:<session> \u2014 terminal session status and a bounded output tail with a full-log path when truncated. Use views: ["image"] to read the current virtual terminal screen as a PNG.'),o.addPromptGuideline("Use read with a returned shell:<session> source to inspect terminal status and output. Add the image view when cursor movement, ANSI layout, or a full-screen terminal interface matters.")}},s={protocol:z,apiVersion:J,id:"terminal",setup(o){o.addResolver({resolver:et(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(ye(l.input,e,n),await he(l.input,e,r),tt(l,W)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await he(l.input,e,r),ye(l.input,e,n),nt(l)),"handler")});for(let l of["write","insert","delete"])o.addToolRenderer({tool:l,matches:a((u,c)=>st(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),E(f.snapshot??{},l,we(l,m),[],c)},renderResult(u,c,d){let m=ot(u.details);return ue(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([K(t,i),Z(t,s)]),t.on("tool_result",async(o,l)=>{if(!w(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:o.details,isError:!0};if(o.toolName==="delete"&&typeof u=="string"&&y(u)){let X=e.get(u);if(X===void 0)return;let Ne=e.snapshot(X);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:Ne,action:"delete",input:"session",changedLines:[]},isError:!1}),L=>({content:[{type:"text",text:L instanceof Error?L.message:String(L)}],details:{source:u,deleted:!1},isError:!0}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,v=we(h,o.input),b=e.screenChangeRegion(d,m,6),q=[{type:"text",text:`Sent ${v} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&q.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:q,details:{source:d.source,action:h,status:d.status,snapshot:f,input:v,changedLines:b.lines},isError:o.isError}})}a(Se,"registerTerminalResources");function Qe(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:rt(r)}]}}}}}}a(Qe,"createReadResolver");function et(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=it(r),s=i.indexOf(W),o=i.indexOf(F);if(s>=0){t.write(n.source,i.slice(s+W.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(et,"createInputResolver");function tt(t,e){return!w(t.input)||!Te(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(tt,"transformWriteInput");function nt(t){if(!w(t.input)||!Te(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${F}${typeof t.input.text=="string"?t.input.text:""}`}}}a(nt,"transformInsertInput");function rt(t){return P(t)}a(rt,"formatSnapshot");function it(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(it,"singleText");function ge(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(ge,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Te(t){return typeof t=="string"&&y(t)}a(Te,"isShellSourceValue");function ot(t){if(!w(t)||!w(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(ot,"terminalActionDetails");async function he(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(he,"rememberScreen");function ye(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(ye,"rememberOutputEnd");function we(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(we,"terminalInputLabel");function st(t,e){if(!w(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return w(n)&&typeof n.source=="string"&&y(n.source)}a(st,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Re(t,e){await te(t,{protocol:Q,apiVersion:ee,id:"terminal",setup(r){r.addResolver({resolver:at(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."),r.addPromptGuideline("Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.")}})}a(Re,"registerTerminalSearch");function at(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=lt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=j(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
18
18
  `)}
19
19
 
20
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,s=H(i)?j(i.payload):j(void 0),o=$(s.snapshot,"search",JSON.stringify(s.query),s.matches.slice(-6).map(l=>`${l.lineNumber}: ${l.lineText}`),r);return new G(o,n.expanded===!0,r)}}}a(at,"terminalSearchResolver");var be=12,G=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{a(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=be)return n;let r=be-1;return[...n.slice(0,r),this.theme.fg("muted",`\u2026 ${String(n.length-r)} visual rows omitted \xB7 ctrl+o to expand`)]}invalidate(){this.content.invalidate()}};function lt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[s,o]of t.output.replaceAll("\r","").split(`
21
- `).entries()){let l=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=l.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||ut(l,c,d))&&r.push({source:t.source,lineNumber:s+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(lt,"findTerminalMatches");function ut(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(ut,"isWordBoundary");function j(t){if(!ct(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function ct(t){return H(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&H(t.snapshot)&&typeof t.snapshot.source=="string"}a(ct,"isTerminalSearchPayload");function H(t){return typeof t=="object"&&t!==null}a(H,"isRecord");import{spawn as dt}from"node:child_process";import{closeSync as mt,mkdirSync as pt,openSync as ft,rmSync as gt,writeSync as ht}from"node:fs";import yt from"node:os";import xe from"node:path";import{createRequire as wt}from"node:module";import{randomUUID as St}from"node:crypto";import{stripVTControlCharacters as Tt}from"node:util";var $e=wt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),ve=1e6,bt=100,Rt=30,xt=2e3,k=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=$t){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(Et(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Mt(n);this.#i.set(n,ft(r,"a",384));let i=e.cols??bt,s=e.rows??Rt,o=Pt(i,s),l=a(p=>{},"resolveCompletion"),u=new Promise(p=>{l=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:s,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=$e("node-pty"),f={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:At(kt())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:It(p)};return this.#e.set(n,f),this.#s(n),l(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{T(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return T(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,s)=>{let o=a(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",o),i(l)},s)})}async waitForForeground(e,n){let r=this.required(e);if(T(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(s=>{let o=!1,l,u=a(p=>{o||(p!==void 0&&T(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!vt(r)){l=void 0;return}l??=Date.now(),Date.now()-l>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,s;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=40)return;await B(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),s=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),l=-1;for(let d=0;d<=e.rows-s;d+=1){let m=0;for(let p=d;p<d+s;p+=1){let f=n[p]??"",h=i[p]??"",v=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(v||b)&&(m+=1)}m>l&&(l=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+s).map((d,m)=>{if(o+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),s=[];for(let o=0;o<e.rows;o+=1){let l=r.getLine(i+o)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&s.push(l)}return s.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Ct(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await Pe(r,!1),await Promise.race([r.completion.then(()=>!0),B(xt).then(()=>!1)])||(await Pe(r,!0),await Promise.race([r.completion,B(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),gt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],s=Math.max(0,r.baseY);for(let o=s;o<s+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!T(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Tt(n),i=this.#i.get(e.id);if(i!==void 0&&ht(i,r),e.output+=r,e.output.length>ve){let s=e.output.length-ve;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(mt(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function vt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(vt,"looksInteractive");function Pt(t,e){let{Terminal:n}=$e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(Pt,"createScreen");function $t(){return St().replaceAll("-","").slice(0,12)}a($t,"defaultSessionId");function Et(t){return t.startsWith("shell:")?t.slice(6):t}a(Et,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function kt(){return process.env}a(kt,"processEnvironment");function At(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(At,"cleanEnvironment");function Ct(t){return t.split(/[\s,]+/u).filter(Boolean).map(Lt).join("")}a(Ct,"encodeTerminalKeys");function Lt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),s=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return s?`\x1B${m}`:m}let l={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!s&&!o&&l[n]!==void 0)return l[n];if(s&&!i&&!o&&l[n]!==void 0)return`\x1B${l[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!s&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(s?2:0)+(i?4:0)}${c}`;if(s&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(Lt,"encodeTerminalKey");async function Pe(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=dt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(Pe,"terminateProcessTree");function B(t){return new Promise(e=>setTimeout(e,t))}a(B,"delay");function It(t){return t instanceof Error?t.message:String(t)}a(It,"errorMessage");function Mt(t){let e=xe.join(yt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return pt(e,{recursive:!0,mode:448}),xe.join(e,`${t}.log`)}a(Mt,"createOutputLog");import _t from"node:os";import Ee from"node:path";function ke(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=Ee.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||_t.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Ee.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a(ke,"resolveShellProfile");function Ae(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(Ae,"shellSyntaxGuidance");import Ce from"node:path";import{stripVTControlCharacters as Dt}from"node:util";import{defineTool as Ot}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Nt=g.Object({command:g.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:g.Optional(g.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:g.Optional(g.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:g.Optional(g.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:g.Optional(g.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:g.Optional(g.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function Le(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(Ot({name:i,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Write commands for ${n.displayName}; commands are not translated between shell languages.`,`Use ${i} with background for servers, watchers, and long builds. Foreground waits become background after timeoutSeconds (60 by default), on a stable interactive prompt, or when the turn is aborted. After a session enters background, do not poll it continuously; continue other work or wait for its automatic completion notification. Keep a short task in foreground wait when it should finish soon and no independent work remains. A background session with no output for two minutes wakes an idle agent so it can be inspected. Sessions survive extension reloads and keep the same shell: source. Large output returns a bounded tail and a fullOutput file path. Use the returned shell: source with read, write, insert, and delete.`],description:`Use ${i} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent, so background sessions do not need continuous polling. Keep short tasks in foreground wait when they should finish soon and no independent work remains. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${Ae(n)}`,parameters:Nt,async execute(s,o,l,u,c){r.bind(c);let d=o.cwd===void 0?c.cwd:Ce.resolve(c.cwd,o.cwd),m=e.start({command:o.command,background:o.background??!1,cwd:d,shell:n,...o.cols===void 0?{}:{cols:o.cols},...o.rows===void 0?{}:{rows:o.rows}});if(o.background===!0&&m.status!=="failed")return await Ut(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),A(e.snapshot(m));if(m.status==="failed")return A(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(o.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),A(e.snapshot(p.session))},renderCall(s,o){let l=typeof s.command=="string"?s.command:"",u=typeof s.cwd=="string"?Ce.resolve(process.cwd(),s.cwd):process.cwd();return le(l,s.background===!0,u,n,o)},renderResult(s,o,l){return ce(s.details,o.expanded,l)}}))}a(Le,"registerTerminalTools");function A(t){return{content:[{type:"text",text:P(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(A,"terminalResult");async function Ut(t,e,n){await new Promise(r=>{let i=!1,s,o=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(s),o(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(A(c)),(Dt(c.output).replaceAll("\r","").split(`
20
+ ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,s=H(i)?j(i.payload):j(void 0),o=E(s.snapshot,"search",JSON.stringify(s.query),s.matches.slice(-6).map(l=>`${l.lineNumber}: ${l.lineText}`),r);return new G(o,n.expanded===!0,r)}}}a(at,"terminalSearchResolver");var be=12,G=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{a(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=be)return n;let r=be-1;return[...n.slice(0,r),this.theme.fg("muted",`\u2026 ${String(n.length-r)} visual rows omitted \xB7 ctrl+o to expand`)]}invalidate(){this.content.invalidate()}};function lt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[s,o]of t.output.replaceAll("\r","").split(`
21
+ `).entries()){let l=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=l.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||ut(l,c,d))&&r.push({source:t.source,lineNumber:s+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(lt,"findTerminalMatches");function ut(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(ut,"isWordBoundary");function j(t){if(!ct(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function ct(t){return H(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&H(t.snapshot)&&typeof t.snapshot.source=="string"}a(ct,"isTerminalSearchPayload");function H(t){return typeof t=="object"&&t!==null}a(H,"isRecord");import{spawn as dt}from"node:child_process";import{closeSync as mt,mkdirSync as pt,openSync as ft,rmSync as gt,writeSync as ht}from"node:fs";import yt from"node:os";import xe from"node:path";import{createRequire as wt}from"node:module";import{randomUUID as St}from"node:crypto";import{stripVTControlCharacters as Tt}from"node:util";var Ee=wt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),ve=1e6,bt=100,Rt=30,xt=2e3,A=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=Et){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get($t(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Mt(n);this.#i.set(n,ft(r,"a",384));let i=e.cols??bt,s=e.rows??Rt,o=Pt(i,s),l=a(p=>{},"resolveCompletion"),u=new Promise(p=>{l=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:s,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=Ee("node-pty"),f={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:kt(At())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:It(p)};return this.#e.set(n,f),this.#s(n),l(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{T(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return T(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,s)=>{let o=a(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",o),i(l)},s)})}async waitForForeground(e,n){let r=this.required(e);if(T(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(s=>{let o=!1,l,u=a(p=>{o||(p!==void 0&&T(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!vt(r)){l=void 0;return}l??=Date.now(),Date.now()-l>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,s;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=40)return;await B(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),s=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),l=-1;for(let d=0;d<=e.rows-s;d+=1){let m=0;for(let p=d;p<d+s;p+=1){let f=n[p]??"",h=i[p]??"",v=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(v||b)&&(m+=1)}m>l&&(l=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+s).map((d,m)=>{if(o+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),s=[];for(let o=0;o<e.rows;o+=1){let l=r.getLine(i+o)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&s.push(l)}return s.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Ct(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await Pe(r,!1),await Promise.race([r.completion.then(()=>!0),B(xt).then(()=>!1)])||(await Pe(r,!0),await Promise.race([r.completion,B(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),gt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],s=Math.max(0,r.baseY);for(let o=s;o<s+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!T(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Tt(n),i=this.#i.get(e.id);if(i!==void 0&&ht(i,r),e.output+=r,e.output.length>ve){let s=e.output.length-ve;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(mt(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function vt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(vt,"looksInteractive");function Pt(t,e){let{Terminal:n}=Ee("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(Pt,"createScreen");function Et(){return St().replaceAll("-","").slice(0,12)}a(Et,"defaultSessionId");function $t(t){return t.startsWith("shell:")?t.slice(6):t}a($t,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function At(){return process.env}a(At,"processEnvironment");function kt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(kt,"cleanEnvironment");function Ct(t){return t.split(/[\s,]+/u).filter(Boolean).map(Lt).join("")}a(Ct,"encodeTerminalKeys");function Lt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),s=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return s?`\x1B${m}`:m}let l={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!s&&!o&&l[n]!==void 0)return l[n];if(s&&!i&&!o&&l[n]!==void 0)return`\x1B${l[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!s&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(s?2:0)+(i?4:0)}${c}`;if(s&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(Lt,"encodeTerminalKey");async function Pe(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=dt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(Pe,"terminateProcessTree");function B(t){return new Promise(e=>setTimeout(e,t))}a(B,"delay");function It(t){return t instanceof Error?t.message:String(t)}a(It,"errorMessage");function Mt(t){let e=xe.join(yt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return pt(e,{recursive:!0,mode:448}),xe.join(e,`${t}.log`)}a(Mt,"createOutputLog");import _t from"node:os";import $e from"node:path";function Ae(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=$e.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||_t.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=$e.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a(Ae,"resolveShellProfile");function ke(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(ke,"shellSyntaxGuidance");import Ce from"node:path";import{stripVTControlCharacters as Dt}from"node:util";import{defineTool as Ot}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Nt=g.Object({command:g.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:g.Optional(g.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:g.Optional(g.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:g.Optional(g.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:g.Optional(g.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:g.Optional(g.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function Le(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(Ot({name:i,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Write commands for ${n.displayName}; commands are not translated between shell languages.`,`Use ${i} with background for servers, watchers, and long builds. After a session enters background, do not poll it continuously; continue other work or wait for completion. Keep short tasks in the foreground. Enable periodic or verbose output for long-running commands. Use the returned shell: source with read, write, insert, and delete.`],description:`Use ${i} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions are treated as potentially stale after two minutes and wake an idle agent for inspection. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${ke(n)}`,parameters:Nt,async execute(s,o,l,u,c){r.bind(c);let d=o.cwd===void 0?c.cwd:Ce.resolve(c.cwd,o.cwd),m=e.start({command:o.command,background:o.background??!1,cwd:d,shell:n,...o.cols===void 0?{}:{cols:o.cols},...o.rows===void 0?{}:{rows:o.rows}});if(o.background===!0&&m.status!=="failed")return await Ut(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),k(e.snapshot(m));if(m.status==="failed")return k(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(o.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),k(e.snapshot(p.session))},renderCall(s,o){let l=typeof s.command=="string"?s.command:"",u=typeof s.cwd=="string"?Ce.resolve(process.cwd(),s.cwd):process.cwd();return le(l,s.background===!0,u,n,o)},renderResult(s,o,l){return ce(s.details,o.expanded,l)}}))}a(Le,"registerTerminalTools");function k(t){return{content:[{type:"text",text:P(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(k,"terminalResult");async function Ut(t,e,n){await new Promise(r=>{let i=!1,s,o=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(s),o(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(k(c)),(Dt(c.output).replaceAll("\r","").split(`
22
22
  `).filter(m=>m.length>0).length>=R||c.status!=="running")&&l()},"publish");o=t.onDidChange(c=>{c.id===e.id&&u()}),s=setTimeout(l,2e3),u()})}a(Ut,"captureInitialBackgroundPreview");import{Box as Ie,Container as Me}from"@earendil-works/pi-tui";var Wt=120,Ft=12e4,C=class{constructor(e,n,r=Ft){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:s},o)=>{let l=_e(i.details)?i.details:void 0,u=new Me;l!==void 0&&u.addChild(S(l,s,o,"stale \xB7 inspect session"));let c=new Ie(1,1,d=>o.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:s},o)=>{let l=new Me;for(let c of jt(i.details))l.addChild(S(c,s,o));let u=new Ie(1,1,c=>o.bg("toolSuccessBg",c));return u.addChild(l),u}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{a(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:Ht(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.#t.set(e.id,setTimeout(()=>this.#n(e),this.staleIntervalMs))}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:Gt(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},Wt)))}};function jt(t){return!Oe(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(_e)}a(jt,"completionSnapshots");function _e(t){return Oe(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}a(_e,"isTerminalSessionSnapshot");function Gt(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
23
23
  ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,s=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${De(n.elapsedMs)}
24
24
  ${s||"(no output)"}`}).join(`
25
25
  `)}`}a(Gt,"formatCompletionMessage");function Ht(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${De(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
26
- ${e||"(no output)"}`}a(Ht,"formatStaleMessage");function De(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(De,"formatElapsed");function Oe(t){return typeof t=="object"&&t!==null}a(Oe,"isRecord");async function Bt(t){let e=ie("terminal")??new k,n=ke(),r=new C(t,e),i=ne(t).add(me(e));await Promise.all([Se(t,e),Re(t,e)]),Le(t,e,n,r),t.on("session_start",(s,o)=>r.bind(o)),t.on("agent_settled",(s,o)=>r.onAgentSettled(o)),t.on("session_shutdown",async s=>{if(r.dispose(),i(),s.reason!=="quit"){re("terminal",e);return}oe("terminal",e),await e.dispose()})}a(Bt,"registerTerminal");export{Bt as default};
26
+ ${e||"(no output)"}`}a(Ht,"formatStaleMessage");function De(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(De,"formatElapsed");function Oe(t){return typeof t=="object"&&t!==null}a(Oe,"isRecord");async function Bt(t){let e=ie("terminal")??new A,n=Ae(),r=new C(t,e),i=ne(t).add(me(e));await Promise.all([Se(t,e),Re(t,e)]),Le(t,e,n,r),t.on("session_start",(s,o)=>r.bind(o)),t.on("agent_settled",(s,o)=>r.onAgentSettled(o)),t.on("session_shutdown",async s=>{if(r.dispose(),i(),s.reason!=="quit"){re("terminal",e);return}oe("terminal",e),await e.dispose()})}a(Bt,"registerTerminal");export{Bt as default};
@@ -1,2 +1,2 @@
1
- import"./chunk-NNCZYO4Q.js";import{d as N}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as E}from"./chunk-6CZO43OH.js";import{a as A,b}from"./chunk-OBNING2A.js";import{d as O}from"./chunk-WGGIQ7IJ.js";import"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as D,g as w,h as k,i as P,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-HKMBQLEK.js";import{a as y,b as I}from"./chunk-Z3VC3S2T.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import S from"node:path";var T="diagnostics",V=N({kind:"code-view",label:"Diagnostics"});async function q(c){let n,t=l((o,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(o,{cwd:f,...e})},"collect"),i={protocol:y,apiVersion:4,id:"diagnostics",setup(o){n=o.readDiagnostics}},r=new WeakMap,s=new WeakMap,a=new WeakMap,d=new WeakMap,M={protocol:A,apiVersion:b,id:"diagnostics",setup(o){o.addResolver({resolver:W(t,s),renderResult:V});let f=v();o.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),o.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=s.get(g);return u&&r.set(e.request,u),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),o.addHandler({stage:"post-read",handler(e){let g=r.get(e.request);if(g&&e.result)return{kind:"continue",context:{...e,result:{...e.result,details:{...e.result.details,diagnosticCheck:g}}}};let u=a.get(e.request),h=u&&d.get(u),p=e.result,R=p?.content[0];return!h||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${h}
1
+ import{d as O}from"./chunk-FEDVTZJG.js";import"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as N}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as E}from"./chunk-6CZO43OH.js";import{a as A,b}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{e as m,f as D,g as w,h as k,i as P,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import{a as C}from"./chunk-HKMBQLEK.js";import{a as y,b as I}from"./chunk-Z3VC3S2T.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import S from"node:path";var T="diagnostics",V=N({kind:"code-view",label:"Diagnostics"});async function q(c){let n,t=l((o,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(o,{cwd:f,...e})},"collect"),i={protocol:y,apiVersion:4,id:"diagnostics",setup(o){n=o.readDiagnostics}},r=new WeakMap,s=new WeakMap,a=new WeakMap,d=new WeakMap,M={protocol:A,apiVersion:b,id:"diagnostics",setup(o){o.addResolver({resolver:W(t,s),renderResult:V});let f=v();o.addView({view:"diagnostics",priority:100,presenter:j(t,d)}),o.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let g=e.state.content[0],u=s.get(g);return u&&r.set(e.request,u),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),o.addHandler({stage:"post-read",handler(e){let g=r.get(e.request);if(g&&e.result)return{kind:"continue",context:{...e,result:{...e.result,details:{...e.result.details,diagnosticCheck:g}}}};let u=a.get(e.request),h=u&&d.get(u),p=e.result,R=p?.content[0];return!h||!p||R?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:{...e,result:{...p,content:[{...R,text:`${h}
2
2
  ${R.text}`},...p.content.slice(1)]}}}}}),o.describe('diagnostics:<path> \u2014 lint and language-server diagnostics. views: ["diagnostics"] \u2014 diagnostics alongside source text. Diagnostic sources name the actual reporting tools. Automatic notices include findings only and wake an idle agent after the notification buffer (five seconds by default); silence does not prove the file is clean. Use an explicit diagnostic read to check readiness. Pending results and snapshots are not completed checks; an empty snapshot does not prove the file is clean.'),o.addPromptGuideline("Use read with `diagnostics:<path>` or the `diagnostics` view for per-file diagnostics instead of running equivalent checks through Bash. Project builds and tests remain separate verification.")}};await Promise.all([C(c,i),E(c,M)])}l(q,"registerDiagnostics");function W(c,n){return{id:"diagnostics",tryResolve(t,i){return Promise.resolve(_(t,i.cwd,c,n,{signal:i.signal,...i.audience==="script"&&{mode:"complete"}}))}}}l(W,"createDiagnosticResolver");function _(c,n,t,i,r){let s;try{s=m(c,T,n)}catch(a){return{kind:"failed",error:a}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:D(T,s),async read(){let a=await t(s,n,r),d=w(s,a.content,a.results);return i.set(d,d.diagnosticCheck),[d]}}}}l(_,"resolveDiagnosticSource");function j(c,n){return{id:"diagnostics",async present(t,i){if(i.purpose!=="read"||!S.isAbsolute(t.source))return t;let r=i.audience==="script"&&!i.requestedViews?.includes("diagnostics");if(r&&O(t.source))return t;let s=await c(t.source,i.cwd,{signal:i.signal,...i.audience==="script"&&{mode:r?"snapshot":"complete"}}).catch(a=>{if(i.signal?.throwIfAborted(),!r)throw a});if(s===void 0||r&&s.content!==t.content)return t;if(s.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,P(s.results)),k(t,s.results)}}}l(j,"createDiagnosticPresenter");export{q as default};
package/dist/entry-10.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-U2JKHKLK.js";import"./chunk-J4RTW44E.js";import"./chunk-NNCZYO4Q.js";import"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as g}from"./chunk-6CZO43OH.js";import{a as f,b as y}from"./chunk-OBNING2A.js";import"./chunk-IQD6PON5.js";import"./chunk-WGGIQ7IJ.js";import{a as l}from"./chunk-L7JMDDSD.js";import{a as s,b as c}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function x(n,e){return u(e),g(n,{protocol:f,apiVersion:y,id:`hook/before-read/${e.id}`,setup(t){t.addResourceGuard({id:e.id,async guard(o){let r=await e.run(o);return r.decision==="allow"?{kind:"accepted"}:{kind:"rejected",reason:r.reason}}})}})}d(x,"connectBeforeReadHook");function A(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/before-edit/${e.id}`,setup(t){t.addMutationGuard({id:e.id,async guard(o,r){let a=await e.run({cwd:r.cwd,intent:r.intent??"edit",resources:o.resources.map(i=>({resourceSource:i.source,existed:i.existed,before:i.before,after:i.after,changes:i.changes})),...r.signal!==void 0&&{signal:r.signal}});return a.decision==="allow"?{kind:"accepted"}:{kind:"rejected",rejection:{code:"MUTATION_REJECTED",reason:a.reason,message:`Edit blocked by hook ${e.id}: ${a.reason}`,effect:"not-applied"}}}})}})}d(A,"connectBeforeEditHook");function m(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/after-edit/${e.id}`,setup(t){t.onDidEdit(async o=>{if(o.postProcessing!=="deferred")try{return await e.run(o)}catch(r){return{feedback:`After-edit hook ${e.id} failed after the edit was saved: ${r instanceof Error?r.message:String(r)}`,tone:"error"}}})}})}d(m,"connectAfterEditHook");function u(n){if(n.id.trim().length===0||typeof n.run!="function")throw new TypeError("A file hook needs a non-empty id and run function")}d(u,"assertHook");export{m as connectAfterEditHook,A as connectBeforeEditHook,x as connectBeforeReadHook};
1
+ import"./chunk-IQD6PON5.js";import"./chunk-FEDVTZJG.js";import{a as l}from"./chunk-L7JMDDSD.js";import{a as s,b as c}from"./chunk-O6LE42GK.js";import"./chunk-U2JKHKLK.js";import"./chunk-22CLOM2D.js";import"./chunk-NNCZYO4Q.js";import"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as g}from"./chunk-6CZO43OH.js";import{a as f,b as y}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function x(n,e){return u(e),g(n,{protocol:f,apiVersion:y,id:`hook/before-read/${e.id}`,setup(t){t.addResourceGuard({id:e.id,async guard(o){let r=await e.run(o);return r.decision==="allow"?{kind:"accepted"}:{kind:"rejected",reason:r.reason}}})}})}d(x,"connectBeforeReadHook");function A(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/before-edit/${e.id}`,setup(t){t.addMutationGuard({id:e.id,async guard(o,r){let a=await e.run({cwd:r.cwd,intent:r.intent??"edit",resources:o.resources.map(i=>({resourceSource:i.source,existed:i.existed,before:i.before,after:i.after,changes:i.changes})),...r.signal!==void 0&&{signal:r.signal}});return a.decision==="allow"?{kind:"accepted"}:{kind:"rejected",rejection:{code:"MUTATION_REJECTED",reason:a.reason,message:`Edit blocked by hook ${e.id}: ${a.reason}`,effect:"not-applied"}}}})}})}d(A,"connectBeforeEditHook");function m(n,e){return u(e),l(n,{protocol:s,apiVersion:c,id:`hook/after-edit/${e.id}`,setup(t){t.onDidEdit(async o=>{if(o.postProcessing!=="deferred")try{return await e.run(o)}catch(r){return{feedback:`After-edit hook ${e.id} failed after the edit was saved: ${r instanceof Error?r.message:String(r)}`,tone:"error"}}})}})}d(m,"connectAfterEditHook");function u(n){if(n.id.trim().length===0||typeof n.run!="function")throw new TypeError("A file hook needs a non-empty id and run function")}d(u,"assertHook");export{m as connectAfterEditHook,A as connectBeforeEditHook,x as connectBeforeReadHook};
package/dist/entry-11.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-U2JKHKLK.js";import{a as k,b as l,c as m,d as n,e as o,f as p,g as q}from"./chunk-J4RTW44E.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as h}from"./chunk-6CZO43OH.js";import{a,b,c,d,e,f,g}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{i as COMPACT_READ_ROWS,b as READ_API_VERSION,c as READ_CORE_READY_EVENT,d as READ_PLUGIN_REGISTER_EVENT,a as READ_PROTOCOL,h as connectReadPlugin,j as createReadResultRenderer,p as isFragmentResolverRegistration,e as isReadCoreReady,q as isReadFragmentResolution,n as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,o as isReadViewRegistration,m as isResourceResolverRegistration,l as isTextTargetResolverRegistration,k as readParameters};
1
+ import{a}from"./chunk-K5G4FDXD.js";import"./chunk-EI7MMDWY.js";export{a as sameFilePath};
package/dist/entry-12.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-S3ZPXWX7.js";import"./chunk-EI7MMDWY.js";export{j as CONTENT_API_VERSION,l as CONTENT_CONVERTER_REGISTER_EVENT,k as CONTENT_HOST_READY_EVENT,i as CONTENT_PROTOCOL,d as UnsupportedContentError,u as connectContentConverter,s as createContentHost,g as createContentRunner,r as isAgentContent,b as isContentConversionAttempt,x as isContentConversionContext,a as isContentConverter,c as isContentConverterRegistration,q as isContentConverterRegistrationRequest,n as isContentHostReady,t as isContentInput,p as isContentTarget,e as isResource,m as isResourceResolutionAttempt,f as isResourceResolver,o as renderContentDescription,h as targetsEqual};
1
+ import"./chunk-U2JKHKLK.js";import{a as k,b as l,c as m,d as n,e as o,f as p,g as q}from"./chunk-22CLOM2D.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as h}from"./chunk-6CZO43OH.js";import{a,b,c,d,e,f,g}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{i as COMPACT_READ_ROWS,b as READ_API_VERSION,c as READ_CORE_READY_EVENT,d as READ_PLUGIN_REGISTER_EVENT,a as READ_PROTOCOL,h as connectReadPlugin,j as createReadResultRenderer,p as isFragmentResolverRegistration,e as isReadCoreReady,q as isReadFragmentResolution,n as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,o as isReadViewRegistration,m as isResourceResolverRegistration,l as isTextTargetResolverRegistration,k as readParameters};
package/dist/entry-13.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-ROXXK6TW.js";import{a}from"./chunk-KII2JQC5.js";import{a as x}from"./chunk-ZTYWHL2F.js";import{a as o,b as r,c as e,d as f,e as m,f as p,g as t}from"./chunk-7UGNGK7Y.js";import"./chunk-EI7MMDWY.js";export{r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,a as searchSchema};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-S3ZPXWX7.js";import"./chunk-EI7MMDWY.js";export{j as CONTENT_API_VERSION,l as CONTENT_CONVERTER_REGISTER_EVENT,k as CONTENT_HOST_READY_EVENT,i as CONTENT_PROTOCOL,d as UnsupportedContentError,u as connectContentConverter,s as createContentHost,g as createContentRunner,r as isAgentContent,b as isContentConversionAttempt,x as isContentConversionContext,a as isContentConverter,c as isContentConverterRegistration,q as isContentConverterRegistrationRequest,n as isContentHostReady,t as isContentInput,p as isContentTarget,e as isResource,m as isResourceResolutionAttempt,f as isResourceResolver,o as renderContentDescription,h as targetsEqual};
package/dist/entry-14.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s}from"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as TextAnchor,r as attachTextAnchorRenderer,j as createTextContentConverter,g as createTextDocument,e as getTextAnchorRenderer,a as getTextSourceLine,t as isTextAnchorRecoveryOutcome,p as isTextAnchorResolutionAttempt,m as isTextAnchorResolver,c as isTextLinePresenter,d as isTextPresenterRegistration,n as isTextTargetResolutionAttempt,k as isTextualMediaType,i as renderPresentedTextDocument,x as renderPresentedTextRows,f as renderTextAnchor,h as renderTextDocument,s as restoreText,q as storeText,l as textFromAgentContent,b as withTextSourceLine};
1
+ import"./chunk-ROXXK6TW.js";import{a}from"./chunk-KII2JQC5.js";import{a as x}from"./chunk-ZTYWHL2F.js";import{a as o,b as r,c as e,d as f,e as m,f as p,g as t}from"./chunk-7UGNGK7Y.js";import"./chunk-EI7MMDWY.js";export{r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,a as searchSchema};
package/dist/entry-15.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-IQD6PON5.js";import{l as o}from"./chunk-WGGIQ7IJ.js";import{a as n}from"./chunk-L7JMDDSD.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,n as connectTextEditorPlugin,o as connectTextEditorPostEditHandler,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s}from"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as TextAnchor,r as attachTextAnchorRenderer,j as createTextContentConverter,g as createTextDocument,e as getTextAnchorRenderer,a as getTextSourceLine,t as isTextAnchorRecoveryOutcome,p as isTextAnchorResolutionAttempt,m as isTextAnchorResolver,c as isTextLinePresenter,d as isTextPresenterRegistration,n as isTextTargetResolutionAttempt,k as isTextualMediaType,i as renderPresentedTextDocument,x as renderPresentedTextRows,f as renderTextAnchor,h as renderTextDocument,s as restoreText,q as storeText,l as textFromAgentContent,b as withTextSourceLine};
@@ -0,0 +1 @@
1
+ import"./chunk-IQD6PON5.js";import{m as o}from"./chunk-FEDVTZJG.js";import{a as n}from"./chunk-L7JMDDSD.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{b as TEXT_EDITOR_API_VERSION,e as TEXT_EDITOR_CORE_READY_EVENT,f as TEXT_EDITOR_PLUGIN_REGISTER_EVENT,a as TEXT_EDITOR_PROTOCOL,c as TEXT_POSITION_ANCHOR_KIND,d as TEXT_SEARCH_ANCHOR_KIND,n as connectTextEditorPlugin,o as connectTextEditorPostEditHandler,h as isResourceResolverRegistration,i as isTextAnchorResolverRegistration,j as isTextAnchorResourceResolutionAttempt,k as isTextEditorCoreReady,l as isTextEditorPlugin,m as isTextEditorPluginRegistrationRequest,g as isTextEditorToolId};
package/dist/entry-18.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-MGCHOGQD.js";import"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{a as connectDoctorPlugin};
1
+ import"./chunk-K4ZMRDEI.js";
package/dist/entry-19.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-WZI4YC2O.js";import"./chunk-EI7MMDWY.js";export{b as hasProjectMarker,a as inspectRecipeEvidence};
1
+ import{a}from"./chunk-MGCHOGQD.js";import"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{a as connectDoctorPlugin};
package/dist/entry-20.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-N34ATN52.js";import"./chunk-EI7MMDWY.js";export{d as isExecutableAvailable,b as normalizeProcessEnvironment,e as probeExecutable,a as projectExecutableDirectories,c as projectProcessEnvironment};
1
+ import{a,b}from"./chunk-WZI4YC2O.js";import"./chunk-EI7MMDWY.js";export{b as hasProjectMarker,a as inspectRecipeEvidence};
package/dist/entry-21.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{b as DOCTOR_API_VERSION,c as DOCTOR_CORE_READY_EVENT,d as DOCTOR_PLUGIN_REGISTER_EVENT,a as DOCTOR_PROTOCOL,e as isDoctorCoreReady,f as isDoctorPluginRegistrationRequest};
1
+ import{a,b,c,d,e}from"./chunk-N34ATN52.js";import"./chunk-EI7MMDWY.js";export{d as isExecutableAvailable,b as normalizeProcessEnvironment,e as probeExecutable,a as projectExecutableDirectories,c as projectProcessEnvironment};
package/dist/entry-22.js CHANGED
@@ -1,2 +1 @@
1
- import"./chunk-NNCZYO4Q.js";import{d as v}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as R}from"./chunk-6CZO43OH.js";import{a as y,b as p}from"./chunk-OBNING2A.js";import{a as w}from"./chunk-L7JMDDSD.js";import{a as h,b as F}from"./chunk-O6LE42GK.js";import{a as g,u as m}from"./chunk-S3ZPXWX7.js";import{r as f}from"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{readdirSync as x,realpathSync as H,statSync as S}from"node:fs";import{mkdir as k,readFile as D,writeFile as O}from"node:fs/promises";import b from"node:path";import{fileURLToPath as I,pathToFileURL as _}from"node:url";function T(e){return P("read",e)}o(T,"createFilesystemReadResolver");function C(e){return P("write",e)}o(C,"createFilesystemWriteResolver");function P(e,s){return{id:"filesystem",tryResolve(t,i){return Promise.resolve(L(t,i,e,s))}}}o(P,"createFilesystemResolver");function L(e,s,t,i){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!W(e))return{kind:"not-handled"};if(s.signal?.aborted===!0)return{kind:"failed",error:E()};let r=e.startsWith("file://")?H(I(new URL(e))):b.resolve(s.cwd,e),l=_(r).href,c=(()=>{try{return S(r).isDirectory()}catch{return!1}})(),n=o(async({signal:d})=>c?U(r,d):V(r,i,d),"read");return t==="read"||c?{kind:"resolved",resource:{source:r,link:l,read:n}}:{kind:"resolved",resource:{source:r,link:l,read:n,async write(d,u){a(u.signal);let A=f(d);await k(b.dirname(r),{recursive:!0}),a(u.signal),await O(r,A,{encoding:"utf8",...u.signal!==void 0&&{signal:u.signal}})}}}}o(L,"resolveFilesystemSource");function U(e,s){a(s);let t=x(e,{withFileTypes:!0}),i=[`\u{1F4C1} ${e}/`];t.length>0&&i.push("");for(let r of t){let l=r.isDirectory()?"\u{1F4C1}":r.isFile()?"\u{1F4C4}":"\u{1F517}";i.push(` ${l} ${r.name}`)}return[{type:"text",text:i.join(`
2
- `)}]}o(U,"readDirectoryContent");async function V(e,s,t){a(t);let i=await D(e,{encoding:null,...t!==void 0&&{signal:t}});return a(t),s.convert({source:e,bytes:i},t===void 0?{}:{signal:t})}o(V,"readFilesystemContent");function W(e){return/^[A-Za-z]:[\\/]/u.test(e)||e.startsWith("file://")?!0:!/^[A-Za-z][A-Za-z\d+.-]*:/u.test(e)}o(W,"isFilesystemSource");function a(e){if(e?.aborted===!0)throw E()}o(a,"throwIfAborted");function E(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(E,"abortError");var z={provider:"filesystem",capability:"read"},Z={provider:"filesystem",capability:"write"},$=v({kind:"source",nativeResources:!0});async function j(e){let s=m(e,z),t=m(e,Z),i=T(s),r=C(t),l={protocol:y,apiVersion:p,id:"filesystem",setup(n){n.addResolver({resolver:i,renderResult:$}),n.describe(()=>g("File path \u2014 file content; directory path \u2014 entry listing. Relative, absolute and file:// paths accepted.",s.listDescriptions())),n.addPromptGuideline("Use read with paths relative to the current working directory for project files. Use read with absolute paths for files elsewhere on the system.")}},c={protocol:h,apiVersion:F,id:"filesystem",setup(n){n.addResolver({resolver:r})}};await Promise.all([R(e,l),w(e,c)])}o(j,"registerFilesystemPlugin");export{j as default};
1
+ import{a,b,c,d,e,f}from"./chunk-T6LX2RX5.js";import"./chunk-EI7MMDWY.js";export{b as DOCTOR_API_VERSION,c as DOCTOR_CORE_READY_EVENT,d as DOCTOR_PLUGIN_REGISTER_EVENT,a as DOCTOR_PROTOCOL,e as isDoctorCoreReady,f as isDoctorPluginRegistrationRequest};
package/dist/entry-23.js CHANGED
@@ -1 +1,2 @@
1
- import{a as r}from"./chunk-QIJMV2P2.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:100};async function i(o){await e(o,n)}t(i,"registerFilesystemImage");export{i as default};
1
+ import{a as w}from"./chunk-L7JMDDSD.js";import{a as h,b as F}from"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as v}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as R}from"./chunk-6CZO43OH.js";import{a as y,b as p}from"./chunk-OBNING2A.js";import{a as g,u as m}from"./chunk-S3ZPXWX7.js";import{r as f}from"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{readdirSync as x,realpathSync as H,statSync as S}from"node:fs";import{mkdir as k,readFile as D,writeFile as O}from"node:fs/promises";import b from"node:path";import{fileURLToPath as I,pathToFileURL as _}from"node:url";function T(e){return P("read",e)}o(T,"createFilesystemReadResolver");function C(e){return P("write",e)}o(C,"createFilesystemWriteResolver");function P(e,s){return{id:"filesystem",tryResolve(t,i){return Promise.resolve(L(t,i,e,s))}}}o(P,"createFilesystemResolver");function L(e,s,t,i){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!W(e))return{kind:"not-handled"};if(s.signal?.aborted===!0)return{kind:"failed",error:E()};let r=e.startsWith("file://")?H(I(new URL(e))):b.resolve(s.cwd,e),l=_(r).href,c=(()=>{try{return S(r).isDirectory()}catch{return!1}})(),n=o(async({signal:d})=>c?U(r,d):V(r,i,d),"read");return t==="read"||c?{kind:"resolved",resource:{source:r,link:l,read:n}}:{kind:"resolved",resource:{source:r,link:l,read:n,async write(d,u){a(u.signal);let A=f(d);await k(b.dirname(r),{recursive:!0}),a(u.signal),await O(r,A,{encoding:"utf8",...u.signal!==void 0&&{signal:u.signal}})}}}}o(L,"resolveFilesystemSource");function U(e,s){a(s);let t=x(e,{withFileTypes:!0}),i=[`\u{1F4C1} ${e}/`];t.length>0&&i.push("");for(let r of t){let l=r.isDirectory()?"\u{1F4C1}":r.isFile()?"\u{1F4C4}":"\u{1F517}";i.push(` ${l} ${r.name}`)}return[{type:"text",text:i.join(`
2
+ `)}]}o(U,"readDirectoryContent");async function V(e,s,t){a(t);let i=await D(e,{encoding:null,...t!==void 0&&{signal:t}});return a(t),s.convert({source:e,bytes:i},t===void 0?{}:{signal:t})}o(V,"readFilesystemContent");function W(e){return/^[A-Za-z]:[\\/]/u.test(e)||e.startsWith("file://")?!0:!/^[A-Za-z][A-Za-z\d+.-]*:/u.test(e)}o(W,"isFilesystemSource");function a(e){if(e?.aborted===!0)throw E()}o(a,"throwIfAborted");function E(){let e=new Error("The operation was aborted");return e.name="AbortError",e}o(E,"abortError");var z={provider:"filesystem",capability:"read"},Z={provider:"filesystem",capability:"write"},$=v({kind:"source",nativeResources:!0});async function j(e){let s=m(e,z),t=m(e,Z),i=T(s),r=C(t),l={protocol:y,apiVersion:p,id:"filesystem",setup(n){n.addResolver({resolver:i,renderResult:$}),n.describe(()=>g("File path \u2014 file content; directory path \u2014 entry listing. Relative, absolute and file:// paths accepted.",s.listDescriptions())),n.addPromptGuideline("Use read with paths relative to the current working directory for project files. Use read with absolute paths for files elsewhere on the system.")}},c={protocol:h,apiVersion:F,id:"filesystem",setup(n){n.addResolver({resolver:r})}};await Promise.all([R(e,l),w(e,c)])}o(j,"registerFilesystemPlugin");export{j as default};
package/dist/entry-24.js CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./chunk-BHSO2MDK.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:200};async function i(o){await e(o,n)}t(i,"registerFilesystemPdf");export{i as default};
1
+ import{a as r}from"./chunk-QIJMV2P2.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:100};async function i(o){await e(o,n)}t(i,"registerFilesystemImage");export{i as default};
package/dist/entry-25.js CHANGED
@@ -1 +1 @@
1
- import{v as t}from"./chunk-S3ZPXWX7.js";import{p as i}from"./chunk-5VSE5X5R.js";import{a as r}from"./chunk-EI7MMDWY.js";var o=i(),n={target:{provider:"filesystem",capability:"read"},converter:o,priority:300},s={target:{provider:"filesystem",capability:"write"},converter:o,priority:300};async function a(e){await Promise.all([t(e,n),t(e,s)])}r(a,"registerFilesystemText");export{a as default};
1
+ import{a as r}from"./chunk-BHSO2MDK.js";import{v as e}from"./chunk-S3ZPXWX7.js";import{a as t}from"./chunk-EI7MMDWY.js";var n={target:{provider:"filesystem",capability:"read"},converter:r(),priority:200};async function i(o){await e(o,n)}t(i,"registerFilesystemPdf");export{i as default};
package/dist/entry-26.js CHANGED
@@ -1 +1 @@
1
- import{b as e,c as o}from"./chunk-25CZ5ZIU.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as AstScopeManager,e as parseDocument};
1
+ import{v as t}from"./chunk-S3ZPXWX7.js";import{p as i}from"./chunk-5VSE5X5R.js";import{a as r}from"./chunk-EI7MMDWY.js";var o=i(),n={target:{provider:"filesystem",capability:"read"},converter:o,priority:300},s={target:{provider:"filesystem",capability:"write"},converter:o,priority:300};async function a(e){await Promise.all([t(e,n),t(e,s)])}r(a,"registerFilesystemText");export{a as default};
package/dist/entry-27.js CHANGED
@@ -1,12 +1 @@
1
- import{b as B,c as V}from"./chunk-25CZ5ZIU.js";import{a as E}from"./chunk-MGCHOGQD.js";import{a as O,b as L}from"./chunk-T6LX2RX5.js";import"./chunk-NNCZYO4Q.js";import{d as $}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as M}from"./chunk-6CZO43OH.js";import{a as k,b as P}from"./chunk-OBNING2A.js";import{a as D}from"./chunk-ZTYWHL2F.js";import{a as H,b as j}from"./chunk-7UGNGK7Y.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as I,b as C,c as N}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{a as S,b as R,c as w,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import"./chunk-KINKBPPX.js";import{j as T}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as x}from"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as te}from"node:fs/promises";var ne={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},y=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),G={protocol:O,apiVersion:1,id:"ast",setup(a){a.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(r=>y.has(r))?await T({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),a.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let r of e.detectedLanguageIds){let t=ne[r];if(t!==void 0){n.push({status:"skip",message:`${r} AST is unavailable: ${t}`});continue}if(!y.has(r))continue;let s=e.files.find(o=>re(o,r));if(s!==void 0)try{let o=await te(s,"utf8"),i=await B(s,e.cwd,o.replaceAll(`\r
2
- `,`
3
- `).split(`
4
- `));n.push(i===void 0?{status:"fail",message:`${r} parser did not return a tree`}:{status:"pass",message:`${r} parser loaded`,detail:s})}catch(o){n.push({status:"fail",message:`${r}: ${o instanceof Error?o.message:String(o)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),a.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(r=>y.has(r)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await x("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function re(a,e){let n=a.slice(a.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}d(re,"matchesLanguage");var se,ae;function F(a){return{id:"ast",tryResolve(e,n){return Promise.resolve(oe(e,n,a))}}}d(F,"createAstOutlineResolver");function oe(a,e,n){let r;try{r=S(a,"ast")}catch(o){return{kind:"failed",error:o}}if(r===void 0)return{kind:"not-handled"};let t;try{t=R(r.path,e.cwd)}catch(o){return{kind:"failed",error:o}}return{kind:"resolved",resource:{source:w("ast",t),async read({signal:o}){o?.throwIfAborted();let i=await(ae??=import("./chunk-5QQABP47.js")),c=await(n??(se??=new i.AstOutlineManager)).readFileOutline(t,e.cwd);return o?.throwIfAborted(),[i.formatAstOutline(c)]}}}}d(oe,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as ie,DEFAULT_MAX_LINES as ce,truncateHead as A}from"@earendil-works/pi-coding-agent";var b=d(async(a,e,n)=>{let{source:r,resolvedBy:t,lines:s,totalLines:o,startLine:i}=a.details;if(!(r===void 0||t!=="filesystem"||s===void 0||s.length!==o||i!==void 0&&i!==1))try{let{AstOutlineManager:l,isSupportedOutlinePath:c}=await import("./chunk-5QQABP47.js");if(!c(r))return;let u=d(m=>[`AST overview of ${m.path}, source lines 1-${m.totalLines}: the requested text exceeded the read buffer.`,"Source line numbers are on the left. Detail is reduced to fit the buffer; omitted bodies are not exact source text. Read a small source range when needed.",...m.renderedLines.map(g=>`${g.sourceLine?.lineNumber??"\u2026"} | ${g.text}`)].join(`
5
- `),"format");e.signal?.throwIfAborted();let p=await new l(12).readDocumentOutline(r,e.cwd,s.map(m=>m.content),m=>(e.signal?.throwIfAborted(),!A(u(m),n).truncated)),f=u(p);return A(f,n).truncated?void 0:{content:[{type:"text",text:f}],details:{source:r,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function z(){return async a=>{let{state:e,result:n}=a,r=n?.content.length===1?n.content[0]:void 0;if(a.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||r?.type!=="text"||!A(r.text).truncated)return{kind:"continue",context:a};let t=await b({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},a.resolverContext,{maxBytes:ie,maxLines:ce});return t===void 0?{kind:"continue",context:a}:{kind:"return",result:t}}}d(z,"createAstOverflowHandler");var X="pi-agent-ast";function K(a){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let r=await a.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),t=de(e.lines,r);return t===e.lines?e:{...e,lines:t}}catch{return e}}}}d(K,"createAstScopePresenter");function U(){return a=>{let e=a.state,n=a.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:a};let r=n.details.lines;if(r===void 0)return{kind:"continue",context:a};let t=new Map(e.text.lines.map(u=>[u.lineNumber,u])),s=new Set(r.map(u=>u.lineNumber)),o=new Map;for(let u of r){let p=t.get(u.lineNumber),f=q(p);for(let m of f?.boundaries??[]){if(s.has(m.endLine))continue;let g=t.get(m.endLine);g!==void 0&&o.set(m.endLine,g)}}if(o.size===0)return{kind:"continue",context:a};let i=[...o.values()].sort((u,p)=>u.lineNumber-p.lineNumber),l=[...r,...i],c=le(n,l,r.at(-1));return{kind:"continue",context:{...a,result:c}}}}d(U,"createAstScopePostReadHandler");function de(a,e){if(e.length===0)return a;let n=new Map,r=new Map;for(let t of e){let s=n.get(t.startLine)??[];s.push(t.beginAnchor.value),n.set(t.startLine,s);let o=r.get(t.startLine)??[];o.push({endLine:t.endLine,beginAnchor:t.beginAnchor.value,endAnchor:t.endScopeAnchor.value}),r.set(t.startLine,o);let i=n.get(t.endLine)??[];i.push(t.endScopeAnchor.value),n.set(t.endLine,i)}return a.map(t=>{let s=n.get(t.lineNumber),o=r.get(t.lineNumber);return s===void 0&&o===void 0?t:{...t,...s!==void 0&&{anchors:[...new Set([...t.anchors??[],...s])],presentation:{...t.presentation,suffix:`${t.presentation?.suffix??""}${s.map(i=>` <!-- ${i} -->`).join("")}`}},metadata:{...t.metadata,[X]:{...q(t),...o!==void 0&&{boundaries:o}}}}})}d(de,"addScopeMarkers");function q(a){let e=a?.metadata?.[X];if(!(typeof e!="object"||e===null))return e}d(q,"getAstScopeMetadata");function le(a,e,n){let r=a.content.length===1?a.content[0]:void 0;if(r?.type!=="text"||a.details.lines===void 0)return a;let t=e.slice(a.details.lines.length);if(t.length===0)return a;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:t[0]?.lineEnding!==void 0&&t[0].lineEnding.length>0?t[0].lineEnding:`
6
- `,o=t.map((c,u)=>{let f=u===t.length-1?c.lineEnding:c.lineEnding||s,m=c.presentation?.prefix??"",g=c.presentation?.suffix??"";return`${m}${c.content}${g}${f}`}).join(""),i=/(?:\r\n|\r|\n)$/.test(r.text)?"":s,l=`${r.text}${i}${o}`;return{...a,content:[{...r,text:l}],details:{...a.details,lines:e}}}d(le,"appendTextLines");var J=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function Y(a){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return J.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!J.test(e))return{kind:"not-handled"};try{let t=(await a.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return t===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:t.beginAnchor.value===e?t.beginAnchor:t.endScopeAnchor}}catch(r){return{kind:"failed",error:r}}}}}d(Y,"createAstScopeAnchorResolver");import{spawn as ue}from"node:child_process";import{readFile as pe,stat as W}from"node:fs/promises";import h from"node:path";function Q(a){return{id:"ast",async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let r=e.query.slice(4).trim();if(r.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let t=d(async i=>{let l=Date.now(),c=await me(r,e,n.cwd,i);c.sort((p,f)=>h.resolve(n.cwd,p.file).localeCompare(h.resolve(n.cwd,f.file))||p.range.byteOffset.start-f.range.byteOffset.start||p.range.byteOffset.end-f.range.byteOffset.end);let u=c.slice(0,e.limit??100);return{raw:u,matches:await fe(u,n.cwd,l,i),complete:c.length<=(e.limit??100)}},"collect"),s=await t(n.signal),o=await a({request:e,matches:s.matches,complete:s.complete,refresh:t},n);return{kind:"resolved",payload:{pattern:r,matches:s.raw.map((i,l)=>({...i,selection:s.matches[l]})),complete:s.complete,sessionId:o.id}}},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n};let r=n.matches.flatMap((t,s)=>[`SEARCH#${n.sessionId}:${String(s+1)}:match ${t.file}:${String(t.range.start.line+1)}:${String(t.range.start.column+1)} ${t.language}`,` ${t.lines.trim()}`]);return n.complete&&r.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),n.complete||r.push("Result limit reached."),{content:[{type:"text",text:r.join(`
7
- `)}],details:n}}}}d(Q,"createAstSearchResolver");async function fe(a,e,n,r){let t=new Map;for(let s of a){let o=h.resolve(e,s.file);if(t.has(o))continue;let i=await W(o),l=await pe(o,{signal:r}),c=await W(o);if(i.mtimeMs>n||i.mtimeMs!==c.mtimeMs||i.size!==c.size)throw new Error("AST source changed during search. Run the structural query again.");t.set(o,l)}return a.map(s=>{let o=h.resolve(e,s.file),i=t.get(o);if(i===void 0)throw new Error("Missing AST source snapshot");let{start:l,end:c}=s.range.byteOffset;if(!Number.isInteger(l)||!Number.isInteger(c)||l<0||c<l||c>i.length||i.subarray(l,c).toString("utf8")!==s.text)throw new Error("AST range does not match its source snapshot. Search again.");let u=i.subarray(0,l).toString("utf8"),p=i.subarray(0,c).toString("utf8"),f=u.split(`
8
- `).length;return{source:o,lineNumber:f,endLineNumber:p.split(`
9
- `).length,startColumn:u.length-u.lastIndexOf(`
10
- `)-1,endColumn:p.length-p.lastIndexOf(`
11
- `)-1,matchedText:s.text,lineText:i.toString("utf8").split(`
12
- `)[f-1]?.replace(/\r$/u,"")??""}})}d(fe,"selectionMatches");function me(a,e,n,r){let t=["run","--pattern",a,"--json=compact","--no-ignore","parent"];for(let s of Z(e.include))t.push("--globs",s);for(let s of Z(e.exclude))t.push("--globs",`!${s}`);return t.push(e.path??"."),new Promise((s,o)=>{let i=ue("ast-grep",t,{cwd:n,stdio:["ignore","pipe","pipe"]}),l="",c="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",p=>l+=p),i.stderr.on("data",p=>c+=p);let u=d(()=>{i.kill("SIGTERM")},"abort");r?.addEventListener("abort",u,{once:!0}),i.once("error",o),i.once("close",p=>{if(r?.removeEventListener("abort",u),r?.aborted===!0){o(r.reason instanceof Error?r.reason:new Error("AST search aborted"));return}if(p!==0&&p!==1){o(new Error(c.trim()||`ast-grep exited with code ${String(p)}`));return}try{let f=JSON.parse(l.length===0?"[]":l);if(!Array.isArray(f))throw new TypeError("ast-grep returned non-array JSON");s(f)}catch(f){o(f instanceof Error?f:new Error(String(f)))}})})}d(me,"runAstGrep");function Z(a){return a?.split(",").map(e=>e.trim()).filter(Boolean)??[]}d(Z,"splitGlobs");var ge=$({kind:"code-view",label:"AST"});async function ee(a){let e=new V,n=K(e),r={protocol:k,apiVersion:P,id:"ast",setup(s){s.addResolver({resolver:F(),renderResult:ge}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:v()}),s.addView({view:"ast",presenter:n});let o=z();s.addOutputReducer(b);let i=U();s.addHandler({stage:"post-read",async handler(l){let c=await o(l);return c.kind==="return"?c:i(c.context)}}),s.describe('ast:<path> \u2014 compact declaration outline. views: ["ast"] \u2014 scope boundaries alongside source text. Oversized code reads may return an outline with source line numbers; offset/limit read a smaller source range.')}},t={protocol:I,apiVersion:C,id:"ast",setup(s){s.addAnchorResolver({resolver:Y(e),kind:N,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([M(a,r),E(a,G),_(a,t),D(a,{protocol:H,apiVersion:j,id:"ast-search",setup(s){s.addResolver({resolver:Q(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use captures in Apply to compute replacement text; these edits do not update imports or references.")}})])}d(ee,"registerAst");export{ee as default};
1
+ import{b as e,c as o}from"./chunk-25CZ5ZIU.js";import"./chunk-5VSE5X5R.js";import"./chunk-EI7MMDWY.js";export{o as AstScopeManager,e as parseDocument};
package/dist/entry-28.js CHANGED
@@ -1 +1,12 @@
1
- import{a,b,c}from"./chunk-DEP55R35.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as createChangeGroups,c as replaceHeadRangeInIndex,b as reverseChangeGroup};
1
+ import{b as D,c as V}from"./chunk-25CZ5ZIU.js";import{a as E}from"./chunk-MGCHOGQD.js";import{a as O,b as L}from"./chunk-T6LX2RX5.js";import{a as _}from"./chunk-L7JMDDSD.js";import{a as I,b as C,c as N}from"./chunk-O6LE42GK.js";import"./chunk-NNCZYO4Q.js";import{d as $}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as M}from"./chunk-6CZO43OH.js";import{a as k,b as P}from"./chunk-OBNING2A.js";import"./chunk-S3ZPXWX7.js";import{a as B}from"./chunk-ZTYWHL2F.js";import{a as H,b as j}from"./chunk-7UGNGK7Y.js";import{a as S,b as R,c as w,l as v}from"./chunk-NTYXZ3EL.js";import"./chunk-5VSE5X5R.js";import"./chunk-KINKBPPX.js";import{j as T}from"./chunk-M5MJP7Z2.js";import"./chunk-WZI4YC2O.js";import{e as x}from"./chunk-N34ATN52.js";import"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as te}from"node:fs/promises";var ne={cmake:"no compatible Tree-sitter parser is packaged",dockerfile:"no compatible Tree-sitter parser is packaged",julia:"no compatible Tree-sitter parser is packaged",powershell:"no compatible Tree-sitter parser is packaged",r:"no compatible Tree-sitter parser is packaged",svelte:"the container grammar is not available as an ast-grep language package",terraform:"the HCL grammar is not available as an ast-grep language package",vue:"the container grammar is not available as an ast-grep language package",xml:"no compatible Tree-sitter parser is packaged",zig:"no compatible Tree-sitter parser is packaged"},y=new Set(["c","cpp","csharp","css","dart","elixir","go","html","java","kotlin","lua","markdown","php","ruby","scala","shell","sql","swift","javascript","typescript","python","rust","json","yaml","toml"]),G={protocol:O,apiVersion:1,id:"ast",setup(a){a.addSetupCheck({id:"structural-search",async inspect(e){return[...e.detectedLanguageIds].some(r=>y.has(r))?await T({command:["ast-grep"]},e.cwd,e.env)?{}:{actions:[{id:"ast-grep-unavailable",message:"Structural search is unavailable because ast-grep was not found"}]}:{}}}),a.addCheck({id:"parsers",title:"AST",async run(e){let n=[];for(let r of e.detectedLanguageIds){let t=ne[r];if(t!==void 0){n.push({status:"skip",message:`${r} AST is unavailable: ${t}`});continue}if(!y.has(r))continue;let s=e.files.find(o=>re(o,r));if(s!==void 0)try{let o=await te(s,"utf8"),i=await D(s,e.cwd,o.replaceAll(`\r
2
+ `,`
3
+ `).split(`
4
+ `));n.push(i===void 0?{status:"fail",message:`${r} parser did not return a tree`}:{status:"pass",message:`${r} parser loaded`,detail:s})}catch(o){n.push({status:"fail",message:`${r}: ${o instanceof Error?o.message:String(o)}`})}}return n.length>0?n:[{status:"skip",message:"No supported AST files found"}]}}),a.addCheck({id:"ast-grep",title:"Structural search",async run(e){if(![...e.detectedLanguageIds].some(r=>y.has(r)))return[{status:"skip",message:"No supported structural-search files found"}];let n=await x("ast-grep",["--version"],e.cwd,e.env);return[n.ok?{status:"pass",message:"ast-grep is available",detail:n.detail}:{status:"fail",message:"ast-grep is not available",detail:n.detail}]}})}};function re(a,e){let n=a.slice(a.lastIndexOf(".")).toLowerCase();return{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"],csharp:[".cs"],css:[".css",".scss",".less"],dart:[".dart"],elixir:[".ex",".exs"],go:[".go"],html:[".html",".htm"],java:[".java"],kotlin:[".kt",".kts"],lua:[".lua"],markdown:[".md",".mdx"],php:[".php"],ruby:[".rb",".rake"],scala:[".scala",".sc"],shell:[".sh",".bash"],sql:[".sql"],swift:[".swift"],javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx",".mts",".cts"],python:[".py",".pyi"],rust:[".rs"],json:[".json",".jsonc"],yaml:[".yaml",".yml"],toml:[".toml"]}[e]?.includes(n)??!1}d(re,"matchesLanguage");var se,ae;function F(a){return{id:"ast",tryResolve(e,n){return Promise.resolve(oe(e,n,a))}}}d(F,"createAstOutlineResolver");function oe(a,e,n){let r;try{r=S(a,"ast")}catch(o){return{kind:"failed",error:o}}if(r===void 0)return{kind:"not-handled"};let t;try{t=R(r.path,e.cwd)}catch(o){return{kind:"failed",error:o}}return{kind:"resolved",resource:{source:w("ast",t),async read({signal:o}){o?.throwIfAborted();let i=await(ae??=import("./chunk-5QQABP47.js")),l=await(n??(se??=new i.AstOutlineManager)).readFileOutline(t,e.cwd);return o?.throwIfAborted(),[i.formatAstOutline(l)]}}}}d(oe,"resolveAstOutlineSource");import{DEFAULT_MAX_BYTES as ie,DEFAULT_MAX_LINES as ce,truncateHead as A}from"@earendil-works/pi-coding-agent";var b=d(async(a,e,n)=>{let{source:r,resolvedBy:t,lines:s,totalLines:o,startLine:i}=a.details;if(!(r===void 0||t!=="filesystem"||s===void 0||s.length!==o||i!==void 0&&i!==1))try{let{AstOutlineManager:c,isSupportedOutlinePath:l}=await import("./chunk-5QQABP47.js");if(!l(r))return;let u=d(m=>[`AST overview of ${m.path}, source lines 1-${m.totalLines}: the requested text exceeded the read buffer.`,"Source line numbers are on the left. Detail is reduced to fit the buffer; omitted bodies are not exact source text. Read a small source range when needed.",...m.renderedLines.map(g=>`${g.sourceLine?.lineNumber??"\u2026"} | ${g.text}`)].join(`
5
+ `),"format");e.signal?.throwIfAborted();let p=await new c(12).readDocumentOutline(r,e.cwd,s.map(m=>m.content),m=>(e.signal?.throwIfAborted(),!A(u(m),n).truncated)),f=u(p);return A(f,n).truncated?void 0:{content:[{type:"text",text:f}],details:{source:r,resolvedBy:"ast-overflow"}}}catch{e.signal?.throwIfAborted();return}},"reduceAstReadOutput");function z(){return async a=>{let{state:e,result:n}=a,r=n?.content.length===1?n.content[0]:void 0;if(a.audience==="script"||n===void 0||e?.contentKind!=="text"||e.resolvedBy!=="filesystem"||r?.type!=="text"||!A(r.text).truncated)return{kind:"continue",context:a};let t=await b({...n,details:{...n.details,source:e.source,resolvedBy:e.resolvedBy,lines:e.text.lines,startLine:1,totalLines:e.text.lines.length}},a.resolverContext,{maxBytes:ie,maxLines:ce});return t===void 0?{kind:"continue",context:a}:{kind:"return",result:t}}}d(z,"createAstOverflowHandler");var X="pi-agent-ast";function K(a){return{id:"ast-scopes",async present(e,n){if(n.resolvedBy!=="filesystem")return e;try{let r=await a.getDocumentScopes(e.source,n.cwd,e.lines.map(s=>s.content)),t=de(e.lines,r);return t===e.lines?e:{...e,lines:t}}catch{return e}}}}d(K,"createAstScopePresenter");function U(){return a=>{let e=a.state,n=a.result;if(e?.contentKind!=="text"||n===void 0)return{kind:"continue",context:a};let r=n.details.lines;if(r===void 0)return{kind:"continue",context:a};let t=new Map(e.text.lines.map(u=>[u.lineNumber,u])),s=new Set(r.map(u=>u.lineNumber)),o=new Map;for(let u of r){let p=t.get(u.lineNumber),f=q(p);for(let m of f?.boundaries??[]){if(s.has(m.endLine))continue;let g=t.get(m.endLine);g!==void 0&&o.set(m.endLine,g)}}if(o.size===0)return{kind:"continue",context:a};let i=[...o.values()].sort((u,p)=>u.lineNumber-p.lineNumber),c=[...r,...i],l=le(n,c,r.at(-1));return{kind:"continue",context:{...a,result:l}}}}d(U,"createAstScopePostReadHandler");function de(a,e){if(e.length===0)return a;let n=new Map,r=new Map;for(let t of e){let s=n.get(t.startLine)??[];s.push(t.beginAnchor.value),n.set(t.startLine,s);let o=r.get(t.startLine)??[];o.push({endLine:t.endLine,beginAnchor:t.beginAnchor.value,endAnchor:t.endScopeAnchor.value}),r.set(t.startLine,o);let i=n.get(t.endLine)??[];i.push(t.endScopeAnchor.value),n.set(t.endLine,i)}return a.map(t=>{let s=n.get(t.lineNumber),o=r.get(t.lineNumber);return s===void 0&&o===void 0?t:{...t,...s!==void 0&&{anchors:[...new Set([...t.anchors??[],...s])],presentation:{...t.presentation,suffix:`${t.presentation?.suffix??""}${s.map(i=>` <!-- ${i} -->`).join("")}`}},metadata:{...t.metadata,[X]:{...q(t),...o!==void 0&&{boundaries:o}}}}})}d(de,"addScopeMarkers");function q(a){let e=a?.metadata?.[X];if(!(typeof e!="object"||e===null))return e}d(q,"getAstScopeMetadata");function le(a,e,n){let r=a.content.length===1?a.content[0]:void 0;if(r?.type!=="text"||a.details.lines===void 0)return a;let t=e.slice(a.details.lines.length);if(t.length===0)return a;let s=n?.lineEnding!==void 0&&n.lineEnding.length>0?n.lineEnding:t[0]?.lineEnding!==void 0&&t[0].lineEnding.length>0?t[0].lineEnding:`
6
+ `,o=t.map((l,u)=>{let f=u===t.length-1?l.lineEnding:l.lineEnding||s,m=l.presentation?.prefix??"",g=l.presentation?.suffix??"";return`${m}${l.content}${g}${f}`}).join(""),i=/(?:\r\n|\r|\n)$/.test(r.text)?"":s,c=`${r.text}${i}${o}`;return{...a,content:[{...r,text:c}],details:{...a.details,lines:e}}}d(le,"appendTextLines");var W=/^scope-(begin|end)-[A-Z0-9]{3,4}(?:-[1-9]\d*)?$/;function J(a){return{id:"ast-scope",description:'`scope-begin-HASH` / `scope-end-HASH` from read views: ["ast"] \u2014 first/last lines of a scope. Any numeric suffix is part of the anchor.',renderFull(e){return e},renderCompact(e){return W.exec(e)?.[1]==="begin"?"scope start":"scope end"},async tryResolve(e,n){if(!W.test(e))return{kind:"not-handled"};try{let t=(await a.getDocumentScopes(n.source,n.cwd,n.lines)).find(s=>s.beginAnchor.value===e||s.endScopeAnchor.value===e);return t===void 0?{kind:"rejected",rejection:{code:"stale",reason:`AST scope anchor ${e} is stale`}}:{kind:"resolved",anchor:t.beginAnchor.value===e?t.beginAnchor:t.endScopeAnchor}}catch(r){return{kind:"failed",error:r}}}}}d(J,"createAstScopeAnchorResolver");import ue from"cross-spawn";import{readFile as pe,stat as Y}from"node:fs/promises";import h from"node:path";function Q(a){return{id:"ast",async tryResolve(e,n){if(!e.query.startsWith("ast:"))return{kind:"not-handled"};let r=e.query.slice(4).trim();if(r.length===0)return{kind:"failed",error:new Error("ast: pattern must not be empty")};let t=d(async i=>{let c=await me(r,e,n.cwd,i);c.sort((u,p)=>h.resolve(n.cwd,u.file).localeCompare(h.resolve(n.cwd,p.file))||u.range.byteOffset.start-p.range.byteOffset.start||u.range.byteOffset.end-p.range.byteOffset.end);let l=c.slice(0,e.limit??100);return{raw:l,matches:await fe(l,n.cwd,i),complete:c.length<=(e.limit??100)}},"collect"),s=await t(n.signal),o=await a({request:e,matches:s.matches,complete:s.complete,refresh:t},n);return{kind:"resolved",payload:{pattern:r,matches:s.raw.map((i,c)=>({...i,selection:s.matches[c]})),complete:s.complete,sessionId:o.id}}},format(e){let n=e;if(n.matches.length===0)return{content:[{type:"text",text:"No AST matches found."}],details:n};let r=n.matches.flatMap((t,s)=>[`SEARCH#${n.sessionId}:${String(s+1)}:match ${t.file}:${String(t.range.start.line+1)}:${String(t.range.start.column+1)} ${t.language}`,` ${t.lines.trim()}`]);return n.complete&&r.unshift(`SEARCH#${n.sessionId}:all:match selects all exact AST matches.`),n.complete||r.push("Result limit reached."),{content:[{type:"text",text:r.join(`
7
+ `)}],details:n}}}}d(Q,"createAstSearchResolver");async function fe(a,e,n){let r=new Map;for(let t of a){let s=h.resolve(e,t.file);if(r.has(s))continue;let o=await Y(s),i=await pe(s,{signal:n}),c=await Y(s);if(o.mtimeMs!==c.mtimeMs||o.size!==c.size)throw new Error("AST source changed during search. Run the structural query again.");r.set(s,i)}return a.map(t=>{let s=h.resolve(e,t.file),o=r.get(s);if(o===void 0)throw new Error("Missing AST source snapshot");let{start:i,end:c}=t.range.byteOffset;if(!Number.isInteger(i)||!Number.isInteger(c)||i<0||c<i||c>o.length||o.subarray(i,c).toString("utf8")!==t.text)throw new Error("AST range does not match its source snapshot. Search again.");let l=o.subarray(0,i).toString("utf8"),u=o.subarray(0,c).toString("utf8"),p=l.split(`
8
+ `).length;return{source:s,lineNumber:p,endLineNumber:u.split(`
9
+ `).length,startColumn:l.length-l.lastIndexOf(`
10
+ `)-1,endColumn:u.length-u.lastIndexOf(`
11
+ `)-1,matchedText:t.text,lineText:o.toString("utf8").split(`
12
+ `)[p-1]?.replace(/\r$/u,"")??""}})}d(fe,"selectionMatches");function me(a,e,n,r){let t=["run","--pattern",a,"--json=compact","--no-ignore","parent"];for(let s of Z(e.include))t.push("--globs",s);for(let s of Z(e.exclude))t.push("--globs",`!${s}`);return t.push(e.path??"."),new Promise((s,o)=>{let i=ue("ast-grep",t,{cwd:n,stdio:["ignore","pipe","pipe"]}),c="",l="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",p=>c+=p),i.stderr.on("data",p=>l+=p);let u=d(()=>{i.kill("SIGTERM")},"abort");r?.addEventListener("abort",u,{once:!0}),i.once("error",o),i.once("close",p=>{if(r?.removeEventListener("abort",u),r?.aborted===!0){o(r.reason instanceof Error?r.reason:new Error("AST search aborted"));return}if(p!==0&&p!==1){o(new Error(l.trim()||`ast-grep exited with code ${String(p)}`));return}try{let f=JSON.parse(c.length===0?"[]":c);if(!Array.isArray(f))throw new TypeError("ast-grep returned non-array JSON");s(f)}catch(f){o(f instanceof Error?f:new Error(String(f)))}})})}d(me,"runAstGrep");function Z(a){return a?.split(",").map(e=>e.trim()).filter(Boolean)??[]}d(Z,"splitGlobs");var ge=$({kind:"code-view",label:"AST"});async function ee(a){let e=new V,n=K(e),r={protocol:k,apiVersion:P,id:"ast",setup(s){s.addResolver({resolver:F(),renderResult:ge}),s.addHandler({stage:"read",when:{resolvedBy:"ast",contentKind:"text"},handler:v()}),s.addView({view:"ast",presenter:n});let o=z();s.addOutputReducer(b);let i=U();s.addHandler({stage:"post-read",async handler(c){let l=await o(c);return l.kind==="return"?l:i(l.context)}}),s.describe('ast:<path> \u2014 compact declaration outline. views: ["ast"] \u2014 scope boundaries alongside source text. Oversized code reads may return an outline with source line numbers; offset/limit read a smaller source range.')}},t={protocol:I,apiVersion:C,id:"ast",setup(s){s.addAnchorResolver({resolver:J(e),kind:N,type:"auxiliary"}),s.addTextPresenter({presenter:n})}};await Promise.all([M(a,r),E(a,G),_(a,t),B(a,{protocol:H,apiVersion:j,id:"ast-search",setup(s){s.addResolver({resolver:Q(s.registerSelection)}),s.describe("Search code structure with ast:<pattern>, using source-code syntax and placeholders such as $NAME for one node and $$$BODY for several nodes. path, include and exclude narrow the search. Use returned SEARCH# references to read, replace, copy, move or delete exact AST matches, including multiline nodes. A single :match reference becomes stale after its file changes; :all:match reruns the original structural query. Incomplete results do not provide all selections. Use captures in Apply to compute replacement text; these edits do not update imports or references.")}})])}d(ee,"registerAst");export{ee as default};
package/dist/entry-29.js CHANGED
@@ -1 +1 @@
1
- import{a as V,b as z,c as Q}from"./chunk-DEP55R35.js";import{a as O}from"./chunk-MGCHOGQD.js";import{a as L,b as N}from"./chunk-T6LX2RX5.js";import{a as j}from"./chunk-6CZO43OH.js";import{a as U,b as F}from"./chunk-OBNING2A.js";import{a as B}from"./chunk-L7JMDDSD.js";import{a as M,b as _}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{a as H}from"./chunk-5VSE5X5R.js";import{d as $,e as D}from"./chunk-N34ATN52.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Value as De}from"typebox/value";import{access as ne}from"node:fs/promises";import re from"node:path";var K={protocol:L,apiVersion:1,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await oe(e.cwd)?await $("git",e.cwd,e.env)?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await D("git",["--version"],e.cwd,e.env);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};async function oe(n){try{return await ne(re.join(n,".git")),!0}catch{return!1}}s(oe,"isGitProject");import{mkdtemp as ae,rm as ie,writeFile as se}from"node:fs/promises";import de from"node:os";import m from"node:path";var b=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,m.resolve(o.stdout.trim()))}}async readTrackedFile(e,t,r){let o=m.resolve(t,e),a=m.relative(this.repositoryRoot,o);return a===".."||a.startsWith(`..${m.sep}`)||m.isAbsolute(a)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(a.split(m.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let a=ce(o.stdout);if(a===void 0)return{status:"untracked"};let i=await this.readBlob(a.blob,"HEAD",e,t);if(i.status!=="found")return i;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let d=ue(c.stdout);if(d.some(({stage:g})=>g!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let u=d.find(({stage:g})=>g===0),l="";if(u!==void 0){let g=await this.readBlob(u.blob,"index",e,t);if(g.status!=="found")return g;l=g.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:i.text,indexText:l,indexMode:u?.mode??a.mode}}async writeIndexFile(e,t,r,o){let a=await ae(m.join(de.tmpdir(),"pi-agent-index-")),i=m.join(a,"content");try{await se(i,r,"utf8");let c=await this.git(["hash-object","-w",`--path=${e}`,i],o);if(c.code!==0||c.stdout.trim().length===0)throw new Error(c.stderr.trim()||`could not write a Git blob for ${e}`);let d=await this.git(["update-index","--add","--cacheinfo",t,c.stdout.trim(),e],o);if(d.code!==0)throw new Error(d.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await ie(a,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let a=await this.git(["cat-file","blob",e],o);return a.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:a.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:a.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ce(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,a]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||a===void 0?void 0:{mode:r,blob:a,path:e.slice(t+1)}}s(ce,"parseTreeEntry");function ue(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,a]=e.slice(0,t).split(" ",3),i=Number(a);return r===void 0||o===void 0||!Number.isInteger(i)?[]:[{mode:r,blob:o,stage:i,path:e.slice(t+1)}]})}s(ue,"parseIndexEntries");function W(n){return{exec:s((e,t,r)=>n.exec(e,t,r),"exec")}}s(W,"extensionGitExecutor");var f=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await b.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=V(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let a=o.groups.find(u=>u.selector===t);if(a===void 0)return A(t,o.groups.map(({selector:u})=>u));let i=r==="stage"?"staged":"unstaged";if(a.state===i)return{status:"unchanged",state:i,group:a};let c=x(a.segments[0]),d={head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(d,e.signal)}catch(u){return{status:"unavailable",reason:"index-write-failed",message:le(u)}}return{status:"applied",state:i,group:a}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(d=>d.selector===t);if(o===void 0)return A(t,r.groups.map(({selector:d})=>d));let a=z(e.worktreeText,o);if(a===void 0)return A(t,r.groups.map(({selector:d})=>d));let i=x(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:i.headStart,headEnd:i.headEnd,replacementText:i.headText};return{status:"applied",worktreeText:a,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=Q(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t)}};function A(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(A,"staleSelector");function le(n){return n instanceof Error?n.message:String(n)}s(le,"errorMessage");var T="pi-agent-ide-changes/change",ge=/^CHANGE#[0-9A-F]{4,64}$/,pe=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,G=class extends H{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function Y(n){return{resolver:fe(s(async t=>{if(pe.test(t.source))return;let r=await f.create(n,t.cwd,t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(Y,"createChangeAnchorRegistration");function fe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!ge.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(a=>a.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new G(o)}}catch(r){return{kind:"failed",error:r}}}}}s(fe,"createChangeAnchorResolver");import{diffLines as he}from"diff";var me="filesystem";function q(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==me)return e;let r=await f.create(n,t.cwd,t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:ye(e,o.groups)}}}s(q,"createCurrentChangePresenter");function ye(n,e){let t=new Map;for(let r of e)xe(n,r,t);return{...n,lines:n.lines.map(r=>be(r,t.get(r.lineNumber)))}}s(ye,"presentChangeGroups");function xe(n,e,t){let r=x(e.segments[0]),o=he(r.headText,r.worktreeText),a=e.currentStartLine,i,c;for(let d of o){let u=ve(d.value);if(d.removed){let l=Te(n,a),g=R(t,l.lineNumber),p=l.after?g.after:g.before;for(let h of u){let w={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:h}),i??=w,c=w}continue}if(d.added){for(let l of u){let g=R(t,a),p={kind:"current",lineNumber:a};g.added=!0,i??=p,c=p,a++}continue}a+=u.length}if(i!==void 0&&c!==void 0){let d=`${e.selector} \xB7 ${e.state}`;we(i,c)?I(t,i,`<!-- change: ${d} -->`):(I(t,i,`<!-- change-begin: ${d} -->`),I(t,c,`<!-- change-end: ${d} -->`))}}s(xe,"presentChangeGroup");function we(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(we,"sameTarget");function I(n,e,t){if(e.kind==="current"){R(n,e.lineNumber).annotations.push(t);return}let r=x(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s(I,"annotateTarget");function be(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s(be,"presentLine");function R(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(R,"presentationsFor");function Te(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Te,"placementFor");function ve(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(ve,"splitLines");var v=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ce}from"node:crypto";import{realpathSync as ke}from"node:fs";import J from"node:path";import{fileURLToPath as Ee}from"node:url";var k=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=X(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t);r&&r.afterDigest===C(e.before.content)?this.#e.set(t,{...r,afterDigest:C(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:C(e.after.content)})}restore(e,t,r){let o=X(e,t),a=this.#e.get(o);if(a===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(a.afterDigest!==C(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return a.before}};function X(n,e){return n.startsWith("file://")?Z(Ee(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:Z(J.resolve(e,n))}s(X,"sourceKey");function Z(n){try{return ke.native(n)}catch{return J.normalize(n)}}s(Z,"canonicalFile");function C(n){return Ce("sha256").update(n).digest("hex")}s(C,"textDigest");import{readFile as Pe}from"node:fs/promises";import Ae from"node:path";import{defineTool as Ge,withFileMutationQueue as Ie}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";var P=S.Object({file:S.String({description:"Path to the tracked text file"}),change:S.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1});function ee(n,e,t){n.registerTool(E("stage",e,t)),n.registerTool(E("unstage",e,t))}s(ee,"registerIndexChangeTools");function E(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return Ge({name:n,label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:`Use ${n} to ${n==="stage"?"add one current Git change to the index":"remove one current Git change from the index"}. Select the change with a CHANGE# anchor; worktree content is kept.`,parameters:P,async execute(a,i,c,d,u){let l=Re(i.file,u.cwd);return Ie(l,()=>t.run(async()=>{let g=await Pe(l,"utf8"),p=await f.create(e,u.cwd,c);if(p.status!=="ready")throw new Error(p.message);let h=await p.service.changeIndex({source:l,worktreeText:g,cwd:u.cwd,...c!==void 0&&{signal:c}},i.change,n);if(h.status==="unavailable")throw new Error(h.message);if(h.status==="not-applicable")throw new Error(`${n} is not applicable to ${l}: ${h.reason}`);let w=h.status==="unchanged";return{content:[{type:"text",text:w?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:l,state:r,unchanged:w}}}))}})}s(E,"createIndexChangeTool");function Re(n,e){let t=n.startsWith("@")?n.slice(1):n;return Ae.resolve(e,t)}s(Re,"resolveFile");import{diffChars as Se}from"diff";import{Type as y}from"typebox";var He=y.Object({file:y.Optional(y.String({description:"File to restore; may be omitted to inherit the previous batched source"})),change:y.Optional(y.String({description:"Complete CHANGE#HASH anchor shown by read, or last for this file's latest text-editor transaction",pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})),transaction:y.Optional(y.String({description:"APPLY# receipt returned by a successful Apply transaction",pattern:"^APPLY#[0-9A-F]{12}$"}))},{additionalProperties:!1});function te(n,e,t,r){return{name:"undo",description:"Use undo to revert an APPLY# transaction receipt, a selected uncommitted Git change, or the latest text-editor transaction for one file. Apply receipts restore every touched path atomically; CHANGE# restores that change to HEAD in both worktree and index; last restores one file's latest text edit.",promptSnippet:"Restore an Apply transaction, Git change, or latest text edit",direct:{matches:s(o=>o!==null&&typeof o=="object"&&"transaction"in o&&typeof o.transaction=="string","matches"),async execute(o,a){if(a.change!==void 0)throw new Error("transaction cannot be combined with change");let i=String(a.transaction),c=await r(i,o.signal);return{source:i,summary:`Restored ${String(c.restored.length)} paths from ${i}.`,data:{kind:"apply-undo",ok:!0,transaction:i,restored:c.restored}}}},parameters:He,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[T],nonAnchorValues:["last"]}],async mutate(o,a){if(a.change===void 0)throw new Error("change is required when transaction is omitted");let i=o.sourceFor("file"),c,d;if(a.change==="last")c=e.restore(i,o.cwd,o.sourceDocument.content);else{await o.resolveAnchor("change");let u=await f.create(n,o.cwd,o.signal);if(u.status!=="ready")throw new Error(u.message);let l=await u.service.prepareUndo({source:i,worktreeText:o.sourceDocument.content,cwd:o.cwd,...o.signal!==void 0&&{signal:o.signal}},a.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(c=l.worktreeText,l.indexUpdate!==void 0){let g=l.indexUpdate;d=s(()=>t.run(()=>u.service.applyIndexUpdate(g,o.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:$e(o.sourceDocument.content,c),action:"edited"}]]),...d!==void 0&&{afterWrite:d}}}}}s(te,"createUndoMutationTool");function $e(n,e){let t=[],r=0,o,a=0,i="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+a,insert:i}),o=void 0,a=0,i="")},"flush");for(let d of Se(n,e)){if(!d.added&&!d.removed){c(),r+=d.value.length;continue}o??=r,d.removed?(r+=d.value.length,a+=d.value.length):i+=d.value}return c(),t}s($e,"createTextChanges");async function Le(n){let e=W(n),t=new k,r=new v,o=q(e),a=Y(e),i={protocol:U,apiVersion:F,id:"current-git-changes",setup(d){d.addView({view:"changes",presenter:o}),d.describe('views: ["changes"] \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo.')}},c={protocol:M,apiVersion:_,id:"current-git-changes",setup(d){d.addAnchorResolver({...a,kind:T,type:"auxiliary"}),d.onDidEdit(u=>{t.observe(u)}),d.addMutationTool(te(e,t,r,d.restoreApplyUndo));for(let u of["stage","unstage"]){let l=E(u,e,r);d.addScriptIndexOperation({name:u,parameters:P,execute:s((g,p,h)=>l.execute(`apply-${u}`,De.Decode(P,g),p,void 0,h),"execute")})}d.addTextPresenter({presenter:o})}};await Promise.all([O(n,K),j(n,i),B(n,c)]),ee(n,e,r)}s(Le,"registerGitChanges");export{Le as default};
1
+ import{a,b,c}from"./chunk-DEP55R35.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{a as createChangeGroups,c as replaceHeadRangeInIndex,b as reverseChangeGroup};