pi-agent-ide 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (606) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +24 -29
  3. package/dist/chunk-2AY526TN.js +3 -0
  4. package/dist/{chunk-LEJKDYCK.js → chunk-2TZDG2JH.js} +1 -1
  5. package/dist/{chunk-XBQR74IK.js → chunk-4GBFIGH3.js} +1 -1
  6. package/dist/{chunk-PJL3UVMJ.js → chunk-4IWEKRSP.js} +1 -1
  7. package/dist/chunk-52PFWQMU.js +5 -0
  8. package/dist/chunk-5BGWNYQS.js +1 -0
  9. package/dist/{chunk-QUYXINGZ.js → chunk-5S74Z6Y4.js} +3 -3
  10. package/dist/chunk-64JTD2DJ.js +1 -0
  11. package/dist/{chunk-XAHU42FP.js → chunk-6A3ORNW3.js} +2 -2
  12. package/dist/{chunk-ANM3Y5FO.js → chunk-6WCHBHFW.js} +5 -5
  13. package/dist/{chunk-IMGIDBCC.js → chunk-7D7PXIVV.js} +1 -1
  14. package/dist/chunk-7PVDTMEM.js +1 -0
  15. package/dist/chunk-7SG756UO.js +4 -0
  16. package/dist/{chunk-GBUJOR6V.js → chunk-7URANI6I.js} +14 -14
  17. package/dist/{chunk-4W7GH3T7.js → chunk-AJZVKDYC.js} +1 -1
  18. package/dist/chunk-AMIIOWFL.js +1 -0
  19. package/dist/{chunk-TOYN4W4F.js → chunk-B25LXXNV.js} +1 -1
  20. package/dist/chunk-C2JT2G5K.js +1 -0
  21. package/dist/chunk-CVOYSEBE.js +1 -0
  22. package/dist/chunk-DDH3FP4G.js +3 -0
  23. package/dist/chunk-FEZLTM4L.js +1 -0
  24. package/dist/{chunk-CPELC6JE.js → chunk-FHRHYY4M.js} +1 -1
  25. package/dist/chunk-FKKAHI62.js +11 -0
  26. package/dist/chunk-FS3KCKFX.js +9 -0
  27. package/dist/chunk-FYOU4RBH.js +2 -0
  28. package/dist/chunk-G4PRFO6G.js +1 -0
  29. package/dist/chunk-GS5ZRTUG.js +1 -0
  30. package/dist/{chunk-XXLLY66B.js → chunk-GXL4NMHR.js} +1 -1
  31. package/dist/{chunk-QT3EAHOG.js → chunk-H3GEEOOL.js} +1 -1
  32. package/dist/chunk-H5Z54BEU.js +25 -0
  33. package/dist/chunk-H7WAM5RH.js +23 -0
  34. package/dist/chunk-HT7LZN5A.js +9 -0
  35. package/dist/chunk-IG5DXVDJ.js +1 -0
  36. package/dist/chunk-K4UTEMDU.js +1 -0
  37. package/dist/chunk-KFBRL2V4.js +3 -0
  38. package/dist/chunk-KN6VPARZ.js +1 -0
  39. package/dist/{chunk-RW2GTYQI.js → chunk-LF325WYO.js} +1 -1
  40. package/dist/chunk-LTADNZKW.js +2 -0
  41. package/dist/{chunk-YJ6T3PEP.js → chunk-MDD5ORB6.js} +1 -1
  42. package/dist/{chunk-S72FVLUX.js → chunk-MLFJU2US.js} +1 -1
  43. package/dist/chunk-NA2NEU4V.js +1 -0
  44. package/dist/chunk-OBTT5INC.js +6 -0
  45. package/dist/{chunk-IICJXZBU.js → chunk-OMNKD7WW.js} +3 -3
  46. package/dist/chunk-PLMHBXWI.js +10 -0
  47. package/dist/{chunk-235QMMVA.js → chunk-PQWANILR.js} +1 -1
  48. package/dist/{chunk-QRJLIV6P.js → chunk-QJ6V5IAY.js} +6 -6
  49. package/dist/chunk-QM5WDEFI.js +1 -0
  50. package/dist/{chunk-SMIFCAAX.js → chunk-RIJRPAL2.js} +1 -1
  51. package/dist/chunk-RIOPUTUJ.js +6 -0
  52. package/dist/chunk-RVFMH77U.js +82 -0
  53. package/dist/{chunk-NJ7C4KMA.js → chunk-SRFWT562.js} +1 -1
  54. package/dist/{chunk-U22JNO6N.js → chunk-STUZZM5B.js} +1 -1
  55. package/dist/{chunk-PT35ZFLH.js → chunk-TNAUCNUT.js} +12 -12
  56. package/dist/{chunk-DUUOCBS3.js → chunk-TVH2ND35.js} +1 -1
  57. package/dist/chunk-TVSZYABY.js +5 -0
  58. package/dist/chunk-TVXZE4KW.js +4 -0
  59. package/dist/chunk-U7YDLVFL.js +1 -0
  60. package/dist/{chunk-KZC7TI5M.js → chunk-UD3DMY3Q.js} +1 -1
  61. package/dist/{chunk-VXP5BMW7.js → chunk-USG6WHAT.js} +1 -1
  62. package/dist/{chunk-RMI3NMQY.js → chunk-V4J3TLCV.js} +2 -2
  63. package/dist/{chunk-ZPT5D4VP.js → chunk-VDJSH3DQ.js} +2 -2
  64. package/dist/{chunk-VMTOFEXF.js → chunk-VMLPXSMK.js} +1 -1
  65. package/dist/{chunk-6T7PSDQW.js → chunk-VN3XBH2Q.js} +1 -1
  66. package/dist/chunk-WAJW4G4F.js +22 -0
  67. package/dist/chunk-WEE3NM6L.js +1 -0
  68. package/dist/{chunk-IM24DB3K.js → chunk-WES2E4VR.js} +1 -1
  69. package/dist/{chunk-RIJMXO43.js → chunk-WQIMM4SU.js} +1 -1
  70. package/dist/chunk-WUO3UW4J.js +17 -0
  71. package/dist/chunk-XE4W5YTE.js +2 -0
  72. package/dist/chunk-XUYIK4TX.js +1 -0
  73. package/dist/{chunk-ZJQRLVVV.js → chunk-Y74EKJOY.js} +1 -1
  74. package/dist/{chunk-AAC77UD4.js → chunk-YPYROPQF.js} +1 -1
  75. package/dist/chunk-ZXO4D5UB.js +1 -0
  76. package/dist/entry-0.js +1 -1
  77. package/dist/entry-1.js +1 -1
  78. package/dist/entry-10.js +1 -1
  79. package/dist/entry-11.js +1 -1
  80. package/dist/entry-12.js +1 -1
  81. package/dist/entry-13.js +1 -1
  82. package/dist/entry-14.js +1 -1
  83. package/dist/entry-15.js +1 -1
  84. package/dist/entry-16.js +1 -1
  85. package/dist/entry-17.js +1 -1
  86. package/dist/entry-18.js +1 -1
  87. package/dist/entry-19.js +1 -1
  88. package/dist/entry-2.js +1 -1
  89. package/dist/entry-20.js +1 -1
  90. package/dist/entry-21.js +1 -0
  91. package/dist/entry-23.js +1 -1
  92. package/dist/entry-24.js +1 -1
  93. package/dist/entry-25.js +1 -1
  94. package/dist/entry-26.js +1 -1
  95. package/dist/entry-27.js +1 -1
  96. package/dist/entry-28.js +1 -1
  97. package/dist/entry-29.js +1 -2
  98. package/dist/entry-3.js +1 -1
  99. package/dist/entry-30.js +2 -1
  100. package/dist/entry-31.js +1 -4
  101. package/dist/entry-32.js +1 -1
  102. package/dist/entry-33.js +1 -1
  103. package/dist/entry-34.js +1 -1
  104. package/dist/entry-35.js +1 -18
  105. package/dist/entry-36.js +1 -1
  106. package/dist/entry-37.js +15 -1
  107. package/dist/entry-38.js +1 -1
  108. package/dist/entry-39.js +1 -1
  109. package/dist/entry-4.js +1 -1
  110. package/dist/entry-40.js +1 -1
  111. package/dist/entry-41.js +1 -1
  112. package/dist/entry-42.js +1 -1
  113. package/dist/entry-43.js +1 -1
  114. package/dist/entry-44.js +1 -1
  115. package/dist/entry-45.js +1 -1
  116. package/dist/entry-46.js +1 -1
  117. package/dist/entry-47.js +1 -1
  118. package/dist/entry-48.js +1 -1
  119. package/dist/entry-49.js +1 -25
  120. package/dist/entry-5.js +1 -1
  121. package/dist/entry-50.js +1 -1
  122. package/dist/entry-51.js +1 -1
  123. package/dist/entry-52.js +1 -1
  124. package/dist/entry-53.js +1 -1
  125. package/dist/entry-54.js +1 -3
  126. package/dist/entry-55.js +1 -13
  127. package/dist/entry-56.js +1 -1
  128. package/dist/entry-57.js +1 -1
  129. package/dist/entry-58.js +1 -1
  130. package/dist/entry-59.js +1 -1
  131. package/dist/entry-6.js +1 -1
  132. package/dist/entry-60.js +1 -1
  133. package/dist/entry-61.js +1 -1
  134. package/dist/entry-62.js +1 -1
  135. package/dist/entry-63.js +1 -1
  136. package/dist/entry-64.js +1 -1
  137. package/dist/entry-65.js +1 -0
  138. package/dist/entry-66.js +1 -1
  139. package/dist/entry-68.js +1 -1
  140. package/dist/entry-69.js +0 -1
  141. package/dist/entry-7.js +1 -1
  142. package/dist/entry-70.js +1 -1
  143. package/dist/entry-71.js +1 -1
  144. package/dist/entry-72.js +1 -1
  145. package/dist/entry-73.js +1 -1
  146. package/dist/entry-74.js +1 -1
  147. package/dist/entry-75.js +1 -0
  148. package/dist/entry-76.js +1 -1
  149. package/dist/entry-78.js +1 -1
  150. package/dist/entry-79.js +0 -1
  151. package/dist/entry-8.js +1 -1
  152. package/dist/entry-80.js +1 -1
  153. package/dist/entry-81.js +1 -80
  154. package/dist/entry-82.js +1 -22
  155. package/dist/entry-83.js +1 -2
  156. package/dist/entry-84.js +1 -1
  157. package/dist/entry-85.js +2 -1
  158. package/dist/entry-86.js +1 -1
  159. package/dist/entry-87.js +1 -1
  160. package/dist/entry-88.js +1 -3
  161. package/dist/entry-89.js +1 -1
  162. package/dist/entry-9.js +1 -1
  163. package/dist/entry-90.js +3 -1
  164. package/dist/entry-91.js +1 -1
  165. package/dist/entry-92.js +1 -0
  166. package/dist/entry-93.js +1 -0
  167. package/dist/pi-agent-ide.js +10 -34
  168. package/docs/agent-guides/ast-search.md +58 -0
  169. package/docs/agent-guides/debugger.md +1 -1
  170. package/docs/agent-guides/editing.md +26 -58
  171. package/docs/agent-guides/git-changes.md +4 -14
  172. package/docs/agent-guides/search.md +38 -0
  173. package/docs/agent-guides/ssh.md +17 -49
  174. package/docs/agent-guides/terminal.md +9 -15
  175. package/docs/configuration.md +9 -13
  176. package/docs/extensions.md +82 -0
  177. package/docs/settings-help.md +2 -2
  178. package/docs/structured-results.md +33 -11
  179. package/docs/tools.md +23 -22
  180. package/node_modules/pi-agent-doctor/package.json +7 -7
  181. package/node_modules/pi-agent-doctor/src/workspace.ts +0 -5
  182. package/node_modules/pi-agent-documentation/package.json +2 -2
  183. package/node_modules/pi-agent-documentation/runtime/entry-29.js +1 -0
  184. package/node_modules/pi-agent-documentation/src/index.ts +26 -10
  185. package/node_modules/pi-agent-filesystem/index.ts +1 -1
  186. package/node_modules/pi-agent-filesystem/package.json +8 -8
  187. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  188. package/node_modules/pi-agent-filesystem-jq/index.ts +9 -63
  189. package/node_modules/pi-agent-filesystem-jq/package.json +12 -6
  190. package/node_modules/pi-agent-filesystem-jq/runtime/entry-32.js +1 -0
  191. package/node_modules/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  192. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  193. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-34.js +2 -0
  194. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  195. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  196. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +13 -1
  197. package/node_modules/pi-agent-ide-ast/src/extension.ts +8 -8
  198. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  199. package/node_modules/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  200. package/node_modules/pi-agent-ide-changes/index.ts +1 -2
  201. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  202. package/node_modules/pi-agent-ide-changes/runtime/entry-38.js +1 -0
  203. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  204. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  205. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  206. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  207. package/node_modules/pi-agent-ide-lint/runtime/entry-42.js +2 -0
  208. package/node_modules/pi-agent-ide-lsp/index.ts +22 -28
  209. package/node_modules/pi-agent-ide-lsp/package.json +14 -10
  210. package/node_modules/pi-agent-ide-lsp/runtime/entry-43.js +2 -0
  211. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  212. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  213. package/node_modules/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  214. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  215. package/node_modules/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  216. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  217. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  218. package/node_modules/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  219. package/node_modules/pi-agent-image/package.json +3 -3
  220. package/node_modules/pi-agent-image/src/image-converter.ts +24 -1
  221. package/node_modules/pi-agent-invariant/package.json +2 -2
  222. package/node_modules/pi-agent-pdf/package.json +3 -3
  223. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +23 -1
  224. package/node_modules/pi-agent-read/package.json +12 -12
  225. package/node_modules/pi-agent-read/runtime/entry-49.js +0 -1
  226. package/node_modules/pi-agent-read/runtime/entry-51.js +2 -0
  227. package/node_modules/pi-agent-read/src/api/read-parameters.ts +4 -7
  228. package/node_modules/pi-agent-read/src/api/tools/read.ts +2 -0
  229. package/node_modules/pi-agent-read/src/core/extension.ts +0 -8
  230. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  231. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  232. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  233. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  234. package/node_modules/pi-agent-resource/package.json +2 -2
  235. package/node_modules/pi-agent-resource/src/index.ts +8 -0
  236. package/node_modules/pi-agent-resource/src/resource-error-metadata.ts +89 -0
  237. package/node_modules/pi-agent-resource/src/resource-error.ts +6 -1
  238. package/node_modules/pi-agent-resource/src/result-images.ts +87 -0
  239. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -3
  240. package/node_modules/pi-agent-resource/src/tool-result.ts +17 -0
  241. package/node_modules/pi-agent-search/package.json +9 -9
  242. package/node_modules/pi-agent-search/runtime/entry-54.js +0 -1
  243. package/node_modules/pi-agent-search/runtime/entry-55.js +1 -0
  244. package/node_modules/pi-agent-search/runtime/entry-56.js +2 -0
  245. package/node_modules/pi-agent-search/src/api/glob-list.ts +35 -0
  246. package/node_modules/pi-agent-search/src/api/search-parameters.ts +8 -8
  247. package/node_modules/pi-agent-search/src/api/search.ts +14 -2
  248. package/node_modules/pi-agent-search/src/core/extension.ts +11 -20
  249. package/node_modules/pi-agent-search/src/core/search-core.ts +30 -10
  250. package/node_modules/pi-agent-search-text/index.ts +34 -12
  251. package/node_modules/pi-agent-search-text/package.json +17 -15
  252. package/node_modules/pi-agent-search-text/runtime/entry-57.js +1 -0
  253. package/node_modules/pi-agent-search-text/runtime/entry-60.js +1 -0
  254. package/node_modules/pi-agent-search-text/src/file-search.ts +59 -25
  255. package/node_modules/pi-agent-search-text/src/resolvers.ts +61 -16
  256. package/node_modules/pi-agent-search-text/src/scoped-search.ts +9 -3
  257. package/node_modules/pi-agent-search-text/src/search-backend.ts +44 -48
  258. package/node_modules/pi-agent-search-text/src/search-presentation.ts +19 -15
  259. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -1
  260. package/node_modules/pi-agent-search-text/src/search-result.ts +6 -2
  261. package/node_modules/pi-agent-search-text/src/search-session.ts +1 -0
  262. package/node_modules/pi-agent-search-text/src/tool-file-search.ts +146 -0
  263. package/node_modules/pi-agent-text/package.json +3 -3
  264. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  265. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  266. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  267. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  268. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +1 -2
  269. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  270. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-66.js +2 -0
  271. package/node_modules/pi-agent-text-editor/package.json +26 -26
  272. package/node_modules/pi-agent-text-editor/runtime/entry-81.js +0 -1
  273. package/node_modules/pi-agent-text-editor/runtime/entry-82.js +1 -0
  274. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  275. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  276. package/node_modules/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  277. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  278. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  279. package/node_modules/pi-agent-text-editor/src/core/extension.ts +13 -7
  280. package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  281. package/node_modules/pi-agent-text-editor/src/core/image-write.ts +111 -0
  282. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  283. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  284. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  285. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  286. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  287. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  288. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +43 -12
  289. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  290. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -5
  291. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +3 -7
  292. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +6 -8
  293. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -6
  294. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  295. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  296. package/node_modules/pi-agent-text-editor-renderer/index.ts +6 -1
  297. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  298. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-84.js +2 -0
  299. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  300. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -6
  301. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-85.js +2 -0
  302. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  303. package/node_modules/pi-agent-tool-ui/package.json +3 -3
  304. package/node_modules/pi-agent-tool-ui/runtime/entry-87.js +1 -0
  305. package/node_modules/pi-agent-tool-ui/runtime/entry-88.js +1 -0
  306. package/node_modules/pi-agent-web/index.ts +28 -6
  307. package/node_modules/pi-agent-web/package.json +8 -8
  308. package/node_modules/pi-agent-web-html/package.json +3 -3
  309. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  310. package/node_modules/pi-agent-web-image/package.json +4 -4
  311. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  312. package/node_modules/pi-agent-web-pdf/runtime/entry-92.js +2 -0
  313. package/node_modules/pi-agent-web-text/package.json +4 -4
  314. package/node_modules/pi-agent-web-text/runtime/entry-93.js +2 -0
  315. package/package.json +61 -58
  316. package/src/api/approval.ts +2 -0
  317. package/src/api/read.ts +2 -0
  318. package/src/api/standalone.ts +7 -0
  319. package/src/backend/doctor-workspace.ts +0 -3
  320. package/src/backend/process-metadata-worker.py +9 -18
  321. package/src/backend/process-metadata.ts +11 -44
  322. package/src/backend/registration.ts +0 -10
  323. package/src/backend/web-browser-worker.mjs +2 -17
  324. package/src/backend/web-browser.ts +1 -26
  325. package/src/composite/builtin-extensions.ts +8 -6
  326. package/src/composite/ide-alias-rendering.ts +18 -2
  327. package/src/composite/module-labels.ts +0 -4
  328. package/src/composite/preferences.ts +0 -36
  329. package/src/composite/settings-documentation.ts +1 -2
  330. package/src/composite/text-results.ts +61 -23
  331. package/src/documentation/extension.ts +39 -15
  332. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +1 -1
  333. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  334. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  335. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +9 -63
  336. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +12 -6
  337. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-32.js +1 -0
  338. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  339. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  340. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-34.js +2 -0
  341. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  342. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-35.js +2 -0
  343. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-30.js +2 -0
  344. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -6
  345. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  346. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  347. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  348. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  349. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  350. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-92.js +2 -0
  351. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  352. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-93.js +2 -0
  353. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-89.js +2 -0
  354. package/src/extensions/pi-agent-read/package.json +12 -12
  355. package/src/extensions/pi-agent-read/runtime/entry-49.js +0 -1
  356. package/src/extensions/pi-agent-read/runtime/entry-50.js +1 -0
  357. package/src/extensions/pi-agent-read/runtime/entry-51.js +2 -0
  358. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +4 -7
  359. package/src/extensions/pi-agent-read/src/api/tools/read.ts +2 -0
  360. package/src/extensions/pi-agent-read/src/core/extension.ts +0 -8
  361. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  362. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  363. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  364. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  365. package/src/extensions/pi-agent-search/package.json +9 -9
  366. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +34 -12
  367. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +17 -15
  368. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +1 -0
  369. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-59.js +1 -0
  370. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-60.js +1 -0
  371. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +59 -25
  372. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +61 -16
  373. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +9 -3
  374. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +44 -48
  375. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +19 -15
  376. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -1
  377. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +6 -2
  378. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +1 -0
  379. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/tool-file-search.ts +146 -0
  380. package/src/extensions/pi-agent-search/runtime/entry-54.js +0 -1
  381. package/src/extensions/pi-agent-search/runtime/entry-55.js +1 -0
  382. package/src/extensions/pi-agent-search/runtime/entry-56.js +2 -0
  383. package/src/extensions/pi-agent-search/src/api/glob-list.ts +35 -0
  384. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +8 -8
  385. package/src/extensions/pi-agent-search/src/api/search.ts +14 -2
  386. package/src/extensions/pi-agent-search/src/core/extension.ts +11 -20
  387. package/src/extensions/pi-agent-search/src/core/search-core.ts +30 -10
  388. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  389. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  390. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  391. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  392. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +1 -2
  393. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  394. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-65.js +1 -0
  395. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-66.js +2 -0
  396. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +6 -1
  397. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  398. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-84.js +2 -0
  399. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  400. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -6
  401. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-85.js +2 -0
  402. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +0 -1
  403. package/src/extensions/pi-agent-text-editor/runtime/entry-82.js +1 -0
  404. package/src/extensions/pi-agent-text-editor/runtime/entry-83.js +2 -0
  405. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  406. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  407. package/src/extensions/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  408. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  409. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  410. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +13 -7
  411. package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  412. package/src/extensions/pi-agent-text-editor/src/core/image-write.ts +111 -0
  413. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  414. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  415. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  416. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  417. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  418. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  419. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +43 -12
  420. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  421. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -5
  422. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +3 -7
  423. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +6 -8
  424. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -6
  425. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  426. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  427. package/src/pi-agent-ide.ts +8 -15
  428. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  429. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +13 -1
  430. package/src/plugins/pi-agent-ide-ast/src/extension.ts +8 -8
  431. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  432. package/src/plugins/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  433. package/src/plugins/pi-agent-ide-changes/index.ts +1 -2
  434. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  435. package/src/plugins/pi-agent-ide-changes/runtime/entry-38.js +1 -0
  436. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  437. package/src/plugins/pi-agent-ide-debugger/index.ts +17 -4
  438. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +2 -11
  439. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  440. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  441. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  442. package/src/plugins/pi-agent-ide-lint/runtime/entry-42.js +2 -0
  443. package/src/plugins/pi-agent-ide-lsp/index.ts +22 -28
  444. package/src/plugins/pi-agent-ide-lsp/package.json +14 -10
  445. package/src/plugins/pi-agent-ide-lsp/runtime/entry-43.js +2 -0
  446. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  447. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  448. package/src/plugins/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  449. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  450. package/src/plugins/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  451. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  452. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  453. package/src/plugins/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  454. package/src/plugins/pi-agent-ide-processes/src/ui.ts +61 -16
  455. package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
  456. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +10 -7
  457. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -3
  458. package/src/standalone/resource-host.ts +147 -0
  459. package/src/standalone/scoped-api.ts +457 -0
  460. package/dist/chunk-2RTCSZB3.js +0 -1
  461. package/dist/chunk-4DIUPEDF.js +0 -2
  462. package/dist/chunk-6EDOLYOV.js +0 -1
  463. package/dist/chunk-6FGLAVPJ.js +0 -1
  464. package/dist/chunk-6H32W35W.js +0 -1
  465. package/dist/chunk-6OJ565FL.js +0 -2
  466. package/dist/chunk-6R3Y4AD3.js +0 -1
  467. package/dist/chunk-6TJPMBUQ.js +0 -1
  468. package/dist/chunk-6XFUICD7.js +0 -1
  469. package/dist/chunk-BHSO2MDK.js +0 -6
  470. package/dist/chunk-GSOYVIQS.js +0 -1
  471. package/dist/chunk-HSRH76JN.js +0 -3
  472. package/dist/chunk-HSZ4AQ6L.js +0 -9
  473. package/dist/chunk-I6NPILT5.js +0 -1
  474. package/dist/chunk-K7SRNBIV.js +0 -1
  475. package/dist/chunk-LCWBVOII.js +0 -3
  476. package/dist/chunk-MKEC3U2M.js +0 -4
  477. package/dist/chunk-NUM3YQGK.js +0 -1
  478. package/dist/chunk-OM4LYD3S.js +0 -1
  479. package/dist/chunk-PLKYHUNT.js +0 -1
  480. package/dist/chunk-QIJMV2P2.js +0 -2
  481. package/dist/chunk-RVU73VKN.js +0 -2
  482. package/dist/chunk-SDAH3ECM.js +0 -5
  483. package/dist/chunk-SGQWRIRJ.js +0 -10
  484. package/dist/chunk-SWBJS3U4.js +0 -1
  485. package/dist/chunk-T7I2VX3J.js +0 -1
  486. package/dist/chunk-T7MWQQIF.js +0 -3
  487. package/dist/chunk-UEVGZUII.js +0 -3
  488. package/dist/chunk-VDP5CQHM.js +0 -3
  489. package/dist/chunk-XG7QNAKW.js +0 -9
  490. package/dist/chunk-XLWCSJMR.js +0 -1
  491. package/dist/chunk-YFP4P2FV.js +0 -1
  492. package/dist/chunk-YIXP2ALP.js +0 -9
  493. package/dist/entry-22.js +0 -1
  494. package/docs/agent-guides/diagnostics.md +0 -5
  495. package/docs/agent-guides/json-reading.md +0 -57
  496. package/docs/agent-guides/read-resources.md +0 -17
  497. package/docs/agent-guides/search-code.md +0 -76
  498. package/docs/agent-guides/select-code.md +0 -119
  499. package/docs/agent-guides/vision.md +0 -11
  500. package/node_modules/pi-agent-doctor/runtime/entry-22.js +0 -1
  501. package/node_modules/pi-agent-filesystem/runtime/entry-29.js +0 -2
  502. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-32.js +0 -2
  503. package/node_modules/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  504. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  505. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  506. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  507. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  508. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  509. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +0 -387
  510. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +0 -41
  511. package/node_modules/pi-agent-ide-ast/src/source-text.ts +0 -92
  512. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +0 -214
  513. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +0 -277
  514. package/node_modules/pi-agent-ide-formatter/runtime/entry-38.js +0 -2
  515. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  516. package/node_modules/pi-agent-image/runtime/entry-42.js +0 -1
  517. package/node_modules/pi-agent-invariant/runtime/entry-43.js +0 -1
  518. package/node_modules/pi-agent-search/runtime/entry-51.js +0 -1
  519. package/node_modules/pi-agent-search-text/runtime/entry-55.js +0 -2
  520. package/node_modules/pi-agent-search-text/runtime/entry-56.js +0 -1
  521. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  522. package/node_modules/pi-agent-text-editor/runtime/entry-66.js +0 -1
  523. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  524. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +0 -1
  525. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +0 -1
  526. package/node_modules/pi-agent-web/runtime/entry-87.js +0 -2
  527. package/node_modules/pi-agent-web-html/runtime/entry-88.js +0 -2
  528. package/src/backend/vision-capture-worker.py +0 -319
  529. package/src/backend/vision-capture.ts +0 -165
  530. package/src/backend/vision-registration.ts +0 -104
  531. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  532. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-32.js +0 -2
  533. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +0 -2
  534. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-88.js +0 -2
  535. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +0 -2
  536. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +0 -2
  537. package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
  538. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  539. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +0 -2
  540. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +0 -1
  541. package/src/extensions/pi-agent-search/runtime/entry-51.js +0 -1
  542. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  543. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  544. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-61.js +0 -1
  545. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  546. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  547. package/src/extensions/pi-agent-text-editor/runtime/entry-65.js +0 -1
  548. package/src/extensions/pi-agent-text-editor/runtime/entry-66.js +0 -1
  549. package/src/plugins/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  550. package/src/plugins/pi-agent-ide-ast/runtime/entry-35.js +0 -2
  551. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  552. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  553. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  554. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  555. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  556. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +0 -387
  557. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +0 -41
  558. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +0 -92
  559. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +0 -214
  560. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +0 -277
  561. package/src/plugins/pi-agent-ide-formatter/runtime/entry-38.js +0 -2
  562. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  563. package/src/plugins/pi-agent-ide-vision/index.ts +0 -439
  564. package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +0 -47
  565. package/src/plugins/pi-agent-ide-vision/src/vision.ts +0 -585
  566. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +0 -30
  567. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +0 -33
  568. /package/dist/{chunk-U2JKHKLK.js → chunk-3PMHFEJY.js} +0 -0
  569. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-28.js +0 -0
  570. /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-30.js +0 -0
  571. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-31.js +0 -0
  572. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-33.js +0 -0
  573. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-text}/runtime/entry-35.js +0 -0
  574. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-36.js +0 -0
  575. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-37.js +0 -0
  576. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-39.js +0 -0
  577. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-40.js +0 -0
  578. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-41.js +0 -0
  579. /package/node_modules/{pi-agent-pdf → pi-agent-image}/runtime/entry-44.js +0 -0
  580. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-45.js +0 -0
  581. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-46.js +0 -0
  582. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-50.js +0 -0
  583. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-52.js +0 -0
  584. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-59.js +0 -0
  585. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-61.js +0 -0
  586. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-62.js +0 -0
  587. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-63.js +0 -0
  588. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-64.js +0 -0
  589. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-65.js +0 -0
  590. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-83.js +0 -0
  591. /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-86.js +0 -0
  592. /package/node_modules/{pi-agent-web-image → pi-agent-web}/runtime/entry-89.js +0 -0
  593. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-90.js +0 -0
  594. /package/node_modules/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-91.js +0 -0
  595. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-31.js +0 -0
  596. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-33.js +0 -0
  597. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-90.js +0 -0
  598. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-91.js +0 -0
  599. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-62.js +0 -0
  600. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-63.js +0 -0
  601. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-64.js +0 -0
  602. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-36.js +0 -0
  603. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-37.js +0 -0
  604. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-39.js +0 -0
  605. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-40.js +0 -0
  606. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-41.js +0 -0
@@ -1,11 +1,11 @@
1
- import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-XLWCSJMR.js";import{h as w,i as P,j as B}from"./chunk-LCWBVOII.js";import{a as u}from"./chunk-EI7MMDWY.js";import{Allow as D}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as W,parse as U}from"partial-json";function O(o,e=W.ALL){if(!(!o||o.trim().length===0))try{let t=U(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}u(O,"resolvePartial");var R=class{static{u(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),i=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let y=e.isCompleteEntry?.(c,t)??c.complete;return y||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:y}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let m=[];for(let c of s)try{e.validateEntry?.(c,t),m.push(c)}catch(y){n.push({index:c.index,reason:y instanceof Error?y.message:String(y)})}let g={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(m.length===0)return{...g,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(m,t),y=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...g,status:"recovered",appliedEntries:e.getAppliedEntries?.(y,m,t)??m.map(C=>C.index),skippedEntries:n,normalResult:y}}catch(c){return{...g,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as Q}from"@earendil-works/pi-ai";var j=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function $(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=u((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let m=u(p=>{let f=s.modelRegistry.getRegisteredNativeProvider(i.provider);if(f)o.registerProvider(K(f,p));else{let v=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...v,api:i.api,streamSimple:p})}},"register"),g=r.get(i.provider);if(g){if(g.subscribers.add(a),g.api===i.api&&d.streamSimple===g.wrapper)return;g.api=i.api,m(g.wrapper);return}let c=d.streamSimple[j];if(c){if(c.subscribers.add(a),r.set(i.provider,c),c.api===i.api)return;c.api=i.api,m(c.wrapper);return}let y=d.streamSimple.bind(d),C=new Set([a]),E=u((p,f,v)=>q(y,p,f,v,C),"wrapper"),b={api:i.api,originalStreamSimple:d.streamSimple,wrapper:E,subscribers:C};E[j]=b,m(E),r.set(i.provider,b)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r){if(s.subscribers.delete(a),s.subscribers.size!==0)continue;let d=a.context?.modelRegistry;if(d?.getProvider(i)?.streamSimple!==s.wrapper)continue;let g=d?.getRegisteredNativeProvider(i);g?o.registerProvider(K(g,s.originalStreamSimple)):o.unregisterProvider(i)}r.clear(),a.context=void 0})}u($,"registerStreamingInterceptorProvider");function K(o,e){return Object.create(Object.getPrototypeOf(o),{...Object.getOwnPropertyDescriptors(o),streamSimple:{value:e,writable:!0,enumerable:!0,configurable:!0}})}u(K,"withStreamSimple");function q(o,e,t,n,r){let a=Q(),l=new AbortController,i=n?.signal,s=!1,d=Z(e),m=new Set,g=new Set,c=new Set,y=new Set,C=u(b=>{for(let p of r)p.markStreamEventProcessed(b)},"markStreamEventProcessed"),E=u(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let b=o(e,t,{...n,signal:l.signal});for await(let p of b){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),J(p,m);let f;for(let v of r){let I=v.context;if(I){let T=await v.processStreamEvent(p,I);f??=T}}if(C(p),V(p,g,c,y),a.push(structuredClone(p)),f){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);s=!0,l.abort();let v=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,S)=>m.has(S)&&(v===void 0||S<=v||y.has(S))).map(x=>x.type==="toolCall"&&x.id===f.toolCallId?{...x,arguments:structuredClone(f.arguments)}:x)};Y(a,C,I,m,g,c,y);let{errorMessage:T,...H}=I;a.push({type:"done",reason:"toolUse",message:{...H,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(b){if(s)return;let p=d,f=i?.aborted===!0?"aborted":"error",v={...p,stopReason:f,errorMessage:b instanceof Error?b.message:String(b)};a.push({type:"error",reason:f,error:v}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}u(q,"wrapStream");function J(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}u(J,"rememberStartEvent");function V(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}u(V,"rememberEndEvent");function Y(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}u(Y,"emitMissingEndEvents");function Z(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}u(Z,"emptyAssistantMessage");var ee="agentic-ide-partial-tool-recovery",L="pi-agent-text-editor/tool-call-annotation",A=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
- `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
3
- `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(i,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role==="toolResult"){let r=this.toolCallRecords.get(t.message.toolCallId),a=r?.blockExecution?r.guardResult:void 0;if(a){this.toolCallRecords.delete(t.message.toolCallId);let l=a.details;l!==void 0&&w(l);let i=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return i!==void 0&&this.completedBatchEntryIndexes.add(i),{message:{...t.message,content:a.content,...l!==void 0&&{details:l},isError:!0}}}}if(t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{u(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=O(a,D.OBJ|D.ARR)??{},i=ne(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let m=i!==void 0;if(m&&this.completeArgumentContentIndices.has(e.contentIndex))return;m&&this.completeArgumentContentIndices.add(e.contentIndex);let g=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:g},args:g,...!m&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=G(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=G(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(L,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=te(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let i={content:[{type:"text",text:e.message.content}],details:M(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:i,...r&&{blockExecution:!0}}),i}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,s=(h.IsObjectNotArray(l)&&h.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(y=>y.ctx.batchEntryIndex).filter(y=>y!==void 0))],s=[...new Set(r.map(y=>y.ctx.toolCall.id))],d=r.map(y=>y.blocked.message.details),m=r[0],g=m?this.recoveryRegistry.recoveryKeyFor(m.ctx.toolCall.name):void 0;if(!g)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:g,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?ae(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=u(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function G(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}u(G,"toolStreamEventKey");function te(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}u(te,"abortReason");function ne(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}u(ne,"parseCompleteArguments");function re(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(s=>h.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(m=>typeof m=="string"):[]});return[...new Set(i)]}u(re,"freshAnchorsAfterRecovery");function oe(o,e){let n=o.indexOf(`
1
+ import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-GS5ZRTUG.js";import{l as w,m as P,n as B}from"./chunk-DDH3FP4G.js";import{a as m}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as h}from"typebox-guard/guard";import{Allow as W,parse as U}from"partial-json";function O(o,e=W.ALL){if(!(!o||o.trim().length===0))try{let t=U(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}m(O,"resolvePartial");var S=class{static{m(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),d=e.extractEntries(t).filter(u=>{if(r.has(u.index))return n.push({index:u.index,reason:"entry already completed before recovery"}),!1;if(a.has(u.index))return n.push({index:u.index,reason:"entry was blocked by a guard"}),!1;let p=e.isCompleteEntry?.(u,t)??u.complete;return p||n.push({index:u.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&u.index>=t.staleEntryIndex?!1:p}),l=e.filterEntries?.(d,t)??d,s=new Set(l.map(u=>u.index));for(let u of d)s.has(u.index)||n.push({index:u.index,reason:"entry was excluded by recovery filtering"});let c=[];for(let u of l)try{e.validateEntry?.(u,t),c.push(u)}catch(p){n.push({index:u.index,reason:p instanceof Error?p.message:String(p)})}let g={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(c.length===0)return{...g,status:"skipped",appliedEntries:[],skippedEntries:n};try{let u=e.buildParams(c,t),p=await e.execute(u,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...g,status:"recovered",appliedEntries:e.getAppliedEntries?.(p,c,t)??c.map(v=>v.index),skippedEntries:n,normalResult:p}}catch(u){return{...g,status:"failed",appliedEntries:[],skippedEntries:n,error:u instanceof Error?u.message:String(u)}}}};import{createAssistantMessageEventStream as Q}from"@earendil-works/pi-ai";var j=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},i=m((s,c)=>{if(!s)return;let g=c.modelRegistry.getProvider(s.provider);if(!g)return;let u=m(f=>{let x=c.modelRegistry.getRegisteredNativeProvider(s.provider);if(x)o.registerProvider(D(x,f));else{let I=c.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...I,api:s.api,streamSimple:f})}},"register"),p=r.get(s.provider);if(p){if(p.subscribers.add(a),p.api===s.api&&g.streamSimple===p.wrapper)return;p.api=s.api,u(p.wrapper);return}let v=g.streamSimple[j];if(v){if(v.subscribers.add(a),r.set(s.provider,v),v.api===s.api)return;v.api=s.api,u(v.wrapper);return}let R=g.streamSimple.bind(g),C=new Set([a]),y=m((f,x,I)=>q(R,f,x,I,C),"wrapper"),b={api:s.api,originalStreamSimple:g.streamSimple,wrapper:y,subscribers:C};y[j]=b,u(y),r.set(s.provider,b)},"install"),d=!1,l=m((s,c)=>{d||(a.context=s,i(c??s.model,s))},"attach");o.on("before_provider_request",(s,c)=>l(c)),o.on("turn_start",(s,c)=>l(c)),o.on("agent_start",(s,c)=>l(c)),o.on("session_start",(s,c)=>{d=!1,l(c)}),o.on("model_select",(s,c)=>l(c,s.model)),o.on("session_shutdown",()=>{d=!0;for(let[s,c]of r){if(c.subscribers.delete(a),c.subscribers.size!==0)continue;let g=a.context?.modelRegistry;if(g?.getProvider(s)?.streamSimple!==c.wrapper)continue;let p=g?.getRegisteredNativeProvider(s);p?o.registerProvider(D(p,c.originalStreamSimple)):o.unregisterProvider(s)}r.clear(),a.context=void 0})}m(K,"registerStreamingInterceptorProvider");function D(o,e){return Object.create(Object.getPrototypeOf(o),{...Object.getOwnPropertyDescriptors(o),streamSimple:{value:e,writable:!0,enumerable:!0,configurable:!0}})}m(D,"withStreamSimple");function q(o,e,t,n,r){let a=Q(),i=new AbortController,d=n?.signal,l=!1,s=Z(e),c=new Set,g=new Set,u=new Set,p=new Set,v=m(C=>{for(let y of r)y.markStreamEventProcessed(C)},"markStreamEventProcessed"),R=m(()=>{i.abort()},"abortFromParent");return d&&(d.aborted?i.abort():d.addEventListener("abort",R,{once:!0})),(async()=>{try{let C=o(e,t,{...n,signal:i.signal});for await(let y of C){if(l)continue;y.type==="done"?s=structuredClone(y.message):y.type==="error"?s=structuredClone(y.error):s=structuredClone(y.partial),J(y,c);let b;for(let f of r){let x=f.context;if(x){let I=await f.processStreamEvent(y,x);b??=I}}if(v(y),V(y,g,u,p),a.push(structuredClone(y)),b){if(y.type==="toolcall_delta"||y.type==="toolcall_end")for(let E of r)E.finalizeStreamInterception(y.contentIndex);l=!0,i.abort();let f=y.type==="toolcall_delta"||y.type==="toolcall_end"?y.contentIndex:void 0,x={...s,content:s.content.filter((E,A)=>c.has(A)&&(f===void 0||A<=f||p.has(A))).map(E=>E.type==="toolCall"&&E.id===b.toolCallId?{...E,arguments:structuredClone(b.arguments)}:E)};Y(a,v,x,c,g,u,p);let{errorMessage:I,...H}=x;a.push({type:"done",reason:"toolUse",message:{...H,stopReason:"toolUse"}}),a.end();continue}if(y.type==="done"||y.type==="error"){a.end();return}}}catch(C){if(l)return;let y=s,b=d?.aborted===!0?"aborted":"error",f={...y,stopReason:b,errorMessage:C instanceof Error?C.message:String(C)};a.push({type:"error",reason:b,error:f}),a.end()}finally{d?.removeEventListener("abort",R)}})(),a}m(q,"wrapStream");function J(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}m(J,"rememberStartEvent");function V(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}m(V,"rememberEndEvent");function Y(o,e,t,n,r,a,i){for(let[d,l]of t.content.entries())if(n.has(d)){if(l.type==="text"&&!r.has(d)){let s={type:"text_end",contentIndex:d,content:l.text,partial:t};e(s),o.push(s)}else if(l.type==="thinking"&&!a.has(d)){let s={type:"thinking_end",contentIndex:d,content:l.thinking,partial:t};e(s),o.push(s)}else if(l.type==="toolCall"&&!i.has(d)){let s={type:"toolcall_end",contentIndex:d,toolCall:l,partial:t};e(s),o.push(s)}}}m(Y,"emitMissingEndEvents");function Z(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}m(Z,"emptyAssistantMessage");var ee="agentic-ide-partial-tool-recovery",L="pi-agent-text-editor/tool-call-annotation",k=new WeakMap,T=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(i=>i.type==="text").map(i=>i.text).join(`
2
+ `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,i=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",d=r.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
3
+ `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(d,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:i,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role==="toolResult"){let r=this.toolCallRecords.get(t.message.toolCallId),a=r?.blockExecution?r.guardResult:void 0;if(a){this.toolCallRecords.delete(t.message.toolCallId);let i=a.details;i!==void 0&&w(i);let d=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return d!==void 0&&this.completedBatchEntryIndexes.add(d),{message:{...t.message,content:a.content,...i!==void 0&&{details:i},isError:!0}}}}if(t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{m(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new S;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let i=O(a,$.OBJ|$.ARR)??{},d=ne(a),l=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:l,toolName:n,args:i,complete:d!==void 0});let s=this.handlers.get(n);if(!r||!s||s.length===0||!d&&Object.keys(i).length===0)return;let c=d!==void 0;if(c&&this.completeArgumentContentIndices.has(e.contentIndex))return;c&&this.completeArgumentContentIndices.add(e.contentIndex);let g=d??i,u=await this.dispatchHandlers(s,{toolCall:{id:r,name:n,arguments:g},args:g,...!c&&{partialArgs:i},batchEntryIndex:l,batchEntries:this.getBatchEntries(l),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return u&&this.rememberOriginalArguments(u.toolCallId,u.arguments),u}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let i=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...i?.guardResult&&{guardResult:i.guardResult},...i?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let d=!this.completeArgumentContentIndices.has(e.contentIndex),l;d&&(this.completeArgumentContentIndices.add(e.contentIndex),l=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let s=this.streamedBatchEntries.get(e.contentIndex);return s&&this.streamedBatchEntries.set(e.contentIndex,{...s,complete:!0}),this.cleanupContent(e.contentIndex,n),l}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=G(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=G(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(L,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=te(e,n),i=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,i));let d={content:[{type:"text",text:e.message.content}],details:M(e.message.details,i,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:d,...r&&{blockExecution:!0}}),d}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let i=a.message.details,l=(h.IsObjectNotArray(i)&&h.IsObjectNotArray(i.recovery)?i.recovery:void 0)?.appliedEntries;if(Array.isArray(l))for(let s of l)typeof s=="number"&&this.recoveryAppliedBatchIndexes.add(s)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,i=h.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,d=[...new Set(r.map(p=>p.ctx.batchEntryIndex).filter(p=>p!==void 0))],l=[...new Set(r.map(p=>p.ctx.toolCall.id))],s=r.map(p=>p.blocked.message.details),c=r[0],g=c?this.recoveryRegistry.recoveryKeyFor(c.ctx.toolCall.name):void 0;if(!g)return e;let u=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...i!==void 0&&{staleEntryIndex:i},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:d,blockedToolCallIds:l,blockedDetails:s,recoveryKey:g,cwd:t.cwd,ctx:t.ctx});return u&&(u.appliedEntries.length>0||u.skippedEntries.length>0)?ae(e,u):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=m(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let i of a??[])i.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let i of a??[])n&&i.onAbort?.(e),i.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(i=>i.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function G(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}m(G,"toolStreamEventKey");function te(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}m(te,"abortReason");function ne(o){try{let e=JSON.parse(o);return h.IsObjectNotArray(e)?e:void 0}catch{return}}m(ne,"parseCompleteArguments");function re(o){let e=o.normalResult;if(!h.IsObjectNotArray(e)||!h.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=h.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(h.IsObjectNotArray).map(l=>h.IsObjectNotArray(l.data)?l.data:l),a=n===void 0?r:r.filter(l=>l.path===n),d=(a.length>0?a:r).flatMap(l=>{let s=l.freshAnchors;return Array.isArray(s)?s.filter(c=>typeof c=="string"):[]});return[...new Set(d)]}m(re,"freshAnchorsAfterRecovery");function oe(o,e){let n=o.indexOf(`
4
4
 
5
5
  Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
6
 
7
7
  Current nearby anchors:
8
8
  ${e.map(a=>` ${a}`).join(`
9
- `)}`}u(oe,"replaceCurrentAnchors");function ae(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(m=>`${m.index} (${m.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=re(e),i=l.length>0&&h.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,s=l.length>0?oe(o.message.content,l):o.message.content,d=l.length>0&&h.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:ee,content:`${s}
9
+ `)}`}m(oe,"replaceCurrentAnchors");function ae(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(c=>`${c.index} (${c.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",i=re(e),d=i.length>0&&h.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:i}:o.message.details,l=i.length>0?oe(o.message.content,i):o.message.content,s=i.length>0&&h.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:i}}:e;return{message:{customType:ee,content:`${l}
10
10
 
11
- [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:i,recovery:d}}}}u(ae,"makeRecoveryResult");var z=new WeakMap;function F(o){let e=z.get(o);if(e)return e;let t=new k(o);return z.set(o,t),$(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}u(F,"coordinatorFor");function se(o,e){F(o).register(e)}u(se,"registerToolCallInterceptor");function ie(o,e){if(A.get(o)?.(),A.delete(o),e===void 0)return;let t=o.events.on(L,n=>{!h.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});A.set(o,t)}u(ie,"registerToolCallAnnotationSink");function Re(o,e){F(o).registerBlockedCallSink(e)}u(Re,"registerBlockedToolCallSink");export{se as a,ie as b,Re as c};
11
+ [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:d,recovery:s}}}}m(ae,"makeRecoveryResult");var z=new WeakMap;function F(o){let e=z.get(o);if(e)return e;let t=new T(o);return z.set(o,t),K(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}m(F,"coordinatorFor");function se(o,e){F(o).register(e)}m(se,"registerToolCallInterceptor");function ie(o,e){if(k.get(o)?.(),k.delete(o),e===void 0)return;let t=o.events.on(L,n=>{!h.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});k.set(o,t)}m(ie,"registerToolCallAnnotationSink");function Re(o,e){F(o).registerBlockedCallSink(e)}m(Re,"registerBlockedToolCallSink");export{se as a,ie as b,Re as c};
@@ -1 +1 @@
1
- import{a as v}from"./chunk-BXGMMZT3.js";import{b as E,c as A,d as j}from"./chunk-756K3LJY.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import F from"cross-spawn";import{access as M,readFile as P,writeFile as D}from"node:fs/promises";import _ from"node:os";import l from"node:path";import{fileURLToPath as U}from"node:url";var N=1;function se(e){return l.win32.basename(h(e[0]))}a(se,"configuredExecutableName");async function ae(e,o,n,r,i){i?.throwIfAborted();let s=l.resolve(e),t=l.resolve(s,o),c=r.filter(d=>H(d,t));if(X(s,t))return s;let f=l.dirname(t);for(;;){if(i?.throwIfAborted(),await Q(S(f,n),i)||[...(await v(f,c,void 0,i)).values()].some(p=>p.score>0))return f;let u=l.dirname(f);if(u===f)return;f=u}}a(ae,"resolveExternalToolProjectRoot");function G(e){return l.join(e,".pi","pi-agent-ide")}a(G,"projectIdeConfigDirectory");function S(e,o){return l.join(G(e),`${o}.json`)}a(S,"projectIdeConfigPath");function B(e,o,n={}){let i=(n.environment??process.env).PI_CODING_AGENT_DIR?.trim(),s=i===void 0||i.length===0?l.join(n.homeDirectory??_.homedir(),".pi","agent"):l.resolve(i);return{project:S(e,o),global:l.join(s,"extensions","pi-agent-ide",`${o}.json`),builtIn:U(new URL(`tool-config/${o}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}a(B,"resolveToolConfigPaths");async function le(e,o,n,r={}){let i=r.signal;i?.throwIfAborted();let s=r.layerAccess;if(e.includes("://")&&!s)throw Object.assign(new Error("No config owner for this project"),{code:"UNSUPPORTED_SOURCE"});let t={...B(e,o,r),...s?await s.paths(e,o,i):{}},c=[{layer:"project",sourcePath:t.project,optional:!0},...r.includeGlobal===!1?[]:[{layer:"global",sourcePath:t.global,optional:!0}],{layer:"built-in",sourcePath:t.builtIn,optional:!1}],f=[],d=new Set;for(let u of c){i?.throwIfAborted();let p=await z(u,o,n,u.layer!=="built-in"&&s?m=>s.readText(m,i):void 0,i);for(let[m,C]of Object.entries(p))d.has(m)||(d.add(m),f.push({id:m,config:C,layer:u.layer,sourcePath:u.sourcePath}))}return{entries:f,paths:t}}a(le,"loadLayeredToolConfig");function J(e,o,n){let r=l.extname(o).toLowerCase();if(e.extensions.every(t=>!(L(t)===r||t==="*"))&&!e.fileNames?.some(t=>process.platform==="win32"?t.toLowerCase()===l.basename(o).toLowerCase():t===l.basename(o)))return!1;let i=l.relative(n,o).split(l.sep).join("/"),s=a(t=>t?.some(c=>l.matchesGlob(i,c))??!1,"matches");return(e.include===void 0||s(e.include))&&!s(e.exclude)}a(J,"matchesConfiguredFile");function ce(e,o,n,r,i){let s=l.resolve(i,r),t=e.filter(d=>J(d.config,s,i)),c=t.find(d=>d.layer!=="built-in");if(c!==void 0)return c;let f=Math.max(0,...t.map(d=>n.get(d.id)?.score??0));return t.find(d=>o.has(d.id)&&(n.get(d.id)?.score??0)===f)}a(ce,"selectConfiguredEntry");async function q(e,o,n=process.env,r){r?.throwIfAborted(),w(e,"process");let i=h(e.command[0]).replaceAll("{project}",o),s=k(e,o,n);return j(i,o,s,r)}a(q,"hasConfiguredExecutable");async function fe(e,o,n,r){if(r.signal?.throwIfAborted(),e.includes("://")&&!r.executableAvailability)throw Object.assign(new Error("Tool probes require their resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r.executableAvailability?await r.executableAvailability(o.map(t=>t.config),r.signal):await Promise.all(o.map(t=>q(t.config,e,r.environment??process.env,r.signal)));if(r.signal?.throwIfAborted(),i.length!==o.length||i.some(t=>typeof t!="boolean"))throw new TypeError("Invalid tool executable availability report");let s=r.recipeEvidence?await r.recipeEvidence(n,r.signal):await v(e,n,void 0,r.signal);return r.signal?.throwIfAborted(),{available:new Set(o.filter((t,c)=>i[c]===!0&&(!r.requireBuiltInEvidence||(s.get(t.id)?.score??0)>0)).map(t=>t.id)),evidence:s}}a(fe,"toolRuntimeEvidence");async function V(e,o){if(w(e,"process"),o.processAccess)return o.processAccess.run(e,o);if(o.projectRoot.includes("://")||o.filePath.includes("://"))throw Object.assign(new Error("No process owner for this resource"),{code:"UNSUPPORTED_SOURCE"});let n=e.command.map(f=>W(f,o)),r=h(n[0]),i=n.slice(1),s=e.cwd==="file"?l.dirname(o.filePath):o.projectRoot,t=e.successExitCodes??[0],c=k(e,o.projectRoot,o.env??process.env);return new Promise((f,d)=>{let u=F(r,i,{cwd:s,env:c,signal:o.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),p="",m="",C=h(u.stdout),x=h(u.stderr),T=!1,R=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);C.setEncoding("utf8"),x.setEncoding("utf8"),C.on("data",g=>{p+=g}),x.on("data",g=>{m+=g}),u.on("error",g=>{clearTimeout(R),d(g)}),u.on("close",g=>{clearTimeout(R),f({ok:!T&&g!==null&&t.includes(g),exitCode:g,stdout:p,stderr:m})})})}a(V,"runConfiguredProcess");async function de(e,o){let n=await P(o.filePath,"utf8"),r=await V(e.run,o);if(!r.ok)return{ok:!1,changed:await P(o.filePath,"utf8")!==n};e.output==="stdout"&&r.stdout!==n&&await D(o.filePath,r.stdout,"utf8");let i=await P(o.filePath,"utf8");return{ok:!0,changed:n!==i}}a(de,"runConfiguredFormatter");function ue(e){let o=$(e,"formatters");for(let[n,r]of Object.entries(o.entries)){let i=y(r,`formatter ${n}`);if(O(i,`formatter ${n}`),w(i.run,`formatter ${n}.run`),i.output!=="in-place"&&i.output!=="stdout")throw new Error(`formatter ${n}.output must be in-place or stdout`)}return e}a(ue,"parseFormattersConfig");function ge(e){let o=$(e,"linters"),n=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,i]of Object.entries(o.entries)){let s=y(i,`linter ${r}`);O(s,`linter ${r}`),w(s.check,`linter ${r}.check`),s.fix!==void 0&&w(s.fix,`linter ${r}.fix`);let t=y(s.diagnostics,`linter ${r}.diagnostics`);if(!n.has(String(t.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(t.columnBase!==void 0&&(t.format!=="regex"||t.columnBase!==0&&t.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(t.format==="regex"&&typeof t.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}a(ge,"parseLintersConfig");function $(e,o){let n=y(e,"tool config");if(n.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:y(n[o],o)}}a($,"configRoot");function O(e,o){b(e.extensions,`${o}.extensions`,!1),e.fileNames!==void 0&&b(e.fileNames,`${o}.fileNames`,!1),e.include!==void 0&&b(e.include,`${o}.include`,!1),e.exclude!==void 0&&b(e.exclude,`${o}.exclude`,!0)}a(O,"assertMatcher");function w(e,o){let n=y(e,o);if(b(n.command,`${o}.command`,!1),n.cwd!==void 0&&n.cwd!=="project"&&n.cwd!=="file")throw new Error(`${o}.cwd must be project or file`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||Number(n.timeoutMs)<=0))throw new Error(`${o}.timeoutMs must be positive`);if(n.successExitCodes!==void 0&&(!Array.isArray(n.successExitCodes)||n.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${o}.successExitCodes must contain integers`);if(n.env!==void 0){let r=y(n.env,`${o}.env`);if(Object.values(r).some(i=>typeof i!="string"))throw new Error(`${o}.env values must be strings`)}}a(w,"assertProcessConfig");function b(e,o,n){if(!Array.isArray(e)||!n&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${o} must be ${n?"an":"a non-empty"} array of strings`)}a(b,"assertStringArray");function y(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${o} must be an object`);return e}a(y,"configRecord");function L(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}a(L,"normalizeExtension");async function z(e,o,n,r,i){i?.throwIfAborted();let s;try{s=r?await r(e.sourcePath):await P(e.sourcePath,{encoding:"utf8",signal:i})}catch(t){if(i?.throwIfAborted(),e.optional&&K(t))return{};throw new Error(`Cannot read ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}i?.throwIfAborted();try{return n(JSON.parse(s))}catch(t){throw new Error(`Invalid ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}}a(z,"readToolConfigLayer");function K(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}a(K,"isMissingFile");function I(e){return e instanceof Error?e.message:String(e)}a(I,"errorMessage");function k(e,o,n){return A(o,{...E(n),...E(e.env??{})})}a(k,"createConfiguredProcessEnvironment");function W(e,o){let n=l.relative(o.projectRoot,o.filePath);return e.replaceAll("{project}",o.projectRoot).replaceAll("{fileDir}",l.dirname(o.filePath)).replaceAll("{relativeFile}",n).replaceAll("{file}",o.filePath)}a(W,"expandPlaceholders");function H(e,o){let n=l.extname(o).toLowerCase(),r=l.basename(o),i=a((s,t=[])=>s.some(c=>L(c)===n)||t.some(c=>c===r),"matches");return e.formatter?i(e.formatter.extensions,e.formatter.fileNames):e.linter?i(e.linter.extensions,e.linter.fileNames):e.lsp?i(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}a(H,"recipeMatchesFile");async function Q(e,o){o?.throwIfAborted();try{return await M(e),o?.throwIfAborted(),!0}catch{return o?.throwIfAborted(),!1}}a(Q,"fileExists");function X(e,o){let n=l.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}a(X,"isPathInside");export{N as a,se as b,ae as c,G as d,S as e,B as f,le as g,J as h,ce as i,q as j,fe as k,V as l,de as m,ue as n,ge as o,k as p,H as q};
1
+ import{a as E}from"./chunk-BXGMMZT3.js";import{b as v,c as A,d as j}from"./chunk-756K3LJY.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import F from"cross-spawn";import{access as M,readFile as P,writeFile as D}from"node:fs/promises";import _ from"node:os";import l from"node:path";import{fileURLToPath as U}from"node:url";var N=1;function se(e){return l.win32.basename(h(e[0]))}a(se,"configuredExecutableName");async function ae(e,o,n,r,i){i?.throwIfAborted();let s=l.resolve(e),t=l.resolve(s,o),c=r.filter(d=>H(d,t));if(X(s,t))return s;let f=l.dirname(t);for(;;){if(i?.throwIfAborted(),await Q(S(f,n),i)||[...(await E(f,c,void 0,i)).values()].some(p=>p.score>0))return f;let u=l.dirname(f);if(u===f)return;f=u}}a(ae,"resolveExternalToolProjectRoot");function G(e){return l.join(e,".pi","pi-agent-ide")}a(G,"projectIdeConfigDirectory");function S(e,o){return l.join(G(e),`${o}.json`)}a(S,"projectIdeConfigPath");function B(e,o,n={}){let i=(n.environment??process.env).PI_CODING_AGENT_DIR?.trim(),s=i===void 0||i.length===0?l.join(n.homeDirectory??_.homedir(),".pi","agent"):l.resolve(i);return{project:S(e,o),global:l.join(s,"extensions","pi-agent-ide",`${o}.json`),builtIn:U(new URL(`tool-config/${o}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}a(B,"resolveToolConfigPaths");async function le(e,o,n,r={}){let i=r.signal;i?.throwIfAborted();let s=r.layerAccess;if(e.includes("://")&&!s)throw Object.assign(new Error("No config owner for this project"),{code:"UNSUPPORTED_SOURCE"});let t={...B(e,o,r),...s?await s.paths(e,o,i):{}},c=[{layer:"project",sourcePath:t.project,optional:!0},...r.includeGlobal===!1?[]:[{layer:"global",sourcePath:t.global,optional:!0}],{layer:"built-in",sourcePath:t.builtIn,optional:!1}],f=[],d=new Set;for(let u of c){i?.throwIfAborted();let p=await z(u,o,n,u.layer!=="built-in"&&s?m=>s.readText(m,i):void 0,i);for(let[m,C]of Object.entries(p))d.has(m)||(d.add(m),f.push({id:m,config:C,layer:u.layer,sourcePath:u.sourcePath}))}return{entries:f,paths:t}}a(le,"loadLayeredToolConfig");function J(e,o,n){let r=l.extname(o).toLowerCase();if(e.extensions.every(t=>!(L(t)===r||t==="*"))&&!e.fileNames?.some(t=>process.platform==="win32"?t.toLowerCase()===l.basename(o).toLowerCase():t===l.basename(o)))return!1;let i=l.relative(n,o).split(l.sep).join("/"),s=a(t=>t?.some(c=>l.matchesGlob(i,c))??!1,"matches");return(e.include===void 0||s(e.include))&&!s(e.exclude)}a(J,"matchesConfiguredFile");function ce(e,o,n,r,i){let s=l.resolve(i,r),t=e.filter(d=>J(d.config,s,i)),c=t.find(d=>d.layer!=="built-in");if(c!==void 0)return c;let f=Math.max(0,...t.map(d=>n.get(d.id)?.score??0));return t.find(d=>o.has(d.id)&&(n.get(d.id)?.score??0)===f)}a(ce,"selectConfiguredEntry");async function q(e,o,n=process.env,r){r?.throwIfAborted(),w(e,"process");let i=h(e.command[0]).replaceAll("{project}",o),s=k(e,o,n);return j(i,o,s,r)}a(q,"hasConfiguredExecutable");async function fe(e,o,n,r){if(r.signal?.throwIfAborted(),e.includes("://")&&!r.executableAvailability)throw Object.assign(new Error("Tool probes require their resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r.executableAvailability?await r.executableAvailability(o.map(t=>t.config),r.signal):await Promise.all(o.map(t=>q(t.config,e,r.environment??process.env,r.signal)));if(r.signal?.throwIfAborted(),i.length!==o.length||i.some(t=>typeof t!="boolean"))throw new TypeError("Invalid tool executable availability report");let s=r.recipeEvidence?await r.recipeEvidence(n,r.signal):await E(e,n,void 0,r.signal);return r.signal?.throwIfAborted(),{available:new Set(o.filter((t,c)=>i[c]===!0&&(!r.requireBuiltInEvidence||(s.get(t.id)?.score??0)>0)).map(t=>t.id)),evidence:s}}a(fe,"toolRuntimeEvidence");async function V(e,o){if(w(e,"process"),o.processAccess)return o.processAccess.run(e,o);if(o.projectRoot.includes("://")||o.filePath.includes("://"))throw Object.assign(new Error("No process owner for this resource"),{code:"UNSUPPORTED_SOURCE"});let n=e.command.map(f=>W(f,o)),r=h(n[0]),i=n.slice(1),s=e.cwd==="file"?l.dirname(o.filePath):o.projectRoot,t=e.successExitCodes??[0],c=k(e,o.projectRoot,o.env??process.env);return new Promise((f,d)=>{let u=F(r,i,{cwd:s,env:c,signal:o.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),p="",m="",C=h(u.stdout),x=h(u.stderr),T=!1,R=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);C.setEncoding("utf8"),x.setEncoding("utf8"),C.on("data",g=>{p+=g}),x.on("data",g=>{m+=g}),u.on("error",g=>{clearTimeout(R),d(g)}),u.on("close",g=>{clearTimeout(R),f({ok:!T&&g!==null&&t.includes(g),exitCode:g,stdout:p,stderr:m})})})}a(V,"runConfiguredProcess");async function de(e,o){let n=await P(o.filePath,"utf8"),r=await V(e.run,o);if(!r.ok)return{ok:!1,changed:await P(o.filePath,"utf8")!==n};e.output==="stdout"&&r.stdout!==n&&await D(o.filePath,r.stdout,"utf8");let i=await P(o.filePath,"utf8");return{ok:!0,changed:n!==i}}a(de,"runConfiguredFormatter");function ue(e){let o=$(e,"formatters");for(let[n,r]of Object.entries(o.entries)){let i=y(r,`formatter ${n}`);if(O(i,`formatter ${n}`),w(i.run,`formatter ${n}.run`),i.output!=="in-place"&&i.output!=="stdout")throw new Error(`formatter ${n}.output must be in-place or stdout`)}return e}a(ue,"parseFormattersConfig");function ge(e){let o=$(e,"linters"),n=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,i]of Object.entries(o.entries)){let s=y(i,`linter ${r}`);O(s,`linter ${r}`),w(s.check,`linter ${r}.check`),s.fix!==void 0&&w(s.fix,`linter ${r}.fix`);let t=y(s.diagnostics,`linter ${r}.diagnostics`);if(!n.has(String(t.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(t.columnBase!==void 0&&(t.format!=="regex"||t.columnBase!==0&&t.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(t.format==="regex"&&typeof t.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}a(ge,"parseLintersConfig");function $(e,o){let n=y(e,"tool config");if(n.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:y(n[o],o)}}a($,"configRoot");function O(e,o){b(e.extensions,`${o}.extensions`,!1),e.fileNames!==void 0&&b(e.fileNames,`${o}.fileNames`,!1),e.include!==void 0&&b(e.include,`${o}.include`,!1),e.exclude!==void 0&&b(e.exclude,`${o}.exclude`,!0)}a(O,"assertMatcher");function w(e,o){let n=y(e,o);if(b(n.command,`${o}.command`,!1),n.cwd!==void 0&&n.cwd!=="project"&&n.cwd!=="file")throw new Error(`${o}.cwd must be project or file`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||Number(n.timeoutMs)<=0))throw new Error(`${o}.timeoutMs must be positive`);if(n.successExitCodes!==void 0&&(!Array.isArray(n.successExitCodes)||n.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${o}.successExitCodes must contain integers`);if(n.env!==void 0){let r=y(n.env,`${o}.env`);if(Object.values(r).some(i=>typeof i!="string"))throw new Error(`${o}.env values must be strings`)}}a(w,"assertProcessConfig");function b(e,o,n){if(!Array.isArray(e)||!n&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${o} must be ${n?"an":"a non-empty"} array of strings`)}a(b,"assertStringArray");function y(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${o} must be an object`);return e}a(y,"configRecord");function L(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}a(L,"normalizeExtension");async function z(e,o,n,r,i){i?.throwIfAborted();let s;try{s=r?await r(e.sourcePath):await P(e.sourcePath,{encoding:"utf8",signal:i})}catch(t){if(i?.throwIfAborted(),e.optional&&K(t))return{};throw new Error(`Cannot read ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}i?.throwIfAborted();try{return n(JSON.parse(s))}catch(t){throw new Error(`Invalid ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}}a(z,"readToolConfigLayer");function K(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}a(K,"isMissingFile");function I(e){return e instanceof Error?e.message:String(e)}a(I,"errorMessage");function k(e,o,n){return A(o,{...v(n),...v(e.env??{})})}a(k,"createConfiguredProcessEnvironment");function W(e,o){let n=l.relative(o.projectRoot,o.filePath);return e.replaceAll("{project}",o.projectRoot).replaceAll("{fileDir}",l.dirname(o.filePath)).replaceAll("{relativeFile}",n).replaceAll("{file}",o.filePath)}a(W,"expandPlaceholders");function H(e,o){let n=l.extname(o).toLowerCase(),r=l.basename(o),i=a((s,t=[])=>s.some(c=>L(c)===n)||t.some(c=>c===r),"matches");return e.formatter?i(e.formatter.extensions,e.formatter.fileNames):e.linter?i(e.linter.extensions,e.linter.fileNames):e.lsp?i(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}a(H,"recipeMatchesFile");async function Q(e,o){o?.throwIfAborted();try{return await M(e),o?.throwIfAborted(),!0}catch{return o?.throwIfAborted(),!1}}a(Q,"fileExists");function X(e,o){let n=l.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}a(X,"isPathInside");export{N as a,se as b,ae as c,G as d,S as e,B as f,le as g,J as h,ce as i,q as j,fe as k,V as l,de as m,ue as n,ge as o,k as p,H as q};
@@ -0,0 +1 @@
1
+ import{K as d,j as c}from"./chunk-DDH3FP4G.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},O=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),S=e.Union([e.Object({...g,fuzzy:e.Optional(O)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),y=c(S);function x(o,l,r,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((n,a)=>({source:n.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:n.lineNumber,startColumn:n.startColumn,endLine:n.endLineNumber??n.lineNumber,endColumn:n.endColumn},...Buffer.byteLength(n.matchedText)<=4096?{matchedText:n.matchedText}:{textTruncated:!0},...r===void 0?{}:{references:{line:`SEARCH#${r}:${a+1}:line`,match:`SEARCH#${r}:${a+1}:match`}}})),...l&&r!==void 0?{all:{line:`SEARCH#${r}:all:line`,match:`SEARCH#${r}:all:match`}}:{}}}s(x,"selectionData");import{Type as t}from"typebox";var j=t.Object({query:t.String({minLength:1,description:"Text to find or a Boolean expression. Quote text to keep it literal. Use regex:<pattern> for regular expressions."}),path:t.Optional(t.Union(d.anyOf,{description:"File, directory, URL (no read needed first), docs:all for all packaged guide bodies, docs:<id> for one guide, unchanged Read/Search/edit result, its UUID, or an array of such results. Use literal text or regex: for docs: sources. Results select only their registered ranges."})),include:t.Optional(t.String({description:"Optional include glob for local or SSH files"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local or SSH files"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),multiline:t.Optional(t.Boolean({description:"Let text or regex:<pattern> match across lines; . also matches line breaks. Local or SSH files and result scopes only."})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum displayed items, including compact file summaries (default 50)."}))},{additionalProperties:!1});export{O as a,S as b,y as c,x as d,j as e};
@@ -0,0 +1,4 @@
1
+ import{m as E}from"./chunk-VDJSH3DQ.js";import{c as q}from"./chunk-756K3LJY.js";import{a}from"./chunk-EI7MMDWY.js";import O from"cross-spawn";import{fileURLToPath as S}from"node:url";var T=5e3,R=10*1024*1024,P=S(new URL(".",new URL("../src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts",import.meta.url).href));function j(n){let t=n?.filter(r=>r==="jq"||r.startsWith("jq:"))??[];if(t.length===0)return;if(t.length>1)throw new Error("Read accepts only one jq view");if(n?.length!==1)throw new Error("The jq view cannot be combined with other views. Keep only one jq:<filter> in views.");let e=t[0];if(e===void 0||e==="jq"||e.slice(3).trim().length===0)throw new Error('The jq view requires a filter, for example views: ["jq:.scripts"]');return{filter:e.slice(3)}}a(j,"parseJqView");function y(n,t,e){return e.signal?.aborted===!0?Promise.reject(new Error("jq execution was cancelled")):J(n)?Promise.reject(new Error("jq module loading is disabled")):new Promise((r,s)=>{let i=O(e.command??"jq",["-L",P,"--",n],{cwd:e.cwd,env:b(e.cwd),shell:!1,stdio:["pipe","pipe","pipe"],windowsHide:!0}),d="",u="",c=!1,p=0,l=a(o=>{c||(c=!0,clearTimeout(h),e.signal?.removeEventListener("abort",m),o===void 0?r(d):s(o))},"finish"),g=a(o=>{i.kill(),l(o)},"stop"),m=a(()=>g(new Error("jq execution was cancelled")),"abort"),h=setTimeout(()=>g(new Error(`jq did not finish within ${T/1e3} seconds`)),T);h.unref(),e.signal?.addEventListener("abort",m,{once:!0}),i.stdout?.setEncoding("utf8"),i.stderr?.setEncoding("utf8"),i.stdout?.on("data",o=>{if(p+=Buffer.byteLength(o),p>R){g(new Error(`jq output exceeded ${R/1024/1024}MB`));return}d+=o}),i.stderr?.on("data",o=>{Buffer.byteLength(u)<16384&&(u+=o)}),i.once("error",o=>l(new Error(`Cannot start jq: ${o.message}`))),i.once("close",(o,w)=>{if(!c)if(o===0)l();else{let x=u.trim().split(/\r?\n/u).slice(0,8).join(`
2
+ `);l(new Error(x||`jq exited ${w===null?`with code ${String(o)}`:`after signal ${w}`}`))}}),i.stdin?.once("error",o=>l(new Error(`Cannot send JSON to jq: ${o.message}`))),i.stdin?.end(t)})}a(y,"executeJq");function J(n){let t=[0],e=0,r="";for(;e<n.length;){let s=n[e],i=t.at(-1);if(i==="string"){s==="\\"?(n[e+1]==="("&&(t.push(0),r=""),e+=2):(s==='"'&&(t.pop(),r='"'),e+=1);continue}if(s==="#"){let d=n.indexOf(`
3
+ `,e);e=d<0?n.length:d+1;continue}if(s==='"')t.push("string");else if(s==="(")t[t.length-1]=(i??0)+1;else if(s===")")t.length>1&&i===0?t.pop():t[t.length-1]=Math.max(0,(i??0)-1);else if(/[A-Za-z_]/u.test(s??"")){let d=e;for(;/[A-Za-z0-9_]/u.test(n[e]??"");)e+=1;let u=n.slice(d,e),c=_(n,e),p=r==="."||r==="$",l=c.startsWith(":")&&!c.startsWith("::");if(!p&&!l&&(u==="include"||u==="import"||u==="modulemeta"))return!0;r=u;continue}s!==void 0&&!/\s/u.test(s)&&(r=s),e+=1}return!1}a(J,"hasModuleOperation");function _(n,t){let e=t;for(;e<n.length;)if(/\s/u.test(n[e]??""))e+=1;else if(n[e]==="#"){let r=n.indexOf(`
4
+ `,e);e=r<0?n.length:r+1}else break;return n.slice(e,e+2)}a(_,"nextCode");function b(n){let t=q(n,process.env),e={};for(let r of["PATH","PATHEXT","SystemRoot","SYSTEMROOT","WINDIR"])t[r]!==void 0&&(e[r]=t[r]);return e}a(b,"safeEnvironment");function $(n){return async t=>{let e;try{e=j(t.request.views)}catch(u){return f(t,n.pluginId,"READ_FAILED",v(u))}if(e===void 0)return{kind:"continue",context:t};if(t.inputScope==="selection"||t.sourceTarget!==void 0)return f(t,n.pluginId,"UNSUPPORTED_RANGE","jq requires a complete JSON source. Read its explicit path instead of a result, search selection or text anchor.");if(t.inputScope!=="source")return f(t,n.pluginId,"READ_FAILED","This jq view requires a matching Read host that classifies complete source inputs.");let r=t.state;if(r?.contentKind!=="text")return f(t,n.pluginId,"UNSUPPORTED_CONTENT","This source does not supply structured JSON for jq.");let s=n.input(t);if(typeof s!="string")return f(t,n.pluginId,"UNSUPPORTED_CONTENT","This source does not supply structured JSON for jq.");let i;try{i=await y(e.filter,s,{cwd:t.resolverContext.cwd,...t.resolverContext.signal===void 0?{}:{signal:t.resolverContext.signal}})}catch(u){return f(t,n.pluginId,"READ_FAILED",v(u))}let d={...r,content:[{type:"text",text:i}],text:E(r.source,i),preserveTruncatedOutput:!0};return{kind:"continue",context:{...t,sourceText:void 0,sourceTarget:void 0,state:d}}}}a($,"createJqReadHandler");function v(n){return n instanceof Error?n.message:String(n)}a(v,"message");function f(n,t,e,r){let s=n.state?.source??n.request.path,i=n.state?.resolvedBy;return{kind:"return",result:{content:[{type:"text",text:`jq failed: ${r}`}],details:{source:s,resolvedBy:i,failure:{code:e,source:s,resolverId:i,pluginId:t,stage:"read",message:r}},isError:!0}}}a(f,"failure");export{$ as a};
@@ -1,28 +1,28 @@
1
- import{a as we,b as Se,c as Te}from"./chunk-PBQDHYNX.js";import{a as ye}from"./chunk-L2B4DTVS.js";import{a as ge,b as he,c as _}from"./chunk-RIJMXO43.js";import"./chunk-PJL3UVMJ.js";import{a as de}from"./chunk-47SPPIXK.js";import{a as me}from"./chunk-4DIUPEDF.js";import{a as ue,b as ce}from"./chunk-VAXLSPPU.js";import{e as pe}from"./chunk-I6NPILT5.js";import{c as fe}from"./chunk-W7CASEO3.js";import"./chunk-QUYXINGZ.js";import{a as D}from"./chunk-XLWCSJMR.js";import{e as te,f as ne}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-XXLLY66B.js";import{c as se,d as ae}from"./chunk-235QMMVA.js";import{b as C}from"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import{a as oe}from"./chunk-BU7IZLKB.js";import{a as re,b as ie}from"./chunk-S5PL5DFQ.js";import{i as q,j as M}from"./chunk-LCWBVOII.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import ut from"node:path";import{stripVTControlCharacters as ct}from"node:util";import{truncateLine as dt}from"@earendil-works/pi-coding-agent";import{Text as E}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as be,DEFAULT_MAX_LINES as xe,formatSize as at,truncateTail as lt}from"@earendil-works/pi-coding-agent";function $(t){return lt(t,{maxBytes:be-4096,maxLines:xe-32})}l($,"terminalOutputTail");function O(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.status==="running"&&t.background?`next: Continue independent work or finish your turn; completion or a one-time idle inspection notice will wake the agent. Read ${t.source} to inspect output; use write or insert when input is needed.`:void 0,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
1
+ import{a as we,b as Se,c as Te}from"./chunk-PBQDHYNX.js";import{a as ye}from"./chunk-L2B4DTVS.js";import{a as ge,b as he,c as O}from"./chunk-WQIMM4SU.js";import"./chunk-4IWEKRSP.js";import{c as fe}from"./chunk-W7CASEO3.js";import{a as ce}from"./chunk-47SPPIXK.js";import{a as le,b as ue}from"./chunk-VAXLSPPU.js";import{a as me}from"./chunk-FYOU4RBH.js";import{d as de}from"./chunk-7PVDTMEM.js";import"./chunk-5S74Z6Y4.js";import{a as _}from"./chunk-GS5ZRTUG.js";import{f as se,g as ae}from"./chunk-KN6VPARZ.js";import{b as C}from"./chunk-OMNKD7WW.js";import"./chunk-PS2B6THP.js";import{a as pe}from"./chunk-GXL4NMHR.js";import{c as ie,d as oe}from"./chunk-PQWANILR.js";import{a as re}from"./chunk-BU7IZLKB.js";import{a as te,b as ne}from"./chunk-S5PL5DFQ.js";import{m as q,n as M}from"./chunk-DDH3FP4G.js";import"./chunk-VDJSH3DQ.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import ut from"node:path";import{stripVTControlCharacters as dt}from"node:util";import{truncateLine as ct}from"@earendil-works/pi-coding-agent";import{Text as E}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as be,DEFAULT_MAX_LINES as ve,formatSize as at,truncateTail as lt}from"@earendil-works/pi-coding-agent";function $(t){return lt(t,{maxBytes:be-4096,maxLines:ve-32})}l($,"terminalOutputTail");function D(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.status==="running"&&t.background?`next: Continue independent work or finish your turn; completion or a one-time idle inspection notice will wake the agent. Read ${t.source} to inspect output; use write or insert when input is needed.`:void 0,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
2
  `)}
3
3
  output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${xe} line output budget`:`${at(be)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
4
+ ${r}`}`;let i=e.truncatedBy==="lines"?`${ve} line output budget`:`${at(be)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
5
  `)}
6
6
  output:
7
7
  ${a}${r.length===0?"":`
8
- ${r}`}`}l(O,"formatAgentTerminalSnapshot");var mt=500;function ve(t,e,n,r,i){let a=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${B(n)} \xB7 ${a}`)}`;return new E(`${o}
9
- ${i.fg("accent",X(r.family))} ${t}`,0,0)}l(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 E(r.join(`
8
+ ${r}`}`}l(D,"formatAgentTerminalSnapshot");var mt=500;function xe(t,e,n,r,i){let a=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${F(n)} \xB7 ${a}`)}`;return new E(`${o}
9
+ ${i.fg("accent",X(r.family))} ${t}`,0,0)}l(xe,"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 E(r.join(`
10
10
  `),0,0)}l(Re,"renderTerminalActionResult");function Pe(t,e,n,r,i){let a=[gt(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&a.push(...r.map(o=>` ${i.fg("dim",o)}`)),new E(a.join(`
11
11
  `),0,0)}l(Pe,"renderTerminalAction");function k(t,e,n,r){let i=ke(t,C,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new E(i.join(`
12
- `),0,0)}l(k,"renderTerminalResult");function Ee(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 E(I(t,(u,c)=>n.fg(u,c)),0,0);let o=N(t.output??"",C),s=[...o.omission===void 0?[]:[` ${n.fg("muted",o.omission)}`],...o.lines.map(u=>` ${n.fg("dim",u)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],I(t,(u,c)=>n.fg(u,c))];return new E(s.join(`
12
+ `),0,0)}l(k,"renderTerminalResult");function Ee(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 E(I(t,(u,d)=>n.fg(u,d)),0,0);let o=N(t.output??"",C),s=[...o.omission===void 0?[]:[` ${n.fg("muted",o.omission)}`],...o.lines.map(u=>` ${n.fg("dim",u)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],I(t,(u,d)=>n.fg(u,d))];return new E(s.join(`
13
13
  `),0,0)}if(e==="full"){let a=ke(t,Number.POSITIVE_INFINITY,n).slice(2);return new E(a.join(`
14
14
  `),0,0)}let r=N(t.output??"",C),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(a=>` ${n.fg("dim",a)}`)];return i.push(I(t,(a,o)=>n.fg(a,o))),new E(i.join(`
15
- `),0,0)}l(Ee,"renderRunResult");function Ae(t,e){let n=l((o,s)=>e?.fg(o,s)??s,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${B(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",X(t.shellFamily))} ${V(t.command,84)}`],a=pt(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",V(o,90))}`)),i.push(I(t,n)),i.join(`
16
- `)}l(Ae,"renderActiveTerminal");function ke(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":B(t.cwd),o=t.shellFamily??"posix",s=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",X(o))} ${t.command??""}`],u=N(t.output??"",e);return u.omission!==void 0&&s.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&s.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),s.push(I(t,(c,d)=>n.fg(c,d))),s}l(ke,"terminalCardLines");function pt(t,e){return N(t,e).lines}l(pt,"outputTail");function N(t,e){let n=$(ct(t).replaceAll("\r","")),r=n.content.split(`
17
- `).map(u=>dt(u.trimEnd(),mt).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),s=a+o;return{lines:r.slice(a),...n.truncated||s>0?{omission:s>0?`\u2026 ${s} earlier lines`:"\u2026 earlier output omitted"}:{}}}l(N,"outputWindow");function I(t,e){let n=t.status??"running",r=ft(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,ht(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}l(I,"statusLine");function ft(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}l(ft,"statusIcon");function X(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}l(X,"promptMarker");function gt(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":B(t.cwd),i=t.background===!0?"background":"wait",a=V(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}l(gt,"terminalIdentity");function B(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${ut.sep}`))?`~${t.slice(e.length)}`:t}l(B,"shortCwd");function V(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}l(V,"oneLine");function ht(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(ht,"formatElapsed");function Ce(t){return{id:"terminal",onDidChange:l(e=>t.onDidChange(e),"onDidChange"),list:l(()=>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:l(n=>Ae(e,n).split(`
18
- `),"renderSummary"),renderDetail:l(n=>k(e,!0,n),"renderDetail"),sendInput:l(n=>{Promise.resolve(t.write(e.source,n)).catch(()=>{})},"sendInput"),stop:l(()=>t.delete(e.source),"stop")})),"list")}}l(Ce,"terminalProcessProvider");import{setTimeout as bt}from"node:timers/promises";var yt="#d8dee9",Y="#111418",wt=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function K(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),s=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),u=i.cols*9+24,c=s*18+24,d=a(Math.max(1,Math.round(u*r)),Math.max(1,Math.round(c*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,h=Math.max(0,p.baseY);for(let g=0;g<s;g+=1){let S=p.getLine(h+o+g);if(S!==void 0)for(let y=0;y<i.cols;y+=1){let v=S.getCell(y);v===void 0||v.getWidth()===0||St(m,v,y,g)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+s&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}l(K,"renderTerminalScreen");function St(t,e,n,r){let i=$e(e,"foreground"),a=$e(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,s=12+r*18;a!==Y&&(t.fillStyle=a,t.fillRect(o,s,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,o,s),e.isUnderline()&&t.fillRect(o,s+18-2,9*Math.max(1,e.getWidth()),1))}l(St,"drawCell");function $e(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?yt:Y;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:Tt(a)}l($e,"cellColor");function Tt(t){let e=wt[t];if(e!==void 0)return e;if(t>=232){let s=8+(t-232)*10;return Ie(s,s,s)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=l(s=>s===0?0:55+s*40,"channel");return Ie(o(r),o(i),o(a))}l(Tt,"ansiColor");function Ie(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}l(Ie,"rgb");var Z="\0pi-terminal-write\0",J="\0pi-terminal-keys\0";function xt(t){let e=t?.find(u=>u==="image"||u==="sequence"||u.startsWith("image:")||u.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 u of e.slice(n+1).split(",")){let[c,d,m]=u.split("=");if(c===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${u}`);if(c!=="duration"&&c!=="interval"&&c!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${c}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${c} must be a number`);i.set(c,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,s=i.get("scale")??1;if(!(s>0&&s<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:s}}l(xt,"parseTerminalVisualView");async function De(t,e){let n=new Map,r=new Map,i={protocol:re,apiVersion:ie,id:"terminal",setup(o){o.addResolver({resolver:vt(e),preserveTruncatedOutput:!0,renderResult(s,u,c){let d=s.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return k(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
- `)},u.expanded,c,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(s){let u=s.request.path;if(u===void 0||!x(u))return{kind:"continue",context:s};let c;try{c=xt(s.request.views)}catch(m){return{kind:"return",result:z(u,m instanceof Error?m.message:String(m))}}if(c===void 0)return{kind:"continue",context:s};let d=e.get(u);if(d===void 0)return{kind:"return",result:z(u,`Unknown terminal session ${u}`)};try{e.markInspected(u);let m=c.mode==="image"?1:Math.floor(c.duration/c.interval)+1,p=[];for(let h=0;h<m;h+=1){s.resolverContext.signal?.throwIfAborted(),h>0&&await bt(c.interval*1e3,void 0,{signal:s.resolverContext.signal});let g=await K(e,u,void 0,c.scale);p.push({type:"image",data:g,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:c.mode}}}}catch(m){return{kind:"return",result:z(u,m instanceof Error?m.message:String(m))}}}}),o.describe({path:"shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated.",views:"On shell:<session>, image[:scale=S] returns the virtual terminal screen; sequence[:duration=D,interval=I,scale=S] returns ordered PNG frames. Defaults: D=2 seconds, I=0.5 seconds, S=1. Scale satisfies 0 < S <= 1; sequences require 0 < D <= 10, I > 0, and at most 20 frames (floor(D/I)+1). Terminal captures do not support region or image grid selection; offset/limit do not crop their frames."})}},a={protocol:se,apiVersion:ae,id:"terminal",setup(o){o.addResolver({resolver:Rt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:l(async s=>(Me(s.input,e,n),await Le(s.input,e,r),Pt(s,Z)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:l(async s=>(await Le(s.input,e,r),Me(s.input,e,n),Et(s)),"handler")});for(let s of["write","insert","delete"])o.addToolRenderer({tool:s,matches:l((u,c)=>$t(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,h=d.state;return p!==void 0&&(h.snapshot=e.snapshot(p)),Pe(h.snapshot??{},s,_e(s,m),[],c)},renderResult(u,c,d){let m=Ct(u.details);return Re(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([oe(t,i),le(t,a)]),t.on("tool_result",async(o,s)=>{if(!R(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&x(u)){let w=`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`;return M({content:[{type:"text",text:w}],details:o.details},D(o.toolName),{status:"error",errors:[q(w,"UNSUPPORTED_OPERATION",u)],data:{operation:"replace",effect:"not-applied",files:[{source:u,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof u=="string"&&x(u)){let w=e.get(u);if(w===void 0)return;let A=e.snapshot(w);return e.delete(u).then(()=>M({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:A,action:"delete",input:"session",changedLines:[]}},D(o.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:u,effect:"applied"}]}}),T=>M({content:[{type:"text",text:T instanceof Error?T.message:String(T)}],details:{source:u,deleted:!1}},D(o.toolName),{status:"error",errors:[q(T,"TERMINAL_DELETE_FAILED",u)],data:{operation:"delete",effect:"unknown",files:[{source:u,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.input.path;if(typeof c!="string"||!x(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let h=e.snapshot(d),g=o.toolName,S=_e(g,o.input),y=e.screenChangeRegion(d,m,6),v=[{type:"text",text:`Sent ${S} to ${d.source}.`}];return s.model?.input.includes("image")===!0&&v.push({type:"image",data:await K(e,c,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:v,details:{source:d.source,action:g,status:d.status,snapshot:h,input:S,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}l(De,"registerTerminalResources");function vt(t){return{id:"terminal",async tryResolve(e){if(!x(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:At(r)}]}}}}}}l(vt,"createReadResolver");function Rt(t){return{id:"terminal-input",async tryResolve(e){if(!x(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=kt(r),a=i.indexOf(Z),o=i.indexOf(J);if(a>=0){await t.write(n.source,i.slice(a+Z.length));return}if(o>=0){await t.sendKeys(n.source,i.slice(o+J.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}l(Rt,"createInputResolver");function Pt(t,e){return!R(t.input)||!Oe(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}l(Pt,"transformWriteInput");function Et(t){if(!R(t.input)||!Oe(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:`${J}${typeof t.input.text=="string"?t.input.text:""}`}}}l(Et,"transformInsertInput");function At(t){return O(t)}l(At,"formatSnapshot");function kt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}l(kt,"singleText");function z(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}l(z,"failure");function x(t){return/^shell:[a-f\d]{12}$/u.test(t)}l(x,"isShellSource");function Oe(t){return typeof t=="string"&&x(t)}l(Oe,"isShellSourceValue");function Ct(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}:{}}}}l(Ct,"terminalActionDetails");async function Le(t,e,n){if(!R(t)||typeof t.path!="string"||!x(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))}l(Le,"rememberScreen");function Me(t,e,n){if(!R(t)||typeof t.path!="string"||!x(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}l(Me,"rememberOutputEnd");function _e(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}`}l(_e,"terminalInputLabel");function $t(t,e){if(!R(t))return!1;if(e==="call")return typeof t.path=="string"&&x(t.path);let n=t.details;return R(n)&&typeof n.source=="string"&&x(n.source)}l($t,"isTerminalRenderValue");function R(t){return typeof t=="object"&&t!==null}l(R,"isRecord");async function Ne(t,e){await de(t,{protocol:ue,apiVersion:ce,id:"terminal",setup(r){r.addResolver({resolver:It(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}l(Ne,"registerTerminalSearch");function It(t){return{readResources:l(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=U(e);return pe(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=Lt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=U(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(`
15
+ `),0,0)}l(Ee,"renderRunResult");function Ae(t,e){let n=l((o,s)=>e?.fg(o,s)??s,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${F(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",X(t.shellFamily))} ${V(t.command,84)}`],a=pt(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",V(o,90))}`)),i.push(I(t,n)),i.join(`
16
+ `)}l(Ae,"renderActiveTerminal");function ke(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":F(t.cwd),o=t.shellFamily??"posix",s=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",X(o))} ${t.command??""}`],u=N(t.output??"",e);return u.omission!==void 0&&s.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&s.push(...u.lines.map(d=>` ${n.fg("dim",d)}`)),s.push(I(t,(d,c)=>n.fg(d,c))),s}l(ke,"terminalCardLines");function pt(t,e){return N(t,e).lines}l(pt,"outputTail");function N(t,e){let n=$(dt(t).replaceAll("\r","")),r=n.content.split(`
17
+ `).map(u=>ct(u.trimEnd(),mt).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),s=a+o;return{lines:r.slice(a),...n.truncated||s>0?{omission:s>0?`\u2026 ${s} earlier lines`:"\u2026 earlier output omitted"}:{}}}l(N,"outputWindow");function I(t,e){let n=t.status??"running",r=ft(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,ht(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}l(I,"statusLine");function ft(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}l(ft,"statusIcon");function X(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}l(X,"promptMarker");function gt(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":F(t.cwd),i=t.background===!0?"background":"wait",a=V(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}l(gt,"terminalIdentity");function F(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${ut.sep}`))?`~${t.slice(e.length)}`:t}l(F,"shortCwd");function V(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}l(V,"oneLine");function ht(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(ht,"formatElapsed");function Ce(t){return{id:"terminal",onDidChange:l(e=>t.onDidChange(e),"onDidChange"),list:l(()=>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:l(n=>Ae(e,n).split(`
18
+ `),"renderSummary"),renderDetail:l(n=>k(e,!0,n),"renderDetail"),sendInput:l(n=>{Promise.resolve(t.write(e.source,n)).catch(()=>{})},"sendInput"),stop:l(()=>t.delete(e.source),"stop")})),"list")}}l(Ce,"terminalProcessProvider");import{setTimeout as bt}from"node:timers/promises";var yt="#d8dee9",Y="#111418",wt=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function K(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),s=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),u=i.cols*9+24,d=s*18+24,c=a(Math.max(1,Math.round(u*r)),Math.max(1,Math.round(d*r))),m=c.getContext("2d");m.scale(r,r),m.fillStyle=Y,m.fillRect(0,0,c.width,c.height),m.textBaseline="top";let p=i.screen.buffer.active,h=Math.max(0,p.baseY);for(let g=0;g<s;g+=1){let S=p.getLine(h+o+g);if(S!==void 0)for(let y=0;y<i.cols;y+=1){let x=S.getCell(y);x===void 0||x.getWidth()===0||St(m,x,y,g)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+s&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),c.toBuffer("image/png").toString("base64")}l(K,"renderTerminalScreen");function St(t,e,n,r){let i=$e(e,"foreground"),a=$e(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,s=12+r*18;a!==Y&&(t.fillStyle=a,t.fillRect(o,s,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,o,s),e.isUnderline()&&t.fillRect(o,s+18-2,9*Math.max(1,e.getWidth()),1))}l(St,"drawCell");function $e(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?yt:Y;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:Tt(a)}l($e,"cellColor");function Tt(t){let e=wt[t];if(e!==void 0)return e;if(t>=232){let s=8+(t-232)*10;return Ie(s,s,s)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=l(s=>s===0?0:55+s*40,"channel");return Ie(o(r),o(i),o(a))}l(Tt,"ansiColor");function Ie(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}l(Ie,"rgb");var Z="\0pi-terminal-write\0",J="\0pi-terminal-keys\0";function vt(t){let e=t?.find(u=>u==="image"||u==="sequence"||u.startsWith("image:")||u.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 u of e.slice(n+1).split(",")){let[d,c,m]=u.split("=");if(d===void 0||c===void 0||m!==void 0||c.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${u}`);if(d!=="duration"&&d!=="interval"&&d!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${d}`);let p=Number(c);if(!Number.isFinite(p))throw new Error(`Terminal ${d} must be a number`);i.set(d,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,s=i.get("scale")??1;if(!(s>0&&s<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:s}}l(vt,"parseTerminalVisualView");async function Oe(t,e){let n=new Map,r=new Map,i={protocol:te,apiVersion:ne,id:"terminal",setup(o){o.addResolver({resolver:xt(e),preserveTruncatedOutput:!0,renderResult(s,u,d){let c=s.details,m=c.source===void 0?void 0:e.get(c.source),p=m===void 0?{}:e.snapshot(m);return k(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
+ `)},u.expanded,d,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(s){let u=s.request.path;if(u===void 0||!v(u))return{kind:"continue",context:s};let d;try{d=vt(s.request.views)}catch(m){return{kind:"return",result:z(u,m instanceof Error?m.message:String(m))}}if(d===void 0)return{kind:"continue",context:s};let c=e.get(u);if(c===void 0)return{kind:"return",result:z(u,`Unknown terminal session ${u}`)};try{e.markInspected(u);let m=d.mode==="image"?1:Math.floor(d.duration/d.interval)+1,p=[];for(let h=0;h<m;h+=1){s.resolverContext.signal?.throwIfAborted(),h>0&&await bt(d.interval*1e3,void 0,{signal:s.resolverContext.signal});let g=await K(e,u,void 0,d.scale);p.push({type:"image",data:g,mimeType:"image/png"})}return{kind:"return",result:{content:p,script:{kind:"native",source:c.source,blocks:p},details:{source:c.source,resolvedBy:"terminal",frames:m,mode:d.mode}}}}catch(m){return{kind:"return",result:z(u,m instanceof Error?m.message:String(m))}}}}),o.describe({path:"shell:<session> \u2014 status and output tail.",views:"On shell:<session>: image[:scale=S] \u2014 screen image; sequence[:duration=D,interval=I,scale=S] \u2014 frames over time, up to 10 s and 20 frames."})}},a={protocol:ie,apiVersion:oe,id:"terminal",setup(o){o.addResolver({resolver:Rt(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:l(async s=>(Me(s.input,e,n),await Le(s.input,e,r),Pt(s,Z)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:l(async s=>(await Le(s.input,e,r),Me(s.input,e,n),Et(s)),"handler")});for(let s of["write","insert","delete"])o.addToolRenderer({tool:s,matches:l((u,d)=>$t(u,d),"matches"),renderCall(u,d,c){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,h=c.state;return p!==void 0&&(h.snapshot=e.snapshot(p)),Pe(h.snapshot??{},s,_e(s,m),[],d)},renderResult(u,d,c){let m=Ct(u.details);return Re(m.action,m.changedLines,c)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describeField("path","shell:<session> types into that terminal."),o.tool("delete").describeField("path","shell:<session> ends that session."),o.tool("write").describeField("content","For shell:<session>, exact input; Enter is not added."),o.tool("insert").describeField("path","shell:<session> sends keys to that terminal."),o.tool("insert").describeField("anchor","Omit for shell:<session>."),o.tool("insert").describeField("text","For shell:<session>: named keys and chords such as Enter, Ctrl+C, Up, or caret forms such as ^C, separated by spaces or commas.")}};await Promise.all([re(t,i),pe(t,a)]),t.on("tool_result",async(o,s)=>{if(!R(o.input))return;let u=o.input.path;if(o.toolName==="replace"&&typeof u=="string"&&v(u)){let w=`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`;return M({content:[{type:"text",text:w}],details:o.details},_(o.toolName),{status:"error",errors:[q(w,"UNSUPPORTED_OPERATION",u)],data:{operation:"replace",effect:"not-applied",files:[{source:u,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof u=="string"&&v(u)){let w=e.get(u);if(w===void 0)return;let A=e.snapshot(w);return e.delete(u).then(()=>M({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:A,action:"delete",input:"session",changedLines:[]}},_(o.toolName),{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:u,effect:"applied"}]}}),T=>M({content:[{type:"text",text:T instanceof Error?T.message:String(T)}],details:{source:u,deleted:!1}},_(o.toolName),{status:"error",errors:[q(T,"TERMINAL_DELETE_FAILED",u)],data:{operation:"delete",effect:"unknown",files:[{source:u,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let d=o.input.path;if(typeof d!="string"||!v(d))return;let c=e.get(d);if(c===void 0)return;let m=r.get(d)??e.screenRows(c);r.delete(d);let p=n.get(d)??c.outputStart+c.output.length;n.delete(d),await e.waitForOutputAfter(c,p);let h=e.snapshot(c),g=o.toolName,S=_e(g,o.input),y=e.screenChangeRegion(c,m,6),x=[{type:"text",text:`Sent ${S} to ${c.source}.`}];return s.model?.input.includes("image")===!0&&x.push({type:"image",data:await K(e,d,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:x,details:{source:c.source,action:g,status:c.status,snapshot:h,input:S,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}l(Oe,"registerTerminalResources");function xt(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:At(r)}]}}}}}}l(xt,"createReadResolver");function Rt(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=kt(r),a=i.indexOf(Z),o=i.indexOf(J);if(a>=0){await t.write(n.source,i.slice(a+Z.length));return}if(o>=0){await t.sendKeys(n.source,i.slice(o+J.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}l(Rt,"createInputResolver");function Pt(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:""}`}}}l(Pt,"transformWriteInput");function Et(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:`${J}${typeof t.input.text=="string"?t.input.text:""}`}}}l(Et,"transformInsertInput");function At(t){return D(t)}l(At,"formatSnapshot");function kt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}l(kt,"singleText");function z(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}l(z,"failure");function v(t){return/^shell:[a-f\d]{12}$/u.test(t)}l(v,"isShellSource");function De(t){return typeof t=="string"&&v(t)}l(De,"isShellSourceValue");function Ct(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}:{}}}}l(Ct,"terminalActionDetails");async 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&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}l(Le,"rememberScreen");function Me(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)}l(Me,"rememberOutputEnd");function _e(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}`}l(_e,"terminalInputLabel");function $t(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)}l($t,"isTerminalRenderValue");function R(t){return typeof t=="object"&&t!==null}l(R,"isRecord");async function Ne(t,e){await ce(t,{protocol:le,apiVersion:ue,id:"terminal",setup(r){r.addResolver({resolver:It(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}l(Ne,"registerTerminalSearch");function It(t){return{readResources:l(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=B(e);return de(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=Lt(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=B(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
20
  `)}
21
21
 
22
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=Q(i)?U(i.payload):U(void 0);return me(a.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${a.snapshot.status} \xB7 read-only`])}}}l(It,"terminalSearchResolver");function Lt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[a,o]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let s=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=s.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||Mt(s,c,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}l(Lt,"findTerminalMatches");function Mt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}l(Mt,"isWordBoundary");function U(t){if(!_t(t))throw new TypeError("Invalid terminal search result");return t}l(U,"parsePayload");function _t(t){return Q(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&Q(t.snapshot)&&typeof t.snapshot.source=="string"}l(_t,"isTerminalSearchPayload");function Q(t){return typeof t=="object"&&t!==null}l(Q,"isRecord");import{spawn as Ot}from"node:child_process";import{closeSync as Nt,mkdirSync as Bt,openSync as Ut,rmSync as Wt,writeSync as Ft}from"node:fs";import jt from"node:os";import Fe from"node:path";import{createRequire as Ht}from"node:module";import{randomUUID as Gt}from"node:crypto";import{stripVTControlCharacters as qt}from"node:util";import{StringDecoder as Vt}from"node:string_decoder";import Dt from"node:os";import Be from"node:path";var W={executable:"/bin/bash",displayName:"Bash over SSH",family:"posix",commandArgs:l(t=>["-lc",t],"commandArgs")};function Ue(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Be.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:l(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:l(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Dt.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Be.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:l(i=>["-c",i],"commandArgs")}}l(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.`}}l(We,"shellSyntaxGuidance");var Ge=Ht(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),je=1e6,Xt=100,Yt=30,Kt=2e3,zt=50,L=class{static{l(this,"TerminalSessionManager")}#l;#e=new Map;#r=new Set;#i=new Set;#o=new Map;#s=new Map;#u=!1;constructor(e=Qt){this.#l=e}onDidChange(e){return this.#r.add(e),()=>this.#r.delete(e)}onDidComplete(e){return this.#i.add(e),()=>this.#i.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(en(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,...e.origin===void 0?{}:{origin:e.origin},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:a}=n,o;try{let u=Ge("node-pty"),c={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:nn(tn()),...globalThis.process.platform==="win32"?{useConptyDll:!0}:{}};o=u.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],c)}catch(u){let c={...n,status:"failed",endedAt:Date.now(),error:F(u)};return this.#e.set(r,c),this.#n(r),n.resolveCompletion(c),queueMicrotask(()=>this.#a(c)),c}let s={...n,process:o};return this.#e.set(r,s),o.onData(u=>this.#d(s,u)),globalThis.process.platform==="win32"&&s.screen.onData(u=>{if(!P(s.status))try{o.write(u)}catch{}}),o.onExit(({exitCode:u,signal:c})=>{P(s.status)||(s.endedAt=Date.now(),s.exitCode=u,c!==0&&(s.signal=c),s.status=s.status==="stopping"?"stopped":u===0?"completed":"failed",(u===124||u===137)&&(s.completionReason="timeout"),this.#n(s.id),s.resolveCompletion(s),this.#t(s),this.#a(s))}),this.#t(s),s}#c(e){if(this.#u)throw new Error("Terminal session manager is closed");let n=this.#l();if(!/^[a-f0-9]{12}$/u.test(n)||this.#e.has(n)||this.#s.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=sn(n);this.#o.set(n,Ut(r,"a",384));let i=e.cols??Xt,a=e.rows??Yt,o=Jt(i,a),s=l(c=>{},"resolveCompletion"),u=new Promise(c=>{s=c});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:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:s,completionDelivered:!1,staleReminderDelivered:!1}}async startRemote(e){let n=W,r=this.#c({...e,cwd:e.remote.location.source,shell:n}),i=new AbortController;this.#s.set(r.id,{abort:i,completion:r.completion});let a=l(()=>i.abort(),"abortStartup");e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a();try{let o=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",a)),s={...r,remote:{target:e.remote.location.target,process:o}};this.#e.set(s.id,s);let u=new Vt("utf8");o.stdout.on("data",d=>this.#d(s,u.write(d))),o.stderr.resume();let c=l(()=>{this.#d(s,u.end()),s.endedAt=Date.now(),this.#n(s.id),s.resolveCompletion(s),this.#t(s),this.#a(s)},"finish");return o.completion.then(({exitCode:d})=>{s.exitCode=d,d<0&&(s.signal=-d),s.status=s.status==="stopping"?"stopped":d===0?"completed":"failed",(d===124||d===137)&&(s.completionReason="timeout"),c()},d=>{s.status="lost",s.error=F(d),c()}),this.#t(s),s}catch(o){let s={...r,status:"failed",endedAt:Date.now(),error:F(o)};return this.#e.set(s.id,s),this.#n(s.id),s.resolveCompletion(s),queueMicrotask(()=>this.#a(s)),s}finally{this.#s.delete(r.id)}}async wait(e,n){let r=this.required(e);return P(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=l(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(s=>{n?.removeEventListener("abort",o),i(s)},a)})}async waitForForeground(e,n){let r=this.required(e);if(P(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,s,u=l(p=>{o||(p!==void 0&&P(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#t(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=l(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Zt(r)){s=void 0;return}s??=Date.now(),Date.now()-s>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await ee(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),s=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let p=d;p<d+a;p+=1){let h=n[p]??"",g=i[p]??"",S=g.length>0&&!n.includes(g),y=h.length>0&&g.length===0;h!==g&&(S||y)&&(m+=1)}m>s&&(s=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==u.cursorY)return d;let h=d.padEnd(u.cursorX," ");return`${h.slice(0,u.cursorX)}\u258C${h.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let s=r.getLine(i+o)?.translateToString(!0).trimEnd();s!==void 0&&s.length>0&&a.push(s)}return a.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=F(i),this.#t(r),i});r.process?.write(n)}sendKeys(e,n){return this.write(e,rn(n))}async stop(e,n="stopped"){let r=this.required(e);return P(r.status)||(r.status="stopping",this.#t(r),await He(r,!1),await Promise.race([r.completion.then(()=>!0),ee(Kt).then(()=>!1)])||(await He(r,!0),await Promise.race([r.completion,ee(1e3)])),P(r.status)||(r.status=n,r.endedAt=Date.now(),this.#n(r.id),r.resolveCompletion(r),this.#a(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.#n(n.id),Wt(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=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(this.#u)return;this.#u=!0;let e=[...this.#s.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=>!P(n.status)).map(n=>this.stop(n.source)));for(let n of this.#e.values())n.screen.dispose(),this.#n(n.id);this.#r.clear(),this.#i.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}#d(e,n){e.lastActivityAt=Date.now();let r=qt(n),i=this.#o.get(e.id);if(i!==void 0&&Ft(i,r),e.output+=r,e.output.length>je){let a=e.output.length-je;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#t(e)}#n(e){let n=this.#o.get(e);n!==void 0&&(Nt(n),this.#o.delete(e))}#t(e){for(let n of this.#r)n(e)}#a(e){for(let n of this.#i)n(e);this.#m()}#m(){let e=[...this.#e.values()].filter(n=>P(n.status)).sort((n,r)=>(r.endedAt??0)-(n.endedAt??0));for(let n of e.slice(zt))n.background&&!n.completionDelivered||(n.screen.dispose(),this.#n(n.id),this.#e.delete(n.id))}};function Zt(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)}l(Zt,"looksInteractive");function Jt(t,e){let{Terminal:n}=Ge("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}l(Jt,"createScreen");function Qt(){return Gt().replaceAll("-","").slice(0,12)}l(Qt,"defaultSessionId");function en(t){return t.startsWith("shell:")?t.slice(6):t}l(en,"normalizeSessionId");function P(t){return t!=="running"&&t!=="stopping"}l(P,"isTerminalStatus");function tn(){return process.env}l(tn,"processEnvironment");function nn(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}l(nn,"cleanEnvironment");function rn(t){return t.split(/[\s,]+/u).filter(Boolean).map(on).join("")}l(rn,"encodeTerminalKeys");function on(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return a?`\x1B${m}`:m}let s={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&s[n]!==void 0)return s[n];if(a&&!i&&!o&&s[n]!==void 0)return`\x1B${s[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!a&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${c}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}l(on,"encodeTerminalKey");async function He(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=Ot("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}l(He,"terminateProcessTree");function ee(t){return new Promise(e=>setTimeout(e,t))}l(ee,"delay");function F(t){return t instanceof Error?t.message:String(t)}l(F,"errorMessage");function sn(t){let e=Fe.join(jt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Bt(e,{recursive:!0,mode:448}),Fe.join(e,`${t}.log`)}l(sn,"createOutputLog");import{AgentSession as an}from"@earendil-works/pi-coding-agent";var j=Symbol.for("pi-agent-ide.terminal-steering-observers");function qe(t){let e=an.prototype,n=e[j]??ln(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}l(qe,"observeQueuedSteering");function ln(t){let e=t.prompt,n=t.steer,r=new Set,i=l(u=>{for(let c of[...r])c(u)},"notify"),a=l(function(u,c){return c?.streamingBehavior!=="steer"?e.call(this,u,c):e.call(this,u,{...c,preflightResult:l(d=>{c.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=l(async function(...u){let c=await n.apply(this,u);return c==="queued"&&i(this),c},"steer");t.prompt=a,t.steer=o;let s={listeners:r,restore:l(()=>{t[j]===s&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[j])},"restore")};return t[j]=s,s}l(ln,"installObservers");import Ke from"node:path";import{stripVTControlCharacters as cn}from"node:util";import{defineTool as dn}from"@earendil-works/pi-coding-agent";import{Type as b}from"typebox";import{Text as mn}from"@earendil-works/pi-tui";import{open as un}from"node:fs/promises";import{Type as f}from"typebox";var Ve=1024*1024,Xe=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 un(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=l(async(s,u)=>{let c=Buffer.alloc(u),d=0;for(;d<u;){let m=await e.read(c,d,u-d,s+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return c},"readRange"),i,a,o=n>Ve;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let s=Ve/2,u=await r(0,s),c=await r(n-s,s),d=new TextDecoder().decode(u,{stream:!0}),m=0;for(;m<c.length&&(c.readUInt8(m)&192)===128;)m++;let p=c.subarray(m).toString("utf8");i=d+p,a=[{start:0,end:Buffer.byteLength(d)},{start:n-s+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,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()}}l(Ye,"structuredShellResult");var pn=l(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 ze(t,e,n,r,i="compact",a=new _([]),o){let s=new Set,u=process.platform==="win32"?"powershell":"bash",c=pn(n);return t.registerTool(dn({name:u,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 ${u} 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 ${u} 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:Xe,async execute(d,m,p,h,g){r.bind(g);let S=o?.(d,g),y=a.resolve(m.cwd??g.cwd,g.cwd),v={command:m.command,background:m.background??!1,...m.cols===void 0?{}:{cols:m.cols},...m.rows===void 0?{}:{rows:m.rows}},w=y?await e.startRemote({...v,remote:y,...p===void 0?{}:{signal:p}}):e.start({...v,cwd:m.cwd===void 0?g.cwd:Ke.resolve(g.cwd,m.cwd),shell:n});if(w.origin??=S,m.background===!0&&w.status!=="failed")return await fn(e,w,h),w.status!=="running"&&(w.completionDelivered=!0),H(e.snapshot(w));if(w.status==="failed")return H(e.snapshot(w));let A=new AbortController;s.add(A);let T;try{T=await e.waitForForeground(w.source,{signal:p===void 0?A.signal:AbortSignal.any([p,A.signal]),timeoutMs:(m.timeoutSeconds??60)*1e3})}finally{s.delete(A)}return T.reason==="aborted"&&A.signal.aborted&&p?.aborted!==!0?(T.session.waitReason="steering",H(e.snapshot(T.session))):(T.reason==="aborted"&&r.notifyWaitTransition(T.session),H(e.snapshot(T.session)))},renderCall(d,m,p){if((p.expanded?"full":i)==="disabled")return new mn(m.fg("toolTitle",u),0,0);let g=typeof d.command=="string"?d.command:"",S=typeof d.cwd=="string"&&d.cwd.startsWith("ssh:"),y=typeof d.cwd=="string"?S?d.cwd:Ke.resolve(process.cwd(),d.cwd):process.cwd();return ve(g,d.background===!0,y,S?W:n,m)},renderResult(d,m,p){return Ee(d.details,m.expanded?"full":i,p)}})),()=>{for(let d of s)d.abort()}}l(ze,"registerTerminalTools");function Ze(t){let e=$(t.output).content;return{content:[{type:"text",text:O(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"}}l(Ze,"terminalPreview");async function H(t){return{...Ze(t),structuredContent:await Ye(t)}}l(H,"terminalResult");async function fn(t,e,n){await new Promise(r=>{let i=!1,a,o=l(()=>{},"unsubscribe"),s=l(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),u=l(()=>{let c=t.snapshot(e);n?.(Ze(c)),(cn(c.output).replaceAll("\r","").split(`
24
- `).filter(m=>m.length>0).length>=C||c.status!=="running")&&s()},"publish");o=t.onDidChange(c=>{c.id===e.id&&u()}),a=setTimeout(s,2e3),u()})}l(fn,"captureInitialBackgroundPreview");import{Box as et,Container as tt}from"@earendil-works/pi-tui";var gn=120,hn=12e4,G=class{constructor(e,n,r=hn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>Je(i.details,a,o)),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>Qe(i.details,a,o)),e.registerEntryRenderer("terminal-stale-display",(i,{expanded:a},o)=>Je(i.data,a,o)),e.registerEntryRenderer("terminal-completion-display",(i,{expanded:a},o)=>Qe(i.data,a,o)),this.#u=[n.onDidChange(i=>this.#c(i)),n.onDidComplete(i=>{this.#a(i.id),i.background&&this.#m(i)})]}static{l(this,"TerminalUi")}#l=new Map;#e;#r=new Map;#i=new Set;#o;#s=!1;#u;bind(e){this.#o=e;for(let n of this.manager.list()){let r=this.manager.get(n.id);r===void 0||!r.background||(r.status==="running"?this.#c(r):r.status!=="stopping"&&this.#m(r))}}onAgentSettled(e){this.#o=e;for(let n of[...this.#i]){this.#i.delete(n);let r=this.manager.get(n);r!==void 0&&this.#c(r,!0)}}notifyWaitTransition(e){let n=this.#n(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.#s=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#l.clear();for(let e of this.#r.values())clearTimeout(e);this.#r.clear(),this.#i.clear(),this.#o=void 0;for(let e of this.#u)e()}#c(e,n=!1){if(this.#a(e.id),this.#s||e.staleReminderDelivered||!e.background||e.status!=="running")return;let r=this.#n(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#d(e);return}this.#r.set(e.id,setTimeout(()=>this.#d(e),i))}#d(e){if(this.#r.delete(e.id),this.#s||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#o?.isIdle()!==!0){this.#i.add(e.id);return}e.staleReminderDelivered=!0;let n=this.#n(e);this.pi.sendMessage({customType:"terminal-stale",display:!1,content:Sn(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.pi.appendEntry("terminal-stale-display",{...n,...this.#t(n)})}#n(e){return{...this.manager.snapshot(e),...e.origin===void 0?{}:{origin:e.origin}}}#t(e){let n=e.origin;return n!==void 0&&n.sessionId===this.#o?.sessionManager.getSessionId()?{parentToolCallId:n.parentToolCallId}:{}}#a(e){let n=this.#r.get(e);n!==void 0&&clearTimeout(n),this.#r.delete(e),this.#i.delete(e)}#m(e){this.#s||e.completionDelivered||(this.#l.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#l.values()].filter(a=>!a.completionDelivered);if(this.#l.clear(),this.#s||n.length===0)return;for(let a of n)a.completionDelivered=!0;let r=n.map(a=>this.#n(a));this.pi.sendMessage({customType:"terminal-completion",display:!1,content:wn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"});let i=new Map;for(let a of r){let o=this.#t(a).parentToolCallId,s=i.get(o)??[];s.push(a),i.set(o,s)}for(let[a,o]of i)this.pi.appendEntry("terminal-completion-display",{sessions:o,...a===void 0?{}:{parentToolCallId:a}})},gn)))}};function Je(t,e,n){let r=new tt;nt(t)&&r.addChild(k(t,e,n,"stale \xB7 inspect session"));let i=new et(1,1,a=>n.bg("toolPendingBg",a));return i.addChild(r),i}l(Je,"renderStale");function Qe(t,e,n){let r=new tt;for(let a of yn(t))r.addChild(k(a,e,n));let i=new et(1,1,a=>n.bg("toolSuccessBg",a));return i.addChild(r),i}l(Qe,"renderCompletion");function yn(t){return!it(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(nt)}l(yn,"completionSnapshots");function nt(t){return it(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"}l(nt,"isTerminalSessionSnapshot");function wn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
22
+ ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=Q(i)?B(i.payload):B(void 0);return me(a.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${a.snapshot.status} \xB7 read-only`])}}}l(It,"terminalSearchResolver");function Lt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[a,o]of t.output.replaceAll("\r","").split(`
23
+ `).entries()){let s=e.caseSensitive===!0?o:o.toLocaleLowerCase(),u=0;for(;r.length<i;){let d=s.indexOf(n,u);if(d<0)break;let c=d+n.length;(e.wholeWord!==!0||Mt(s,d,c))&&r.push({source:t.source,lineNumber:a+1,startColumn:d,endColumn:c,matchedText:o.slice(d,c),lineText:o}),u=Math.max(c,d+1)}if(r.length>=i)break}return r}l(Lt,"findTerminalMatches");function Mt(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}l(Mt,"isWordBoundary");function B(t){if(!_t(t))throw new TypeError("Invalid terminal search result");return t}l(B,"parsePayload");function _t(t){return Q(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&Q(t.snapshot)&&typeof t.snapshot.source=="string"}l(_t,"isTerminalSearchPayload");function Q(t){return typeof t=="object"&&t!==null}l(Q,"isRecord");import{spawn as Dt}from"node:child_process";import{closeSync as Nt,mkdirSync as Ft,openSync as Bt,rmSync as Wt,writeSync as jt}from"node:fs";import Ut from"node:os";import je from"node:path";import{createRequire as Ht}from"node:module";import{randomUUID as Gt}from"node:crypto";import{stripVTControlCharacters as qt}from"node:util";import{StringDecoder as Vt}from"node:string_decoder";import Ot from"node:os";import Fe from"node:path";var W={executable:"/bin/bash",displayName:"Bash over SSH",family:"posix",commandArgs:l(t=>["-lc",t],"commandArgs")};function Be(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Fe.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:l(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:l(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||Ot.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Fe.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:l(i=>["-c",i],"commandArgs")}}l(Be,"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.`}}l(We,"shellSyntaxGuidance");var Ge=Ht(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Ue=1e6,Xt=100,Yt=30,Kt=2e3,zt=50,L=class{static{l(this,"TerminalSessionManager")}#l;#e=new Map;#r=new Set;#i=new Set;#o=new Map;#s=new Map;#u=!1;constructor(e=Qt){this.#l=e}onDidChange(e){return this.#r.add(e),()=>this.#r.delete(e)}onDidComplete(e){return this.#i.add(e),()=>this.#i.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(en(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,...e.origin===void 0?{}:{origin:e.origin},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.#d(e),{id:r,cols:i,rows:a}=n,o;try{let u=Ge("node-pty"),d={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:nn(tn()),...globalThis.process.platform==="win32"?{useConptyDll:!0}:{}};o=u.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],d)}catch(u){let d={...n,status:"failed",endedAt:Date.now(),error:j(u)};return this.#e.set(r,d),this.#n(r),n.resolveCompletion(d),queueMicrotask(()=>this.#a(d)),d}let s={...n,process:o};return this.#e.set(r,s),o.onData(u=>this.#c(s,u)),globalThis.process.platform==="win32"&&s.screen.onData(u=>{if(!P(s.status))try{o.write(u)}catch{}}),o.onExit(({exitCode:u,signal:d})=>{P(s.status)||(s.endedAt=Date.now(),s.exitCode=u,d!==0&&(s.signal=d),s.status=s.status==="stopping"?"stopped":u===0?"completed":"failed",(u===124||u===137)&&(s.completionReason="timeout"),this.#n(s.id),s.resolveCompletion(s),this.#t(s),this.#a(s))}),this.#t(s),s}#d(e){if(this.#u)throw new Error("Terminal session manager is closed");let n=this.#l();if(!/^[a-f0-9]{12}$/u.test(n)||this.#e.has(n)||this.#s.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=sn(n);this.#o.set(n,Bt(r,"a",384));let i=e.cols??Xt,a=e.rows??Yt,o=Jt(i,a),s=l(d=>{},"resolveCompletion"),u=new Promise(d=>{s=d});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:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:s,completionDelivered:!1,staleReminderDelivered:!1}}async startRemote(e){let n=W,r=this.#d({...e,cwd:e.remote.location.source,shell:n}),i=new AbortController;this.#s.set(r.id,{abort:i,completion:r.completion});let a=l(()=>i.abort(),"abortStartup");e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a();try{let o=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",a)),s={...r,remote:{target:e.remote.location.target,process:o}};this.#e.set(s.id,s);let u=new Vt("utf8");o.stdout.on("data",c=>this.#c(s,u.write(c))),o.stderr.resume();let d=l(()=>{this.#c(s,u.end()),s.endedAt=Date.now(),this.#n(s.id),s.resolveCompletion(s),this.#t(s),this.#a(s)},"finish");return o.completion.then(({exitCode:c})=>{s.exitCode=c,c<0&&(s.signal=-c),s.status=s.status==="stopping"?"stopped":c===0?"completed":"failed",(c===124||c===137)&&(s.completionReason="timeout"),d()},c=>{s.status="lost",s.error=j(c),d()}),this.#t(s),s}catch(o){let s={...r,status:"failed",endedAt:Date.now(),error:j(o)};return this.#e.set(s.id,s),this.#n(s.id),s.resolveCompletion(s),queueMicrotask(()=>this.#a(s)),s}finally{this.#s.delete(r.id)}}async wait(e,n){let r=this.required(e);return P(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=l(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(s=>{n?.removeEventListener("abort",o),i(s)},a)})}async waitForForeground(e,n){let r=this.required(e);if(P(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,s,u=l(p=>{o||(p!==void 0&&P(r.status)&&(p=void 0),o=!0,clearTimeout(c),clearInterval(m),n.signal?.removeEventListener("abort",d),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#t(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),d=l(()=>u("aborted"),"onAbort"),c=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Zt(r)){s=void 0;return}s??=Date.now(),Date.now()-s>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",d,{once:!0}),n.signal?.aborted===!0&&d(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await ee(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),s=-1;for(let c=0;c<=e.rows-a;c+=1){let m=0;for(let p=c;p<c+a;p+=1){let h=n[p]??"",g=i[p]??"",S=g.length>0&&!n.includes(g),y=h.length>0&&g.length===0;h!==g&&(S||y)&&(m+=1)}m>s&&(s=m,o=c)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((c,m)=>{if(o+m!==u.cursorY)return c;let h=c.padEnd(u.cursorX," ");return`${h.slice(0,u.cursorX)}\u258C${h.slice(u.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let s=r.getLine(i+o)?.translateToString(!0).trimEnd();s!==void 0&&s.length>0&&a.push(s)}return a.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=j(i),this.#t(r),i});r.process?.write(n)}sendKeys(e,n){return this.write(e,rn(n))}async stop(e,n="stopped"){let r=this.required(e);return P(r.status)||(r.status="stopping",this.#t(r),await He(r,!1),await Promise.race([r.completion.then(()=>!0),ee(Kt).then(()=>!1)])||(await He(r,!0),await Promise.race([r.completion,ee(1e3)])),P(r.status)||(r.status=n,r.endedAt=Date.now(),this.#n(r.id),r.resolveCompletion(r),this.#a(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.#n(n.id),Wt(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=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(this.#u)return;this.#u=!0;let e=[...this.#s.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=>!P(n.status)).map(n=>this.stop(n.source)));for(let n of this.#e.values())n.screen.dispose(),this.#n(n.id);this.#r.clear(),this.#i.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}#c(e,n){e.lastActivityAt=Date.now();let r=qt(n),i=this.#o.get(e.id);if(i!==void 0&&jt(i,r),e.output+=r,e.output.length>Ue){let a=e.output.length-Ue;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#t(e)}#n(e){let n=this.#o.get(e);n!==void 0&&(Nt(n),this.#o.delete(e))}#t(e){for(let n of this.#r)n(e)}#a(e){for(let n of this.#i)n(e);this.#m()}#m(){let e=[...this.#e.values()].filter(n=>P(n.status)).sort((n,r)=>(r.endedAt??0)-(n.endedAt??0));for(let n of e.slice(zt))n.background&&!n.completionDelivered||(n.screen.dispose(),this.#n(n.id),this.#e.delete(n.id))}};function Zt(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)}l(Zt,"looksInteractive");function Jt(t,e){let{Terminal:n}=Ge("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}l(Jt,"createScreen");function Qt(){return Gt().replaceAll("-","").slice(0,12)}l(Qt,"defaultSessionId");function en(t){return t.startsWith("shell:")?t.slice(6):t}l(en,"normalizeSessionId");function P(t){return t!=="running"&&t!=="stopping"}l(P,"isTerminalStatus");function tn(){return process.env}l(tn,"processEnvironment");function nn(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}l(nn,"cleanEnvironment");function rn(t){return t.split(/[\s,]+/u).filter(Boolean).map(on).join("")}l(rn,"encodeTerminalKeys");function on(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let c=t.slice(1).toUpperCase();return c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(c=>!["ctrl","control","alt","meta","shift"].includes(c)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let c=n.toUpperCase(),m=c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31);return a?`\x1B${m}`:m}let s={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&s[n]!==void 0)return s[n];if(a&&!i&&!o&&s[n]!==void 0)return`\x1B${s[n]}`;let d={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(d!==void 0)return!i&&!a&&!o?`\x1B[${d}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${d}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}l(on,"encodeTerminalKey");async function He(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=Dt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}l(He,"terminateProcessTree");function ee(t){return new Promise(e=>setTimeout(e,t))}l(ee,"delay");function j(t){return t instanceof Error?t.message:String(t)}l(j,"errorMessage");function sn(t){let e=je.join(Ut.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Ft(e,{recursive:!0,mode:448}),je.join(e,`${t}.log`)}l(sn,"createOutputLog");import{AgentSession as an}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function qe(t){let e=an.prototype,n=e[U]??ln(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}l(qe,"observeQueuedSteering");function ln(t){let e=t.prompt,n=t.steer,r=new Set,i=l(u=>{for(let d of[...r])d(u)},"notify"),a=l(function(u,d){return d?.streamingBehavior!=="steer"?e.call(this,u,d):e.call(this,u,{...d,preflightResult:l(c=>{d.preflightResult?.(c),c==="queued"&&i(this)},"preflightResult")})},"prompt"),o=l(async function(...u){let d=await n.apply(this,u);return d==="queued"&&i(this),d},"steer");t.prompt=a,t.steer=o;let s={listeners:r,restore:l(()=>{t[U]===s&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=s,s}l(ln,"installObservers");import Ke from"node:path";import{stripVTControlCharacters as dn}from"node:util";import{defineTool as cn}from"@earendil-works/pi-coding-agent";import{Type as b}from"typebox";import{Text as mn}from"@earendil-works/pi-tui";import{open as un}from"node:fs/promises";import{Type as f}from"typebox";var Ve=1024*1024,Xe=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 un(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=l(async(s,u)=>{let d=Buffer.alloc(u),c=0;for(;c<u;){let m=await e.read(d,c,u-c,s+c);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");c+=m.bytesRead}return d},"readRange"),i,a,o=n>Ve;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let s=Ve/2,u=await r(0,s),d=await r(n-s,s),c=new TextDecoder().decode(u,{stream:!0}),m=0;for(;m<d.length&&(d.readUInt8(m)&192)===128;)m++;let p=d.subarray(m).toString("utf8");i=c+p,a=[{start:0,end:Buffer.byteLength(c)},{start:n-s+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,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()}}l(Ye,"structuredShellResult");var pn=l(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 ze(t,e,n,r,i="compact",a=new O([]),o){let s=new Set,u=process.platform==="win32"?"powershell":"bash",d=pn(n);return t.registerTool(cn({name:u,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:[`Edit files with the edit tools, not ${u}.`],description:`Use ${u} 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:d,outputSchema:Xe,async execute(c,m,p,h,g){r.bind(g);let S=o?.(c,g),y=a.resolve(m.cwd??g.cwd,g.cwd),x={command:m.command,background:m.background??!1,...m.cols===void 0?{}:{cols:m.cols},...m.rows===void 0?{}:{rows:m.rows}},w=y?await e.startRemote({...x,remote:y,...p===void 0?{}:{signal:p}}):e.start({...x,cwd:m.cwd===void 0?g.cwd:Ke.resolve(g.cwd,m.cwd),shell:n});if(w.origin??=S,m.background===!0&&w.status!=="failed")return await fn(e,w,h),w.status!=="running"&&(w.completionDelivered=!0),H(e.snapshot(w));if(w.status==="failed")return H(e.snapshot(w));let A=new AbortController;s.add(A);let T;try{T=await e.waitForForeground(w.source,{signal:p===void 0?A.signal:AbortSignal.any([p,A.signal]),timeoutMs:(m.timeoutSeconds??60)*1e3})}finally{s.delete(A)}return T.reason==="aborted"&&A.signal.aborted&&p?.aborted!==!0?(T.session.waitReason="steering",H(e.snapshot(T.session))):(T.reason==="aborted"&&r.notifyWaitTransition(T.session),H(e.snapshot(T.session)))},renderCall(c,m,p){if((p.expanded?"full":i)==="disabled")return new mn(m.fg("toolTitle",u),0,0);let g=typeof c.command=="string"?c.command:"",S=typeof c.cwd=="string"&&c.cwd.startsWith("ssh:"),y=typeof c.cwd=="string"?S?c.cwd:Ke.resolve(process.cwd(),c.cwd):process.cwd();return xe(g,c.background===!0,y,S?W:n,m)},renderResult(c,m,p){return Ee(c.details,m.expanded?"full":i,p)}})),()=>{for(let c of s)c.abort()}}l(ze,"registerTerminalTools");function Ze(t){let e=$(t.output).content;return{content:[{type:"text",text:D(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"}}l(Ze,"terminalPreview");async function H(t){return{...Ze(t),structuredContent:await Ye(t)}}l(H,"terminalResult");async function fn(t,e,n){await new Promise(r=>{let i=!1,a,o=l(()=>{},"unsubscribe"),s=l(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),u=l(()=>{let d=t.snapshot(e);n?.(Ze(d)),(dn(d.output).replaceAll("\r","").split(`
24
+ `).filter(m=>m.length>0).length>=C||d.status!=="running")&&s()},"publish");o=t.onDidChange(d=>{d.id===e.id&&u()}),a=setTimeout(s,2e3),u()})}l(fn,"captureInitialBackgroundPreview");import{Box as et,Container as tt}from"@earendil-works/pi-tui";var gn=120,hn=12e4,G=class{constructor(e,n,r=hn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>Je(i.details,a,o)),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>Qe(i.details,a,o)),e.registerEntryRenderer("terminal-stale-display",(i,{expanded:a},o)=>Je(i.data,a,o)),e.registerEntryRenderer("terminal-completion-display",(i,{expanded:a},o)=>Qe(i.data,a,o)),this.#u=[n.onDidChange(i=>this.#d(i)),n.onDidComplete(i=>{this.#a(i.id),i.background&&this.#m(i)})]}static{l(this,"TerminalUi")}#l=new Map;#e;#r=new Map;#i=new Set;#o;#s=!1;#u;bind(e){this.#o=e;for(let n of this.manager.list()){let r=this.manager.get(n.id);r===void 0||!r.background||(r.status==="running"?this.#d(r):r.status!=="stopping"&&this.#m(r))}}onAgentSettled(e){this.#o=e;for(let n of[...this.#i]){this.#i.delete(n);let r=this.manager.get(n);r!==void 0&&this.#d(r,!0)}}notifyWaitTransition(e){let n=this.#n(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.#s=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#l.clear();for(let e of this.#r.values())clearTimeout(e);this.#r.clear(),this.#i.clear(),this.#o=void 0;for(let e of this.#u)e()}#d(e,n=!1){if(this.#a(e.id),this.#s||e.staleReminderDelivered||!e.background||e.status!=="running")return;let r=this.#n(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#c(e);return}this.#r.set(e.id,setTimeout(()=>this.#c(e),i))}#c(e){if(this.#r.delete(e.id),this.#s||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#o?.isIdle()!==!0){this.#i.add(e.id);return}e.staleReminderDelivered=!0;let n=this.#n(e);this.pi.sendMessage({customType:"terminal-stale",display:!1,content:Sn(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.pi.appendEntry("terminal-stale-display",{...n,...this.#t(n)})}#n(e){return{...this.manager.snapshot(e),...e.origin===void 0?{}:{origin:e.origin}}}#t(e){let n=e.origin;return n!==void 0&&n.sessionId===this.#o?.sessionManager.getSessionId()?{parentToolCallId:n.parentToolCallId}:{}}#a(e){let n=this.#r.get(e);n!==void 0&&clearTimeout(n),this.#r.delete(e),this.#i.delete(e)}#m(e){this.#s||e.completionDelivered||(this.#l.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#l.values()].filter(a=>!a.completionDelivered);if(this.#l.clear(),this.#s||n.length===0)return;for(let a of n)a.completionDelivered=!0;let r=n.map(a=>this.#n(a));this.pi.sendMessage({customType:"terminal-completion",display:!1,content:wn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"});let i=new Map;for(let a of r){let o=this.#t(a).parentToolCallId,s=i.get(o)??[];s.push(a),i.set(o,s)}for(let[a,o]of i)this.pi.appendEntry("terminal-completion-display",{sessions:o,...a===void 0?{}:{parentToolCallId:a}})},gn)))}};function Je(t,e,n){let r=new tt;nt(t)&&r.addChild(k(t,e,n,"stale \xB7 inspect session"));let i=new et(1,1,a=>n.bg("toolPendingBg",a));return i.addChild(r),i}l(Je,"renderStale");function Qe(t,e,n){let r=new tt;for(let a of yn(t))r.addChild(k(a,e,n));let i=new et(1,1,a=>n.bg("toolSuccessBg",a));return i.addChild(r),i}l(Qe,"renderCompletion");function yn(t){return!it(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(nt)}l(yn,"completionSnapshots");function nt(t){return it(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"}l(nt,"isTerminalSessionSnapshot");function wn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
25
  ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,a=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${rt(n.elapsedMs)}
26
26
  ${a||"(no output)"}`}).join(`
27
27
  `)}`}l(wn,"formatCompletionMessage");function Sn(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${rt(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}l(Sn,"formatStaleMessage");function rt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(rt,"formatElapsed");function it(t){return typeof t=="object"&&t!==null}l(it,"isRecord");function ot(t){let e=new Map;return t.on("tool_call",n=>{let r=n.parentToolCallId;e.set(n.toolCallId,r===void 0?n.toolCallId:e.get(r)??r)}),t.on("tool_result",n=>{e.delete(n.toolCallId)}),t.on("agent_end",()=>{e.clear()}),t.on("session_shutdown",()=>{e.clear()}),(n,r)=>({toolCallId:n,parentToolCallId:e.get(n)??n,sessionId:r.sessionManager.getSessionId()})}l(ot,"registerTerminalOrigins");function st(t){return t==="full"||t==="disabled"?t:"compact"}l(st,"toolPresentation");async function Tn(t,e){ne(t,[await te({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(c=>({tool:c,resourcePrefixes:["shell:","process:"]}))]})]);let n=Se("terminal",L)??new L,r=Ue(),i=new _(await he(ge(fe()))),a=new G(t,n),o=ye(t).add(Ce(n));await Promise.all([De(t,n),Ne(t,n)]);let s=ze(t,n,r,a,st(e?.preferences["ui.terminal"]),i,ot(t)),u=l(()=>{},"removeSteeringObserver");t.on("session_start",(c,d)=>{a.bind(d),u(),u=qe(m=>{m.sessionManager===d.sessionManager&&s()})}),t.on("agent_settled",(c,d)=>a.onAgentSettled(d)),t.on("session_shutdown",async c=>{if(u(),a.dispose(),o(),c.reason!=="quit"){we("terminal",n);return}Te("terminal",n),await n.dispose()})}l(Tn,"registerTerminal");export{Tn as default};
28
+ ${e||"(no output)"}`}l(Sn,"formatStaleMessage");function rt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(rt,"formatElapsed");function it(t){return typeof t=="object"&&t!==null}l(it,"isRecord");function ot(t){let e=new Map;return t.on("tool_call",n=>{let r=n.parentToolCallId;e.set(n.toolCallId,r===void 0?n.toolCallId:e.get(r)??r)}),t.on("tool_result",n=>{e.delete(n.toolCallId)}),t.on("agent_end",()=>{e.clear()}),t.on("session_shutdown",()=>{e.clear()}),(n,r)=>({toolCallId:n,parentToolCallId:e.get(n)??n,sessionId:r.sessionManager.getSessionId()})}l(ot,"registerTerminalOrigins");function st(t){return t==="full"||t==="disabled"?t:"compact"}l(st,"toolPresentation");async function Tn(t,e){ae(t,[await se({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(d=>({tool:d,resourcePrefixes:["shell:"]}))]})]);let n=Se("terminal",L)??new L,r=Be(),i=new O(await he(ge(fe()))),a=new G(t,n),o=ye(t).add(Ce(n));await Promise.all([Oe(t,n),Ne(t,n)]);let s=ze(t,n,r,a,st(e?.preferences["ui.terminal"]),i,ot(t)),u=l(()=>{},"removeSteeringObserver");t.on("session_start",(d,c)=>{a.bind(c),u(),u=qe(m=>{m.sessionManager===c.sessionManager&&s()})}),t.on("agent_settled",(d,c)=>a.onAgentSettled(c)),t.on("session_shutdown",async d=>{if(u(),a.dispose(),o(),d.reason!=="quit"){we("terminal",n);return}Te("terminal",n),await n.dispose()})}l(Tn,"registerTerminal");export{Tn as default};
@@ -1,4 +1,4 @@
1
- import{b as N}from"./chunk-LEKC4GQK.js";import{a as k,b as E,c as v}from"./chunk-UEVGZUII.js";import{f as I,g as S}from"./chunk-DUUOCBS3.js";import"./chunk-T4FTT3U4.js";import"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as Y}from"node:fs/promises";import K from"node:path";async function P(e){let n=[],t=await Y(e,{withFileTypes:!0});for(let i of t){let o=K.join(e,i.name);i.isDirectory()?n.push(...await P(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}a(P,"collectFiles");var W=new Set([...Object.keys(k),".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py",".pyi",".rs",".c",".cc",".hh",".hxx",".cpp",".cxx",".h",".hpp",".json",".jsonc",".yaml",".yml",".toml"]),H=new Set([".json",".jsonc",".yaml",".yml",".toml"]),j=new Set(["class_declaration","class_definition","class_specifier","enum_declaration","enum_definition","enum_item","enum_specifier","export_statement","function_declaration","function_definition","function_item","impl_item","interface_declaration","lexical_declaration","namespace_definition","mod_item","public_field_definition","method_definition","method_signature","property_signature","field_declaration","struct_item","struct_specifier","trait_item","type_alias_declaration","type_item","variable_declaration","assignment"]),X=new Set(["module","program","source_file"]),G=new Set(["import_declaration","import_from_statement","import_statement","use_declaration"]),A=new Set(["arrow_function","function_declaration","function_definition","function_item","function_expression","method_definition"]),q=new Set(["public_field_definition","variable_declarator","assignment"]),F=new Set(["field_identifier","identifier","property_identifier","shorthand_property_identifier_pattern","type_identifier"]);function w(e){return W.has(h.extname(e).toLowerCase())}a(w,"isSupportedOutlinePath");var L={failureLabel:"PEEK_FAILED",emptyReason:"no entries to peek.",recovery:['Call peek with { peers: [{ path: "path/to/file.ts" }, ...] }.']},Z={failureLabel:"AST_OUTLINE_FAILED",emptyReason:"no AST outline was produced."};function Ie(e){return S([e],Z)}a(Ie,"formatAstOutline");var M=class{constructor(n=Number.POSITIVE_INFINITY){this.maxDepth=n}static{a(this,"AstOutlineManager")}fallbackScopeManager=new v;async readFileOutline(n,t){let i=T(n,t),o=i.includes("://")?i:h.relative(t,i)||i;if(!w(i))throw new Error(`AST outline is not supported for ${o}.`);let r=await N(i);return this.readDocumentOutline(i,t,r.lines)}async readDocumentOutline(n,t,i,o){let r=T(n,t),c=r.includes("://")?r:h.relative(t,r)||r;if(!w(r))throw new Error(`AST outline is not supported for ${c}.`);let s=await E(r,t,i);if(!s)throw new Error(`No AST parser is available for ${c}.`);if(Number.isFinite(this.maxDepth)&&s.rootNode.hasError)throw new Error(`Cannot build an automatic outline from invalid syntax in ${c}.`);let u=i.join(`
1
+ import{b as N}from"./chunk-LEKC4GQK.js";import{a as k,b as E,c as v}from"./chunk-2AY526TN.js";import{f as I,g as S}from"./chunk-TVH2ND35.js";import"./chunk-T4FTT3U4.js";import"./chunk-VDJSH3DQ.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as Y}from"node:fs/promises";import K from"node:path";async function P(e){let n=[],t=await Y(e,{withFileTypes:!0});for(let i of t){let o=K.join(e,i.name);i.isDirectory()?n.push(...await P(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}a(P,"collectFiles");var W=new Set([...Object.keys(k),".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py",".pyi",".rs",".c",".cc",".hh",".hxx",".cpp",".cxx",".h",".hpp",".json",".jsonc",".yaml",".yml",".toml"]),H=new Set([".json",".jsonc",".yaml",".yml",".toml"]),j=new Set(["class_declaration","class_definition","class_specifier","enum_declaration","enum_definition","enum_item","enum_specifier","export_statement","function_declaration","function_definition","function_item","impl_item","interface_declaration","lexical_declaration","namespace_definition","mod_item","public_field_definition","method_definition","method_signature","property_signature","field_declaration","struct_item","struct_specifier","trait_item","type_alias_declaration","type_item","variable_declaration","assignment"]),X=new Set(["module","program","source_file"]),G=new Set(["import_declaration","import_from_statement","import_statement","use_declaration"]),A=new Set(["arrow_function","function_declaration","function_definition","function_item","function_expression","method_definition"]),q=new Set(["public_field_definition","variable_declarator","assignment"]),F=new Set(["field_identifier","identifier","property_identifier","shorthand_property_identifier_pattern","type_identifier"]);function w(e){return W.has(h.extname(e).toLowerCase())}a(w,"isSupportedOutlinePath");var L={failureLabel:"PEEK_FAILED",emptyReason:"no entries to peek.",recovery:['Call peek with { peers: [{ path: "path/to/file.ts" }, ...] }.']},Z={failureLabel:"AST_OUTLINE_FAILED",emptyReason:"no AST outline was produced."};function Ie(e){return S([e],Z)}a(Ie,"formatAstOutline");var M=class{constructor(n=Number.POSITIVE_INFINITY){this.maxDepth=n}static{a(this,"AstOutlineManager")}fallbackScopeManager=new v;async readFileOutline(n,t){let i=T(n,t),o=i.includes("://")?i:h.relative(t,i)||i;if(!w(i))throw new Error(`AST outline is not supported for ${o}.`);let r=await N(i);return this.readDocumentOutline(i,t,r.lines)}async readDocumentOutline(n,t,i,o){let r=T(n,t),c=r.includes("://")?r:h.relative(t,r)||r;if(!w(r))throw new Error(`AST outline is not supported for ${c}.`);let s=await E(r,t,i);if(!s)throw new Error(`No AST parser is available for ${c}.`);if(Number.isFinite(this.maxDepth)&&s.rootNode.hasError)throw new Error(`Cannot build an automatic outline from invalid syntax in ${c}.`);let u=i.join(`
2
2
  `);for(let d=this.maxDepth;;d-=1){let l=await this.createSourceViewBlock(s.rootNode,r,c,t,i,u,h.extname(r).toLowerCase(),void 0,void 0,d);if(o===void 0||o(l)||d<=0||!Number.isFinite(d))return l}}async formatFile(n,t){let i=T(n,t),o=i.includes("://")?i:h.relative(t,i)||i;if(!w(i)){let r=await N(i);return S([z(i,o,r.lines)],L)}try{return S([await this.readFileOutline(i,t)],L)}catch(r){let c=r instanceof Error?r.message:String(r);return S([R(o,c)],L)}}async formatSymbol(n,t){let o=(await P(t)).filter(r=>w(r)).sort();for(let r of o){let c;try{c=await N(r)}catch{continue}let s;try{s=await E(r,t,c.lines)}catch{continue}if(!s)continue;let u=ee(s.rootNode,n);if(!u)continue;let d=h.relative(t,r)||r,l=await this.createSourceViewBlock(u,r,d,t,c.lines,c.content,h.extname(r).toLowerCase(),n,[`defined in: ${d}:${u.startPosition.row+1}`]);return S([l],L)}return S([R("",`symbol not found: ${n}`,"PEEK_NOT_FOUND")],L)}async createSourceViewBlock(n,t,i,o,r,c,s,u,d,l=this.maxDepth){let f=re(n,c,s,l),m=await J(this.fallbackScopeManager,t,o,r),_=Q(m),g=f.map(y=>{let p=y.sourceLine,x=p===void 0?void 0:r[p-1]??"",O=(p===void 0?void 0:_.get(p))?.map(U=>` <!-- ${U} -->`).join("")??"";return I({content:y.content,...!(p===void 0||x===void 0)&&{sourceLine:{source:t,lineNumber:p,content:x}},...O.length>0&&{suffix:O}})});return{path:i,...u!==void 0&&{heading:u},...d!==void 0&&{details:d},startLine:n.startPosition.row+1,endLine:n.endPosition.row+1,totalLines:r.length,renderedLines:g}}};function z(e,n,t){return{path:n,startLine:t.length>0?1:0,endLine:t.length,totalLines:t.length,renderedLines:t.map((i,o)=>I({content:i,sourceLine:{source:e,lineNumber:o+1,content:i}}))}}a(z,"formatUnsupportedSourceBlock");function R(e,n,t="PEEK_FAILED"){return{path:e,startLine:0,endLine:0,totalLines:0,renderedLines:[],status:"failed",error:n,code:t}}a(R,"failedSourceViewBlock");function J(e,n,t,i){return e.getDocumentScopes(n,t,i)}a(J,"getOutlineScopes");function Q(e){let n=new Map;for(let t of e){let i=n.get(t.startLine)??[];i.push(t.beginAnchor.value),n.set(t.startLine,i);let o=n.get(t.endLine)??[];o.push(t.endScopeAnchor.value),n.set(t.endLine,o)}return n}a(Q,"buildScopeMarkers");function T(e,n){return e.startsWith("ssh://")?e:e.startsWith("file://")?decodeURIComponent(e.slice(7)):h.isAbsolute(e)?e:h.resolve(n,e)}a(T,"resolvePath");function ee(e,n){let t,i=a(o=>{if(!t){if(j.has(o.type)&&te(o)===n){t=ne(o);return}for(let r of o.namedChildren)i(r)}},"visit");return i(e),t}a(ee,"findSymbol");function te(e){let n=e.childForFieldName("name");if(n&&F.has(n.type))return n.text;for(let t of e.namedChildren)if(F.has(t.type))return t.text;if(e.type==="lexical_declaration"||e.type==="variable_declaration")return e.namedChildren.find(o=>o.type==="variable_declarator")?.childForFieldName("name")?.text;if(e.type==="function_definition"){let t=e.childForFieldName("declarator");return t?B(t):void 0}}a(te,"getNodeName");function B(e){if(F.has(e.type))return e.text;for(let n of e.namedChildren){let t=B(n);if(t)return t}}a(B,"findNestedName");function ne(e){let n=e.parent;return n&&(n.type==="export_statement"||n.type==="decorated_definition"||n.type==="template_declaration")?n:e}a(ne,"unwrapDeclaration");function re(e,n,t,i){let o=[];H.has(t)?D(e,t,o,i):$(e,t,o,!1,i);let r=ie(n,e.startIndex),c=oe(n,e.endIndex),s=o.filter(l=>l.start>=r&&l.end<=c).sort((l,f)=>f.start-l.start),u=se(n,r,c);for(let l of s){let f=l.start-r,m=l.end-r,_=ae(l);u.splice(f,m-f,..._)}for(;u.length>0&&/\s/u.test(b(u.at(-1)).char);)u.pop();let d=[[]];for(let l of u)l.char===`
3
3
  `?d.push([]):b(d.at(-1)).push(l);return d.map(l=>{let f=[...new Set(l.flatMap(m=>m.sourceLine===void 0?[]:[m.sourceLine]))];return{content:l.map(m=>m.char).join(""),...f.length===1&&{sourceLine:f[0]}}})}a(re,"renderNodeLines");function ie(e,n){return e.lastIndexOf(`
4
4
  `,Math.max(0,n-1))+1}a(ie,"lineStartAt");function oe(e,n){let t=e.indexOf(`
@@ -0,0 +1 @@
1
+ import{g as n}from"./chunk-4IWEKRSP.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as h}from"node:fs/promises";import{Type as t}from"typebox";import{Value as f}from"typebox/value";var w=t.Object({pid:t.Integer({minimum:1}),parentPid:t.Integer({minimum:0}),command:t.String(),started:t.String(),identity:t.String({pattern:"^[a-f0-9-]+:[0-9]+$"}),executable:t.Union([t.String(),t.Null()])}),u=t.Object({processes:t.Array(w)}),p;async function S(s,o,a,r){if(r?.throwIfAborted(),!Number.isSafeInteger(a)||a<1)throw new Error("Invalid process PID");let i=s.resolve(o);if(!i)throw new n("UNSUPPORTED_SOURCE",o,"not-applied");p??=h(new URL("./process-metadata-worker.py",new URL("../src/backend/process-metadata.ts",import.meta.url).href),"utf8");let c=await i.backend.execute("python3",["-c",await p,String(a)],i.location.path,{signal:r});if(r?.throwIfAborted(),c.exitCode!==0)throw new n("CAPABILITY_UNAVAILABLE",o,"not-applied");let e;try{e=JSON.parse(c.stdout.toString("utf8"))}catch{throw new n("INVALID_RESPONSE",o,"not-applied")}if(typeof e=="object"&&e!==null&&"error"in e){if(e.error==="ENOENT")return;let m=new Set(["CAPABILITY_UNAVAILABLE","EACCES","BYTE_LIMIT"]);throw new n(typeof e.error=="string"&&m.has(e.error)?e.error:"INVALID_RESPONSE",o,"not-applied")}if(!f.Check(u,e)||e.processes.length!==1||e.processes[0]?.pid!==a)throw new n("INVALID_RESPONSE",o,"not-applied");return e.processes[0]}d(S,"findSshProcessMetadata");async function k(s,o,a){try{await s.stop()}catch(r){if(!(r instanceof n)||r.code!=="TRANSPORT_FAILED"||!s.identity)throw r;let i;try{i=await S(o,a,s.pid)}catch(c){throw new AggregateError([r,c],"Owned SSH cleanup could not be reconciled",{cause:c})}if(i===void 0||i.identity!==s.identity)return;throw r}}d(k,"stopOwnedSshProcess");export{k as a};
@@ -1 +1 @@
1
- import{j as s}from"./chunk-IMGIDBCC.js";import{a as i}from"./chunk-EI7MMDWY.js";import{copyFile as c,mkdtemp as l,rm as p}from"node:fs/promises";import a from"node:path";function d(o){let e=o.workspace;return{environment:o.env,signal:o.signal,...e?{layerAccess:{paths:i((r,t,n)=>e.configPaths(t,n),"paths"),async readText(r,t){let n=await e.readText(r,t);if(n===void 0)throw Object.assign(new Error(`ENOENT: ${r}`),{code:"ENOENT"});return n}},executableAvailability:i((r,t)=>e.executableAvailability(r,t),"executableAvailability"),recipeEvidence:i((r,t)=>e.evidence(r,t),"recipeEvidence")}:{}}}i(d,"doctorRuntimeOptions");function f(o){let e=o.workspace;return e?{run:i((r,t)=>e.run(r,t.filePath,t.signal),"run")}:void 0}i(f,"doctorProcessAccess");async function u(o,e){if(o.signal?.throwIfAborted(),!o.workspace)return s(e,o.cwd,o.env,o.signal);let r=await o.workspace.executableAvailability([e],o.signal);if(o.signal?.throwIfAborted(),r.length!==1||typeof r[0]!="boolean")throw new TypeError("Invalid Doctor executable availability report");return r[0]}i(u,"doctorExecutableAvailable");async function w(o,e,r){if(o.signal?.throwIfAborted(),o.workspace)return o.workspace.withProbeCopy(e,r,o.signal);if(e.includes("://"))throw Object.assign(new Error(`Doctor requires the owner of ${e}`),{code:"UNSUPPORTED_SOURCE"});let t=await l(a.join(a.dirname(e),".pi-agent-ide-doctor-")),n=a.join(t,a.basename(e));try{return await c(e,n),o.signal?.throwIfAborted(),await r(n)}finally{await p(t,{recursive:!0,force:!0})}}i(w,"withDoctorProbeCopy");export{d as a,f as b,u as c,w as d};
1
+ import{j as s}from"./chunk-7D7PXIVV.js";import{a as i}from"./chunk-EI7MMDWY.js";import{copyFile as c,mkdtemp as l,rm as p}from"node:fs/promises";import a from"node:path";function d(o){let e=o.workspace;return{environment:o.env,signal:o.signal,...e?{layerAccess:{paths:i((r,t,n)=>e.configPaths(t,n),"paths"),async readText(r,t){let n=await e.readText(r,t);if(n===void 0)throw Object.assign(new Error(`ENOENT: ${r}`),{code:"ENOENT"});return n}},executableAvailability:i((r,t)=>e.executableAvailability(r,t),"executableAvailability"),recipeEvidence:i((r,t)=>e.evidence(r,t),"recipeEvidence")}:{}}}i(d,"doctorRuntimeOptions");function f(o){let e=o.workspace;return e?{run:i((r,t)=>e.run(r,t.filePath,t.signal),"run")}:void 0}i(f,"doctorProcessAccess");async function u(o,e){if(o.signal?.throwIfAborted(),!o.workspace)return s(e,o.cwd,o.env,o.signal);let r=await o.workspace.executableAvailability([e],o.signal);if(o.signal?.throwIfAborted(),r.length!==1||typeof r[0]!="boolean")throw new TypeError("Invalid Doctor executable availability report");return r[0]}i(u,"doctorExecutableAvailable");async function w(o,e,r){if(o.signal?.throwIfAborted(),o.workspace)return o.workspace.withProbeCopy(e,r,o.signal);if(e.includes("://"))throw Object.assign(new Error(`Doctor requires the owner of ${e}`),{code:"UNSUPPORTED_SOURCE"});let t=await l(a.join(a.dirname(e),".pi-agent-ide-doctor-")),n=a.join(t,a.basename(e));try{return await c(e,n),o.signal?.throwIfAborted(),await r(n)}finally{await p(t,{recursive:!0,force:!0})}}i(w,"withDoctorProbeCopy");export{d as a,f as b,u as c,w as d};