pi-agent-ide 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/chunk-6U5OU77O.js +3 -0
  3. package/dist/chunk-EURHXLN3.js +2 -0
  4. package/dist/{chunk-WMO6RNE2.js → chunk-F6IWZKOG.js} +6 -6
  5. package/dist/{chunk-HZEY4GT4.js → chunk-H445SHSJ.js} +2 -2
  6. package/dist/chunk-IG56UGSO.js +2 -0
  7. package/dist/chunk-IICJXZBU.js +6 -0
  8. package/dist/{chunk-XYS4FSCC.js → chunk-IM24DB3K.js} +1 -1
  9. package/dist/{chunk-PKKDDIWW.js → chunk-KOVPDKSJ.js} +1 -1
  10. package/dist/chunk-MXLSGMRZ.js +3 -0
  11. package/dist/chunk-OB46OPMZ.js +1 -0
  12. package/dist/chunk-PKSQT6TC.js +1 -0
  13. package/dist/{chunk-PNU3E7IO.js → chunk-Q6CZ6GBR.js} +2 -2
  14. package/dist/chunk-QUYXINGZ.js +7 -0
  15. package/dist/{chunk-OMVRLWMX.js → chunk-SBP3ABH4.js} +1 -1
  16. package/dist/{chunk-4GCWGE2C.js → chunk-SJ4UZ4GU.js} +1 -1
  17. package/dist/{chunk-2TRHFMCZ.js → chunk-SNF7PDDX.js} +1 -1
  18. package/dist/{chunk-YP46DVVP.js → chunk-STBJO3Z3.js} +1 -1
  19. package/dist/{chunk-76ZK5ODR.js → chunk-TQGE7RH6.js} +13 -13
  20. package/dist/{chunk-LEEQIQ7D.js → chunk-XDG7EQRN.js} +6 -6
  21. package/dist/chunk-YWQS33DF.js +1 -0
  22. package/dist/chunk-ZIWPKIBZ.js +1 -0
  23. package/dist/entry-11.js +1 -1
  24. package/dist/entry-13.js +1 -1
  25. package/dist/entry-14.js +1 -1
  26. package/dist/entry-15.js +1 -1
  27. package/dist/entry-17.js +1 -1
  28. package/dist/entry-25.js +1 -1
  29. package/dist/entry-26.js +1 -1
  30. package/dist/entry-27.js +1 -1
  31. package/dist/entry-28.js +1 -1
  32. package/dist/entry-29.js +1 -1
  33. package/dist/entry-31.js +13 -12
  34. package/dist/entry-33.js +2 -1
  35. package/dist/entry-37.js +2 -2
  36. package/dist/entry-42.js +1 -1
  37. package/dist/entry-44.js +1 -1
  38. package/dist/entry-45.js +20 -12
  39. package/dist/entry-46.js +1 -1
  40. package/dist/entry-49.js +1 -1
  41. package/dist/entry-50.js +1 -1
  42. package/dist/entry-51.js +7 -6
  43. package/dist/entry-52.js +1 -1
  44. package/dist/entry-53.js +1 -1
  45. package/dist/entry-54.js +1 -1
  46. package/dist/entry-56.js +1 -1
  47. package/dist/entry-58.js +1 -1
  48. package/dist/entry-60.js +1 -1
  49. package/dist/entry-62.js +1 -1
  50. package/dist/entry-65.js +1 -1
  51. package/dist/entry-66.js +1 -1
  52. package/dist/entry-68.js +1 -1
  53. package/dist/entry-70.js +1 -1
  54. package/dist/entry-75.js +1 -1
  55. package/dist/entry-77.js +51 -42
  56. package/dist/entry-78.js +14 -14
  57. package/dist/entry-79.js +1 -1
  58. package/dist/entry-82.js +5 -5
  59. package/dist/entry-83.js +1 -1
  60. package/dist/entry-84.js +1 -1
  61. package/dist/entry-85.js +1 -1
  62. package/dist/entry-86.js +1 -1
  63. package/dist/pi-agent-ide.js +34 -11
  64. package/docs/agent-guides/editing.md +5 -5
  65. package/docs/agent-guides/git-changes.md +10 -0
  66. package/docs/agent-guides/read-resources.md +9 -46
  67. package/docs/agent-guides/search-code.md +7 -1
  68. package/docs/agent-guides/select-code.md +1 -0
  69. package/docs/agent-guides/terminal.md +9 -1
  70. package/docs/configuration.md +1 -1
  71. package/docs/releases.md +4 -0
  72. package/docs/research/native-codemode-batch-decision.md +2 -0
  73. package/docs/structured-results.md +2 -2
  74. package/docs/tools.md +10 -2
  75. package/node_modules/pi-agent-doctor/package.json +1 -1
  76. package/node_modules/pi-agent-documentation/package.json +1 -1
  77. package/node_modules/pi-agent-filesystem/package.json +7 -7
  78. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  79. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  80. package/node_modules/pi-agent-filesystem-jq/src/jq.ts +4 -1
  81. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  82. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  83. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  84. package/node_modules/pi-agent-ide-ast/src/extension.ts +0 -2
  85. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  86. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +0 -3
  87. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +8 -6
  88. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +13 -5
  89. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  90. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +66 -4
  91. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +8 -11
  92. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  93. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  94. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  95. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  96. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +0 -1
  97. package/node_modules/pi-agent-image/package.json +2 -2
  98. package/node_modules/pi-agent-invariant/package.json +1 -1
  99. package/node_modules/pi-agent-pdf/package.json +2 -2
  100. package/node_modules/pi-agent-read/package.json +7 -7
  101. package/node_modules/pi-agent-read/src/api/read-parameters.ts +3 -3
  102. package/node_modules/pi-agent-read/src/api/tools/read.ts +11 -0
  103. package/node_modules/pi-agent-read/src/core/extension.ts +1 -1
  104. package/node_modules/pi-agent-read/src/core/read-core.ts +5 -1
  105. package/node_modules/pi-agent-read/src/core/tools/read/output-truncation.ts +91 -18
  106. package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +8 -2
  107. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +38 -1
  108. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +57 -2
  109. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +99 -44
  110. package/node_modules/pi-agent-resource/package.json +1 -1
  111. package/node_modules/pi-agent-resource/src/index.ts +1 -0
  112. package/node_modules/pi-agent-resource/src/result-targets.ts +6 -3
  113. package/node_modules/{pi-agent-read/src/core/tools/read → pi-agent-resource/src}/temp-resource-store.ts +17 -7
  114. package/node_modules/pi-agent-search/package.json +5 -5
  115. package/node_modules/pi-agent-search/src/api/fuzzy.ts +5 -1
  116. package/node_modules/pi-agent-search/src/api/search-parameters.ts +2 -2
  117. package/node_modules/pi-agent-search/src/core/extension.ts +2 -1
  118. package/node_modules/pi-agent-search/src/core/search-core.ts +13 -4
  119. package/node_modules/pi-agent-search-text/package.json +7 -7
  120. package/node_modules/pi-agent-search-text/src/resolvers.ts +11 -1
  121. package/node_modules/pi-agent-search-text/src/scoped-search.ts +1 -1
  122. package/node_modules/pi-agent-search-text/src/search-presentation.ts +42 -32
  123. package/node_modules/pi-agent-search-text/src/search-recipe.ts +1 -1
  124. package/node_modules/pi-agent-search-text/src/search-renderer.ts +6 -0
  125. package/node_modules/pi-agent-search-text/src/search-result.ts +17 -3
  126. package/node_modules/pi-agent-text/package.json +2 -2
  127. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  128. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  129. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  130. package/node_modules/pi-agent-text-editor/package.json +9 -9
  131. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -2
  132. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +1 -2
  133. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +4 -0
  134. package/node_modules/pi-agent-text-editor/src/api/stale-anchor-message.ts +1 -1
  135. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +54 -12
  136. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +1 -1
  137. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +35 -6
  138. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +19 -1
  139. package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +132 -11
  140. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +232 -151
  141. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +34 -10
  142. package/node_modules/pi-agent-text-editor/src/core/result-input.ts +24 -4
  143. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +7 -2
  144. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +14 -13
  145. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +5 -1
  146. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +152 -22
  147. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +4 -0
  148. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +76 -32
  149. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +381 -187
  150. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +4 -2
  151. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +9 -2
  152. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +9 -4
  153. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +7 -8
  154. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +2 -3
  155. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +10 -4
  156. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  157. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +11 -0
  158. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +54 -5
  159. package/node_modules/pi-agent-text-editor-renderer/src/status-summary.ts +18 -3
  160. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  161. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  162. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  163. package/node_modules/pi-agent-web/package.json +7 -7
  164. package/node_modules/pi-agent-web/src/resolver.ts +11 -13
  165. package/node_modules/pi-agent-web-html/package.json +2 -2
  166. package/node_modules/pi-agent-web-image/package.json +3 -3
  167. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  168. package/node_modules/pi-agent-web-text/package.json +3 -3
  169. package/package.json +35 -35
  170. package/src/composite/nested-tool-rendering.ts +64 -6
  171. package/src/composite/output-limits.ts +125 -0
  172. package/src/composite/responses-tools.ts +25 -0
  173. package/src/composite/text-results.ts +158 -7
  174. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  175. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  176. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  177. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts +4 -1
  178. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  179. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  180. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  181. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  182. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  183. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  184. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  185. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +11 -13
  186. package/src/extensions/pi-agent-read/package.json +7 -7
  187. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +3 -3
  188. package/src/extensions/pi-agent-read/src/api/tools/read.ts +11 -0
  189. package/src/extensions/pi-agent-read/src/core/extension.ts +1 -1
  190. package/src/extensions/pi-agent-read/src/core/read-core.ts +5 -1
  191. package/src/extensions/pi-agent-read/src/core/tools/read/output-truncation.ts +91 -18
  192. package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +8 -2
  193. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +38 -1
  194. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +57 -2
  195. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +99 -44
  196. package/src/extensions/pi-agent-search/package.json +5 -5
  197. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -7
  198. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +11 -1
  199. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +1 -1
  200. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +42 -32
  201. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +1 -1
  202. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +6 -0
  203. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +17 -3
  204. package/src/extensions/pi-agent-search/src/api/fuzzy.ts +5 -1
  205. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +2 -2
  206. package/src/extensions/pi-agent-search/src/core/extension.ts +2 -1
  207. package/src/extensions/pi-agent-search/src/core/search-core.ts +13 -4
  208. package/src/extensions/pi-agent-text-editor/package.json +9 -9
  209. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  210. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  211. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  212. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  213. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +11 -0
  214. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +54 -5
  215. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/status-summary.ts +18 -3
  216. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  217. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -2
  218. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +1 -2
  219. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +4 -0
  220. package/src/extensions/pi-agent-text-editor/src/api/stale-anchor-message.ts +1 -1
  221. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +54 -12
  222. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +1 -1
  223. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +35 -6
  224. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +19 -1
  225. package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +132 -11
  226. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +232 -151
  227. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +34 -10
  228. package/src/extensions/pi-agent-text-editor/src/core/result-input.ts +24 -4
  229. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +7 -2
  230. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +14 -13
  231. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +5 -1
  232. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +152 -22
  233. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +4 -0
  234. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +76 -32
  235. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +381 -187
  236. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +4 -2
  237. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +9 -2
  238. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +9 -4
  239. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +7 -8
  240. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +2 -3
  241. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +10 -4
  242. package/src/pi-agent-ide.ts +11 -0
  243. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  244. package/src/plugins/pi-agent-ide-ast/src/extension.ts +0 -2
  245. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  246. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +0 -3
  247. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +8 -6
  248. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +13 -5
  249. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  250. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +66 -4
  251. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +8 -11
  252. package/src/plugins/pi-agent-ide-debugger/index.ts +17 -7
  253. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -0
  254. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +93 -38
  255. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +3 -2
  256. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  257. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  258. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  259. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  260. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +0 -1
  261. package/src/plugins/pi-agent-ide-terminal/src/output-limits.ts +3 -3
  262. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +3 -3
  263. package/src/plugins/pi-agent-ide-vision/index.ts +1 -0
  264. package/src/post-edit/gate.ts +13 -2
  265. package/dist/chunk-4XMY4H4V.js +0 -1
  266. package/dist/chunk-64M3SQPG.js +0 -3
  267. package/dist/chunk-CWD4O5PM.js +0 -3
  268. package/dist/chunk-D3WTDA6V.js +0 -2
  269. package/dist/chunk-EAZGN5ND.js +0 -7
  270. package/dist/chunk-GXEGY7GV.js +0 -1
  271. package/dist/chunk-MBUXFKIW.js +0 -3
  272. package/dist/chunk-PGIVHICI.js +0 -1
  273. package/dist/chunk-VMTR74FF.js +0 -2
  274. package/dist/chunk-WU6ZK6YD.js +0 -1
  275. package/src/extensions/pi-agent-read/src/core/tools/read/temp-resource-store.ts +0 -105
@@ -1,7 +1,7 @@
1
- import{a as de,b as me,c as fe}from"./chunk-ESPNEJHK.js";import{a as ce}from"./chunk-M5IVSCR2.js";import"./chunk-EAZGN5ND.js";import{a as I}from"./chunk-4XMY4H4V.js";import{e as Z,f as J}from"./chunk-T7I2VX3J.js";import{a as ie}from"./chunk-PKKDDIWW.js";import{a as ne,b as re}from"./chunk-4GCWGE2C.js";import{b as E}from"./chunk-64M3SQPG.js";import{a as te}from"./chunk-BU7IZLKB.js";import{a as Q,b as ee}from"./chunk-S5PL5DFQ.js";import{a as le}from"./chunk-YP46DVVP.js";import{e as ue}from"./chunk-GXEGY7GV.js";import{a as ae}from"./chunk-ZTYWHL2F.js";import{a as oe,b as se}from"./chunk-7UGNGK7Y.js";import"./chunk-PS2B6THP.js";import{h as j,i as L}from"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import et from"node:path";import{stripVTControlCharacters as tt}from"node:util";import{truncateLine as nt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as pe,DEFAULT_MAX_LINES as ge,formatSize as Je,truncateTail as Qe}from"@earendil-works/pi-coding-agent";function $(t){return Qe(t,{maxBytes:pe-4096,maxLines:ge-32})}s($,"terminalOutputTail");function M(t){let e=$(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||t.status!=="running"?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 de,b as me,c as pe}from"./chunk-ESPNEJHK.js";import{a as ce}from"./chunk-M5IVSCR2.js";import"./chunk-QUYXINGZ.js";import{a as I}from"./chunk-PKSQT6TC.js";import{e as Z,f as J}from"./chunk-T7I2VX3J.js";import{a as ie}from"./chunk-KOVPDKSJ.js";import{a as ne,b as re}from"./chunk-SJ4UZ4GU.js";import{b as E}from"./chunk-IICJXZBU.js";import{a as te}from"./chunk-BU7IZLKB.js";import{a as Q,b as ee}from"./chunk-S5PL5DFQ.js";import{a as le}from"./chunk-STBJO3Z3.js";import{e as ue}from"./chunk-OB46OPMZ.js";import{a as ae}from"./chunk-ZTYWHL2F.js";import{a as oe,b as se}from"./chunk-7UGNGK7Y.js";import"./chunk-PS2B6THP.js";import{i as j,j as L}from"./chunk-6U5OU77O.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import et from"node:path";import{stripVTControlCharacters as tt}from"node:util";import{truncateLine as nt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as fe,DEFAULT_MAX_LINES as ge,formatSize as Je,truncateTail as Qe}from"@earendil-works/pi-coding-agent";function $(t){return Qe(t,{maxBytes:fe-4096,maxLines:ge-32})}s($,"terminalOutputTail");function M(t){let e=$(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.status==="running"&&t.background?`next: Continue independent work or finish your turn; completion or a one-time idle inspection notice will wake the agent. Read ${t.source} to inspect output; use write or insert when input is needed.`:void 0,`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
- ${r}`}`;let i=e.truncatedBy==="lines"?`${ge} line output budget`:`${Je(pe)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
4
+ ${r}`}`;let i=e.truncatedBy==="lines"?`${ge} line output budget`:`${Je(fe)} output budget`,a=`[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
  ${a}${r.length===0?"":`
@@ -15,14 +15,14 @@ ${i.fg("accent",H(r.family))} ${t}`,0,0)}s(he,"renderRunCall");function ye(t,e,n
15
15
  `),0,0)}s(Se,"renderRunResult");function Te(t,e){let n=s((o,c)=>e?.fg(o,c)??c,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${D(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",H(t.shellFamily))} ${B(t.command,84)}`],a=it(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",B(o,90))}`)),i.push(k(t,n)),i.join(`
16
16
  `)}s(Te,"renderActiveTerminal");function be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":D(t.cwd),o=t.shellFamily??"posix",c=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",H(o))} ${t.command??""}`],l=_(t.output??"",e);return l.omission!==void 0&&c.push(` ${n.fg("muted",l.omission)}`),l.lines.length>0&&c.push(...l.lines.map(u=>` ${n.fg("dim",u)}`)),c.push(k(t,(u,d)=>n.fg(u,d))),c}s(be,"terminalCardLines");function it(t,e){return _(t,e).lines}s(it,"outputTail");function _(t,e){let n=$(tt(t).replaceAll("\r","")),r=n.content.split(`
17
17
  `).map(l=>nt(l.trimEnd(),rt).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),c=a+o;return{lines:r.slice(a),...n.truncated||c>0?{omission:c>0?`\u2026 ${c} earlier lines`:"\u2026 earlier output omitted"}:{}}}s(_,"outputWindow");function k(t,e){let n=t.status??"running",r=ot(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,at(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}s(k,"statusLine");function ot(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}s(ot,"statusIcon");function H(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}s(H,"promptMarker");function st(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":D(t.cwd),i=t.background===!0?"background":"wait",a=B(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}s(st,"terminalIdentity");function D(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${et.sep}`))?`~${t.slice(e.length)}`:t}s(D,"shortCwd");function B(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}s(B,"oneLine");function at(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(at,"formatElapsed");function Re(t){return{id:"terminal",onDidChange:s(e=>t.onDidChange(e),"onDidChange"),list:s(()=>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:s(n=>Te(e,n).split(`
18
- `),"renderSummary"),renderDetail:s(n=>x(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as mt}from"node:timers/promises";var lt="#d8dee9",G="#111418",ut=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function q(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=G,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let f=i.screen.buffer.active,p=Math.max(0,f.baseY);for(let h=0;h<c;h+=1){let w=f.getLine(p+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||ct(m,P,y,h)}}return i.status==="running"&&f.cursorY>=o&&f.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+f.cursorX*9,12+(f.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(q,"renderTerminalScreen");function ct(t,e,n,r){let i=xe(e,"foreground"),a=xe(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==G&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(ct,"drawCell");function xe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?lt:G;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:dt(a)}s(xe,"cellColor");function dt(t){let e=ut[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return ve(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return ve(o(r),o(i),o(a))}s(dt,"ansiColor");function ve(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(ve,"rgb");var Y="\0pi-terminal-write\0",X="\0pi-terminal-keys\0";function ft(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let f=Number(d);if(!Number.isFinite(f))throw new Error(`Terminal ${u} must be a number`);i.set(u,f)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(ft,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:Q,apiVersion:ee,id:"terminal",setup(o){o.addResolver({resolver:pt(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),f=m===void 0?{}:e.snapshot(m);return x(m===void 0?f:{...f,output:e.screenTail(m).join(`
19
- `)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=ft(c.request.views)}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:V(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,f=[];for(let p=0;p<m;p+=1){c.resolverContext.signal?.throwIfAborted(),p>0&&await mt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await q(e,l,void 0,u.scale);f.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:f,script:{kind:"native",source:d.source,blocks:f},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}}}),o.describe({path:"shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated.",views:"On shell:<session>, image[:scale=S] returns the virtual terminal screen; sequence[:duration=D,interval=I,scale=S] returns ordered PNG frames. Defaults: D=2 seconds, I=0.5 seconds, S=1. Scale satisfies 0 < S <= 1; sequences require 0 < D <= 10, I > 0, and at most 20 frames (floor(D/I)+1). Terminal captures do not support region or image grid selection; offset/limit do not crop their frames."})}},a={protocol:ne,apiVersion:re,id:"terminal",setup(o){o.addResolver({resolver:gt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),ht(c,Y)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),yt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>bt(l,u),"matches"),renderCall(l,u,d){let m=l,f=typeof m.path=="string"?e.get(m.path):void 0,p=d.state;return f!==void 0&&(p.snapshot=e.snapshot(f)),we(p.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=Tt(l.details);return ye(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([te(t,i),ie(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I(o.toolName),{status:"error",errors:[j(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I(o.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I(o.toolName),{status:"error",errors:[j(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let f=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,f);let p=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await q(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:p,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function pt(t){return{id:"terminal",async tryResolve(e){if(!T(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:wt(r)}]}}}}}}s(pt,"createReadResolver");function gt(t){return{id:"terminal-input",async tryResolve(e){if(!T(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=St(r),a=i.indexOf(Y),o=i.indexOf(X);if(a>=0){t.write(n.source,i.slice(a+Y.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+X.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(gt,"createInputResolver");function ht(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(ht,"transformWriteInput");function yt(t){if(!b(t.input)||!ke(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:`${X}${typeof t.input.text=="string"?t.input.text:""}`}}}s(yt,"transformInsertInput");function wt(t){return M(t)}s(wt,"formatSnapshot");function St(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(St,"singleText");function V(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(V,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function Tt(t){if(!b(t)||!b(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}:{}}}}s(Tt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(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))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(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}`}s(Ae,"terminalInputLabel");function bt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(bt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");async function Ce(t,e){await ae(t,{protocol:oe,apiVersion:se,id:"terminal",setup(r){r.addResolver({resolver:Rt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Ce,"registerTerminalSearch");function Rt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=O(e);return ue(n.matches,!1)},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=xt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=O(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
+ `),"renderSummary"),renderDetail:s(n=>x(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as mt}from"node:timers/promises";var lt="#d8dee9",G="#111418",ut=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function q(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=G,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,f=Math.max(0,p.baseY);for(let h=0;h<c;h+=1){let w=p.getLine(f+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||ct(m,P,y,h)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(q,"renderTerminalScreen");function ct(t,e,n,r){let i=xe(e,"foreground"),a=xe(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==G&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(ct,"drawCell");function xe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?lt:G;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:dt(a)}s(xe,"cellColor");function dt(t){let e=ut[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return ve(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return ve(o(r),o(i),o(a))}s(dt,"ansiColor");function ve(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(ve,"rgb");var Y="\0pi-terminal-write\0",X="\0pi-terminal-keys\0";function pt(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${u} must be a number`);i.set(u,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(pt,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:Q,apiVersion:ee,id:"terminal",setup(o){o.addResolver({resolver:ft(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return x(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
+ `)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=pt(c.request.views)}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:V(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,p=[];for(let f=0;f<m;f+=1){c.resolverContext.signal?.throwIfAborted(),f>0&&await mt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await q(e,l,void 0,u.scale);p.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:p,script:{kind:"native",source:d.source,blocks:p},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:V(l,m instanceof Error?m.message:String(m))}}}}),o.describe({path:"shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated.",views:"On shell:<session>, image[:scale=S] returns the virtual terminal screen; sequence[:duration=D,interval=I,scale=S] returns ordered PNG frames. Defaults: D=2 seconds, I=0.5 seconds, S=1. Scale satisfies 0 < S <= 1; sequences require 0 < D <= 10, I > 0, and at most 20 frames (floor(D/I)+1). Terminal captures do not support region or image grid selection; offset/limit do not crop their frames."})}},a={protocol:ne,apiVersion:re,id:"terminal",setup(o){o.addResolver({resolver:gt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),ht(c,Y)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),yt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>bt(l,u),"matches"),renderCall(l,u,d){let m=l,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),we(f.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=Tt(l.details);return ye(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([te(t,i),ie(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I(o.toolName),{status:"error",errors:[j(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I(o.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I(o.toolName),{status:"error",errors:[j(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let p=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await q(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:f,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function ft(t){return{id:"terminal",async tryResolve(e){if(!T(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:wt(r)}]}}}}}}s(ft,"createReadResolver");function gt(t){return{id:"terminal-input",async tryResolve(e){if(!T(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=St(r),a=i.indexOf(Y),o=i.indexOf(X);if(a>=0){t.write(n.source,i.slice(a+Y.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+X.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(gt,"createInputResolver");function ht(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(ht,"transformWriteInput");function yt(t){if(!b(t.input)||!ke(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:`${X}${typeof t.input.text=="string"?t.input.text:""}`}}}s(yt,"transformInsertInput");function wt(t){return M(t)}s(wt,"formatSnapshot");function St(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(St,"singleText");function V(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(V,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function Tt(t){if(!b(t)||!b(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}:{}}}}s(Tt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(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))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(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}`}s(Ae,"terminalInputLabel");function bt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(bt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");async function Ce(t,e){await ae(t,{protocol:oe,apiVersion:se,id:"terminal",setup(r){r.addResolver({resolver:Rt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Ce,"registerTerminalSearch");function Rt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=O(e);return ue(n.matches,!1)},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=xt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=O(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
20
  `)}
21
21
 
22
22
  ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=K(i)?O(i.payload):O(void 0);return le(a.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${a.snapshot.status} \xB7 read-only`])}}}s(Rt,"terminalSearchResolver");function xt(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[a,o]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||vt(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(xt,"findTerminalMatches");function vt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(vt,"isWordBoundary");function O(t){if(!Pt(t))throw new TypeError("Invalid terminal search result");return t}s(O,"parsePayload");function Pt(t){return K(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&K(t.snapshot)&&typeof t.snapshot.source=="string"}s(Pt,"isTerminalSearchPayload");function K(t){return typeof t=="object"&&t!==null}s(K,"isRecord");import{spawn as Et}from"node:child_process";import{closeSync as At,mkdirSync as $t,openSync as kt,rmSync as Ct,writeSync as Lt}from"node:fs";import It from"node:os";import Le from"node:path";import{createRequire as Mt}from"node:module";import{randomUUID as _t}from"node:crypto";import{stripVTControlCharacters as Dt}from"node:util";var _e=Mt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Ie=1e6,Ot=100,Nt=30,Ut=2e3,N=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=jt){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(Bt(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=Xt(n);this.#i.set(n,kt(r,"a",384));let i=e.cols??Ot,a=e.rows??Nt,o=Ft(i,a),c=s(f=>{},"resolveCompletion"),l=new Promise(f=>{c=f}),u={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:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let f=_e("node-pty"),p={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Gt(Ht())};d=f.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],p)}catch(f){let p={...u,status:"failed",endedAt:Date.now(),error:Yt(f)};return this.#e.set(n,p),this.#s(n),c(p),queueMicrotask(()=>this.#l(p)),p}let m={...u,process:d};return this.#e.set(n,m),d.onData(f=>this.#u(m,f)),d.onExit(({exitCode:f,signal:p})=>{v(m.status)||(m.endedAt=Date.now(),m.exitCode=f,p!==0&&(m.signal=p),m.status=m.status==="stopping"?"stopped":f===0?"completed":"failed",(f===124||f===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 v(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(v(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(f=>{o||(f!==void 0&&v(r.status)&&(f=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),f!==void 0&&(r.background=!0,f!=="aborted"&&(r.waitReason=f),this.#n(r)),a({session:r,...f===void 0?{}:{reason:f}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Wt(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await z(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),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let f=d;f<d+a;f+=1){let p=n[f]??"",h=i[f]??"",w=h.length>0&&!n.includes(h),y=p.length>0&&h.length===0;p!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let p=d.padEnd(l.cursorX," ");return`${p.slice(0,l.cursorX)}\u258C${p.slice(l.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),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.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(qt(n))}async stop(e,n="stopped"){let r=this.required(e);return v(r.status)||(r.status="stopping",this.#n(r),await Me(r,!1),await Promise.race([r.completion.then(()=>!0),z(Ut).then(()=>!1)])||(await Me(r,!0),await Promise.race([r.completion,z(1e3)])),v(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),Ct(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=[],a=Math.max(0,r.baseY);for(let o=a;o<a+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=>!v(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=Dt(n),i=this.#i.get(e.id);if(i!==void 0&&Lt(i,r),e.output+=r,e.output.length>Ie){let a=e.output.length-Ie;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(At(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 Wt(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)}s(Wt,"looksInteractive");function Ft(t,e){let{Terminal:n}=_e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Ft,"createScreen");function jt(){return _t().replaceAll("-","").slice(0,12)}s(jt,"defaultSessionId");function Bt(t){return t.startsWith("shell:")?t.slice(6):t}s(Bt,"normalizeSessionId");function v(t){return t!=="running"&&t!=="stopping"}s(v,"isTerminalStatus");function Ht(){return process.env}s(Ht,"processEnvironment");function Gt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Gt,"cleanEnvironment");function qt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Vt).join("")}s(qt,"encodeTerminalKeys");function Vt(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"),a=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 a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Vt,"encodeTerminalKey");async function Me(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=Et("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(Me,"terminateProcessTree");function z(t){return new Promise(e=>setTimeout(e,t))}s(z,"delay");function Yt(t){return t instanceof Error?t.message:String(t)}s(Yt,"errorMessage");function Xt(t){let e=Le.join(It.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return $t(e,{recursive:!0,mode:448}),Le.join(e,`${t}.log`)}s(Xt,"createOutputLog");import{AgentSession as Kt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Kt.prototype,n=e[U]??zt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function zt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(zt,"installObservers");import Zt from"node:os";import Oe from"node:path";function Ne(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Oe.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Zt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Oe.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(Ne,"resolveShellProfile");function Ue(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.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as Qt}from"node:util";import{defineTool as en}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as tn}from"@earendil-works/pi-tui";import{open as Jt}from"node:fs/promises";import{Type as g}from"typebox";var We=1024*1024,Fe=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function je(t){let e=await Jt(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>We;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=We/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let f=u.subarray(m).toString("utf8");i=d+f,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(je,"structuredShellResult");var nn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function He(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=nn(n);return t.registerTool(en({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} 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 wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,parameters:c,outputSchema:Fe,async execute(l,u,d,m,f){r.bind(f);let p=u.cwd===void 0?f.cwd:Be.resolve(f.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:p,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await rn(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),W(e.snapshot(h));if(h.status==="failed")return W(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",W(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),W(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new tn(u.fg("toolTitle",o),0,0);let f=typeof l.command=="string"?l.command:"",p=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return he(f,l.background===!0,p,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(He,"registerTerminalTools");function Ge(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(Ge,"terminalPreview");async function W(t){return{...Ge(t),structuredContent:await je(t)}}s(W,"terminalResult");async function rn(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(Ge(u)),(Qt(u.output).replaceAll("\r","").split(`
23
+ `).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||vt(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(xt,"findTerminalMatches");function vt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(vt,"isWordBoundary");function O(t){if(!Pt(t))throw new TypeError("Invalid terminal search result");return t}s(O,"parsePayload");function Pt(t){return K(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&K(t.snapshot)&&typeof t.snapshot.source=="string"}s(Pt,"isTerminalSearchPayload");function K(t){return typeof t=="object"&&t!==null}s(K,"isRecord");import{spawn as Et}from"node:child_process";import{closeSync as At,mkdirSync as $t,openSync as kt,rmSync as Ct,writeSync as Lt}from"node:fs";import It from"node:os";import Le from"node:path";import{createRequire as Mt}from"node:module";import{randomUUID as _t}from"node:crypto";import{stripVTControlCharacters as Dt}from"node:util";var _e=Mt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Ie=1e6,Ot=100,Nt=30,Ut=2e3,N=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=jt){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(Bt(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=Xt(n);this.#i.set(n,kt(r,"a",384));let i=e.cols??Ot,a=e.rows??Nt,o=Ft(i,a),c=s(p=>{},"resolveCompletion"),l=new Promise(p=>{c=p}),u={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:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let p=_e("node-pty"),f={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Gt(Ht())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...u,status:"failed",endedAt:Date.now(),error:Yt(p)};return this.#e.set(n,f),this.#s(n),c(f),queueMicrotask(()=>this.#l(f)),f}let m={...u,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{v(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 v(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(v(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(p=>{o||(p!==void 0&&v(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Wt(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await z(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),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let p=d;p<d+a;p+=1){let f=n[p]??"",h=i[p]??"",w=h.length>0&&!n.includes(h),y=f.length>0&&h.length===0;f!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let f=d.padEnd(l.cursorX," ");return`${f.slice(0,l.cursorX)}\u258C${f.slice(l.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),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.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(qt(n))}async stop(e,n="stopped"){let r=this.required(e);return v(r.status)||(r.status="stopping",this.#n(r),await Me(r,!1),await Promise.race([r.completion.then(()=>!0),z(Ut).then(()=>!1)])||(await Me(r,!0),await Promise.race([r.completion,z(1e3)])),v(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),Ct(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=[],a=Math.max(0,r.baseY);for(let o=a;o<a+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=>!v(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=Dt(n),i=this.#i.get(e.id);if(i!==void 0&&Lt(i,r),e.output+=r,e.output.length>Ie){let a=e.output.length-Ie;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(At(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 Wt(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)}s(Wt,"looksInteractive");function Ft(t,e){let{Terminal:n}=_e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Ft,"createScreen");function jt(){return _t().replaceAll("-","").slice(0,12)}s(jt,"defaultSessionId");function Bt(t){return t.startsWith("shell:")?t.slice(6):t}s(Bt,"normalizeSessionId");function v(t){return t!=="running"&&t!=="stopping"}s(v,"isTerminalStatus");function Ht(){return process.env}s(Ht,"processEnvironment");function Gt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Gt,"cleanEnvironment");function qt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Vt).join("")}s(qt,"encodeTerminalKeys");function Vt(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"),a=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 a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Vt,"encodeTerminalKey");async function Me(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=Et("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(Me,"terminateProcessTree");function z(t){return new Promise(e=>setTimeout(e,t))}s(z,"delay");function Yt(t){return t instanceof Error?t.message:String(t)}s(Yt,"errorMessage");function Xt(t){let e=Le.join(It.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return $t(e,{recursive:!0,mode:448}),Le.join(e,`${t}.log`)}s(Xt,"createOutputLog");import{AgentSession as Kt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Kt.prototype,n=e[U]??zt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function zt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(zt,"installObservers");import Zt from"node:os";import Oe from"node:path";function Ne(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Oe.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Zt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Oe.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(Ne,"resolveShellProfile");function Ue(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.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as Qt}from"node:util";import{defineTool as en}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as tn}from"@earendil-works/pi-tui";import{open as Jt}from"node:fs/promises";import{Type as g}from"typebox";var We=1024*1024,Fe=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function je(t){let e=await Jt(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>We;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=We/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let p=u.subarray(m).toString("utf8");i=d+p,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(je,"structuredShellResult");var nn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Set true to return after an initial output preview instead of waiting for completion. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Set the foreground wait limit in seconds. On expiry, the live session returns in background without stopping the process. Ignored when background is true. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function He(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=nn(n);return t.registerTool(en({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} to execute a command in the user's configured shell. Each call creates a new terminal session and returns its shell: source for inspection and interaction.`,parameters:c,outputSchema:Fe,async execute(l,u,d,m,p){r.bind(p);let f=u.cwd===void 0?p.cwd:Be.resolve(p.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:f,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await rn(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),W(e.snapshot(h));if(h.status==="failed")return W(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",W(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),W(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new tn(u.fg("toolTitle",o),0,0);let p=typeof l.command=="string"?l.command:"",f=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return he(p,l.background===!0,f,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(He,"registerTerminalTools");function Ge(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(Ge,"terminalPreview");async function W(t){return{...Ge(t),structuredContent:await je(t)}}s(W,"terminalResult");async function rn(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(Ge(u)),(Qt(u.output).replaceAll("\r","").split(`
24
24
  `).filter(m=>m.length>0).length>=E||u.status!=="running")&&c()},"publish");o=t.onDidChange(u=>{u.id===e.id&&l()}),a=setTimeout(c,2e3),l()})}s(rn,"captureInitialBackgroundPreview");import{Box as qe,Container as Ve}from"@earendil-works/pi-tui";var on=120,sn=12e4,F=class{constructor(e,n,r=sn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>{let c=Ye(i.details)?i.details:void 0,l=new Ve;c!==void 0&&l.addChild(x(c,a,o,"stale \xB7 inspect session"));let u=new qe(1,1,d=>o.bg("toolPendingBg",d));return u.addChild(l),u}),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>{let c=new Ve;for(let u of an(i.details))c.addChild(x(u,a,o));let l=new qe(1,1,u=>o.bg("toolSuccessBg",u));return l.addChild(c),l}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{s(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.staleReminderDelivered||!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.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}e.staleReminderDelivered=!0;let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:un(n),details:n},{triggerTurn:!0,deliverAs:"followUp"})}#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:ln(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},on)))}};function an(t){return!Ke(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Ye)}s(an,"completionSnapshots");function Ye(t){return Ke(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"}s(Ye,"isTerminalSessionSnapshot");function ln(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
25
  ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,a=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Xe(n.elapsedMs)}
26
26
  ${a||"(no output)"}`}).join(`
27
27
  `)}`}s(ln,"formatCompletionMessage");function un(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Xe(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}s(un,"formatStaleMessage");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Xe,"formatElapsed");function Ke(t){return typeof t=="object"&&t!==null}s(Ke,"isRecord");function ze(t){return t==="full"||t==="disabled"?t:"compact"}s(ze,"toolPresentation");async function cn(t,e){J(t,[await Z({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=me("terminal")??new N,r=Ne(),i=new F(t,n),a=ce(t).add(Re(n));await Promise.all([$e(t,n),Ce(t,n)]);let o=He(t,n,r,i,ze(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){de("terminal",n);return}fe("terminal",n),await n.dispose()})}s(cn,"registerTerminal");export{cn as default};
28
+ ${e||"(no output)"}`}s(un,"formatStaleMessage");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Xe,"formatElapsed");function Ke(t){return typeof t=="object"&&t!==null}s(Ke,"isRecord");function ze(t){return t==="full"||t==="disabled"?t:"compact"}s(ze,"toolPresentation");async function cn(t,e){J(t,[await Z({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=me("terminal")??new N,r=Ne(),i=new F(t,n),a=ce(t).add(Re(n));await Promise.all([$e(t,n),Ce(t,n)]);let o=He(t,n,r,i,ze(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){de("terminal",n);return}pe("terminal",n),await n.dispose()})}s(cn,"registerTerminal");export{cn as default};
@@ -0,0 +1 @@
1
+ import{a as h,e as w,k as P}from"./chunk-SJ4UZ4GU.js";import{a as E,c as T}from"./chunk-6U5OU77O.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as S}from"node:async_hooks";var p=new S,m=new S;function C(t){let e=m.getStore();e?e.push(t):t()}o(C,"afterPostEditScope");async function D(t){if(m.getStore())return t();let e=[];try{return await m.run(e,t)}finally{for(let r of e)r()}}o(D,"collectPostEditNotifications");function q(t,e){let r=p.getStore();return r?r.immediate?(r.pending.delete(t),!1):(r.pending.set(t,e),!0):!1}o(q,"deferPostEdit");function O(t){return p.getStore()?.pending.has(t)??!1}o(O,"hasDeferredPostEdit");function F(t){p.getStore()?.pending.delete(t)}o(F,"forgetDeferredPostEdit");function L(t=process.cwd()){let e=new Map;return{run(r,a=!1){return p.run({pending:e,immediate:a},r)},forget(r){e.delete(r)},sources(){return[...e.keys()]},async finish(r,a){let s=[...e];e.clear();let c=[],i=[];if(await D(async()=>{let u=new E,b=await Promise.allSettled(s.map(([g,d])=>u.run(T(g,t,"write"),d)));for(let[g,d]of b.entries()){let y=x(s[g])[0];if(d.status==="rejected"){i.push(d.reason);try{a?.(y,d.reason)}catch(l){i.push(l)}continue}c.push(d.value);try{r?.(d.value)}catch(l){i.push(l);try{a?.(y,l)}catch(k){i.push(k)}}}}),i.length>0)throw new AggregateError(i,`Some final post-processing failed; completed edits remain applied. ${i.map(u=>u instanceof Error?u.message:String(u)).join("; ")}`);return c}}}o(L,"createPostEditScope");import{Type as n}from"typebox";import{Value as f}from"typebox/value";var A=`${h}/post-edit/register`;function $(t){return f.Check(n.Object({formatting:n.Object({status:n.Union(["disabled","unavailable","skipped-syntax","unchanged","changed","failed","not-reported","deferred"].map(e=>n.Literal(e))),formatter:n.Optional(n.String())})}),t)}o($,"isFormattingContribution");function W(t){return f.Check(n.Object({diffStatuses:n.Array(n.Object({text:n.String({minLength:1}),formatter:n.Optional(n.String()),tone:n.Optional(n.Union(["muted","success","warning","error"].map(e=>n.Literal(e))))}))}),t)}o(W,"isDiffStatusContribution");var R=n.Function([],n.Unknown()),v=n.Object({id:n.String({minLength:1}),handler:R}),H=n.Object({registration:v,accept:R});function j(t){return f.Check(v,t)}o(j,"isTextPostEditHandlerRegistration");function B(t){return f.Check(H,t)}o(B,"isTextPostEditHandlerRegistrationRequest");function G(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.hints)&&typeof e.scopeMarkers=="object"&&e.scopeMarkers!==null&&Array.isArray(e.warnings)}o(G,"isTextMutationResultContributionData");function K(t,e){if(!j(e))throw new TypeError("Invalid text editor post-edit handler registration");let r,a=o(()=>{let c={registration:e,accept(i){if(r!==void 0)throw new Error(`Post-edit handler ${e.id} was accepted more than once`);r=i}};return t.events.emit(A,c),r!==void 0},"announce"),s=o(()=>{},"unsubscribeReady");s=t.events.on(w,c=>{if(!P(c))throw new Error("Invalid pi-agent-text-editor core readiness event");if(!a())throw new Error("pi-agent-text-editor core announced readiness without accepting the post-edit handler");s()}),t.on("session_shutdown",()=>{s(),r?.()}),a()&&s()}o(K,"connectTextEditorPostEditHandler");export{C as a,D as b,q as c,O as d,F as e,L as f,A as g,$ as h,W as i,j,B as k,G as l,K as m};
@@ -0,0 +1 @@
1
+ import{c as S,d as C}from"./chunk-STBJO3Z3.js";import{a as h}from"./chunk-EI7MMDWY.js";import z from"node:path";import{pathToFileURL as x}from"node:url";function b(e,n){let r=new Map;for(let t of e){let i=r.get(t.source)??[];i.push(t),r.set(t.source,i)}let a=new Set,u=e.length,s=[...r].sort(([t,i],[d,m])=>m.length-i.length||t.localeCompare(d));for(let[t,i]of s){if(u<=n)break;a.add(t),u-=i.length-1}let c=[],o=n,l=[...r].sort(([t],[i])=>Number(a.has(t))-Number(a.has(i))||t.localeCompare(i));for(let[t,i]of l){if(!a.has(t)){if(i.length>o)continue;c.push({kind:"detailed",source:t,matches:i}),o-=i.length;continue}if(o<1)continue;o--;let d=new Map;for(let g of i)d.set(g.lineText,(d.get(g.lineText)??0)+1);let m=r.size===1?[...d].sort(([g,p],[F,w])=>w-p||g.localeCompare(F)).slice(0,o).map(([g,p])=>({text:g,matchCount:p})):[];o-=m.length,c.push({kind:"compacted",source:t,matchCount:i.length,uniqueLineCount:d.size,groups:m})}return c.sort((t,i)=>t.source.localeCompare(i.source)),{files:c}}h(b,"planSearchPresentation");function N(e,n,r,a,u,s=50){let c=b(n,s),o=new Set(n.map(t=>t.source)).size,l=c.files.map(t=>t.kind==="detailed"?L(t.source,t.matches,a):{path:M(t.source,a),link:x(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups,lines:[]});return{...u!==void 0&&{sessionId:u},query:e,matchCount:n.length,fileCount:o,...c.files.length<o?{omittedFileCount:o-l.length,omittedMatchCount:n.length-l.reduce((t,i)=>t+i.matchCount,0)}:{},complete:r,files:l}}h(N,"createSearchToolDetails");function $(e,n){return{fileCount:new Set(e.flatMap(r=>r.matches.map(a=>a.source))).size,groups:e.map(r=>{let u=N(r.identifier,r.matches.slice(0,S.previewMatches),r.complete,n).files.map(s=>{let c=s.lines.map(o=>{let l=Math.max(0,(o.ranges[0]?.from??0)-64),t=Math.min(o.text.length,(o.ranges[0]?.to??0)+64),i=l>0?"\u2026":"",d=o.ranges.filter(m=>m.from>=l&&m.to<=t).map(m=>({from:m.from-l+i.length,to:m.to-l+i.length}));return{...o,text:i+o.text.slice(l,t)+(t<o.text.length?"\u2026":""),ranges:d,matchCount:d.length}});return{...s,lines:c,matchCount:c.reduce((o,l)=>o+l.matchCount,0)}});return{identifier:r.identifier,files:u}})}}h($,"createFuzzyPresentation");function k(e){return f(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(n=>f(n)&&typeof n.identifier=="string"&&Array.isArray(n.files)&&n.files.every(R))}h(k,"isFuzzyPresentation");function E(e){if(!f(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||e.omittedFileCount!==void 0&&!y(e.omittedFileCount)||e.omittedMatchCount!==void 0&&!y(e.omittedMatchCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!C(e.fuzzy)||e.fuzzyPresentation!==void 0&&!k(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(R))return!1;let n=e.files;return e.fileCount===n.length+(e.omittedFileCount??0)&&e.matchCount===n.reduce((r,a)=>r+a.matchCount,0)+(e.omittedMatchCount??0)}h(E,"isSearchToolDetails");function L(e,n,r){let a=new Map;for(let s of n){let c=a.get(s.lineNumber);if(c!==void 0&&c.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let o=c??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};o.ranges.push({from:s.startColumn,to:s.endColumn}),a.set(s.lineNumber,o)}let u=[...a.values()].sort((s,c)=>s.lineNumber-c.lineNumber).map(s=>{let c=[...s.ranges].sort((o,l)=>o.from-l.from||o.to-l.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:c.length,ranges:c}});return{path:M(e,r),link:x(e).href,matchCount:n.length,lines:u}}h(L,"createSearchResultFile");function R(e){if(!f(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(P))return!1;let n=e.lines,r=e.groups,a=new Set(n.flatMap(u=>u.logicalMatchIds??[]));return(r===void 0||Array.isArray(r)&&r.every(u=>f(u)&&typeof u.text=="string"&&y(u.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(n.length===0||(a.size>0?a.size===e.matchCount:e.matchCount===n.reduce((u,s)=>u+s.matchCount,0)))}h(R,"isSearchResultFile");function P(e){return f(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(n=>typeof n=="string"))&&e.ranges.every(n=>A(n,e.text))}h(P,"isSearchResultLine");function A(e,n){return f(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=n.length}h(A,"isSearchResultRange");function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}h(f,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}h(y,"isCount");function M(e,n){let r=z.relative(n,e);return r.length>0&&!r.startsWith("..")&&!z.isAbsolute(r)?r:e}h(M,"displaySource");export{b as a,N as b,$ as c,E as d};
package/dist/entry-11.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-IQD6PON5.js";import"./chunk-PGIVHICI.js";import{a as l}from"./chunk-PKKDDIWW.js";import{a as s,b as c}from"./chunk-4GCWGE2C.js";import"./chunk-U2JKHKLK.js";import"./chunk-D3WTDA6V.js";import"./chunk-NNCZYO4Q.js";import"./chunk-64M3SQPG.js";import{a as g}from"./chunk-BU7IZLKB.js";import{a as f,b as y}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.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-YWQS33DF.js";import{a as l}from"./chunk-KOVPDKSJ.js";import{a as s,b as c}from"./chunk-SJ4UZ4GU.js";import"./chunk-U2JKHKLK.js";import"./chunk-IG56UGSO.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import{a as g}from"./chunk-BU7IZLKB.js";import{a as f,b as y}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import"./chunk-6U5OU77O.js";import"./chunk-ZPT5D4VP.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-13.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-U2JKHKLK.js";import{a as k,c as l,d as m,e as n,f as o,g as p,h as q,i as r,j as s,k as t}from"./chunk-D3WTDA6V.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-64M3SQPG.js";import{a as h}from"./chunk-BU7IZLKB.js";import{a,b,c,d,e,f,g}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.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,s as isFragmentResolverRegistration,e as isReadCoreReady,t as isReadFragmentResolution,q as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,r as isReadViewRegistration,p as isResourceResolverRegistration,o as isTextTargetResolverRegistration,l as readDataSchema,m as readOutputSchema,k as readParameters,n as structuredRead};
1
+ import"./chunk-U2JKHKLK.js";import{a as k,c as l,d as m,e as n,f as o,g as p,h as q,i as r,j as s,k as t}from"./chunk-IG56UGSO.js";import"./chunk-NNCZYO4Q.js";import{b as i,d as j}from"./chunk-IICJXZBU.js";import{a as h}from"./chunk-BU7IZLKB.js";import{a,b,c,d,e,f,g}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import"./chunk-6U5OU77O.js";import"./chunk-ZPT5D4VP.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,s as isFragmentResolverRegistration,e as isReadCoreReady,t as isReadFragmentResolution,q as isReadHandlerRegistration,f as isReadPlugin,g as isReadPluginRegistrationRequest,r as isReadViewRegistration,p as isResourceResolverRegistration,o as isTextTargetResolverRegistration,l as readDataSchema,m as readOutputSchema,k as readParameters,n as structuredRead};
package/dist/entry-14.js CHANGED
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,I,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,w as v,x as w,y,z}from"./chunk-CWD4O5PM.js";import"./chunk-EI7MMDWY.js";export{y as CONTENT_API_VERSION,A as CONTENT_CONVERTER_REGISTER_EVENT,z as CONTENT_HOST_READY_EVENT,w as CONTENT_PROTOCOL,p as MAX_STRUCTURED_BYTES,o as ResourceScheduler,G as ResultTargetStore,s as UnsupportedContentError,t as assertJsonData,E as connectContentConverter,I as connectResultTargets,D as createContentHost,u as createContentRunner,c as isAgentContent,n as isContentConversionAttempt,k as isContentConversionContext,l as isContentConverter,q as isContentConverterRegistration,C as isContentConverterRegistrationRequest,B as isContentHostReady,j as isContentInput,i as isContentTarget,d as isResource,h as isResourceResolutionAttempt,g as isResourceResolver,b as renderContentDescription,e as resourceAccesses,r as resourceScheduler,x as resultError,f as resultErrorSchema,F as resultInputSchema,m as structuredResultSchema,v as targetsEqual,H as verifyResultTargets,a as withStructuredResult};
1
+ import{A,B,C,D,E,F,G,H,I,J,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,w as v,x as w,y,z}from"./chunk-6U5OU77O.js";import"./chunk-EI7MMDWY.js";export{z as CONTENT_API_VERSION,B as CONTENT_CONVERTER_REGISTER_EVENT,A as CONTENT_HOST_READY_EVENT,y as CONTENT_PROTOCOL,t as MAX_STRUCTURED_BYTES,o as ResourceScheduler,H as ResultTargetStore,f as TempResourceStore,u as UnsupportedContentError,x as assertJsonData,F as connectContentConverter,J as connectResultTargets,E as createContentHost,v as createContentRunner,d as isAgentContent,q as isContentConversionAttempt,l as isContentConversionContext,n as isContentConverter,s as isContentConverterRegistration,D as isContentConverterRegistrationRequest,C as isContentHostReady,k as isContentInput,j as isContentTarget,g as isResource,i as isResourceResolutionAttempt,h as isResourceResolver,c as renderContentDescription,e as resourceAccesses,r as resourceScheduler,a as resultError,m as resultErrorSchema,G as resultInputSchema,p as structuredResultSchema,w as targetsEqual,I as verifyResultTargets,b as withStructuredResult};
package/dist/entry-15.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c,c as i,d as j,e as k,f as l,g as n,h as q,i as s}from"./chunk-YP46DVVP.js";import{a,c as d,d as g,e as h}from"./chunk-GXEGY7GV.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-PS2B6THP.js";import"./chunk-CWD4O5PM.js";import"./chunk-EI7MMDWY.js";export{l as FuzzyVocabulary,r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,c as containsSearchMatch,s as formatFuzzyCandidate,q as fuzzyCandidateData,i as fuzzyLimits,k as isFuzzyQuery,j as isFuzzyResultData,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,n as rankFuzzyIdentifiers,b as renderSearchMatches,d as searchDataSchema,g as searchOutputSchema,a as searchSchema,h as selectionData};
1
+ import{a as b,b as c,c as i,d as j,e as k,f as l,g as n,h as q,i as s}from"./chunk-STBJO3Z3.js";import{a,c as d,d as g,e as h}from"./chunk-OB46OPMZ.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-PS2B6THP.js";import"./chunk-6U5OU77O.js";import"./chunk-EI7MMDWY.js";export{l as FuzzyVocabulary,r as SEARCH_API_VERSION,e as SEARCH_CORE_READY_EVENT,f as SEARCH_PLUGIN_REGISTER_EVENT,o as SEARCH_PROTOCOL,x as connectSearchPlugin,c as containsSearchMatch,s as formatFuzzyCandidate,q as fuzzyCandidateData,i as fuzzyLimits,k as isFuzzyQuery,j as isFuzzyResultData,m as isSearchCoreReady,p as isSearchPlugin,t as isSearchPluginRegistrationRequest,n as rankFuzzyIdentifiers,b as renderSearchMatches,d as searchDataSchema,g as searchOutputSchema,a as searchSchema,h as selectionData};
package/dist/entry-17.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-IQD6PON5.js";import{m as o}from"./chunk-PGIVHICI.js";import{a as n}from"./chunk-PKKDDIWW.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-4GCWGE2C.js";import"./chunk-CWD4O5PM.js";import"./chunk-ZPT5D4VP.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"./chunk-IQD6PON5.js";import{m as o}from"./chunk-YWQS33DF.js";import{a as n}from"./chunk-KOVPDKSJ.js";import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-SJ4UZ4GU.js";import"./chunk-6U5OU77O.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.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-25.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as k}from"./chunk-PKKDDIWW.js";import{a as A,b as D}from"./chunk-4GCWGE2C.js";import"./chunk-NNCZYO4Q.js";import{d as T}from"./chunk-64M3SQPG.js";import{a as P}from"./chunk-BU7IZLKB.js";import{a as F,b as C}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import{D as v,j as E}from"./chunk-CWD4O5PM.js";import{r as b}from"./chunk-ZPT5D4VP.js";import{a as p}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readdirSync as V,realpathSync as j,statSync as U}from"node:fs";import{mkdir as $,readFile as z,writeFile as Z}from"node:fs/promises";import I from"node:path";import{fileURLToPath as B,pathToFileURL as G}from"node:url";function O(e){return _("read",e)}s(O,"createFilesystemReadResolver");function S(e){return _("write",e)}s(S,"createFilesystemWriteResolver");function _(e,t){return{id:"filesystem",tryResolve(r,n){return Promise.resolve(X(r,n,e,t))}}}s(_,"createFilesystemResolver");function X(e,t,r,n){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!K(e))return{kind:"not-handled"};if(t.signal?.aborted===!0)return{kind:"failed",error:x()};let o=e.startsWith("file://")?j(B(new URL(e))):I.resolve(t.cwd,e),i=G(o).href,d=(()=>{try{return U(o).isDirectory()}catch{return!1}})(),u=s(async({signal:f})=>d?q(o,f):J(o,n,f),"read");return r==="read"||d?{kind:"resolved",resource:{source:o,link:i,read:u}}:{kind:"resolved",resource:{source:o,link:i,read:u,async write(f,m){y(m.signal);let h=b(f);await $(I.dirname(o),{recursive:!0}),y(m.signal),await Z(o,h,{encoding:"utf8",...m.signal!==void 0&&{signal:m.signal}})}}}}s(X,"resolveFilesystemSource");function q(e,t){y(t);let r=V(e,{withFileTypes:!0}),n=[`\u{1F4C1} ${e}/`];r.length>0&&n.push("");for(let o of r){let i=o.isDirectory()?"\u{1F4C1}":o.isFile()?"\u{1F4C4}":"\u{1F517}";n.push(` ${i} ${o.name}`)}return[{type:"text",text:n.join(`
1
+ import{a as k}from"./chunk-KOVPDKSJ.js";import{a as A,b as D}from"./chunk-SJ4UZ4GU.js";import"./chunk-NNCZYO4Q.js";import{d as T}from"./chunk-IICJXZBU.js";import{a as P}from"./chunk-BU7IZLKB.js";import{a as F,b as C}from"./chunk-S5PL5DFQ.js";import"./chunk-PS2B6THP.js";import{E as v,k as E}from"./chunk-6U5OU77O.js";import{r as b}from"./chunk-ZPT5D4VP.js";import{a as p}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readdirSync as V,realpathSync as j,statSync as U}from"node:fs";import{mkdir as $,readFile as z,writeFile as Z}from"node:fs/promises";import I from"node:path";import{fileURLToPath as B,pathToFileURL as G}from"node:url";function O(e){return _("read",e)}s(O,"createFilesystemReadResolver");function S(e){return _("write",e)}s(S,"createFilesystemWriteResolver");function _(e,t){return{id:"filesystem",tryResolve(r,n){return Promise.resolve(X(r,n,e,t))}}}s(_,"createFilesystemResolver");function X(e,t,r,n){if(e.length===0)return{kind:"failed",error:new TypeError("Filesystem source must not be empty")};if(!K(e))return{kind:"not-handled"};if(t.signal?.aborted===!0)return{kind:"failed",error:x()};let o=e.startsWith("file://")?j(B(new URL(e))):I.resolve(t.cwd,e),i=G(o).href,d=(()=>{try{return U(o).isDirectory()}catch{return!1}})(),u=s(async({signal:f})=>d?q(o,f):J(o,n,f),"read");return r==="read"||d?{kind:"resolved",resource:{source:o,link:i,read:u}}:{kind:"resolved",resource:{source:o,link:i,read:u,async write(f,m){y(m.signal);let h=b(f);await $(I.dirname(o),{recursive:!0}),y(m.signal),await Z(o,h,{encoding:"utf8",...m.signal!==void 0&&{signal:m.signal}})}}}}s(X,"resolveFilesystemSource");function q(e,t){y(t);let r=V(e,{withFileTypes:!0}),n=[`\u{1F4C1} ${e}/`];r.length>0&&n.push("");for(let o of r){let i=o.isDirectory()?"\u{1F4C1}":o.isFile()?"\u{1F4C4}":"\u{1F517}";n.push(` ${i} ${o.name}`)}return[{type:"text",text:n.join(`
2
2
  `)}]}s(q,"readDirectoryContent");async function J(e,t,r){y(r);let n=await z(e,{encoding:null,...r!==void 0&&{signal:r}});return y(r),t.convert({source:e,bytes:n},r===void 0?{}:{signal:r})}s(J,"readFilesystemContent");function K(e){return/^[A-Za-z]:[\\/]/u.test(e)||e.startsWith("file://")?!0:!/^[A-Za-z][A-Za-z\d+.-]*:/u.test(e)}s(K,"isFilesystemSource");function y(e){if(e?.aborted===!0)throw x()}s(y,"throwIfAborted");function x(){let e=new Error("The operation was aborted");return e.name="AbortError",e}s(x,"abortError");import{execFile as Q}from"node:child_process";import{existsSync as Y}from"node:fs";import{realpath as H}from"node:fs/promises";import ee from"node:os";import c from"node:path";import{fileURLToPath as te}from"node:url";async function L(e,t){let r=e.cause,n=Date.now()+500;if(t.signal?.aborted||e.source===void 0||typeof r!="object"||r===null||!("code"in r)||r.code!=="ENOENT")return;let o=e.source.startsWith("file://")?te(e.source):e.source,i=c.relative(t.cwd,c.resolve(t.cwd,o));if(!w(i)||i.includes("#"))return;let d=c.basename(i).toLowerCase();if(d.length<3||d.length>160)return;let u=c.join(process.env.PI_CODING_AGENT_DIR??c.join(ee.homedir(),".pi","agent"),"bin",process.platform==="win32"?"rg.exe":"rg"),f=await new Promise(a=>{Q(Y(u)?u:"rg",["--files","--hidden","--no-config","--no-ignore-parent","--null","--glob","!.git/**"],{cwd:t.cwd,timeout:250,maxBuffer:2*1024*1024,...t.signal===void 0?{}:{signal:t.signal}},(l,R)=>a(l?[]:R.split("\0").filter(Boolean).slice(0,2e4)))}),m=Math.min(3,Math.max(1,Math.floor(d.length*.2))),h=f.flatMap(a=>{if(t.signal?.aborted||Date.now()>n||!w(a))return[];let l=c.basename(a).toLowerCase();if(l.length>160||Math.abs(l.length-d.length)>m)return[];let R=re(d,l);if(R>m)return[];let M=c.dirname(i).toLowerCase(),W=c.dirname(a).toLowerCase();return[{path:a,distance:R,directoryDistance:M===W?0:1}]}).sort((a,l)=>a.distance-l.distance||a.directoryDistance-l.directoryDistance||a.path.localeCompare(l.path)),g=[],N=await H(t.cwd);for(let a of h.slice(0,20)){if(t.signal?.aborted||Date.now()>n)return;try{let l=await H(c.resolve(t.cwd,a.path));w(c.relative(N,l))&&g.push({path:a.path})}catch{}if(g.length===3)break}return g.length?g:void 0}s(L,"recoverFilesystemPath");function w(e){return e!==""&&!/^\.\.(?:[\\/]|$)/u.test(e)&&!c.isAbsolute(e)}s(w,"insideWorkspace");function re(e,t){let r=Array.from({length:t.length+1},(n,o)=>o);for(let n=1;n<=e.length;n++){let o=[n];for(let i=1;i<=t.length;i++)o[i]=Math.min(p(o[i-1])+1,p(r[i])+1,p(r[i-1])+(e[n-1]===t[i-1]?0:1));r=o}return p(r[t.length])}s(re,"editDistance");var oe={provider:"filesystem",capability:"read"},ne={provider:"filesystem",capability:"write"},ie=T({kind:"source",nativeResources:!0});async function se(e){let t=v(e,oe),r=v(e,ne),n=O(t),o=S(r),i={protocol:F,apiVersion:C,id:"filesystem",setup(u){u.addResolver({resolver:n,renderResult:ie,recoverFailure:L}),u.describe({path:s(()=>E("File path \u2014 file content; directory path \u2014 entry listing. Relative, absolute and file:// paths accepted.",t.listDescriptions()),"path")})}},d={protocol:A,apiVersion:D,id:"filesystem",setup(u){u.addResolver({resolver:o})}};await Promise.all([P(e,i),k(e,d)])}s(se,"registerFilesystemPlugin");export{se as default};
package/dist/entry-26.js CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./chunk-QIJMV2P2.js";import{E as e}from"./chunk-CWD4O5PM.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 r}from"./chunk-QIJMV2P2.js";import{F as e}from"./chunk-6U5OU77O.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-27.js CHANGED
@@ -1,2 +1,2 @@
1
- import{e as x,f as P}from"./chunk-T7I2VX3J.js";import{a as T}from"./chunk-MGCHOGQD.js";import{a as E,b as h}from"./chunk-T6LX2RX5.js";import{a as b}from"./chunk-BU7IZLKB.js";import{a as R,b as O}from"./chunk-S5PL5DFQ.js";import{m as q}from"./chunk-ZPT5D4VP.js";import{c as j,d as y,e as v}from"./chunk-N34ATN52.js";import{a as o}from"./chunk-EI7MMDWY.js";import C from"cross-spawn";import{fileURLToPath as L}from"node:url";var S=5e3,J=10*1024*1024,k=L(new URL(".",new URL("../src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts",import.meta.url).href));function _(r){let e=r?.filter(i=>i==="jq"||i.startsWith("jq:"))??[];if(e.length===0)return;if(e.length>1)throw new Error("Read accepts only one jq view");if(r?.length!==1)throw new Error("The jq view cannot be combined with other views");let t=e[0];if(t===void 0||t==="jq"||t.slice(3).trim().length===0)throw new Error('The jq view requires a filter, for example views: ["jq:.scripts"]');return{filter:t.slice(3)}}o(_,"parseJqView");function A(r,e,t){return t.signal?.aborted===!0?Promise.reject(new Error("jq execution was cancelled")):new Promise((i,d)=>{let s=C(t.command??"jq",["-L",k,"--",r],{cwd:t.cwd,env:V(t.cwd),shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0}),a="",c="",u=!1,m=0,l=o(n=>{u||(u=!0,clearTimeout(p),t.signal?.removeEventListener("abort",g),n===void 0?i(a):d(n))},"finish"),f=o(n=>{s.kill(),l(n)},"stop"),g=o(()=>f(new Error("jq execution was cancelled")),"abort"),p=setTimeout(()=>f(new Error(`jq did not finish within ${S/1e3} seconds`)),S);p.unref(),t.signal?.addEventListener("abort",g,{once:!0}),s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",n=>{if(m+=Buffer.byteLength(n),m>J){f(new Error(`jq output exceeded ${J/1024/1024}MB`));return}a+=n}),s.stderr?.on("data",n=>{Buffer.byteLength(c)<16384&&(c+=n)}),s.once("error",n=>l(new Error(`Cannot start jq: ${n.message}`))),s.once("close",(n,w)=>{if(!u)if(n===0)l();else{let I=c.trim().split(/\r?\n/u).slice(0,8).join(`
1
+ import{e as x,f as P}from"./chunk-T7I2VX3J.js";import{a as T}from"./chunk-MGCHOGQD.js";import{a as E,b as h}from"./chunk-T6LX2RX5.js";import{a as b}from"./chunk-BU7IZLKB.js";import{a as R,b as O}from"./chunk-S5PL5DFQ.js";import{m as q}from"./chunk-ZPT5D4VP.js";import{c as j,d as y,e as v}from"./chunk-N34ATN52.js";import{a as o}from"./chunk-EI7MMDWY.js";import C from"cross-spawn";import{fileURLToPath as L}from"node:url";var S=5e3,J=10*1024*1024,k=L(new URL(".",new URL("../src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts",import.meta.url).href));function _(r){let e=r?.filter(i=>i==="jq"||i.startsWith("jq:"))??[];if(e.length===0)return;if(e.length>1)throw new Error("Read accepts only one jq view");if(r?.length!==1)throw new Error("The jq view cannot be combined with other views. Keep only one jq:<filter> in views.");let t=e[0];if(t===void 0||t==="jq"||t.slice(3).trim().length===0)throw new Error('The jq view requires a filter, for example views: ["jq:.scripts"]');return{filter:t.slice(3)}}o(_,"parseJqView");function A(r,e,t){return t.signal?.aborted===!0?Promise.reject(new Error("jq execution was cancelled")):new Promise((i,d)=>{let s=C(t.command??"jq",["-L",k,"--",r],{cwd:t.cwd,env:V(t.cwd),shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0}),a="",c="",u=!1,m=0,l=o(n=>{u||(u=!0,clearTimeout(g),t.signal?.removeEventListener("abort",p),n===void 0?i(a):d(n))},"finish"),f=o(n=>{s.kill(),l(n)},"stop"),p=o(()=>f(new Error("jq execution was cancelled")),"abort"),g=setTimeout(()=>f(new Error(`jq did not finish within ${S/1e3} seconds`)),S);g.unref(),t.signal?.addEventListener("abort",p,{once:!0}),s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",n=>{if(m+=Buffer.byteLength(n),m>J){f(new Error(`jq output exceeded ${J/1024/1024}MB`));return}a+=n}),s.stderr?.on("data",n=>{Buffer.byteLength(c)<16384&&(c+=n)}),s.once("error",n=>l(new Error(`Cannot start jq: ${n.message}`))),s.once("close",(n,w)=>{if(!u)if(n===0)l();else{let I=c.trim().split(/\r?\n/u).slice(0,8).join(`
2
2
  `);l(new Error(I||`jq exited ${w===null?`with code ${String(n)}`:`after signal ${w}`}`))}}),s.stdin?.once("error",n=>l(new Error(`Cannot send JSON to jq: ${n.message}`))),s.stdin?.end(e)})}o(A,"executeJq");function V(r){let e=j(r,process.env),t={};for(let i of["PATH","PATHEXT","SystemRoot","SYSTEMROOT","WINDIR"])e[i]!==void 0&&(t[i]=e[i]);return t}o(V,"safeEnvironment");async function N(r){P(r,[await x({id:"json-reading",description:"Query and transform JSON resources with jq read views",triggers:[{tool:"read",viewPrefixes:["jq:"]}]})]),await Promise.all([b(r,B),T(r,$)])}o(N,"registerFilesystemJq");var B={protocol:R,apiVersion:O,id:"filesystem-jq",setup(r){r.addView({view:"jq",presenter:{id:"filesystem-jq",present:o(e=>e,"present")}}),r.addHandler({stage:"read",when:{resolvedBy:"filesystem",contentKind:"text"},async handler(e){let t=e.state;if(t?.contentKind!=="text")return{kind:"continue",context:e};let i;try{i=_(e.request.views)}catch(a){return D(t,a instanceof Error?a.message:String(a))}if(i===void 0)return{kind:"continue",context:e};let d;try{d=await A(i.filter,t.content[0].text,{cwd:e.resolverContext.cwd,...e.resolverContext.signal===void 0?{}:{signal:e.resolverContext.signal}})}catch(a){return D(t,a instanceof Error?a.message:String(a))}let s={...t,content:[{type:"text",text:d}],text:q(t.source,d),preserveTruncatedOutput:!0};return{kind:"continue",context:{...e,state:s}}}}),r.describe({views:'jq:<filter> \u2014 query local JSON text with the installed jq executable, e.g. ["jq:.scripts | keys"]. Exactly one non-empty jq filter is required; it cannot be combined with other views. offset/limit apply to the transformed output, not original source lines.'})}};function D(r,e){return{kind:"return",result:{content:[{type:"text",text:`jq failed: ${e}`}],details:{source:r.source,resolvedBy:r.resolvedBy,failure:{code:"READ_FAILED",source:r.source,resolverId:r.resolvedBy,pluginId:"filesystem-jq",stage:"read",message:e}},isError:!0}}}o(D,"jqFailure");var $={protocol:E,apiVersion:1,id:"filesystem-jq",setup(r){r.addSetupCheck({id:"jq",async inspect(e){return await y("jq",e.cwd,e.env)?{}:{actions:[{id:"jq-unavailable",message:"JSON jq views are unavailable because jq was not found"}]}}}),r.addCheck({id:"jq",title:"JSON jq views",async run(e){let t=await v("jq",["--version"],e.cwd,e.env);return[t.ok?{status:"pass",message:"jq is available",detail:t.detail}:{status:"fail",message:"jq is not available",detail:t.detail}]}})}};export{N as default};
package/dist/entry-28.js CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./chunk-BHSO2MDK.js";import{E as e}from"./chunk-CWD4O5PM.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-BHSO2MDK.js";import{F as e}from"./chunk-6U5OU77O.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-29.js CHANGED
@@ -1 +1 @@
1
- import{E as t}from"./chunk-CWD4O5PM.js";import{p as i}from"./chunk-ZPT5D4VP.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{F as t}from"./chunk-6U5OU77O.js";import{p as i}from"./chunk-ZPT5D4VP.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};