pi-agent-ide 0.8.1 → 0.8.3

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 (417) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +5 -3
  3. package/dist/{chunk-TGC2ZACO.js → chunk-235QMMVA.js} +1 -1
  4. package/dist/{chunk-OI3HBIPK.js → chunk-4DIUPEDF.js} +1 -1
  5. package/dist/{chunk-2ITKAXHO.js → chunk-6FGLAVPJ.js} +1 -1
  6. package/dist/{chunk-7LOVUWNI.js → chunk-6H32W35W.js} +1 -1
  7. package/dist/{chunk-YHREORHH.js → chunk-6OJ565FL.js} +1 -1
  8. package/dist/{chunk-E2PHA4SQ.js → chunk-6R3Y4AD3.js} +1 -1
  9. package/dist/{chunk-VNTY7BKC.js → chunk-6T7PSDQW.js} +1 -1
  10. package/dist/{chunk-D4IA2MTA.js → chunk-6TJPMBUQ.js} +1 -1
  11. package/dist/{chunk-JKMXND6V.js → chunk-6XFUICD7.js} +1 -1
  12. package/dist/{chunk-A64JRDZK.js → chunk-AAC77UD4.js} +1 -1
  13. package/dist/{chunk-HFJGCYFO.js → chunk-ANM3Y5FO.js} +5 -5
  14. package/dist/{chunk-Q5X6OXNS.js → chunk-CPELC6JE.js} +1 -1
  15. package/dist/chunk-GBUJOR6V.js +28 -0
  16. package/dist/{chunk-3WO2NOEQ.js → chunk-GSOYVIQS.js} +1 -1
  17. package/dist/{chunk-AIT3YWR5.js → chunk-HSRH76JN.js} +1 -1
  18. package/dist/{chunk-ID4RJIVZ.js → chunk-HSZ4AQ6L.js} +1 -1
  19. package/dist/chunk-I6NPILT5.js +1 -0
  20. package/dist/chunk-K7SRNBIV.js +1 -0
  21. package/dist/{chunk-DXONCYWF.js → chunk-LCWBVOII.js} +3 -3
  22. package/dist/{chunk-EMRJP6EM.js → chunk-LEJKDYCK.js} +1 -1
  23. package/dist/{chunk-HCK7OIQ3.js → chunk-NJ7C4KMA.js} +1 -1
  24. package/dist/{chunk-BQAKA3FU.js → chunk-NUM3YQGK.js} +1 -1
  25. package/dist/chunk-OJEIX7OZ.js +1 -0
  26. package/dist/chunk-PBQDHYNX.js +1 -0
  27. package/dist/{chunk-4HWKBCBH.js → chunk-PJL3UVMJ.js} +1 -1
  28. package/dist/chunk-PT35ZFLH.js +33 -0
  29. package/dist/{chunk-AKNHSDGV.js → chunk-QT3EAHOG.js} +1 -1
  30. package/dist/{chunk-LLRUJD62.js → chunk-RIJMXO43.js} +1 -1
  31. package/dist/chunk-RMI3NMQY.js +23 -0
  32. package/dist/chunk-RQ7JJ7GV.js +4 -0
  33. package/dist/{chunk-AUL5FGGK.js → chunk-RVU73VKN.js} +1 -1
  34. package/dist/{chunk-WPBQ45ZL.js → chunk-RW2GTYQI.js} +1 -1
  35. package/dist/{chunk-BR7GRH4A.js → chunk-SDAH3ECM.js} +1 -1
  36. package/dist/chunk-SGQWRIRJ.js +10 -0
  37. package/dist/{chunk-N56WAVYA.js → chunk-SMIFCAAX.js} +1 -1
  38. package/dist/chunk-SWBJS3U4.js +1 -0
  39. package/dist/{chunk-WXGTU2M6.js → chunk-VMTOFEXF.js} +1 -1
  40. package/dist/{chunk-GEMDU6XW.js → chunk-VXP5BMW7.js} +1 -1
  41. package/dist/{chunk-LAJQSHEI.js → chunk-XAHU42FP.js} +3 -3
  42. package/dist/{chunk-ZV5ETNLQ.js → chunk-XBQR74IK.js} +1 -1
  43. package/dist/{chunk-TXG2H7YQ.js → chunk-XG7QNAKW.js} +1 -1
  44. package/dist/{chunk-PRLIHLCS.js → chunk-XLWCSJMR.js} +1 -1
  45. package/dist/{chunk-M4TVRCMZ.js → chunk-XXLLY66B.js} +1 -1
  46. package/dist/chunk-YFP4P2FV.js +1 -0
  47. package/dist/{chunk-SWA5B5B2.js → chunk-YIXP2ALP.js} +1 -1
  48. package/dist/{chunk-246NTPOS.js → chunk-ZJQRLVVV.js} +1 -1
  49. package/dist/entry-0.js +1 -1
  50. package/dist/entry-1.js +1 -1
  51. package/dist/entry-10.js +1 -1
  52. package/dist/entry-11.js +1 -1
  53. package/dist/entry-12.js +1 -1
  54. package/dist/entry-13.js +1 -1
  55. package/dist/entry-14.js +1 -1
  56. package/dist/entry-15.js +1 -1
  57. package/dist/entry-16.js +1 -1
  58. package/dist/entry-17.js +1 -1
  59. package/dist/entry-18.js +1 -1
  60. package/dist/entry-19.js +1 -0
  61. package/dist/entry-2.js +1 -1
  62. package/dist/entry-20.js +1 -1
  63. package/dist/entry-22.js +1 -1
  64. package/dist/entry-23.js +1 -1
  65. package/dist/entry-24.js +1 -1
  66. package/dist/entry-25.js +1 -1
  67. package/dist/entry-26.js +1 -1
  68. package/dist/entry-27.js +1 -2
  69. package/dist/entry-28.js +1 -1
  70. package/dist/entry-29.js +2 -4
  71. package/dist/entry-3.js +1 -1
  72. package/dist/entry-30.js +1 -1
  73. package/dist/entry-31.js +4 -1
  74. package/dist/entry-32.js +1 -1
  75. package/dist/entry-33.js +1 -18
  76. package/dist/entry-34.js +1 -1
  77. package/dist/entry-35.js +18 -1
  78. package/dist/entry-36.js +1 -1
  79. package/dist/entry-37.js +1 -1
  80. package/dist/entry-38.js +1 -1
  81. package/dist/entry-39.js +1 -1
  82. package/dist/entry-4.js +1 -1
  83. package/dist/entry-40.js +1 -1
  84. package/dist/entry-41.js +1 -1
  85. package/dist/entry-42.js +1 -1
  86. package/dist/entry-43.js +1 -1
  87. package/dist/entry-44.js +1 -1
  88. package/dist/entry-45.js +1 -1
  89. package/dist/entry-46.js +1 -1
  90. package/dist/entry-47.js +1 -25
  91. package/dist/entry-48.js +1 -1
  92. package/dist/entry-49.js +25 -1
  93. package/dist/entry-5.js +1 -1
  94. package/dist/entry-50.js +1 -1
  95. package/dist/entry-51.js +1 -1
  96. package/dist/entry-52.js +1 -3
  97. package/dist/entry-53.js +1 -13
  98. package/dist/entry-54.js +3 -1
  99. package/dist/entry-55.js +13 -1
  100. package/dist/entry-56.js +1 -1
  101. package/dist/entry-57.js +1 -1
  102. package/dist/entry-58.js +1 -1
  103. package/dist/entry-59.js +1 -1
  104. package/dist/entry-6.js +1 -1
  105. package/dist/entry-60.js +1 -1
  106. package/dist/entry-61.js +1 -1
  107. package/dist/entry-62.js +1 -1
  108. package/dist/entry-63.js +1 -0
  109. package/dist/entry-64.js +1 -1
  110. package/dist/entry-66.js +1 -1
  111. package/dist/entry-67.js +0 -1
  112. package/dist/entry-68.js +1 -1
  113. package/dist/entry-69.js +1 -1
  114. package/dist/entry-7.js +1 -1
  115. package/dist/entry-70.js +1 -1
  116. package/dist/entry-71.js +1 -1
  117. package/dist/entry-72.js +1 -1
  118. package/dist/entry-73.js +1 -0
  119. package/dist/entry-74.js +1 -1
  120. package/dist/entry-76.js +1 -1
  121. package/dist/entry-77.js +0 -1
  122. package/dist/entry-78.js +1 -1
  123. package/dist/entry-79.js +1 -80
  124. package/dist/entry-8.js +1 -1
  125. package/dist/entry-80.js +1 -22
  126. package/dist/entry-81.js +80 -2
  127. package/dist/entry-82.js +22 -1
  128. package/dist/entry-83.js +2 -1
  129. package/dist/entry-84.js +1 -1
  130. package/dist/entry-85.js +1 -3
  131. package/dist/entry-86.js +1 -1
  132. package/dist/entry-87.js +1 -1
  133. package/dist/entry-88.js +3 -1
  134. package/dist/entry-89.js +1 -0
  135. package/dist/entry-9.js +1 -1
  136. package/dist/entry-90.js +1 -0
  137. package/dist/entry-91.js +1 -0
  138. package/dist/pi-agent-ide.js +29 -36
  139. package/docs/agent-guides/debugger.md +2 -0
  140. package/docs/agent-guides/editing.md +3 -3
  141. package/docs/agent-guides/search-code.md +2 -2
  142. package/docs/agent-guides/select-code.md +9 -6
  143. package/docs/code-review.md +5 -0
  144. package/docs/configuration.md +36 -4
  145. package/docs/development.md +8 -0
  146. package/docs/directory-operations.md +1 -1
  147. package/docs/extensions.md +98 -1
  148. package/docs/structured-results.md +11 -6
  149. package/docs/user-hooks.md +2 -2
  150. package/node_modules/pi-agent-doctor/package.json +7 -7
  151. package/node_modules/pi-agent-doctor/runtime/entry-27.js +1 -0
  152. package/node_modules/pi-agent-documentation/package.json +2 -2
  153. package/node_modules/pi-agent-documentation/runtime/entry-28.js +1 -0
  154. package/node_modules/pi-agent-filesystem/package.json +8 -8
  155. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  156. package/node_modules/pi-agent-filesystem-jq/package.json +6 -6
  157. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  158. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-32.js +2 -0
  159. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  160. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  161. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +6 -5
  162. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  163. package/node_modules/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  164. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  165. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  166. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  167. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  168. package/node_modules/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  169. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  170. package/node_modules/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  171. package/node_modules/pi-agent-image/package.json +3 -3
  172. package/node_modules/pi-agent-invariant/package.json +2 -2
  173. package/node_modules/pi-agent-pdf/package.json +3 -3
  174. package/node_modules/pi-agent-read/package.json +12 -12
  175. package/node_modules/pi-agent-read/runtime/entry-47.js +0 -1
  176. package/node_modules/pi-agent-read/runtime/entry-49.js +2 -0
  177. package/node_modules/pi-agent-resource/package.json +2 -2
  178. package/node_modules/pi-agent-resource/src/resource-error.ts +11 -0
  179. package/node_modules/pi-agent-search/package.json +9 -9
  180. package/node_modules/pi-agent-search/runtime/entry-52.js +0 -1
  181. package/node_modules/pi-agent-search/runtime/entry-53.js +1 -0
  182. package/node_modules/pi-agent-search/runtime/entry-54.js +2 -0
  183. package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -5
  184. package/node_modules/pi-agent-search-text/package.json +14 -14
  185. package/node_modules/pi-agent-search-text/runtime/entry-55.js +1 -0
  186. package/node_modules/pi-agent-search-text/runtime/entry-58.js +1 -0
  187. package/node_modules/pi-agent-text/package.json +3 -3
  188. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  189. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  190. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  191. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  192. package/node_modules/pi-agent-text-editor/index.ts +2 -0
  193. package/node_modules/pi-agent-text-editor/package.json +26 -26
  194. package/node_modules/pi-agent-text-editor/runtime/entry-79.js +0 -1
  195. package/node_modules/pi-agent-text-editor/runtime/entry-80.js +1 -0
  196. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  197. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  198. package/node_modules/pi-agent-text-editor/src/core/extension.ts +3 -1
  199. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +45 -44
  200. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  201. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +27 -18
  202. package/node_modules/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  203. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  204. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +29 -6
  205. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  206. package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  207. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  208. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  209. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  210. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  211. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +14 -3
  212. package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  213. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -5
  214. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +2 -0
  215. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  216. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +1 -0
  217. package/node_modules/pi-agent-tool-ui/package.json +6 -2
  218. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +1 -0
  219. package/node_modules/pi-agent-tool-ui/runtime/entry-86.js +1 -0
  220. package/node_modules/pi-agent-tool-ui/src/operation-approval.ts +271 -0
  221. package/node_modules/pi-agent-web/package.json +8 -8
  222. package/node_modules/pi-agent-web-html/package.json +3 -3
  223. package/node_modules/pi-agent-web-image/package.json +4 -4
  224. package/node_modules/pi-agent-web-image/runtime/entry-89.js +2 -0
  225. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  226. package/node_modules/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  227. package/node_modules/pi-agent-web-text/package.json +4 -4
  228. package/node_modules/pi-agent-web-text/runtime/entry-91.js +2 -0
  229. package/package.json +62 -54
  230. package/src/api/approval.ts +5 -0
  231. package/src/api/settings.ts +198 -0
  232. package/src/backend/debugger-registration.ts +5 -1
  233. package/src/code-review/extension.ts +10 -4
  234. package/src/code-review/reviewer.ts +8 -0
  235. package/src/composite/host-version.ts +29 -5
  236. package/src/composite/ide-alias-rendering.ts +97 -0
  237. package/src/composite/nested-tool-rendering.ts +74 -4
  238. package/src/composite/search-facts.ts +45 -0
  239. package/src/composite/settings-documentation.ts +32 -23
  240. package/src/composite/settings-registry.ts +94 -0
  241. package/src/composite/text-results.ts +120 -8
  242. package/src/composite/tool-availability.ts +11 -2
  243. package/src/core/diagnostic-entry.ts +31 -8
  244. package/src/core/diagnostic-store.ts +19 -3
  245. package/src/core/extension.ts +7 -2
  246. package/src/core/reload-resource-store.ts +23 -3
  247. package/src/documentation/registry.ts +10 -2
  248. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  249. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  250. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -6
  251. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  252. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-32.js +2 -0
  253. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  254. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-33.js +2 -0
  255. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +2 -0
  256. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  257. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  258. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  259. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +2 -0
  260. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  261. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-90.js +2 -0
  262. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  263. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-91.js +2 -0
  264. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +2 -0
  265. package/src/extensions/pi-agent-read/package.json +12 -12
  266. package/src/extensions/pi-agent-read/runtime/entry-47.js +0 -1
  267. package/src/extensions/pi-agent-read/runtime/entry-48.js +1 -0
  268. package/src/extensions/pi-agent-read/runtime/entry-49.js +2 -0
  269. package/src/extensions/pi-agent-search/package.json +9 -9
  270. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -14
  271. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +1 -0
  272. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +1 -0
  273. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-58.js +1 -0
  274. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  275. package/src/extensions/pi-agent-search/runtime/entry-53.js +1 -0
  276. package/src/extensions/pi-agent-search/runtime/entry-54.js +2 -0
  277. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -5
  278. package/src/extensions/pi-agent-text-editor/index.ts +2 -0
  279. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  280. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  281. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  282. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  283. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-63.js +1 -0
  284. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-64.js +2 -0
  285. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +2 -0
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +14 -3
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +17 -0
  289. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -5
  290. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +2 -0
  291. package/src/extensions/pi-agent-text-editor/runtime/entry-79.js +0 -1
  292. package/src/extensions/pi-agent-text-editor/runtime/entry-80.js +1 -0
  293. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +2 -0
  294. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +2 -0
  295. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +5 -0
  296. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +3 -1
  297. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +45 -44
  298. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  299. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +27 -18
  300. package/src/extensions/pi-agent-text-editor/src/core/text-edit-origin.ts +38 -0
  301. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +106 -48
  302. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +29 -6
  303. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +39 -44
  304. package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +3 -1
  305. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +1 -1
  306. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +6 -5
  307. package/src/pi-agent-ide.ts +61 -14
  308. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  309. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +6 -5
  310. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  311. package/src/plugins/pi-agent-ide-changes/runtime/entry-36.js +1 -0
  312. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +6 -5
  313. package/src/plugins/pi-agent-ide-debugger/index.ts +159 -60
  314. package/src/plugins/pi-agent-ide-debugger/src/debugmcp-client.ts +118 -0
  315. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +47 -0
  316. package/src/plugins/pi-agent-ide-debugger/src/renderer.ts +2 -0
  317. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +146 -1
  318. package/src/plugins/pi-agent-ide-debugger/src/ui.ts +12 -0
  319. package/src/plugins/pi-agent-ide-debugger/src/vscode-backend.ts +497 -0
  320. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  321. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  322. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  323. package/src/plugins/pi-agent-ide-lint/runtime/entry-40.js +2 -0
  324. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  325. package/src/plugins/pi-agent-ide-lsp/runtime/entry-41.js +2 -0
  326. package/src/plugins/pi-agent-ide-terminal/index.ts +3 -2
  327. package/src/plugins/pi-agent-ide-terminal/src/origin.ts +30 -0
  328. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +34 -0
  329. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +11 -2
  330. package/src/plugins/pi-agent-ide-terminal/src/types.ts +9 -0
  331. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +72 -26
  332. package/dist/chunk-ESPNEJHK.js +0 -1
  333. package/dist/chunk-GNACBJM3.js +0 -1
  334. package/dist/chunk-VMGZMXEM.js +0 -10
  335. package/dist/chunk-W3YFF6OO.js +0 -1
  336. package/dist/chunk-W7M3V7FR.js +0 -28
  337. package/dist/chunk-WMHSVEIT.js +0 -29
  338. package/dist/chunk-XSIKDVAR.js +0 -25
  339. package/dist/chunk-YTYLS2UM.js +0 -1
  340. package/dist/chunk-Z2QGNTGQ.js +0 -1
  341. package/dist/entry-21.js +0 -1
  342. package/node_modules/pi-agent-doctor/runtime/entry-20.js +0 -1
  343. package/node_modules/pi-agent-doctor/runtime/entry-21.js +0 -1
  344. package/node_modules/pi-agent-filesystem/runtime/entry-27.js +0 -2
  345. package/node_modules/pi-agent-filesystem-image/runtime/entry-28.js +0 -2
  346. package/node_modules/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  347. package/node_modules/pi-agent-ide-formatter/runtime/entry-36.js +0 -2
  348. package/node_modules/pi-agent-image/runtime/entry-40.js +0 -1
  349. package/node_modules/pi-agent-invariant/runtime/entry-41.js +0 -1
  350. package/node_modules/pi-agent-search/runtime/entry-49.js +0 -1
  351. package/node_modules/pi-agent-search-text/runtime/entry-53.js +0 -2
  352. package/node_modules/pi-agent-search-text/runtime/entry-54.js +0 -1
  353. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-58.js +0 -2
  354. package/node_modules/pi-agent-text-editor/runtime/entry-64.js +0 -1
  355. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-80.js +0 -2
  356. package/node_modules/pi-agent-tool-call-interception/runtime/entry-82.js +0 -1
  357. package/node_modules/pi-agent-tool-ui/runtime/entry-83.js +0 -1
  358. package/node_modules/pi-agent-web/runtime/entry-84.js +0 -2
  359. package/node_modules/pi-agent-web-html/runtime/entry-85.js +0 -2
  360. package/node_modules/pi-agent-web-image/runtime/entry-86.js +0 -2
  361. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-28.js +0 -2
  362. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-29.js +0 -2
  363. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-27.js +0 -2
  364. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-85.js +0 -2
  365. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-86.js +0 -2
  366. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-87.js +0 -2
  367. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-84.js +0 -2
  368. package/src/extensions/pi-agent-read/runtime/entry-43.js +0 -1
  369. package/src/extensions/pi-agent-read/runtime/entry-44.js +0 -1
  370. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +0 -2
  371. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-54.js +0 -1
  372. package/src/extensions/pi-agent-search/runtime/entry-49.js +0 -1
  373. package/src/extensions/pi-agent-search/runtime/entry-50.js +0 -1
  374. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-58.js +0 -2
  375. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-59.js +0 -1
  376. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-80.js +0 -2
  377. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +0 -2
  378. package/src/extensions/pi-agent-text-editor/runtime/entry-63.js +0 -1
  379. package/src/extensions/pi-agent-text-editor/runtime/entry-64.js +0 -1
  380. package/src/plugins/pi-agent-ide-ast/runtime/entry-32.js +0 -1
  381. package/src/plugins/pi-agent-ide-ast/runtime/entry-33.js +0 -2
  382. package/src/plugins/pi-agent-ide-formatter/runtime/entry-36.js +0 -2
  383. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-26.js +0 -0
  384. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem}/runtime/entry-29.js +0 -0
  385. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  386. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-31.js +0 -0
  387. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-text}/runtime/entry-33.js +0 -0
  388. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-34.js +0 -0
  389. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  390. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  391. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
  392. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-39.js +0 -0
  393. /package/node_modules/{pi-agent-pdf → pi-agent-image}/runtime/entry-42.js +0 -0
  394. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-43.js +0 -0
  395. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-44.js +0 -0
  396. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-48.js +0 -0
  397. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-50.js +0 -0
  398. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-57.js +0 -0
  399. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-59.js +0 -0
  400. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-60.js +0 -0
  401. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-61.js +0 -0
  402. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-62.js +0 -0
  403. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-63.js +0 -0
  404. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-81.js +0 -0
  405. /package/node_modules/{pi-agent-web-pdf → pi-agent-web}/runtime/entry-87.js +0 -0
  406. /package/node_modules/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-88.js +0 -0
  407. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-30.js +0 -0
  408. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-31.js +0 -0
  409. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-88.js +0 -0
  410. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-60.js +0 -0
  411. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-61.js +0 -0
  412. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-62.js +0 -0
  413. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-34.js +0 -0
  414. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-35.js +0 -0
  415. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-37.js +0 -0
  416. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-38.js +0 -0
  417. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-39.js +0 -0
@@ -24,6 +24,9 @@ const MAX_OUTPUT_CHARS = 1_000_000;
24
24
  const DEFAULT_COLS = 100;
25
25
  const DEFAULT_ROWS = 30;
26
26
  const STOP_GRACE_MS = 2_000;
27
+ // Finished sessions keep their output and virtual screen in memory. Bound how many stay so a
28
+ // long-lived Pi process does not grow with every command it has ever run.
29
+ const MAX_FINISHED_SESSIONS = 50;
27
30
 
28
31
  type SessionListener = (session: TerminalSession) => void;
29
32
 
@@ -68,6 +71,7 @@ export class TerminalSessionManager {
68
71
  return {
69
72
  id: session.id,
70
73
  source: session.source,
74
+ ...(session.origin === undefined ? {} : { origin: session.origin }),
71
75
  command: session.command,
72
76
  cwd: session.cwd,
73
77
  shell: session.shell.displayName,
@@ -133,6 +137,10 @@ export class TerminalSessionManager {
133
137
  rows,
134
138
  cwd: options.cwd,
135
139
  env: cleanEnvironment(processEnvironment()),
140
+ // The inbox ConPTY never closes the pseudoconsole when the shell exits on its own,
141
+ // leaving one headless conhost.exe per command (microsoft/node-pty#965). The bundled
142
+ // ConPTY releases its console host once the last client exits.
143
+ ...(globalThis.process.platform === "win32" ? { useConptyDll: true } : {}),
136
144
  };
137
145
  process = pty.spawn(
138
146
  options.shell.executable,
@@ -156,6 +164,15 @@ export class TerminalSessionManager {
156
164
  const session: TerminalSession = { ...base, process };
157
165
  this.#sessions.set(id, session);
158
166
  process.onData((data) => this.#appendOutput(session, data));
167
+ // Answer terminal queries such as PowerShell's startup device-attributes probe, which
168
+ // otherwise waits about two seconds for a reply under the bundled ConPTY.
169
+ if (globalThis.process.platform === "win32")
170
+ session.screen.onData((reply) => {
171
+ if (isTerminalStatus(session.status)) return;
172
+ try {
173
+ process.write(reply);
174
+ } catch {}
175
+ });
159
176
  process.onExit(({ exitCode, signal }) => {
160
177
  if (isTerminalStatus(session.status)) return;
161
178
  session.endedAt = Date.now();
@@ -594,6 +611,23 @@ export class TerminalSessionManager {
594
611
 
595
612
  #emitCompleted(session: TerminalSession): void {
596
613
  for (const listener of this.#completionListeners) listener(session);
614
+ this.#evictFinishedSessions();
615
+ }
616
+
617
+ /**
618
+ * Forget the oldest finished sessions beyond the retention bound. Their full-output logs stay
619
+ * on disk; background sessions whose completion was not delivered yet are kept.
620
+ */
621
+ #evictFinishedSessions(): void {
622
+ const finished = [...this.#sessions.values()]
623
+ .filter((session) => isTerminalStatus(session.status))
624
+ .sort((left, right) => (right.endedAt ?? 0) - (left.endedAt ?? 0));
625
+ for (const session of finished.slice(MAX_FINISHED_SESSIONS)) {
626
+ if (session.background && !session.completionDelivered) continue;
627
+ session.screen.dispose();
628
+ this.#closeOutputLog(session.id);
629
+ this.#sessions.delete(session.id);
630
+ }
597
631
  }
598
632
  }
599
633
 
@@ -2,7 +2,11 @@ import path from "node:path";
2
2
  import { stripVTControlCharacters } from "node:util";
3
3
  import { SshBackendRegistry } from "#src/backend/registry.js";
4
4
 
5
- import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ defineTool,
7
+ type ExtensionAPI,
8
+ type ExtensionContext,
9
+ } from "@earendil-works/pi-coding-agent";
6
10
  import { Type } from "typebox";
7
11
  import { Text } from "@earendil-works/pi-tui";
8
12
 
@@ -25,6 +29,7 @@ import type { TerminalSessionManager } from "#src/plugins/pi-agent-ide-terminal/
25
29
  import type { TerminalUi } from "#src/plugins/pi-agent-ide-terminal/src/ui.js";
26
30
  import type {
27
31
  ShellProfile,
32
+ TerminalExecutionOrigin,
28
33
  TerminalSessionSnapshot,
29
34
  } from "#src/plugins/pi-agent-ide-terminal/src/types.js";
30
35
 
@@ -72,6 +77,7 @@ export function registerTerminalTools(
72
77
  ui: Pick<TerminalUi, "bind" | "notifyWaitTransition">,
73
78
  presentation: "full" | "compact" | "disabled" = "compact",
74
79
  targets: SshBackendRegistry = new SshBackendRegistry([]),
80
+ executionOrigin?: (toolCallId: string, context: ExtensionContext) => TerminalExecutionOrigin,
75
81
  ): () => void {
76
82
  // Keep wait cancellation in this registration, not in a PTY manager retained from older code.
77
83
  const foregroundWaits = new Set<AbortController>();
@@ -99,8 +105,9 @@ export function registerTerminalTools(
99
105
  description: `Use ${toolName} to execute a command in the user's configured shell. Each call creates a new terminal session and returns its shell: source for inspection and interaction.`,
100
106
  parameters: runParameters,
101
107
  outputSchema: shellOutputSchema,
102
- async execute(_toolCallId, input, signal, onUpdate, context) {
108
+ async execute(toolCallId, input, signal, onUpdate, context) {
103
109
  ui.bind(context);
110
+ const origin = executionOrigin?.(toolCallId, context);
104
111
  const remote = targets.resolve(input.cwd ?? context.cwd, context.cwd);
105
112
  const options = {
106
113
  command: input.command,
@@ -119,6 +126,8 @@ export function registerTerminalTools(
119
126
  cwd: input.cwd === undefined ? context.cwd : path.resolve(context.cwd, input.cwd),
120
127
  shell: profile,
121
128
  });
129
+ // Set once at launch, including when the manager was retained from older code.
130
+ session.origin ??= origin;
122
131
  if (input.background === true && session.status !== "failed") {
123
132
  await captureInitialBackgroundPreview(manager, session, onUpdate);
124
133
  if (session.status !== "running") session.completionDelivered = true;
@@ -22,7 +22,15 @@ export interface ShellProfile {
22
22
  readonly commandArgs: (command: string) => readonly string[];
23
23
  }
24
24
 
25
+ /** Real launch and visible execution identities; never reassigned by later shell interaction. */
26
+ export interface TerminalExecutionOrigin {
27
+ readonly toolCallId: string;
28
+ readonly parentToolCallId: string;
29
+ readonly sessionId: string;
30
+ }
25
31
  export interface TerminalSession {
32
+ /** Assigned once by the launching tool; retained with the process across reload. */
33
+ origin?: TerminalExecutionOrigin;
26
34
  readonly id: string;
27
35
  readonly source: string;
28
36
  readonly command: string;
@@ -56,6 +64,7 @@ export interface TerminalSession {
56
64
  }
57
65
 
58
66
  export interface TerminalSessionSnapshot {
67
+ readonly origin?: TerminalExecutionOrigin;
59
68
  readonly id: string;
60
69
  readonly source: string;
61
70
  readonly command: string;
@@ -1,5 +1,5 @@
1
1
  import { Box, Container } from "@earendil-works/pi-tui";
2
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
3
3
 
4
4
  import { renderTerminalResult } from "#src/plugins/pi-agent-ide-terminal/src/renderer.js";
5
5
  import type { TerminalSessionManager } from "#src/plugins/pi-agent-ide-terminal/src/session-manager.js";
@@ -26,25 +26,19 @@ export class TerminalUi {
26
26
  private readonly manager: TerminalSessionManager,
27
27
  private readonly staleIntervalMs = DEFAULT_STALE_INTERVAL_MS,
28
28
  ) {
29
- pi.registerMessageRenderer("terminal-stale", (message, { expanded }, theme) => {
30
- const snapshot = isTerminalSessionSnapshot(message.details) ? message.details : undefined;
31
- const content = new Container();
32
- if (snapshot !== undefined)
33
- content.addChild(
34
- renderTerminalResult(snapshot, expanded, theme, "stale · inspect session"),
35
- );
36
- const card = new Box(1, 1, (line) => theme.bg("toolPendingBg", line));
37
- card.addChild(content);
38
- return card;
39
- });
40
- pi.registerMessageRenderer("terminal-completion", (message, { expanded }, theme) => {
41
- const content = new Container();
42
- for (const session of completionSnapshots(message.details))
43
- content.addChild(renderTerminalResult(session, expanded, theme));
44
- const card = new Box(1, 1, (line) => theme.bg("toolSuccessBg", line));
45
- card.addChild(content);
46
- return card;
47
- });
29
+ // Keep historical visible messages readable; new delivery uses UI-only linked entries.
30
+ pi.registerMessageRenderer("terminal-stale", (message, { expanded }, theme) =>
31
+ renderStale(message.details, expanded, theme),
32
+ );
33
+ pi.registerMessageRenderer("terminal-completion", (message, { expanded }, theme) =>
34
+ renderCompletion(message.details, expanded, theme),
35
+ );
36
+ pi.registerEntryRenderer("terminal-stale-display", (entry, { expanded }, theme) =>
37
+ renderStale(entry.data, expanded, theme),
38
+ );
39
+ pi.registerEntryRenderer("terminal-completion-display", (entry, { expanded }, theme) =>
40
+ renderCompletion(entry.data, expanded, theme),
41
+ );
48
42
  this.#removeManagerListeners = [
49
43
  manager.onDidChange((session) => this.#refreshStaleTimer(session)),
50
44
  manager.onDidComplete((session) => {
@@ -56,6 +50,13 @@ export class TerminalUi {
56
50
 
57
51
  bind(context: ExtensionContext): void {
58
52
  this.#context = context;
53
+ // A retained manager can finish work while the previous UI is being replaced.
54
+ for (const snapshot of this.manager.list()) {
55
+ const session = this.manager.get(snapshot.id);
56
+ if (session === undefined || !session.background) continue;
57
+ if (session.status === "running") this.#refreshStaleTimer(session);
58
+ else if (session.status !== "stopping") this.#queueCompletion(session);
59
+ }
59
60
  }
60
61
 
61
62
  /** Deliver deferred stale notices after Pi has fully settled. */
@@ -70,7 +71,7 @@ export class TerminalUi {
70
71
 
71
72
  /** Notify the agent when an aborted tool result may no longer be deliverable. */
72
73
  notifyWaitTransition(session: TerminalSession): void {
73
- const snapshot = this.manager.snapshot(session);
74
+ const snapshot = this.#snapshot(session);
74
75
  this.pi.sendMessage(
75
76
  {
76
77
  customType: "terminal-wait-transition",
@@ -103,7 +104,7 @@ export class TerminalUi {
103
104
  session.status !== "running"
104
105
  )
105
106
  return;
106
- const snapshot = this.manager.snapshot(session);
107
+ const snapshot = this.#snapshot(session);
107
108
  const remaining = Math.max(0, this.staleIntervalMs - snapshot.idleMs);
108
109
  if (checkNow && remaining === 0) {
109
110
  this.#handleStale(session);
@@ -129,18 +130,33 @@ export class TerminalUi {
129
130
  return;
130
131
  }
131
132
  session.staleReminderDelivered = true;
132
- const snapshot = this.manager.snapshot(session);
133
+ const snapshot = this.#snapshot(session);
133
134
  this.pi.sendMessage(
134
135
  {
135
136
  customType: "terminal-stale",
136
- display: true,
137
+ display: false,
137
138
  content: formatStaleMessage(snapshot),
138
139
  details: snapshot,
139
140
  },
140
141
  { triggerTurn: true, deliverAs: "followUp" },
141
142
  );
143
+ this.pi.appendEntry("terminal-stale-display", { ...snapshot, ...this.#visibleOwner(snapshot) });
142
144
  }
143
145
 
146
+ #snapshot(session: TerminalSession): TerminalSessionSnapshot {
147
+ // The process manager can be an instance retained from before origin metadata existed.
148
+ return {
149
+ ...this.manager.snapshot(session),
150
+ ...(session.origin === undefined ? {} : { origin: session.origin }),
151
+ };
152
+ }
153
+ #visibleOwner(snapshot: TerminalSessionSnapshot): { readonly parentToolCallId?: string } {
154
+ const origin = snapshot.origin;
155
+ // Retained processes may outlive their session. Never attach them to a reused call ID.
156
+ return origin !== undefined && origin.sessionId === this.#context?.sessionManager.getSessionId()
157
+ ? { parentToolCallId: origin.parentToolCallId }
158
+ : {};
159
+ }
144
160
  #clearStaleTimer(id: string): void {
145
161
  const timer = this.#staleTimers.get(id);
146
162
  if (timer !== undefined) clearTimeout(timer);
@@ -160,20 +176,50 @@ export class TerminalUi {
160
176
  this.#pending.clear();
161
177
  if (this.#closed || sessions.length === 0) return;
162
178
  for (const completed of sessions) completed.completionDelivered = true;
163
- const snapshots = sessions.map((completed) => this.manager.snapshot(completed));
179
+ const snapshots = sessions.map((completed) => this.#snapshot(completed));
164
180
  this.pi.sendMessage(
165
181
  {
166
182
  customType: "terminal-completion",
167
- display: true,
183
+ display: false,
168
184
  content: formatCompletionMessage(snapshots),
169
185
  details: { sessions: snapshots },
170
186
  },
171
187
  { triggerTurn: true, deliverAs: "steer" },
172
188
  );
189
+ const groups = new Map<string | undefined, TerminalSessionSnapshot[]>();
190
+ for (const snapshot of snapshots) {
191
+ const owner = this.#visibleOwner(snapshot).parentToolCallId;
192
+ const group = groups.get(owner) ?? [];
193
+ group.push(snapshot);
194
+ groups.set(owner, group);
195
+ }
196
+ for (const [parentToolCallId, sessions] of groups) {
197
+ this.pi.appendEntry("terminal-completion-display", {
198
+ sessions,
199
+ ...(parentToolCallId === undefined ? {} : { parentToolCallId }),
200
+ });
201
+ }
173
202
  }, COMPLETION_DELAY_MS);
174
203
  }
175
204
  }
176
205
 
206
+ function renderStale(details: unknown, expanded: boolean, theme: Theme): Box {
207
+ const content = new Container();
208
+ if (isTerminalSessionSnapshot(details))
209
+ content.addChild(renderTerminalResult(details, expanded, theme, "stale · inspect session"));
210
+ const card = new Box(1, 1, (line) => theme.bg("toolPendingBg", line));
211
+ card.addChild(content);
212
+ return card;
213
+ }
214
+
215
+ function renderCompletion(details: unknown, expanded: boolean, theme: Theme): Box {
216
+ const content = new Container();
217
+ for (const session of completionSnapshots(details))
218
+ content.addChild(renderTerminalResult(session, expanded, theme));
219
+ const card = new Box(1, 1, (line) => theme.bg("toolSuccessBg", line));
220
+ card.addChild(content);
221
+ return card;
222
+ }
177
223
  function completionSnapshots(details: unknown): readonly TerminalSessionSnapshot[] {
178
224
  if (!isRecord(details) || !Array.isArray(details.sessions)) return [];
179
225
  return details.sessions.filter(isTerminalSessionSnapshot);
@@ -1 +0,0 @@
1
- import{a as t}from"./chunk-EI7MMDWY.js";var s=Symbol.for("pi-agent-ide.reload-resource-store");function n(){let e=globalThis,o=e[s];if(o!==void 0)return o;let r=new Map;return e[s]=r,r}t(n,"store");function u(e,o){n().set(e,o)}t(u,"retainReloadResource");function a(e){let o=n(),r=o.get(e);return o.delete(e),r}t(a,"takeReloadResource");function c(e,o){let r=n();r.get(e)===o&&r.delete(e)}t(c,"forgetReloadResource");export{u as a,a as b,c};
@@ -1 +0,0 @@
1
- import{b as n}from"./chunk-E2PHA4SQ.js";import"./chunk-JKMXND6V.js";import"./chunk-WXGTU2M6.js";import{a as o,b as t,c as i}from"./chunk-LLRUJD62.js";import"./chunk-Q5X6OXNS.js";import"./chunk-4HWKBCBH.js";import{b as s}from"./chunk-AIT3YWR5.js";import"./chunk-VDP5CQHM.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-OI3HBIPK.js";import"./chunk-YTYLS2UM.js";import{c as r}from"./chunk-W7CASEO3.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as e}from"./chunk-EI7MMDWY.js";async function g(a){let m=new i(await t(o(r())));await s(a,f=>n(f,m))}e(g,"registerOwnedWeb");export{g as default};
@@ -1,10 +0,0 @@
1
- import{a as N}from"./chunk-47SPPIXK.js";import{a as C,b as O}from"./chunk-VAXLSPPU.js";import{a as b}from"./chunk-OI3HBIPK.js";import{e as v}from"./chunk-YTYLS2UM.js";import"./chunk-MPT3R4BL.js";import{a as k,b as A,c as E,d as x}from"./chunk-T7I2VX3J.js";import"./chunk-PS2B6THP.js";import{a as P}from"./chunk-BU7IZLKB.js";import{a as S,b as I}from"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import{a as s}from"./chunk-EI7MMDWY.js";var W=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/,w=class{static{s(this,"AgentDocumentationRegistry")}#e=new Map;register(t){let o=new Set(this.#e.keys());for(let r of t)U(r,o),o.add(r.id);for(let r of t)this.#e.set(r.id,V(r))}list(){return[...this.#e.values()].sort((t,o)=>t.id.localeCompare(o.id))}get(t){return this.#e.get(t)}matching(t,o){let r=L(o);return r?.startsWith("docs:")===!0?[]:this.list().filter(i=>i.triggers.some(d=>{if(d.tool!==t)return!1;let l=d.resourcePrefixes===void 0||r!==void 0&&d.resourcePrefixes.some(a=>r.startsWith(a)),n=d.viewPrefixes===void 0||z(o).some(a=>d.viewPrefixes?.some(u=>a.startsWith(u)));return l&&n}))}};function U(e,t){if(!W.test(e.id))throw new Error(`Invalid documentation ID: ${e.id}`);if(e.description.trim().length===0)throw new Error(`Documentation ${e.id} has no description`);if(e.markdown.trim().length===0)throw new Error(`Documentation ${e.id} has no Markdown content`);if(e.triggers.length===0||e.triggers.some(o=>o.tool.trim().length===0||o.resourcePrefixes?.some(r=>r.length===0)===!0||o.viewPrefixes?.some(r=>r.length===0)===!0))throw new Error(`Documentation ${e.id} has no valid triggers`);if(t.has(e.id))throw new Error(`Documentation ${e.id} is already registered`)}s(U,"validateDocument");function V(e){return Object.freeze({...e,triggers:Object.freeze(e.triggers.map(t=>Object.freeze({...t,...t.resourcePrefixes===void 0?{}:{resourcePrefixes:Object.freeze([...t.resourcePrefixes])},...t.viewPrefixes===void 0?{}:{viewPrefixes:Object.freeze([...t.viewPrefixes])}})))})}s(V,"freezeDocument");function z(e){if(typeof e!="object"||e===null)return[];let t=e.views;return Array.isArray(t)?t.filter(o=>typeof o=="string"):[]}s(z,"readViews");function L(e){if(typeof e!="object"||e===null)return;let t=e.path;return typeof t=="string"?t:void 0}s(L,"readPath");function _(e){return{id:"agent-documentation",readResources:s(t=>t.path?.startsWith("docs:")===!0?[t.path]:[],"readResources"),async tryResolve(t,o){let r=t.path;if(r===void 0||!r.startsWith("docs:"))return{kind:"not-handled"};if(t.include!==void 0||t.exclude!==void 0)return{kind:"failed",error:new Error("File include/exclude globs do not apply to docs: resources.")};if(/^(?:files|ast|symbols|process):/u.test(t.query))return{kind:"failed",error:new Error("Use a text or regex: query for docs: resources.")};let i=r.slice(5);if(i.length===0)return{kind:"failed",error:new Error("Use docs:all to search all guides or docs:<id> for one guide. Read docs: to list IDs.")};let d=i==="all"?void 0:e.get(i);if(i!=="all"&&d===void 0)return{kind:"failed",error:new Error(`Unknown documentation ID: ${i}`)};let l=G(t),n=[],a=t.limit??50,u=0;for(let h of d===void 0?e.list():[d]){o.signal?.throwIfAborted();for(let[f,c]of h.markdown.split(/\r\n|\n|\r/u).entries()){o.signal?.throwIfAborted();for(let g of c.matchAll(l)){if(g[0].length===0)continue;let p=g.index,y=p+g[0].length;if(t.wholeWord===!0&&(/[\p{L}\p{N}_]/u.test(c[p-1]??"")||/[\p{L}\p{N}_]/u.test(c[y]??"")))continue;if(n.length===a)return{kind:"resolved",payload:{source:r,matches:n,complete:!1,reason:"limit"}};let D={source:`docs:${h.id}`,lineNumber:f+1,startColumn:p,endColumn:y,matchedText:g[0],lineText:c};if(u+=Buffer.byteLength(T(D))+1,u>48*1024)return{kind:"resolved",payload:{source:r,matches:n,complete:!1,reason:"output"}};n.push(D)}}}return{kind:"resolved",payload:{source:r,matches:n,complete:!0}}},toScriptData(t){let o=t;return v(o.matches,o.complete)},format(t){let o=t,r=`${o.matches.length}${o.complete?"":"+"}`;return{content:[{type:"text",text:[o.matches.length===0&&o.complete?`No matches in ${o.source}`:`${r} matches in ${o.source}`,...$(o),...o.matches.map(T)].join(`
2
- `)}],details:o}},renderResult(t,o,r){let i=t.details;return b(i.matches,i.complete,r,o.expanded,void 0,$(i))}}}s(_,"createDocumentationSearchResolver");function $(e){return["Packaged guides \xB7 read-only. Read docs:<id> for the full guide; search excerpts do not mark it read.",...e.reason==="limit"?["Limit reached \xB7 incomplete results. Narrow the query or raise limit."]:[],...e.reason==="output"?["Output shortened \xB7 incomplete results. Narrow the query."]:[]]}s($,"notices");function T(e){let t=Math.max(0,e.startColumn-64),o=Math.min(e.lineText.length,e.startColumn+192),r=`${t>0?"\u2026":""}${e.lineText.slice(t,o)}${o<e.lineText.length?"\u2026":""}`;return`${e.source}:${e.lineNumber}:${e.startColumn+1} ${r}`}s(T,"matchRow");function G(e){if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let t=e.query,o=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t,r=t.startsWith("regex:")?t.slice(6):o.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(r,e.caseSensitive===!0?"gu":"giu")}s(G,"searchPattern");var M="agent-documentation-read";async function B(e){let t=new w,o=new Set,r=new Map,i=new Map,d=s(n=>{let a=n.filter(u=>!o.has(u));if(a.length!==0){e.appendEntry(M,{ids:a});for(let u of a)o.add(u)}},"remember"),l=e.events.on(x,n=>{if(!K(n))throw new Error("Invalid agent documentation registration");t.register(n.documents)});e.on("session_shutdown",l),await P(e,{protocol:S,apiVersion:I,id:"agent-documentation",setup(n){n.addResolver({resolver:{id:"agent-documentation",tryResolve(a){if(!a.startsWith("docs:"))return Promise.resolve({kind:"not-handled"});let u=a.slice(5),h=u.length===0?void 0:t.get(u),f=u.length===0?q(t.list()):h?.markdown;return f===void 0?Promise.resolve({kind:"failed",error:new Error(`Unknown documentation ID: ${u}`)}):Promise.resolve({kind:"resolved",resource:{source:a,read:s(()=>Promise.resolve([{type:"text",text:f}]),"read")}})}}}),n.describe({path:s(()=>t.list().length===0?void 0:"docs: lists packaged agent guidance; docs:<id> reads a listed guide.","path")}),n.addPromptGuideline(()=>F(t.list()))}}),await N(e,{protocol:C,apiVersion:O,id:"agent-documentation",setup(n){n.addResolver({resolver:_(t),priority:-20})}}),e.on("session_start",(n,a)=>{R(a.sessionManager.getBranch(),t,o)}),e.on("session_tree",(n,a)=>{R(a.sessionManager.getBranch(),t,o)}),e.on("session_compact",(n,a)=>{R(a.sessionManager.getBranch(),t,o)}),e.on("tool_call",n=>{n.toolCallId.includes("-preflight-")||n.parentToolCallId!==void 0&&r.set(n.toolCallId,n.parentToolCallId)}),e.on("tool_result",n=>{if(n.toolCallId.includes("-preflight-"))return;let a=r.get(n.toolCallId);r.delete(n.toolCallId);let u=i.get(n.toolCallId)??[];i.delete(n.toolCallId);let h=n.toolName==="read"?H(n.input):void 0;if(h!==void 0){let c=h.slice(5),g=c.length===0||t.get(c)!==void 0,p=t.get(c);return p!==void 0&&!n.isError&&j(n.content,p)&&d([c]),{content:n.content,structuredContent:n.structuredContent,details:{...m(n.details)?n.details:{},documentation:g?c.length===0?{kind:"list",ids:t.list().map(y=>y.id)}:{kind:"document",id:c}:{kind:"error",code:"UNKNOWN_DOCUMENTATION",id:c}},isError:n.isError}}let f=[...u,...t.matching(n.toolName,n.input).filter(c=>!o.has(c.id))];if(f.length!==0){if(d(f.map(c=>c.id)),a!==void 0){i.set(a,[...i.get(a)??[],...f]);return}return{content:[...n.content,...f.map(c=>({type:"text",text:`
3
-
4
- ---
5
-
6
- # Guide: ${c.id}
7
-
8
- ${c.markdown.trim()}`}))],structuredContent:n.structuredContent,details:{...m(n.details)?n.details:{},documentation:{kind:"attachment",ids:f.map(c=>c.id)}},isError:n.isError}}}),e.events.emit(E,{protocol:k,apiVersion:A})}s(B,"registerProgressiveDocumentation");function q(e){return e.length===0?"No agent documentation is currently available.":["# Available agent documentation","",...e.map(t=>`- \`${t.id}\` \u2014 ${t.description}`)].join(`
9
- `)}s(q,"renderListing");function F(e){if(e.length!==0)return["Read the matching docs:<id> before using any tool or feature with packaged guidance, including tools discovered later or called through Codemode. Read each guide once per branch. Tool descriptions and docs: listings do not replace the full guide.","If a result includes a Guide, read it before your next use. The call has already run: do not repeat it just to obtain documentation. Nested calls keep their guides on the parent result, even when the script does not print the child output.","Available documents:",...e.map(t=>` - ${t.id} \u2014 ${t.description}`)].join(`
10
- `)}s(F,"renderPromptGuideline");function R(e,t,o){o.clear();for(let i of e){if(!m(i))continue;if(i.type==="custom"&&i.customType===M&&m(i.data)){r(i.data.ids);continue}if(i.type!=="message"||!m(i.message))continue;let d=i.message;if(d.role!=="toolResult"||!m(d.details))continue;let l=d.details.documentation;if(m(l)&&(l.kind==="attachment"&&r(l.ids),l.kind==="document"&&!d.isError&&typeof l.id=="string")){let n=t.get(l.id);n!==void 0&&j(d.content,n)&&r([n.id])}}function r(i){if(Array.isArray(i))for(let d of i)typeof d=="string"&&t.get(d)!==void 0&&o.add(d)}s(r,"addIds")}s(R,"restoreClaims");function j(e,t){return Array.isArray(e)&&e.some(o=>m(o)&&o.type==="text"&&typeof o.text=="string"&&o.text.includes(t.markdown.trim()))}s(j,"containsFullGuide");function H(e){if(!(!m(e)||typeof e.path!="string"||!e.path.startsWith("docs:")))return e.path}s(H,"documentationSource");function K(e){return m(e)&&Array.isArray(e.documents)}s(K,"isRegistrationRequest");function m(e){return typeof e=="object"&&e!==null}s(m,"isRecord");export{B as default};
@@ -1 +0,0 @@
1
- import{a}from"./chunk-Q5X6OXNS.js";import"./chunk-4HWKBCBH.js";import"./chunk-DXONCYWF.js";import"./chunk-EI7MMDWY.js";export{a as startSshProcess};
@@ -1,28 +0,0 @@
1
- import{a as we,b as ye,c as Se}from"./chunk-ESPNEJHK.js";import{a as he}from"./chunk-L2B4DTVS.js";import{a as fe,b as ge,c as L}from"./chunk-LLRUJD62.js";import"./chunk-4HWKBCBH.js";import{a as ce}from"./chunk-47SPPIXK.js";import{a as le,b as ue}from"./chunk-VAXLSPPU.js";import{a as de}from"./chunk-OI3HBIPK.js";import{e as me}from"./chunk-YTYLS2UM.js";import{c as pe}from"./chunk-W7CASEO3.js";import"./chunk-QUYXINGZ.js";import{a as M}from"./chunk-PRLIHLCS.js";import{e as ee,f as te}from"./chunk-T7I2VX3J.js";import{a as ae}from"./chunk-M4TVRCMZ.js";import{c as oe,d as se}from"./chunk-TGC2ZACO.js";import{b as A}from"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import{a as ie}from"./chunk-BU7IZLKB.js";import{a as ne,b as re}from"./chunk-S5PL5DFQ.js";import{i as G,j as I}from"./chunk-DXONCYWF.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import st from"node:path";import{stripVTControlCharacters as at}from"node:util";import{truncateLine as lt}from"@earendil-works/pi-coding-agent";import{Text as P}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as Te,DEFAULT_MAX_LINES as be,formatSize as it,truncateTail as ot}from"@earendil-works/pi-coding-agent";function k(t){return ot(t,{maxBytes:Te-4096,maxLines:be-32})}a(k,"terminalOutputTail");function _(t){let e=k(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(s=>s!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
- `)}
3
- output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${be} line output budget`:`${it(Te)} output budget`,l=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
- `)}
6
- output:
7
- ${l}${r.length===0?"":`
8
- ${r}`}`}a(_,"formatAgentTerminalSnapshot");var ut=500;function ve(t,e,n,r,i){let l=e?"background":"wait",s=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${O(n)} \xB7 ${l}`)}`;return new P(`${s}
9
- ${i.fg("accent",V(r.family))} ${t}`,0,0)}a(ve,"renderRunCall");function Re(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new P(r.join(`
10
- `),0,0)}a(Re,"renderTerminalActionResult");function Pe(t,e,n,r,i){let l=[mt(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&l.push(...r.map(s=>` ${i.fg("dim",s)}`)),new P(l.join(`
11
- `),0,0)}a(Pe,"renderTerminalAction");function x(t,e,n,r){let i=Ae(t,A,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new P(i.join(`
12
- `),0,0)}a(x,"renderTerminalResult");function xe(t,e,n){if(e===!0?e="full":e===!1&&(e="compact"),e==="disabled"){if(!(t.status!==void 0&&!["running","completed"].includes(t.status)||t.exitCode!==void 0&&t.exitCode!==0||t.error!==void 0))return new P($(t,(c,u)=>n.fg(c,u)),0,0);let s=D(t.output??"",A),o=[...s.omission===void 0?[]:[` ${n.fg("muted",s.omission)}`],...s.lines.map(c=>` ${n.fg("dim",c)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],$(t,(c,u)=>n.fg(c,u))];return new P(o.join(`
13
- `),0,0)}if(e==="full"){let l=Ae(t,Number.POSITIVE_INFINITY,n).slice(2);return new P(l.join(`
14
- `),0,0)}let r=D(t.output??"",A),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(l=>` ${n.fg("dim",l)}`)];return i.push($(t,(l,s)=>n.fg(l,s))),new P(i.join(`
15
- `),0,0)}a(xe,"renderRunResult");function Ee(t,e){let n=a((s,o)=>e?.fg(s,o)??o,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${O(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",V(t.shellFamily))} ${q(t.command,84)}`],l=ct(t.output,2);return l.length>0&&i.push(...l.map(s=>` ${n("dim",q(s,90))}`)),i.push($(t,n)),i.join(`
16
- `)}a(Ee,"renderActiveTerminal");function Ae(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",l=t.cwd===void 0?"workspace":O(t.cwd),s=t.shellFamily??"posix",o=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${l} \xB7 ${i}`)}`,`${n.fg("accent",V(s))} ${t.command??""}`],c=D(t.output??"",e);return c.omission!==void 0&&o.push(` ${n.fg("muted",c.omission)}`),c.lines.length>0&&o.push(...c.lines.map(u=>` ${n.fg("dim",u)}`)),o.push($(t,(u,d)=>n.fg(u,d))),o}a(Ae,"terminalCardLines");function ct(t,e){return D(t,e).lines}a(ct,"outputTail");function D(t,e){let n=k(at(t).replaceAll("\r","")),r=n.content.split(`
17
- `).map(c=>lt(c.trimEnd(),ut).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,l=Math.max(0,r.length-i),s=Math.max(0,n.totalLines-n.outputLines),o=l+s;return{lines:r.slice(l),...n.truncated||o>0?{omission:o>0?`\u2026 ${o} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(D,"outputWindow");function $(t,e){let n=t.status??"running",r=dt(n),i=n==="completed"?"success":n==="running"?"accent":"error",l=[`${r} ${n}`,pt(t.elapsedMs??0)];return t.waitReason!==void 0&&l.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&l.push(`reason ${t.completionReason}`),t.exitCode!==void 0?l.push(`exit ${t.exitCode}`):t.signal!==void 0&&l.push(`signal ${t.signal}`),e(i,l.join(" \xB7 "))}a($,"statusLine");function dt(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(dt,"statusIcon");function V(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(V,"promptMarker");function mt(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":O(t.cwd),i=t.background===!0?"background":"wait",l=q(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${l}`)}`}a(mt,"terminalIdentity");function O(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${st.sep}`))?`~${t.slice(e.length)}`:t}a(O,"shortCwd");function q(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(q,"oneLine");function pt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(pt,"formatElapsed");function ke(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},...e.remote===void 0?{}:{remote:e.remote,owned:!0},renderSummary:a(n=>Ee(e,n).split(`
18
- `),"renderSummary"),renderDetail:a(n=>x(e,!0,n),"renderDetail"),sendInput:a(n=>{Promise.resolve(t.write(e.source,n)).catch(()=>{})},"sendInput"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(ke,"terminalProcessProvider");import{setTimeout as yt}from"node:timers/promises";var ft="#d8dee9",Y="#111418",gt=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function X(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:l}=await import("@napi-rs/canvas"),s=Math.max(0,Math.min(i.rows-1,n?.start??0)),o=Math.max(1,Math.min(i.rows-s,n?.count??i.rows)),c=i.cols*9+24,u=o*18+24,d=l(Math.max(1,Math.round(c*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=Y,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,g=Math.max(0,p.baseY);for(let h=0;h<o;h+=1){let S=p.getLine(g+s+h);if(S!==void 0)for(let w=0;w<i.cols;w+=1){let T=S.getCell(w);T===void 0||T.getWidth()===0||ht(m,T,w,h)}}return i.status==="running"&&p.cursorY>=s&&p.cursorY<s+o&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-s)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}a(X,"renderTerminalScreen");function ht(t,e,n,r){let i=$e(e,"foreground"),l=$e(e,"background");e.isInverse()&&([i,l]=[l,i]);let s=12+n*9,o=12+r*18;l!==Y&&(t.fillStyle=l,t.fillRect(s,o,9*Math.max(1,e.getWidth()),18));let c=e.getChars();c.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(c,s,o),e.isUnderline()&&t.fillRect(s,o+18-2,9*Math.max(1,e.getWidth()),1))}a(ht,"drawCell");function $e(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?ft:Y;let i=n?t.isFgRGB():t.isBgRGB(),l=n?t.getFgColor():t.getBgColor();return i?`#${l.toString(16).padStart(6,"0")}`:wt(l)}a($e,"cellColor");function wt(t){let e=gt[t];if(e!==void 0)return e;if(t>=232){let o=8+(t-232)*10;return Ce(o,o,o)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),l=n%6,s=a(o=>o===0?0:55+o*40,"channel");return Ce(s(r),s(i),s(l))}a(wt,"ansiColor");function Ce(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(Ce,"rgb");var z="\0pi-terminal-write\0",Z="\0pi-terminal-keys\0";function St(t){let e=t?.find(c=>c==="image"||c==="sequence"||c.startsWith("image:")||c.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 c of e.slice(n+1).split(",")){let[u,d,m]=c.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${c}`);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 l=i.get("duration")??2,s=i.get("interval")??.5,o=i.get("scale")??1;if(!(o>0&&o<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(l>0&&l<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(s>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(l/s)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:l,interval:s,scale:o}}a(St,"parseTerminalVisualView");async function _e(t,e){let n=new Map,r=new Map,i={protocol:ne,apiVersion:re,id:"terminal",setup(s){s.addResolver({resolver:Tt(e),preserveTruncatedOutput:!0,renderResult(o,c,u){let d=o.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
- `)},c.expanded,u,"read terminal")}}),s.addHandler({stage:"pre-read",async handler(o){let c=o.request.path;if(c===void 0||!v(c))return{kind:"continue",context:o};let u;try{u=St(o.request.views)}catch(m){return{kind:"return",result:K(c,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:o};let d=e.get(c);if(d===void 0)return{kind:"return",result:K(c,`Unknown terminal session ${c}`)};try{e.markInspected(c);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,p=[];for(let g=0;g<m;g+=1){o.resolverContext.signal?.throwIfAborted(),g>0&&await yt(u.interval*1e3,void 0,{signal:o.resolverContext.signal});let h=await X(e,c,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:K(c,m instanceof Error?m.message:String(m))}}}}),s.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."})}},l={protocol:oe,apiVersion:se,id:"terminal",setup(s){s.addResolver({resolver:bt(e)}),s.tool("write").addHandler({stage:"text-pre-edit",handler:a(async o=>(Le(o.input,e,n),await Ie(o.input,e,r),vt(o,z)),"handler")}),s.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async o=>(await Ie(o.input,e,r),Le(o.input,e,n),Rt(o)),"handler")});for(let o of["write","insert","delete"])s.addToolRenderer({tool:o,matches:a((c,u)=>At(c,u),"matches"),renderCall(c,u,d){let m=c,p=typeof m.path=="string"?e.get(m.path):void 0,g=d.state;return p!==void 0&&(g.snapshot=e.snapshot(p)),Pe(g.snapshot??{},o,Me(o,m),[],u)},renderResult(c,u,d){let m=Et(c.details);return Re(m.action,m.changedLines,d)}});s.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."),s.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),s.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([ie(t,i),ae(t,l)]),t.on("tool_result",async(s,o)=>{if(!R(s.input))return;let c=s.input.path;if(s.toolName==="replace"&&typeof c=="string"&&v(c)){let y=`replace is unsupported for ${c}; use write for text, insert for keys, or delete to terminate and remove the session.`;return I({content:[{type:"text",text:y}],details:s.details},M(s.toolName),{status:"error",errors:[G(y,"UNSUPPORTED_OPERATION",c)],data:{operation:"replace",effect:"not-applied",files:[{source:c,effect:"not-applied"}]}})}if(s.toolName==="delete"&&typeof c=="string"&&v(c)){let y=e.get(c);if(y===void 0)return;let rt=e.snapshot(y);return e.delete(c).then(()=>I({content:[{type:"text",text:`Deleted terminal session ${c}.`}],details:{source:c,deleted:!0,snapshot:rt,action:"delete",input:"session",changedLines:[]}},M(s.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:c,effect:"applied"}]}}),C=>I({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:c,deleted:!1}},M(s.toolName),{status:"error",errors:[G(C,"TERMINAL_DELETE_FAILED",c)],data:{operation:"delete",effect:"unknown",files:[{source:c,effect:"unknown"}]}}))}if(s.toolName!=="write"&&s.toolName!=="insert"||s.isError)return;let u=s.input.path;if(typeof u!="string"||!v(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 g=e.snapshot(d),h=s.toolName,S=Me(h,s.input),w=e.screenChangeRegion(d,m,6),T=[{type:"text",text:`Sent ${S} to ${d.source}.`}];return o.model?.input.includes("image")===!0&&T.push({type:"image",data:await X(e,u,{start:w.startRow,count:w.lines.length}),mimeType:"image/png"}),{content:T,details:{source:d.source,action:h,status:d.status,snapshot:g,input:S,changedLines:w.lines},isError:s.isError,...s.structuredContent===void 0?{}:{structuredContent:s.structuredContent}}})}a(_e,"registerTerminalResources");function Tt(t){return{id:"terminal",async tryResolve(e){if(!v(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:Pt(r)}]}}}}}}a(Tt,"createReadResolver");function bt(t){return{id:"terminal-input",async tryResolve(e){if(!v(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=xt(r),l=i.indexOf(z),s=i.indexOf(Z);if(l>=0){await t.write(n.source,i.slice(l+z.length));return}if(s>=0){await t.sendKeys(n.source,i.slice(s+Z.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(bt,"createInputResolver");function vt(t,e){return!R(t.input)||!De(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(vt,"transformWriteInput");function Rt(t){if(!R(t.input)||!De(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:`${Z}${typeof t.input.text=="string"?t.input.text:""}`}}}a(Rt,"transformInsertInput");function Pt(t){return _(t)}a(Pt,"formatSnapshot");function xt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(xt,"singleText");function K(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(K,"failure");function v(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(v,"isShellSource");function De(t){return typeof t=="string"&&v(t)}a(De,"isShellSourceValue");function Et(t){if(!R(t)||!R(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(Et,"terminalActionDetails");async function Ie(t,e,n){if(!R(t)||typeof t.path!="string"||!v(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(Ie,"rememberScreen");function Le(t,e,n){if(!R(t)||typeof t.path!="string"||!v(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(Le,"rememberOutputEnd");function Me(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(Me,"terminalInputLabel");function At(t,e){if(!R(t))return!1;if(e==="call")return typeof t.path=="string"&&v(t.path);let n=t.details;return R(n)&&typeof n.source=="string"&&v(n.source)}a(At,"isTerminalRenderValue");function R(t){return typeof t=="object"&&t!==null}a(R,"isRecord");async function Oe(t,e){await ce(t,{protocol:le,apiVersion:ue,id:"terminal",setup(r){r.addResolver({resolver:kt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}a(Oe,"registerTerminalSearch");function kt(t){return{readResources:a(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=N(e);return me(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=$t(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=N(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
- `)}
21
-
22
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,l=J(i)?N(i.payload):N(void 0);return de(l.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${l.snapshot.status} \xB7 read-only`])}}}a(kt,"terminalSearchResolver");function $t(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[l,s]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let o=e.caseSensitive===!0?s:s.toLocaleLowerCase(),c=0;for(;r.length<i;){let u=o.indexOf(n,c);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||Ct(o,u,d))&&r.push({source:t.source,lineNumber:l+1,startColumn:u,endColumn:d,matchedText:s.slice(u,d),lineText:s}),c=Math.max(d,u+1)}if(r.length>=i)break}return r}a($t,"findTerminalMatches");function Ct(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(Ct,"isWordBoundary");function N(t){if(!It(t))throw new TypeError("Invalid terminal search result");return t}a(N,"parsePayload");function It(t){return J(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&J(t.snapshot)&&typeof t.snapshot.source=="string"}a(It,"isTerminalSearchPayload");function J(t){return typeof t=="object"&&t!==null}a(J,"isRecord");import{spawn as Mt}from"node:child_process";import{closeSync as _t,mkdirSync as Dt,openSync as Ot,rmSync as Nt,writeSync as Ut}from"node:fs";import Wt from"node:os";import Be from"node:path";import{createRequire as Bt}from"node:module";import{randomUUID as Ft}from"node:crypto";import{stripVTControlCharacters as jt}from"node:util";import{StringDecoder as Ht}from"node:string_decoder";import Lt from"node:os";import Ne from"node:path";var U={executable:"/bin/bash",displayName:"Bash over SSH",family:"posix",commandArgs:a(t=>["-lc",t],"commandArgs")};function Ue(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",l=Ne.win32.basename(i).toLowerCase();return l==="cmd"||l==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(s=>["/d","/s","/c",s],"commandArgs")}:{executable:i,displayName:l.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(s=>["-NoLogo","-NoProfile","-Command",s],"commandArgs")}}let n=e.SHELL?.trim()||Lt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Ne.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a(Ue,"resolveShellProfile");function We(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(We,"shellSyntaxGuidance");var He=Bt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Fe=1e6,Gt=100,qt=30,Vt=2e3,B=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#n=new Set;#r=new Set;#s=new Map;#i=new Map;#l=!1;constructor(e=Kt){this.#a=e}onDidChange(e){return this.#n.add(e),()=>this.#n.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(zt(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},...e.remote===void 0?{}:{remote:{target:e.remote.target,pid:e.remote.process.pid,...e.remote.process.identity===void 0?{}:{identity:e.remote.process.identity}}},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){let n=this.#c(e),{id:r,cols:i,rows:l}=n,s;try{let c=He("node-pty"),u={name:"xterm-256color",cols:i,rows:l,cwd:e.cwd,env:Jt(Zt())};s=c.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],u)}catch(c){let u={...n,status:"failed",endedAt:Date.now(),error:W(c)};return this.#e.set(r,u),this.#o(r),n.resolveCompletion(u),queueMicrotask(()=>this.#d(u)),u}let o={...n,process:s};return this.#e.set(r,o),s.onData(c=>this.#u(o,c)),s.onExit(({exitCode:c,signal:u})=>{E(o.status)||(o.endedAt=Date.now(),o.exitCode=c,u!==0&&(o.signal=u),o.status=o.status==="stopping"?"stopped":c===0?"completed":"failed",(c===124||c===137)&&(o.completionReason="timeout"),this.#o(o.id),o.resolveCompletion(o),this.#t(o),this.#d(o))}),this.#t(o),o}#c(e){if(this.#l)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f0-9]{12}$/u.test(n)||this.#e.has(n)||this.#i.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=tn(n);this.#s.set(n,Ot(r,"a",384));let i=e.cols??Gt,l=e.rows??qt,s=Xt(i,l),o=a(u=>{},"resolveCompletion"),c=new Promise(u=>{o=u});return{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:l,fullOutputPath:r,screen:s,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:c,resolveCompletion:o,completionDelivered:!1,staleReminderDelivered:!1}}async startRemote(e){let n=U,r=this.#c({...e,cwd:e.remote.location.source,shell:n}),i=new AbortController;this.#i.set(r.id,{abort:i,completion:r.completion});let l=a(()=>i.abort(),"abortStartup");e.signal?.addEventListener("abort",l,{once:!0}),e.signal?.aborted&&l();try{let s=await e.remote.backend.startProcess(n.executable,n.commandArgs(e.command),e.remote.location.path,{pty:{cols:r.cols,rows:r.rows},signal:i.signal}).finally(()=>e.signal?.removeEventListener("abort",l)),o={...r,remote:{target:e.remote.location.target,process:s}};this.#e.set(o.id,o);let c=new Ht("utf8");s.stdout.on("data",d=>this.#u(o,c.write(d))),s.stderr.resume();let u=a(()=>{this.#u(o,c.end()),o.endedAt=Date.now(),this.#o(o.id),o.resolveCompletion(o),this.#t(o),this.#d(o)},"finish");return s.completion.then(({exitCode:d})=>{o.exitCode=d,d<0&&(o.signal=-d),o.status=o.status==="stopping"?"stopped":d===0?"completed":"failed",(d===124||d===137)&&(o.completionReason="timeout"),u()},d=>{o.status="lost",o.error=W(d),u()}),this.#t(o),o}catch(s){let o={...r,status:"failed",endedAt:Date.now(),error:W(s)};return this.#e.set(o.id,o),this.#o(o.id),o.resolveCompletion(o),queueMicrotask(()=>this.#d(o)),o}finally{this.#i.delete(r.id)}}async wait(e,n){let r=this.required(e);return E(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,l)=>{let s=a(()=>{this.stop(r.source,"cancelled").then(i,l)},"onAbort");n?.addEventListener("abort",s,{once:!0}),r.completion.then(o=>{n?.removeEventListener("abort",s),i(o)},l)})}async waitForForeground(e,n){let r=this.required(e);if(E(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(l=>{let s=!1,o,c=a(p=>{s||(p!==void 0&&E(r.status)&&(p=void 0),s=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#t(r)),l({session:r,...p===void 0?{}:{reason:p}}))},"finish"),u=a(()=>c("aborted"),"onAbort"),d=setTimeout(()=>c("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Yt(r)){o=void 0;return}o??=Date.now(),Date.now()-o>=i&&c("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>c())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,l;for(;Date.now()<r;){let s=e.outputStart+e.output.length;if(s!==i)i=s,l=Date.now(),await e.screenReady;else if(l!==void 0&&Date.now()-l>=40)return;await Q(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),l=Math.max(1,Math.min(e.rows,r)),s=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(l/2)),o=-1;for(let d=0;d<=e.rows-l;d+=1){let m=0;for(let p=d;p<d+l;p+=1){let g=n[p]??"",h=i[p]??"",S=h.length>0&&!n.includes(h),w=g.length>0&&h.length===0;g!==h&&(S||w)&&(m+=1)}m>o&&(o=m,s=d)}let c=e.screen.buffer.active;return{lines:i.slice(s,s+l).map((d,m)=>{if(s+m!==c.cursorY)return d;let g=d.padEnd(c.cursorX," ");return`${g.slice(0,c.cursorX)}\u258C${g.slice(c.cursorX)}`}),startRow:s}}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),l=[];for(let s=0;s<e.rows;s+=1){let o=r.getLine(i+s)?.translateToString(!0).trimEnd();o!==void 0&&o.length>0&&l.push(o)}return l.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#t(n))}write(e,n){let r=this.requiredRunning(e);if(r.remote)return r.remote.process.write(Buffer.from(n)).catch(i=>{throw r.error=W(i),this.#t(r),i});r.process?.write(n)}sendKeys(e,n){return this.write(e,Qt(n))}async stop(e,n="stopped"){let r=this.required(e);return E(r.status)||(r.status="stopping",this.#t(r),await je(r,!1),await Promise.race([r.completion.then(()=>!0),Q(Vt).then(()=>!1)])||(await je(r,!0),await Promise.race([r.completion,Q(1e3)])),E(r.status)||(r.status=n,r.endedAt=Date.now(),this.#o(r.id),r.resolveCompletion(r),this.#d(r)),n==="cancelled"&&(r.status="cancelled"),this.#t(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#o(n.id),Nt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#t(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],l=Math.max(0,r.baseY);for(let s=l;s<l+n.rows;s+=1)i.push(r.getLine(s)?.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.#l)return;this.#l=!0;let e=[...this.#i.values()];for(let n of e)n.abort.abort();await Promise.all(e.map(n=>n.completion)),await Promise.all([...this.#e.values()].filter(n=>!E(n.status)).map(n=>this.stop(n.source)));for(let n of this.#e.values())n.screen.dispose(),this.#o(n.id);this.#n.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=jt(n),i=this.#s.get(e.id);if(i!==void 0&&Ut(i,r),e.output+=r,e.output.length>Fe){let l=e.output.length-Fe;e.output=e.output.slice(l),e.outputStart+=l}e.screenReady=e.screenReady.then(()=>new Promise(l=>{e.screen.write(n,l)})),this.#t(e)}#o(e){let n=this.#s.get(e);n!==void 0&&(_t(n),this.#s.delete(e))}#t(e){for(let n of this.#n)n(e)}#d(e){for(let n of this.#r)n(e)}};function Yt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(Yt,"looksInteractive");function Xt(t,e){let{Terminal:n}=He("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(Xt,"createScreen");function Kt(){return Ft().replaceAll("-","").slice(0,12)}a(Kt,"defaultSessionId");function zt(t){return t.startsWith("shell:")?t.slice(6):t}a(zt,"normalizeSessionId");function E(t){return t!=="running"&&t!=="stopping"}a(E,"isTerminalStatus");function Zt(){return process.env}a(Zt,"processEnvironment");function Jt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(Jt,"cleanEnvironment");function Qt(t){return t.split(/[\s,]+/u).filter(Boolean).map(en).join("")}a(Qt,"encodeTerminalKeys");function en(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"),l=r.has("alt")||r.has("meta"),s=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 l?`\x1B${m}`:m}let o={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!l&&!s&&o[n]!==void 0)return o[n];if(l&&!i&&!s&&o[n]!==void 0)return`\x1B${o[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!l&&!s?`\x1B[${u}`:`\x1B[1;${1+(s?1:0)+(l?2:0)+(i?4:0)}${u}`;if(l&&!i&&n.length===1)return`\x1B${s?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(en,"encodeTerminalKey");async function je(t,e){if(t.remote){await t.remote.process.stop().catch(()=>{});return}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=Mt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(je,"terminateProcessTree");function Q(t){return new Promise(e=>setTimeout(e,t))}a(Q,"delay");function W(t){return t instanceof Error?t.message:String(t)}a(W,"errorMessage");function tn(t){let e=Be.join(Wt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Dt(e,{recursive:!0,mode:448}),Be.join(e,`${t}.log`)}a(tn,"createOutputLog");import{AgentSession as nn}from"@earendil-works/pi-coding-agent";var F=Symbol.for("pi-agent-ide.terminal-steering-observers");function Ge(t){let e=nn.prototype,n=e[F]??rn(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}a(Ge,"observeQueuedSteering");function rn(t){let e=t.prompt,n=t.steer,r=new Set,i=a(c=>{for(let u of[...r])u(c)},"notify"),l=a(function(c,u){return u?.streamingBehavior!=="steer"?e.call(this,c,u):e.call(this,c,{...u,preflightResult:a(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),s=a(async function(...c){let u=await n.apply(this,c);return u==="queued"&&i(this),u},"steer");t.prompt=l,t.steer=s;let o={listeners:r,restore:a(()=>{t[F]===o&&(t.prompt===l&&(t.prompt=e),t.steer===s&&(t.steer=n),delete t[F])},"restore")};return t[F]=o,o}a(rn,"installObservers");import Xe from"node:path";import{stripVTControlCharacters as sn}from"node:util";import{defineTool as an}from"@earendil-works/pi-coding-agent";import{Type as b}from"typebox";import{Text as ln}from"@earendil-works/pi-tui";import{open as on}from"node:fs/promises";import{Type as f}from"typebox";var qe=1024*1024,Ve=f.Object({output:f.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:f.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:f.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:f.Array(f.Object({start:f.Integer(),end:f.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:f.Optional(f.Number({description:"Process exit code, only when known."})),wall_time_seconds:f.Number(),session:f.String({description:"Session ID."}),source:f.String({description:"Persistent shell: source for Read, input and termination."}),status:f.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>f.Literal(t))),background:f.Boolean(),cwd:f.String({description:"Actual working directory; SSH sessions retain their canonical ssh:// target URI."}),remote:f.Optional(f.Object({target:f.String(),pid:f.Integer({minimum:1})},{description:"Remote process identity, never a local native PID."})),wait_reason:f.Optional(f.Union([f.Literal("timeout"),f.Literal("interactive"),f.Literal("steering")])),completion_reason:f.Optional(f.Literal("timeout")),signal:f.Optional(f.Number()),error:f.Optional(f.String())});async function Ye(t){let e=await on(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=a(async(o,c)=>{let u=Buffer.alloc(c),d=0;for(;d<c;){let m=await e.read(u,d,c-d,o+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,l,s=n>qe;if(!s)i=(await r(0,n)).toString("utf8"),l=[{start:0,end:n}];else{let o=qe/2,c=await r(0,o),u=await r(n-o,o),d=new TextDecoder().decode(c,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let p=u.subarray(m).toString("utf8");i=d+p,l=[{start:0,end:Buffer.byteLength(d)},{start:n-o+m,end:n}]}return{output:i,truncated:s,full_output_path:t.fullOutputPath,output_ranges:l,...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,cwd:t.cwd,...t.remote===void 0?{}:{remote:t.remote},...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()}}a(Ye,"structuredShellResult");var un=a(t=>b.Object({command:b.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${We(t)}`}),background:b.Optional(b.Boolean({description:"Set true to return after an initial output preview instead of waiting for completion. Defaults to false."})),timeoutSeconds:b.Optional(b.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:b.Optional(b.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:b.Optional(b.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:b.Optional(b.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function Ke(t,e,n,r,i="compact",l=new L([])){let s=new Set,o=process.platform==="win32"?"powershell":"bash",c=un(n);return t.registerTool(an({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:Ve,async execute(u,d,m,p,g){r.bind(g);let h=l.resolve(d.cwd??g.cwd,g.cwd),S={command:d.command,background:d.background??!1,...d.cols===void 0?{}:{cols:d.cols},...d.rows===void 0?{}:{rows:d.rows}},w=h?await e.startRemote({...S,remote:h,...m===void 0?{}:{signal:m}}):e.start({...S,cwd:d.cwd===void 0?g.cwd:Xe.resolve(g.cwd,d.cwd),shell:n});if(d.background===!0&&w.status!=="failed")return await cn(e,w,p),w.status!=="running"&&(w.completionDelivered=!0),j(e.snapshot(w));if(w.status==="failed")return j(e.snapshot(w));let T=new AbortController;s.add(T);let y;try{y=await e.waitForForeground(w.source,{signal:m===void 0?T.signal:AbortSignal.any([m,T.signal]),timeoutMs:(d.timeoutSeconds??60)*1e3})}finally{s.delete(T)}return y.reason==="aborted"&&T.signal.aborted&&m?.aborted!==!0?(y.session.waitReason="steering",j(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),j(e.snapshot(y.session)))},renderCall(u,d,m){if((m.expanded?"full":i)==="disabled")return new ln(d.fg("toolTitle",o),0,0);let g=typeof u.command=="string"?u.command:"",h=typeof u.cwd=="string"&&u.cwd.startsWith("ssh:"),S=typeof u.cwd=="string"?h?u.cwd:Xe.resolve(process.cwd(),u.cwd):process.cwd();return ve(g,u.background===!0,S,h?U:n,d)},renderResult(u,d,m){return xe(u.details,d.expanded?"full":i,m)}})),()=>{for(let u of s)u.abort()}}a(Ke,"registerTerminalTools");function ze(t){let e=k(t.output).content;return{content:[{type:"text",text:_(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"}}a(ze,"terminalPreview");async function j(t){return{...ze(t),structuredContent:await Ye(t)}}a(j,"terminalResult");async function cn(t,e,n){await new Promise(r=>{let i=!1,l,s=a(()=>{},"unsubscribe"),o=a(()=>{i||(i=!0,clearTimeout(l),s(),r())},"finish"),c=a(()=>{let u=t.snapshot(e);n?.(ze(u)),(sn(u.output).replaceAll("\r","").split(`
24
- `).filter(m=>m.length>0).length>=A||u.status!=="running")&&o()},"publish");s=t.onDidChange(u=>{u.id===e.id&&c()}),l=setTimeout(o,2e3),c()})}a(cn,"captureInitialBackgroundPreview");import{Box as Ze,Container as Je}from"@earendil-works/pi-tui";var dn=120,mn=12e4,H=class{constructor(e,n,r=mn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:l},s)=>{let o=Qe(i.details)?i.details:void 0,c=new Je;o!==void 0&&c.addChild(x(o,l,s,"stale \xB7 inspect session"));let u=new Ze(1,1,d=>s.bg("toolPendingBg",d));return u.addChild(c),u}),e.registerMessageRenderer("terminal-completion",(i,{expanded:l},s)=>{let o=new Je;for(let u of pn(i.details))o.addChild(x(u,l,s));let c=new Ze(1,1,u=>s.bg("toolSuccessBg",u));return c.addChild(o),c}),this.#l=[n.onDidChange(i=>this.#c(i)),n.onDidComplete(i=>{this.#o(i.id),i.background&&this.#t(i)})]}static{a(this,"TerminalUi")}#a=new Map;#e;#n=new Map;#r=new Set;#s;#i=!1;#l;bind(e){this.#s=e}onAgentSettled(e){this.#s=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#c(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.#i=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#n.values())clearTimeout(e);this.#n.clear(),this.#r.clear(),this.#s=void 0;for(let e of this.#l)e()}#c(e,n=!1){if(this.#o(e.id),this.#i||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.#u(e);return}this.#n.set(e.id,setTimeout(()=>this.#u(e),i))}#u(e){if(this.#n.delete(e.id),this.#i||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#s?.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:gn(n),details:n},{triggerTurn:!0,deliverAs:"followUp"})}#o(e){let n=this.#n.get(e);n!==void 0&&clearTimeout(n),this.#n.delete(e),this.#r.delete(e)}#t(e){this.#i||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.#i||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:fn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},dn)))}};function pn(t){return!tt(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Qe)}a(pn,"completionSnapshots");function Qe(t){return tt(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}a(Qe,"isTerminalSessionSnapshot");function fn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
- ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,l=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${et(n.elapsedMs)}
26
- ${l||"(no output)"}`}).join(`
27
- `)}`}a(fn,"formatCompletionMessage");function gn(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${et(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}a(gn,"formatStaleMessage");function et(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(et,"formatElapsed");function tt(t){return typeof t=="object"&&t!==null}a(tt,"isRecord");function nt(t){return t==="full"||t==="disabled"?t:"compact"}a(nt,"toolPresentation");async function hn(t,e){te(t,[await ee({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(u=>({tool:u,resourcePrefixes:["shell:","process:"]}))]})]);let n=ye("terminal")??new B,r=Ue(),i=new L(await ge(fe(pe()))),l=new H(t,n),s=he(t).add(ke(n));await Promise.all([_e(t,n),Oe(t,n)]);let o=Ke(t,n,r,l,nt(e?.preferences["ui.terminal"]),i),c=a(()=>{},"removeSteeringObserver");t.on("session_start",(u,d)=>{l.bind(d),c(),c=Ge(m=>{m.sessionManager===d.sessionManager&&o()})}),t.on("agent_settled",(u,d)=>l.onAgentSettled(d)),t.on("session_shutdown",async u=>{if(c(),l.dispose(),s(),u.reason!=="quit"){we("terminal",n);return}Se("terminal",n),await n.dispose()})}a(hn,"registerTerminal");export{hn as default};