pi-agent-ide 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (649) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +24 -29
  3. package/dist/{chunk-CM3XGY72.js → chunk-2AY526TN.js} +1 -1
  4. package/dist/{chunk-LEJKDYCK.js → chunk-2TZDG2JH.js} +1 -1
  5. package/dist/{chunk-DUUOCBS3.js → chunk-35LZOKEW.js} +1 -1
  6. package/dist/chunk-3LVBARLW.js +33 -0
  7. package/dist/{chunk-XBQR74IK.js → chunk-4GBFIGH3.js} +1 -1
  8. package/dist/{chunk-PJL3UVMJ.js → chunk-4IWEKRSP.js} +1 -1
  9. package/dist/chunk-52PFWQMU.js +5 -0
  10. package/dist/chunk-5BGWNYQS.js +1 -0
  11. package/dist/chunk-5PC5INOL.js +1 -0
  12. package/dist/{chunk-QUYXINGZ.js → chunk-5S74Z6Y4.js} +3 -3
  13. package/dist/{chunk-XAHU42FP.js → chunk-6A3ORNW3.js} +2 -2
  14. package/dist/{chunk-ANM3Y5FO.js → chunk-6WCHBHFW.js} +5 -5
  15. package/dist/{chunk-IMGIDBCC.js → chunk-7D7PXIVV.js} +1 -1
  16. package/dist/chunk-7PVDTMEM.js +1 -0
  17. package/dist/chunk-AMIIOWFL.js +1 -0
  18. package/dist/{chunk-TOYN4W4F.js → chunk-B25LXXNV.js} +1 -1
  19. package/dist/chunk-BT2CFM7D.js +11 -0
  20. package/dist/chunk-C2JT2G5K.js +1 -0
  21. package/dist/chunk-DDH3FP4G.js +3 -0
  22. package/dist/{chunk-6T7PSDQW.js → chunk-DVNL5NZE.js} +1 -1
  23. package/dist/chunk-FEZLTM4L.js +1 -0
  24. package/dist/{chunk-CPELC6JE.js → chunk-FHRHYY4M.js} +1 -1
  25. package/dist/chunk-FXPY3V4L.js +10 -0
  26. package/dist/chunk-FYOU4RBH.js +2 -0
  27. package/dist/chunk-G4PRFO6G.js +1 -0
  28. package/dist/chunk-GS5ZRTUG.js +1 -0
  29. package/dist/{chunk-XXLLY66B.js → chunk-GXL4NMHR.js} +1 -1
  30. package/dist/{chunk-QT3EAHOG.js → chunk-H3GEEOOL.js} +1 -1
  31. package/dist/chunk-H5Z54BEU.js +25 -0
  32. package/dist/chunk-H7WAM5RH.js +23 -0
  33. package/dist/{chunk-Z2MNHSJ4.js → chunk-HGCJDIRR.js} +1 -1
  34. package/dist/chunk-HISGZD3C.js +81 -0
  35. package/dist/chunk-HKYVP2Q6.js +3 -0
  36. package/dist/chunk-HRBUY2FF.js +4 -0
  37. package/dist/chunk-IG5DXVDJ.js +1 -0
  38. package/dist/chunk-IOGWZNWT.js +1 -0
  39. package/dist/chunk-IUJUECXH.js +9 -0
  40. package/dist/chunk-KN6VPARZ.js +1 -0
  41. package/dist/{chunk-RW2GTYQI.js → chunk-LF325WYO.js} +1 -1
  42. package/dist/chunk-LXDF2NWX.js +1 -0
  43. package/dist/{chunk-YJ6T3PEP.js → chunk-MDD5ORB6.js} +1 -1
  44. package/dist/{chunk-S72FVLUX.js → chunk-MLFJU2US.js} +1 -1
  45. package/dist/chunk-MPNE25CY.js +5 -0
  46. package/dist/chunk-NA2NEU4V.js +1 -0
  47. package/dist/{chunk-ZJQRLVVV.js → chunk-O7V6G3OO.js} +1 -1
  48. package/dist/chunk-OBTT5INC.js +6 -0
  49. package/dist/{chunk-IICJXZBU.js → chunk-OMNKD7WW.js} +3 -3
  50. package/dist/chunk-OUCVZBOR.js +28 -0
  51. package/dist/chunk-PCGBM2D6.js +17 -0
  52. package/dist/{chunk-235QMMVA.js → chunk-PQWANILR.js} +1 -1
  53. package/dist/{chunk-QRJLIV6P.js → chunk-QJ6V5IAY.js} +6 -6
  54. package/dist/{chunk-SMIFCAAX.js → chunk-RIJRPAL2.js} +1 -1
  55. package/dist/chunk-RIOPUTUJ.js +6 -0
  56. package/dist/{chunk-RMI3NMQY.js → chunk-RIZARTUM.js} +2 -2
  57. package/dist/{chunk-NJ7C4KMA.js → chunk-SRFWT562.js} +1 -1
  58. package/dist/{chunk-U22JNO6N.js → chunk-STUZZM5B.js} +1 -1
  59. package/dist/chunk-T3Z4KXOX.js +2 -0
  60. package/dist/chunk-TSQ6FBTB.js +1 -0
  61. package/dist/chunk-U7YDLVFL.js +1 -0
  62. package/dist/{chunk-KZC7TI5M.js → chunk-UD3DMY3Q.js} +1 -1
  63. package/dist/{chunk-VXP5BMW7.js → chunk-USG6WHAT.js} +1 -1
  64. package/dist/{chunk-ZPT5D4VP.js → chunk-VDJSH3DQ.js} +2 -2
  65. package/dist/{chunk-VMTOFEXF.js → chunk-VMLPXSMK.js} +1 -1
  66. package/dist/chunk-VNWGT367.js +1 -0
  67. package/dist/chunk-WAJW4G4F.js +22 -0
  68. package/dist/chunk-WEE3NM6L.js +1 -0
  69. package/dist/{chunk-IM24DB3K.js → chunk-WES2E4VR.js} +1 -1
  70. package/dist/{chunk-RIJMXO43.js → chunk-WQIMM4SU.js} +1 -1
  71. package/dist/chunk-X2WFNMQR.js +9 -0
  72. package/dist/chunk-XCPIIDFS.js +4 -0
  73. package/dist/chunk-XE4W5YTE.js +2 -0
  74. package/dist/chunk-XUYIK4TX.js +1 -0
  75. package/dist/{chunk-AAC77UD4.js → chunk-YPYROPQF.js} +1 -1
  76. package/dist/chunk-ZXO4D5UB.js +1 -0
  77. package/dist/entry-0.js +1 -1
  78. package/dist/entry-1.js +1 -1
  79. package/dist/entry-10.js +1 -1
  80. package/dist/entry-11.js +1 -1
  81. package/dist/entry-12.js +1 -1
  82. package/dist/entry-13.js +1 -1
  83. package/dist/entry-14.js +1 -1
  84. package/dist/entry-15.js +1 -1
  85. package/dist/entry-16.js +1 -1
  86. package/dist/entry-17.js +1 -1
  87. package/dist/entry-18.js +1 -1
  88. package/dist/entry-19.js +1 -1
  89. package/dist/entry-2.js +1 -1
  90. package/dist/entry-20.js +1 -1
  91. package/dist/entry-21.js +1 -0
  92. package/dist/entry-22.js +1 -1
  93. package/dist/entry-24.js +1 -1
  94. package/dist/entry-25.js +1 -1
  95. package/dist/entry-26.js +1 -1
  96. package/dist/entry-27.js +1 -1
  97. package/dist/entry-28.js +1 -1
  98. package/dist/entry-29.js +1 -2
  99. package/dist/entry-3.js +1 -1
  100. package/dist/entry-30.js +1 -1
  101. package/dist/entry-31.js +2 -4
  102. package/dist/entry-32.js +1 -1
  103. package/dist/entry-33.js +1 -1
  104. package/dist/entry-34.js +1 -1
  105. package/dist/entry-35.js +1 -18
  106. package/dist/entry-36.js +1 -1
  107. package/dist/entry-37.js +1 -1
  108. package/dist/entry-38.js +15 -1
  109. package/dist/entry-39.js +1 -1
  110. package/dist/entry-4.js +1 -1
  111. package/dist/entry-40.js +1 -1
  112. package/dist/entry-41.js +1 -1
  113. package/dist/entry-42.js +1 -1
  114. package/dist/entry-43.js +1 -1
  115. package/dist/entry-44.js +1 -1
  116. package/dist/entry-45.js +1 -1
  117. package/dist/entry-46.js +1 -1
  118. package/dist/entry-47.js +1 -1
  119. package/dist/entry-48.js +1 -1
  120. package/dist/entry-49.js +1 -25
  121. package/dist/entry-5.js +1 -1
  122. package/dist/entry-50.js +1 -1
  123. package/dist/entry-51.js +1 -1
  124. package/dist/entry-52.js +1 -1
  125. package/dist/entry-53.js +1 -1
  126. package/dist/entry-54.js +1 -3
  127. package/dist/entry-55.js +1 -13
  128. package/dist/entry-56.js +1 -1
  129. package/dist/entry-57.js +1 -1
  130. package/dist/entry-58.js +1 -1
  131. package/dist/entry-59.js +1 -1
  132. package/dist/entry-6.js +1 -1
  133. package/dist/entry-60.js +1 -1
  134. package/dist/entry-61.js +1 -1
  135. package/dist/entry-62.js +1 -1
  136. package/dist/entry-63.js +1 -1
  137. package/dist/entry-64.js +1 -1
  138. package/dist/entry-65.js +1 -0
  139. package/dist/entry-66.js +1 -1
  140. package/dist/entry-67.js +1 -0
  141. package/dist/entry-68.js +0 -1
  142. package/dist/entry-69.js +1 -1
  143. package/dist/entry-7.js +1 -1
  144. package/dist/entry-70.js +0 -1
  145. package/dist/entry-71.js +1 -1
  146. package/dist/entry-72.js +1 -1
  147. package/dist/entry-73.js +1 -1
  148. package/dist/entry-74.js +1 -1
  149. package/dist/entry-75.js +1 -0
  150. package/dist/entry-76.js +1 -1
  151. package/dist/entry-77.js +1 -0
  152. package/dist/entry-78.js +0 -1
  153. package/dist/entry-79.js +1 -1
  154. package/dist/entry-8.js +1 -1
  155. package/dist/entry-80.js +0 -1
  156. package/dist/entry-81.js +1 -80
  157. package/dist/entry-82.js +1 -22
  158. package/dist/entry-83.js +1 -2
  159. package/dist/entry-84.js +1 -1
  160. package/dist/entry-85.js +1 -1
  161. package/dist/entry-86.js +2 -1
  162. package/dist/entry-87.js +1 -1
  163. package/dist/entry-88.js +1 -3
  164. package/dist/entry-89.js +1 -1
  165. package/dist/entry-9.js +1 -1
  166. package/dist/entry-90.js +1 -1
  167. package/dist/entry-91.js +3 -1
  168. package/dist/entry-92.js +1 -0
  169. package/dist/entry-93.js +1 -0
  170. package/dist/entry-94.js +1 -0
  171. package/dist/pi-agent-ide.js +13 -34
  172. package/docs/agent-guides/ast-search.md +58 -0
  173. package/docs/agent-guides/debugger.md +1 -1
  174. package/docs/agent-guides/editing.md +29 -58
  175. package/docs/agent-guides/git-changes.md +4 -14
  176. package/docs/agent-guides/search.md +38 -0
  177. package/docs/agent-guides/ssh.md +17 -49
  178. package/docs/agent-guides/terminal.md +9 -15
  179. package/docs/configuration.md +9 -13
  180. package/docs/extensions.md +82 -0
  181. package/docs/settings-help.md +2 -2
  182. package/docs/structured-results.md +33 -11
  183. package/docs/tools.md +24 -23
  184. package/node_modules/pi-agent-doctor/package.json +7 -7
  185. package/node_modules/pi-agent-doctor/runtime/entry-29.js +1 -0
  186. package/node_modules/pi-agent-doctor/src/workspace.ts +0 -5
  187. package/node_modules/pi-agent-documentation/package.json +2 -2
  188. package/node_modules/pi-agent-documentation/runtime/entry-30.js +1 -0
  189. package/node_modules/pi-agent-documentation/src/index.ts +26 -10
  190. package/node_modules/pi-agent-filesystem/index.ts +1 -1
  191. package/node_modules/pi-agent-filesystem/package.json +8 -8
  192. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  193. package/node_modules/pi-agent-filesystem-jq/index.ts +9 -63
  194. package/node_modules/pi-agent-filesystem-jq/package.json +12 -6
  195. package/node_modules/pi-agent-filesystem-jq/runtime/entry-33.js +1 -0
  196. package/node_modules/pi-agent-filesystem-jq/runtime/entry-34.js +2 -0
  197. package/node_modules/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  198. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  199. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  200. package/node_modules/pi-agent-filesystem-text/runtime/entry-36.js +2 -0
  201. package/node_modules/pi-agent-ide-ast/package.json +15 -15
  202. package/node_modules/pi-agent-ide-ast/runtime/entry-37.js +1 -0
  203. package/node_modules/pi-agent-ide-ast/src/extension.ts +8 -8
  204. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  205. package/node_modules/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  206. package/node_modules/pi-agent-ide-changes/index.ts +1 -2
  207. package/node_modules/pi-agent-ide-changes/package.json +10 -10
  208. package/node_modules/pi-agent-ide-changes/runtime/entry-39.js +1 -0
  209. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  210. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  211. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  212. package/node_modules/pi-agent-ide-languages/runtime/entry-42.js +2 -0
  213. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  214. package/node_modules/pi-agent-ide-lint/runtime/entry-43.js +2 -0
  215. package/node_modules/pi-agent-ide-lsp/index.ts +22 -28
  216. package/node_modules/pi-agent-ide-lsp/package.json +14 -10
  217. package/node_modules/pi-agent-ide-lsp/runtime/entry-44.js +2 -0
  218. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  219. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  220. package/node_modules/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  221. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  222. package/node_modules/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  223. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  224. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  225. package/node_modules/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  226. package/node_modules/pi-agent-image/package.json +3 -3
  227. package/node_modules/pi-agent-image/src/image-converter.ts +24 -1
  228. package/node_modules/pi-agent-invariant/package.json +2 -2
  229. package/node_modules/pi-agent-pdf/package.json +3 -3
  230. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +23 -1
  231. package/node_modules/pi-agent-read/package.json +12 -12
  232. package/node_modules/pi-agent-read/runtime/entry-49.js +0 -1
  233. package/node_modules/pi-agent-read/runtime/entry-52.js +2 -0
  234. package/node_modules/pi-agent-read/src/api/read-parameters.ts +4 -7
  235. package/node_modules/pi-agent-read/src/api/tools/read.ts +2 -0
  236. package/node_modules/pi-agent-read/src/core/extension.ts +0 -8
  237. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  238. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  239. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  240. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  241. package/node_modules/pi-agent-resource/package.json +2 -2
  242. package/node_modules/pi-agent-resource/src/index.ts +8 -0
  243. package/node_modules/pi-agent-resource/src/resource-error-metadata.ts +89 -0
  244. package/node_modules/pi-agent-resource/src/resource-error.ts +6 -1
  245. package/node_modules/pi-agent-resource/src/result-images.ts +87 -0
  246. package/node_modules/pi-agent-resource/src/result-targets.ts +9 -3
  247. package/node_modules/pi-agent-resource/src/tool-result.ts +17 -0
  248. package/node_modules/pi-agent-search/package.json +9 -9
  249. package/node_modules/pi-agent-search/runtime/entry-54.js +0 -1
  250. package/node_modules/pi-agent-search/runtime/entry-55.js +1 -0
  251. package/node_modules/pi-agent-search/runtime/entry-57.js +2 -0
  252. package/node_modules/pi-agent-search/src/api/glob-list.ts +35 -0
  253. package/node_modules/pi-agent-search/src/api/search-parameters.ts +8 -8
  254. package/node_modules/pi-agent-search/src/api/search.ts +14 -2
  255. package/node_modules/pi-agent-search/src/core/extension.ts +11 -20
  256. package/node_modules/pi-agent-search/src/core/search-core.ts +30 -10
  257. package/node_modules/pi-agent-search-text/index.ts +34 -12
  258. package/node_modules/pi-agent-search-text/package.json +17 -15
  259. package/node_modules/pi-agent-search-text/runtime/entry-58.js +1 -0
  260. package/node_modules/pi-agent-search-text/runtime/entry-60.js +1 -0
  261. package/node_modules/pi-agent-search-text/src/file-search.ts +59 -25
  262. package/node_modules/pi-agent-search-text/src/resolvers.ts +61 -16
  263. package/node_modules/pi-agent-search-text/src/scoped-search.ts +9 -3
  264. package/node_modules/pi-agent-search-text/src/search-backend.ts +44 -48
  265. package/node_modules/pi-agent-search-text/src/search-presentation.ts +19 -15
  266. package/node_modules/pi-agent-search-text/src/search-recipe.ts +2 -1
  267. package/node_modules/pi-agent-search-text/src/search-result.ts +6 -2
  268. package/node_modules/pi-agent-search-text/src/search-session.ts +1 -0
  269. package/node_modules/pi-agent-search-text/src/tool-file-search.ts +146 -0
  270. package/node_modules/pi-agent-text/package.json +3 -3
  271. package/node_modules/pi-agent-text/runtime/entry-62.js +1 -0
  272. package/node_modules/pi-agent-text/src/text-converter.ts +1 -1
  273. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  274. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-63.js +2 -0
  275. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  276. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-64.js +1 -0
  277. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-65.js +2 -0
  278. package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  279. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +1 -2
  280. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  281. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-67.js +2 -0
  282. package/node_modules/pi-agent-text-editor/package.json +26 -26
  283. package/node_modules/pi-agent-text-editor/runtime/entry-81.js +0 -1
  284. package/node_modules/pi-agent-text-editor/runtime/entry-82.js +1 -0
  285. package/node_modules/pi-agent-text-editor/runtime/entry-83.js +1 -0
  286. package/node_modules/pi-agent-text-editor/runtime/entry-84.js +2 -0
  287. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  288. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  289. package/node_modules/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  290. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  291. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  292. package/node_modules/pi-agent-text-editor/src/core/extension.ts +13 -7
  293. package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  294. package/node_modules/pi-agent-text-editor/src/core/image-write.ts +111 -0
  295. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  296. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +2 -6
  297. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  298. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +17 -36
  299. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  300. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  301. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  302. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  303. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +63 -74
  304. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  305. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +7 -10
  306. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +4 -10
  307. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +8 -8
  308. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +5 -8
  309. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  310. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  311. package/node_modules/pi-agent-text-editor-renderer/index.ts +6 -1
  312. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  313. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-85.js +2 -0
  314. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  315. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +6 -6
  316. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-86.js +2 -0
  317. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  318. package/node_modules/pi-agent-tool-call-interception/runtime/entry-87.js +1 -0
  319. package/node_modules/pi-agent-tool-ui/package.json +3 -3
  320. package/node_modules/pi-agent-tool-ui/runtime/entry-88.js +1 -0
  321. package/node_modules/pi-agent-tool-ui/runtime/entry-89.js +1 -0
  322. package/node_modules/pi-agent-web/index.ts +28 -6
  323. package/node_modules/pi-agent-web/package.json +8 -8
  324. package/node_modules/pi-agent-web-html/package.json +3 -3
  325. package/node_modules/pi-agent-web-html/src/html-converter.ts +1 -1
  326. package/node_modules/pi-agent-web-image/package.json +4 -4
  327. package/node_modules/pi-agent-web-image/runtime/entry-92.js +2 -0
  328. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  329. package/node_modules/pi-agent-web-pdf/runtime/entry-93.js +2 -0
  330. package/node_modules/pi-agent-web-text/package.json +4 -4
  331. package/node_modules/pi-agent-web-text/runtime/entry-94.js +2 -0
  332. package/package.json +65 -58
  333. package/src/api/approval.ts +2 -0
  334. package/src/api/capabilities.ts +60 -0
  335. package/src/api/read.ts +2 -0
  336. package/src/api/standalone.ts +7 -0
  337. package/src/backend/doctor-workspace.ts +0 -3
  338. package/src/backend/process-metadata-worker.py +9 -18
  339. package/src/backend/process-metadata.ts +11 -44
  340. package/src/backend/registration.ts +0 -10
  341. package/src/backend/web-browser-worker.mjs +2 -17
  342. package/src/backend/web-browser.ts +1 -26
  343. package/src/composite/builtin-extensions.ts +8 -6
  344. package/src/composite/capabilities.ts +252 -0
  345. package/src/composite/capability-schemas.ts +53 -0
  346. package/src/composite/ide-alias-rendering.ts +18 -2
  347. package/src/composite/module-labels.ts +0 -4
  348. package/src/composite/preferences.ts +0 -36
  349. package/src/composite/responses-tools.ts +27 -9
  350. package/src/composite/settings-documentation.ts +1 -2
  351. package/src/composite/text-results.ts +61 -23
  352. package/src/composite/tool-availability.ts +28 -13
  353. package/src/documentation/extension.ts +39 -15
  354. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +1 -1
  355. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  356. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  357. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +9 -63
  358. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +12 -6
  359. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-33.js +1 -0
  360. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-34.js +2 -0
  361. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/api/jq.ts +112 -0
  362. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  363. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-35.js +2 -0
  364. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  365. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-36.js +2 -0
  366. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-31.js +2 -0
  367. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -6
  368. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  369. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  370. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +1 -1
  371. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  372. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-92.js +2 -0
  373. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  374. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-93.js +2 -0
  375. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  376. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-94.js +2 -0
  377. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-90.js +2 -0
  378. package/src/extensions/pi-agent-read/package.json +12 -12
  379. package/src/extensions/pi-agent-read/runtime/entry-49.js +0 -1
  380. package/src/extensions/pi-agent-read/runtime/entry-50.js +1 -0
  381. package/src/extensions/pi-agent-read/runtime/entry-52.js +2 -0
  382. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +4 -7
  383. package/src/extensions/pi-agent-read/src/api/tools/read.ts +2 -0
  384. package/src/extensions/pi-agent-read/src/core/extension.ts +0 -8
  385. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +47 -14
  386. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +3 -1
  387. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +14 -2
  388. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +21 -8
  389. package/src/extensions/pi-agent-search/package.json +9 -9
  390. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +34 -12
  391. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +17 -15
  392. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-58.js +1 -0
  393. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-59.js +1 -0
  394. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-60.js +1 -0
  395. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +59 -25
  396. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +61 -16
  397. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +9 -3
  398. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +44 -48
  399. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-presentation.ts +19 -15
  400. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +2 -1
  401. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +6 -2
  402. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +1 -0
  403. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/tool-file-search.ts +146 -0
  404. package/src/extensions/pi-agent-search/runtime/entry-54.js +0 -1
  405. package/src/extensions/pi-agent-search/runtime/entry-55.js +1 -0
  406. package/src/extensions/pi-agent-search/runtime/entry-56.js +1 -0
  407. package/src/extensions/pi-agent-search/runtime/entry-57.js +2 -0
  408. package/src/extensions/pi-agent-search/src/api/glob-list.ts +35 -0
  409. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +8 -8
  410. package/src/extensions/pi-agent-search/src/api/search.ts +14 -2
  411. package/src/extensions/pi-agent-search/src/core/extension.ts +11 -20
  412. package/src/extensions/pi-agent-search/src/core/search-core.ts +30 -10
  413. package/src/extensions/pi-agent-text-editor/package.json +26 -26
  414. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  415. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-63.js +2 -0
  416. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  417. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-64.js +1 -0
  418. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-65.js +2 -0
  419. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +6 -1
  420. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +1 -2
  421. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  422. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-66.js +1 -0
  423. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-67.js +2 -0
  424. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +6 -1
  425. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  426. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-85.js +2 -0
  427. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +18 -5
  428. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +6 -6
  429. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-86.js +2 -0
  430. package/src/extensions/pi-agent-text-editor/runtime/entry-81.js +0 -1
  431. package/src/extensions/pi-agent-text-editor/runtime/entry-82.js +1 -0
  432. package/src/extensions/pi-agent-text-editor/runtime/entry-83.js +1 -0
  433. package/src/extensions/pi-agent-text-editor/runtime/entry-84.js +2 -0
  434. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +2 -0
  435. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +23 -0
  436. package/src/extensions/pi-agent-text-editor/src/api/text-selection-anchor.ts +31 -1
  437. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +11 -21
  438. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +5 -5
  439. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +13 -7
  440. package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +22 -4
  441. package/src/extensions/pi-agent-text-editor/src/core/image-write.ts +111 -0
  442. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +3 -0
  443. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +2 -6
  444. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +5 -1
  445. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +17 -36
  446. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +8 -2
  447. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +103 -20
  448. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +146 -62
  449. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +14 -19
  450. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +63 -74
  451. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +5 -5
  452. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +7 -10
  453. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +4 -10
  454. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +8 -8
  455. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +5 -8
  456. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +3 -4
  457. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +37 -22
  458. package/src/pi-agent-ide.ts +12 -16
  459. package/src/plugins/pi-agent-ide-ast/package.json +15 -15
  460. package/src/plugins/pi-agent-ide-ast/runtime/entry-37.js +1 -0
  461. package/src/plugins/pi-agent-ide-ast/src/extension.ts +8 -8
  462. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +104 -26
  463. package/src/plugins/pi-agent-ide-ast/src/tool-ast-search.ts +210 -0
  464. package/src/plugins/pi-agent-ide-changes/index.ts +1 -2
  465. package/src/plugins/pi-agent-ide-changes/package.json +10 -10
  466. package/src/plugins/pi-agent-ide-changes/runtime/entry-39.js +1 -0
  467. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +3 -3
  468. package/src/plugins/pi-agent-ide-debugger/index.ts +31 -13
  469. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +2 -11
  470. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  471. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  472. package/src/plugins/pi-agent-ide-languages/runtime/entry-42.js +2 -0
  473. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  474. package/src/plugins/pi-agent-ide-lint/runtime/entry-43.js +2 -0
  475. package/src/plugins/pi-agent-ide-lsp/index.ts +22 -28
  476. package/src/plugins/pi-agent-ide-lsp/package.json +14 -10
  477. package/src/plugins/pi-agent-ide-lsp/runtime/entry-44.js +2 -0
  478. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +1 -1
  479. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +8 -84
  480. package/src/plugins/pi-agent-ide-lsp/src/lsp/index.ts +1 -6
  481. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +11 -11
  482. package/src/plugins/pi-agent-ide-lsp/src/manager-provider.ts +8 -0
  483. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  484. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +234 -36
  485. package/src/plugins/pi-agent-ide-lsp/src/tool-lsp-search.ts +212 -0
  486. package/src/plugins/pi-agent-ide-processes/src/ui.ts +61 -16
  487. package/src/plugins/pi-agent-ide-terminal/index.ts +43 -1
  488. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +0 -18
  489. package/src/plugins/pi-agent-ide-terminal/src/search.ts +0 -3
  490. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -3
  491. package/src/standalone/resource-host.ts +147 -0
  492. package/src/standalone/scoped-api.ts +457 -0
  493. package/dist/chunk-2RTCSZB3.js +0 -1
  494. package/dist/chunk-4DIUPEDF.js +0 -2
  495. package/dist/chunk-6EDOLYOV.js +0 -1
  496. package/dist/chunk-6FGLAVPJ.js +0 -1
  497. package/dist/chunk-6H32W35W.js +0 -1
  498. package/dist/chunk-6OJ565FL.js +0 -2
  499. package/dist/chunk-6R3Y4AD3.js +0 -1
  500. package/dist/chunk-6TJPMBUQ.js +0 -1
  501. package/dist/chunk-6XFUICD7.js +0 -1
  502. package/dist/chunk-BHSO2MDK.js +0 -6
  503. package/dist/chunk-GBUJOR6V.js +0 -28
  504. package/dist/chunk-GSOYVIQS.js +0 -1
  505. package/dist/chunk-HSRH76JN.js +0 -3
  506. package/dist/chunk-HSZ4AQ6L.js +0 -9
  507. package/dist/chunk-I6NPILT5.js +0 -1
  508. package/dist/chunk-K7SRNBIV.js +0 -1
  509. package/dist/chunk-LCWBVOII.js +0 -3
  510. package/dist/chunk-MKEC3U2M.js +0 -4
  511. package/dist/chunk-NUM3YQGK.js +0 -1
  512. package/dist/chunk-OM4LYD3S.js +0 -1
  513. package/dist/chunk-PLKYHUNT.js +0 -1
  514. package/dist/chunk-PT35ZFLH.js +0 -33
  515. package/dist/chunk-QIJMV2P2.js +0 -2
  516. package/dist/chunk-RVU73VKN.js +0 -2
  517. package/dist/chunk-SDAH3ECM.js +0 -5
  518. package/dist/chunk-SGQWRIRJ.js +0 -10
  519. package/dist/chunk-SWBJS3U4.js +0 -1
  520. package/dist/chunk-T7I2VX3J.js +0 -1
  521. package/dist/chunk-T7MWQQIF.js +0 -3
  522. package/dist/chunk-VDP5CQHM.js +0 -3
  523. package/dist/chunk-XG7QNAKW.js +0 -9
  524. package/dist/chunk-XLWCSJMR.js +0 -1
  525. package/dist/chunk-YFP4P2FV.js +0 -1
  526. package/dist/chunk-YIXP2ALP.js +0 -9
  527. package/dist/entry-23.js +0 -1
  528. package/docs/agent-guides/diagnostics.md +0 -5
  529. package/docs/agent-guides/json-reading.md +0 -57
  530. package/docs/agent-guides/read-resources.md +0 -17
  531. package/docs/agent-guides/search-code.md +0 -76
  532. package/docs/agent-guides/select-code.md +0 -119
  533. package/docs/agent-guides/vision.md +0 -11
  534. package/node_modules/pi-agent-doctor/runtime/entry-22.js +0 -1
  535. package/node_modules/pi-agent-doctor/runtime/entry-23.js +0 -1
  536. package/node_modules/pi-agent-filesystem/runtime/entry-29.js +0 -2
  537. package/node_modules/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  538. package/node_modules/pi-agent-filesystem-text/runtime/entry-33.js +0 -2
  539. package/node_modules/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  540. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  541. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  542. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  543. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  544. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  545. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +0 -387
  546. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +0 -41
  547. package/node_modules/pi-agent-ide-ast/src/source-text.ts +0 -92
  548. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +0 -214
  549. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +0 -277
  550. package/node_modules/pi-agent-ide-changes/runtime/entry-36.js +0 -1
  551. package/node_modules/pi-agent-ide-changes/runtime/entry-37.js +0 -2
  552. package/node_modules/pi-agent-ide-languages/runtime/entry-39.js +0 -2
  553. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  554. package/node_modules/pi-agent-image/runtime/entry-42.js +0 -1
  555. package/node_modules/pi-agent-invariant/runtime/entry-43.js +0 -1
  556. package/node_modules/pi-agent-pdf/runtime/entry-44.js +0 -1
  557. package/node_modules/pi-agent-search/runtime/entry-52.js +0 -1
  558. package/node_modules/pi-agent-search-text/runtime/entry-55.js +0 -2
  559. package/node_modules/pi-agent-search-text/runtime/entry-57.js +0 -1
  560. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  561. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-62.js +0 -2
  562. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-63.js +0 -1
  563. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-64.js +0 -2
  564. package/node_modules/pi-agent-text-editor/runtime/entry-65.js +0 -1
  565. package/node_modules/pi-agent-text-editor/runtime/entry-67.js +0 -1
  566. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  567. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  568. package/node_modules/pi-agent-tool-call-interception/runtime/entry-84.js +0 -1
  569. package/node_modules/pi-agent-tool-ui/runtime/entry-85.js +0 -1
  570. package/node_modules/pi-agent-tool-ui/runtime/entry-86.js +0 -1
  571. package/node_modules/pi-agent-web/runtime/entry-87.js +0 -2
  572. package/node_modules/pi-agent-web-html/runtime/entry-88.js +0 -2
  573. package/node_modules/pi-agent-web-image/runtime/entry-89.js +0 -2
  574. package/src/backend/vision-capture-worker.py +0 -319
  575. package/src/backend/vision-capture.ts +0 -165
  576. package/src/backend/vision-registration.ts +0 -104
  577. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-30.js +0 -2
  578. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-31.js +0 -2
  579. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-33.js +0 -2
  580. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-29.js +0 -2
  581. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-88.js +0 -2
  582. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-89.js +0 -2
  583. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-90.js +0 -2
  584. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-87.js +0 -2
  585. package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
  586. package/src/extensions/pi-agent-read/runtime/entry-46.js +0 -1
  587. package/src/extensions/pi-agent-read/runtime/entry-47.js +0 -1
  588. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +0 -2
  589. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +0 -1
  590. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-57.js +0 -1
  591. package/src/extensions/pi-agent-search/runtime/entry-52.js +0 -1
  592. package/src/extensions/pi-agent-search/runtime/entry-53.js +0 -1
  593. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-60.js +0 -2
  594. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-62.js +0 -2
  595. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-63.js +0 -1
  596. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-64.js +0 -2
  597. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-82.js +0 -2
  598. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-83.js +0 -2
  599. package/src/extensions/pi-agent-text-editor/runtime/entry-65.js +0 -1
  600. package/src/extensions/pi-agent-text-editor/runtime/entry-66.js +0 -1
  601. package/src/extensions/pi-agent-text-editor/runtime/entry-67.js +0 -1
  602. package/src/plugins/pi-agent-ide-ast/runtime/entry-34.js +0 -1
  603. package/src/plugins/pi-agent-ide-ast/runtime/entry-35.js +0 -2
  604. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +0 -193
  605. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +0 -59
  606. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +0 -204
  607. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +0 -184
  608. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +0 -105
  609. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +0 -387
  610. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +0 -41
  611. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +0 -92
  612. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +0 -214
  613. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +0 -277
  614. package/src/plugins/pi-agent-ide-changes/runtime/entry-36.js +0 -1
  615. package/src/plugins/pi-agent-ide-changes/runtime/entry-37.js +0 -2
  616. package/src/plugins/pi-agent-ide-languages/runtime/entry-39.js +0 -2
  617. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +0 -136
  618. package/src/plugins/pi-agent-ide-vision/index.ts +0 -439
  619. package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +0 -47
  620. package/src/plugins/pi-agent-ide-vision/src/vision.ts +0 -585
  621. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +0 -30
  622. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +0 -33
  623. /package/dist/{chunk-U2JKHKLK.js → chunk-3PMHFEJY.js} +0 -0
  624. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-28.js +0 -0
  625. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem}/runtime/entry-31.js +0 -0
  626. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-32.js +0 -0
  627. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-pdf}/runtime/entry-35.js +0 -0
  628. /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-38.js +0 -0
  629. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-40.js +0 -0
  630. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-41.js +0 -0
  631. /package/node_modules/{pi-agent-read → pi-agent-image}/runtime/entry-45.js +0 -0
  632. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-46.js +0 -0
  633. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-47.js +0 -0
  634. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-50.js +0 -0
  635. /package/node_modules/{pi-agent-search → pi-agent-read}/runtime/entry-51.js +0 -0
  636. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-53.js +0 -0
  637. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-56.js +0 -0
  638. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-59.js +0 -0
  639. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-search-text}/runtime/entry-61.js +0 -0
  640. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-66.js +0 -0
  641. /package/node_modules/{pi-agent-web-pdf → pi-agent-web}/runtime/entry-90.js +0 -0
  642. /package/node_modules/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-91.js +0 -0
  643. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-32.js +0 -0
  644. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-html}/runtime/entry-91.js +0 -0
  645. /package/src/extensions/{pi-agent-search → pi-agent-read}/runtime/entry-51.js +0 -0
  646. /package/src/extensions/{pi-agent-text-editor/plugins/pi-agent-text-anchor-exact → pi-agent-search/plugins/pi-agent-search-text}/runtime/entry-61.js +0 -0
  647. /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-ast}/runtime/entry-38.js +0 -0
  648. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-changes}/runtime/entry-40.js +0 -0
  649. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-formatter}/runtime/entry-41.js +0 -0
@@ -0,0 +1,4 @@
1
+ import{a as M}from"./chunk-K5G4FDXD.js";import{a as v,b as _,c as z,d as F}from"./chunk-B25LXXNV.js";import{b as S,c as I,g as $,i as A,k as T,l as N,o as O}from"./chunk-7D7PXIVV.js";import{a as j}from"./chunk-MDD5ORB6.js";import{b as R,c as b}from"./chunk-MLFJU2US.js";import{a as u}from"./chunk-ZC65Z3CK.js";import{a as D}from"./chunk-ZAWRSA7N.js";import{a as P,b as E}from"./chunk-OFILFO6D.js";import{a as l}from"./chunk-EI7MMDWY.js";import le from"node:path";var p=[c("dart-analyze",["dart"],["dart"],["analysis_options.yaml","pubspec.yaml"],[".dart"],["dart","analyze","--format","machine","{file}"],"regex","https://dart.dev/tools/dart-analyze","^(?<severity>[^|]+)\\|[^|]+\\|(?<code>[^|]+)\\|(?<file>[^|]+)\\|(?<line>\\d+)\\|(?<column>\\d+)\\|\\d+\\|(?<message>.*)$",void 0,[0,1,2,3]),c("zig-ast-check",["zig"],["zig"],["build.zig","build.zig.zon","zls.json"],[".zig",".zon"],["zig","ast-check","{file}"],"gcc","https://ziglang.org/documentation/master/"),c("lintr",["r"],["Rscript"],[".lintr","DESCRIPTION"],[".r"],["Rscript","-e","print(lintr::lint(commandArgs(TRUE)[1]))","{file}"],"regex","https://lintr.r-lib.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[^:]+): \\[(?<code>[^\\]]+)\\] (?<message>.*)$"),c("clang-tidy",["c","cpp"],["clang-tidy"],[".clang-tidy","compile_commands.json"],[".c",".h",".cc",".cpp",".cxx",".hh",".hpp",".hxx"],["clang-tidy","{file}"],"clang","https://clang.llvm.org/extra/clang-tidy/"),c("eslint",["javascript","typescript","vue","svelte"],["eslint"],["eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","eslint.config.mts","eslint.config.cts",".eslintrc",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".eslintrc.yaml",".eslintrc.yml"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".vue",".svelte"],["eslint","--format","json","{file}"],"eslint-json","https://eslint.org/docs/latest/",void 0,["eslint"]),c("oxlint",["javascript","typescript"],["oxlint"],[".oxlintrc.json",".oxlintrc.jsonc","oxlint.config.ts","oxlint.config.mts"],[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],["oxlint","--format","sarif","{file}"],"sarif","https://oxc.rs/docs/guide/usage/linter.html",void 0,["oxlint"]),c("ruff",["python"],["ruff"],["pyproject.toml","ruff.toml",".ruff.toml"],[".py",".pyi"],["ruff","check","--output-format","concise","{file}"],"regex","https://docs.astral.sh/ruff/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<code>\\S+) (?<message>.+)$",["ruff"]),c("golangci-lint",["go"],["golangci-lint"],[".golangci.yml",".golangci.yaml","go.mod"],[".go"],["golangci-lint","run","--output.text.path=","--output.checkstyle.path=stdout","--show-stats=false","./..."],"checkstyle","https://golangci-lint.run/"),c("clippy",["rust"],["cargo"],["Cargo.toml","clippy.toml"],[".rs"],["cargo","clippy","--message-format","short"],"gcc","https://doc.rust-lang.org/clippy/"),c("dotnet-format",["csharp"],["dotnet"],[".editorconfig","global.json"],[".cs"],["dotnet","format","--verify-no-changes","--include","{relativeFile}"],"regex","https://learn.microsoft.com/dotnet/core/tools/dotnet-format","^(?<file>.+)\\((?<line>\\d+),(?<column>\\d+)\\): (?<severity>error|warning) (?<code>[^:]+): (?<message>.*?)(?: \\[.*\\])?$",void 0,[0,2]),c("checkstyle",["java"],["checkstyle"],["checkstyle.xml","pom.xml"],[".java"],["checkstyle","-c","checkstyle.xml","-f","xml","{file}"],"checkstyle","https://checkstyle.org/"),c("detekt",["kotlin"],["detekt"],["detekt.yml","build.gradle.kts"],[".kt",".kts"],["detekt","--input","{file}","--config","detekt.yml"],"regex","https://detekt.dev/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<message>.*?) \\[(?<code>[^\\]]+)\\]$",void 0,[0,2]),c("rubocop",["ruby"],["rubocop"],[".rubocop.yml","Gemfile"],[".rb",".rake"],["rubocop","--format","clang","{file}"],"regex","https://docs.rubocop.org/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?:\\[Correctable\\] )?(?<code>[^:]+): (?<message>.*)$"),c("phpcs",["php"],["phpcs"],["phpcs.xml","phpcs.xml.dist","composer.json"],[".php"],["phpcs","--report=checkstyle","{file}"],"checkstyle","https://github.com/PHPCSStandards/PHP_CodeSniffer",void 0,void 0,[0,1,2,3]),c("swiftlint",["swift"],["swiftlint"],[".swiftlint.yml","Package.swift"],[".swift"],["swiftlint","lint","--quiet","--reporter","checkstyle","{file}"],"checkstyle","https://github.com/realm/SwiftLint",void 0,void 0,[0,2]),c("scalafix",["scala"],["scalafix"],[".scalafix.conf"],[".scala",".sc"],["scalafix","--check","--files","{file}"],"gcc","https://scalacenter.github.io/scalafix/",void 0,void 0,[0,2,64,66]),c("credo",["elixir"],["mix"],["mix.exs",".credo.exs"],[".ex",".exs"],["mix","credo","--strict","--format","flycheck","--files-included","{file}"],"regex","https://hexdocs.pm/credo/","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>[A-Z]): (?<message>.+)$",void 0,Array.from({length:32},(t,e)=>e)),c("psscriptanalyzer",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],[".ps1",".psm1",".psd1"],["pwsh","-NoProfile","-NonInteractive","-CommandWithArgs",'$ErrorActionPreference="Stop";$options=@{};if(Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1){$options.Settings="PSScriptAnalyzerSettings.psd1"};Invoke-ScriptAnalyzer -Path $args[0] @options | ForEach-Object {"$($_.ScriptPath):$($_.Line):$($_.Column): $($_.Severity): $($_.Message) [$($_.RuleName)]"}',"{file}"],"regex","https://learn.microsoft.com/powershell/module/psscriptanalyzer/invoke-scriptanalyzer","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): (?<severity>\\w+): (?<message>.+) \\[(?<code>[^\\]]+)\\]$",void 0,[0]),c("luacheck",["lua"],["luacheck"],[".luacheckrc"],[".lua"],["luacheck","--formatter","plain","--codes","--no-color","{file}"],"regex","https://github.com/lunarmodules/luacheck","^(?<file>.+):(?<line>\\d+):(?<column>\\d+): \\((?<code>(?<severity>[WE])\\d+)\\) (?<message>.+)$",void 0,[0,1,2]),c("shellcheck",["shell"],["shellcheck"],[".shellcheckrc"],[".sh",".bash",".zsh"],["shellcheck","-f","gcc","{file}"],"gcc","https://www.shellcheck.net/"),c("stylelint",["css"],["stylelint"],["stylelint.config.js",".stylelintrc.json"],[".css",".scss",".sass",".less"],["stylelint","--formatter","compact","{file}"],"regex","https://stylelint.io/","^(?<file>.+): line (?<line>\\d+), col (?<column>\\d+), (?<severity>error|warning) - (?<message>.+) \\((?<code>[^)]+)\\)$",["stylelint"],[0,2]),c("yamllint",["yaml"],["yamllint"],[".yamllint",".yamllint.yml"],[".yaml",".yml"],["yamllint","-f","parsable","{file}"],"regex","https://yamllint.readthedocs.io/","^(?<file>.+?):(?<line>\\d+):(?<column>\\d+): \\[(?<severity>[^\\]]+)\\] (?<message>.*?) \\((?<code>[^)]+)\\)$"),c("markdownlint",["markdown"],["markdownlint"],[".markdownlint.json",".markdownlint.yaml"],[".md",".mdx"],["markdownlint","{file}"],"regex","https://github.com/DavidAnson/markdownlint","^(?<file>.+?):(?<line>\\d+)(?::(?<column>\\d+))? (?<severity>error|warning) (?<code>MD\\d+)(?:/\\S+)? (?<message>.*)$"),c("sqlfluff",["sql"],["sqlfluff"],[".sqlfluff","pyproject.toml"],[".sql"],["sqlfluff","lint","--format","sarif","{file}"],"sarif","https://docs.sqlfluff.com/"),c("hadolint",["dockerfile"],["hadolint"],[".hadolint.yaml"],[".dockerfile"],["hadolint","--format","checkstyle","{file}"],"checkstyle","https://github.com/hadolint/hadolint",void 0,void 0,[0,1],void 0,["Dockerfile","Containerfile"]),c("tflint",["terraform"],["tflint"],[".tflint.hcl"],[".tf"],["tflint","--format","checkstyle"],"checkstyle","https://github.com/terraform-linters/tflint",void 0,void 0,[0,2]),c("cmake-lint",["cmake"],["cmake-lint"],[".cmake-format.py","CMakeLists.txt"],[".cmake"],["cmake-lint","{file}"],"regex","https://cmake-format.readthedocs.io/","^(?<file>.+?):(?<line>\\d+),(?<column>\\d+): \\[(?<code>(?<severity>[A-Z])\\d+)\\] (?<message>.*)$",void 0,[0,1],0,["CMakeLists.txt"]),c("htmlhint",["html"],["htmlhint"],[".htmlhintrc"],[".html",".htm"],["htmlhint","--format","checkstyle","--nocolor","{file}"],"checkstyle","https://htmlhint.com/"),c("jsonlint",["json"],["jsonlint"],[".jsonlintrc",".jsonlintrc.json",".jsonlintrc.yaml",".jsonlintrc.yml",".jsonlintrc.js",".jsonlintrc.cjs","jsonlint.config.js","jsonlint.config.cjs"],[".json"],["jsonlint","-q","{file}"],"regex","https://github.com/prantlf/jsonlint","^(?:Error: )?(?<message>Parse (?<severity>error) on line (?<line>\\d+)(?:, column (?<column>\\d+))?:[^\\n]*)$",["@prantlf/jsonlint","jsonlint"]),c("taplo-check",["toml"],["taplo"],["taplo.toml"],[".toml"],["taplo","check","--colors","never","{file}"],"regex","https://taplo.tamasfe.dev/","^(?<severity>error): (?<message>[^\\n]+)\\n\\s*\u250C\u2500 (?<file>.+):(?<line>\\d+):(?<column>\\d+)"),c("xmllint",["xml"],["xmllint"],[".xmllintrc"],[".xml",".xsd",".xsl"],["xmllint","--noout","{file}"],"regex","https://gnome.pages.gitlab.gnome.org/libxml2/xmllint.html","^(?<file>.+?):(?<line>\\d+): (?<severity>(?:parser |validity )?(?:error|warning)) : (?<message>.*)$",void 0,[0,1,2,3,4])];function c(t,e,n,r,o,s,f,i,a,d,m=[0,1],k,y){return{id:t,name:t,kind:"linter",languages:e,executables:n,configFiles:r,documentation:i,...d&&{dependencies:d},linter:{extensions:o,...y&&{fileNames:y},check:{command:s,successExitCodes:m},diagnostics:{format:f,...a&&{pattern:a},...k!==void 0&&{columnBase:k}}}}}l(c,"recipe");import x from"node:path";import ie from"node:os";import{fileURLToPath as re}from"node:url";function V(t,e){if(t.trim().length===0)return[];switch(e.format){case"pi-json":return H(t);case"eslint-json":return B(t);case"sarif":return Z(t);case"checkstyle":return X(t);case"gcc":case"clang":return K(t);case"regex":return Q(t,u(e.pattern),e.columnBase??1)}}l(V,"parseDiagnostics");function H(t){let e=JSON.parse(t);return Array.isArray(e.diagnostics)?e.diagnostics.flatMap(h):[]}l(H,"parsePiJson");function B(t){return JSON.parse(t).flatMap(n=>Array.isArray(n.messages)?n.messages.flatMap(r=>h(r).map(o=>({...o,...n.filePath&&{file:n.filePath}}))):[])}l(B,"parseEslintJson");function Z(t){return(JSON.parse(t).runs??[]).flatMap(n=>(n.results??[]).flatMap(r=>{let o=r.locations?.[0]?.physicalLocation,s=o?.region??{},f=r.message;return h({file:o?.artifactLocation?.uri,line:s.startLine,column:s.startColumn,message:f?.text,code:r.ruleId,severity:te(r.level)})}))}l(Z,"parseSarif");function X(t){let e=[];for(let n of t.matchAll(/<file\s+([^>]+)>([\s\S]*?)<\/file>/gu)){let r=q(u(n[1])).name;for(let o of u(n[2]).matchAll(/<error\s+([^>]+?)\/?>(?:<\/error>)?/gu)){let s=q(u(o[1]));e.push(...h({file:r,line:Number(s.line),column:Number(s.column??1),message:s.message,code:s.source,severity:s.severity}))}}return e}l(X,"parseCheckstyle");function q(t){return Object.fromEntries([...t.matchAll(/([\w-]+)="([^"]*)"/gu)].map(e=>[u(e[1]),ne(u(e[2]))]))}l(q,"xmlAttributes");function K(t){return Y(t,/^(?<file>.+?):(?<line>\d+):(?<column>\d+):\s*(?<severity>fatal error|error|warning|note|info|hint):\s*(?<message>.*?)(?:\s+\[(?<code>[^\]]+)\])?$/u)}l(K,"parseCompilerLines");function Q(t,e,n){return[...t.replaceAll(`\r
2
+ `,`
3
+ `).matchAll(new RegExp(e,"gmu"))].flatMap(r=>r.groups===void 0?[]:h({...r.groups,...r.groups.column!==void 0&&{column:Number(r.groups.column)+(1-n)}}))}l(Q,"parseRegexLines");function Y(t,e){return t.split(/\r?\n/u).flatMap(n=>{let r=n.match(e)?.groups;return r===void 0?[]:h(r)})}l(Y,"parseMatchingLines");function h(t){if(typeof t!="object"||t===null)return[];let e=t,n=J(e.line??e.startLine),r=J(e.column??e.startColumn,1),o=typeof e.message=="string"?e.message:void 0;return n===void 0||o===void 0?[]:[{...typeof e.file=="string"&&{file:e.file},code:U(e.code??e.ruleId,"lint"),message:o,line:n,column:r??1,severity:ee(e.severity)}]}l(h,"normalizeDiagnostic");function J(t,e){let n=typeof t=="string"?Number.parseInt(t,10):t;return typeof n=="number"&&Number.isInteger(n)&&n>=1?n:e}l(J,"numberValue");function U(t,e){return typeof t=="string"||typeof t=="number"?String(t):e}l(U,"stringValue");function ee(t){if(t===2)return"error";if(t===1)return"warning";let e=U(t,"warning").toLowerCase();return e.includes("error")||e==="e"||e==="f"||e==="fatal"?"error":e==="info"||e==="note"||e==="notice"?"info":e==="hint"?"hint":"warning"}l(ee,"severityValue");function te(t){return t==="error"||t==="warning"||t==="note"?t:"warning"}l(te,"sarifSeverity");function ne(t){return t.replace(/&#(x[0-9a-f]+|\d+);/giu,(e,n)=>{let r=n.toLowerCase().startsWith("x")?Number.parseInt(n.slice(1),16):Number(n);return r<=1114111?String.fromCodePoint(r):e}).replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}l(ne,"decodeXml");var g=class t{constructor(e,n,r=new Map){this.linters=e;this.availableBuiltIns=n;this.evidence=r}static{l(this,"LintCommandRegistry")}static async fromDirectory(e,n={}){let r=await $(e,"linters",i=>O(i).linters,n),{available:o,evidence:s}=await T(e,r.entries.filter(i=>i.layer==="built-in").map(i=>({id:i.id,config:i.config.check})),p,n),f=[...r.entries].sort((i,a)=>i.layer==="built-in"&&a.layer==="built-in"?(s.get(a.id)?.score??0)-(s.get(i.id)?.score??0):0);return new t(f,o,s)}static fromConfig(e){return new t(Object.entries(e.linters).map(([n,r])=>({id:n,config:r,layer:"project",sourcePath:"<memory>"})),new Set)}resolve(e,n){return this.resolveEntry(e,n)?.config}resolveEntry(e,n){return A(this.linters,this.availableBuiltIns,this.evidence,e,n)}get entries(){return this.linters}};async function C(t,e){let n;try{let i=x.basename(t.check.command[0]??"").toLocaleLowerCase(),a=i==="ruff"||i==="ruff.exe",d=e.env??process.env;n=await N(t.check,{...e,...a&&!e.processAccess?{env:{...d,RUFF_CACHE_DIR:d.RUFF_CACHE_DIR??x.join(ie.tmpdir(),"pi-agent-ide","ruff-cache")}}:{}})}catch(i){return{ok:!1,diagnostics:[],failure:`command could not start: ${i instanceof Error?i.message:String(i)}`}}let r=t.diagnostics.format==="regex"||t.diagnostics.format==="clang"?[n.stdout,n.stderr].filter(i=>i.trim().length>0).join(`
4
+ `):n.stdout.trim().length>0?n.stdout:n.stderr,o;try{o=V(r,t.diagnostics)}catch{return{ok:!1,diagnostics:[],failure:`invalid ${t.diagnostics.format} diagnostics: ${r.trim().slice(0,200)||"empty command output"}`}}let s=n.ok&&(n.exitCode===0||o.length>0),f=t.check.cwd==="file"?x.dirname(e.filePath):e.projectRoot;return o=o.filter(i=>{if(i.file===void 0)return!0;if(e.acceptsFile)return e.acceptsFile(i.file);let a=i.file.startsWith("file:")?re(i.file):i.file;return M(x.resolve(f,a),e.filePath)}).map(({file:i,...a})=>a),{ok:s,diagnostics:o,...!s&&{failure:n.stderr.trim().slice(0,200)||`command exited with code ${String(n.exitCode)}`}}}l(C,"runConfiguredLinter");function W(t,e=C){return{kind:"linter",name:"command-lint",priority:100,extensions:["*"],detect:l(()=>Promise.resolve(!0),"detect"),async lint({filePath:n,fix:r},o){let s=t.resolve(n,o.cwd);if(s===void 0)return{ok:!0,diagnostics:[]};let f=r===!0&&s.fix!==void 0?s.fix:s.check,i=await e({...s,check:f},{projectRoot:o.cwd,filePath:n});return{ok:i.ok,diagnostics:i.diagnostics}}}}l(W,"createCommandLinter");var G={protocol:R,apiVersion:b,id:"lint",setup(t){for(let e of p)t.addToolRecipe(e);t.addSetupCheck({id:"effective-config",inspect:oe}),t.addCheck({id:"config",title:"Linter",async run(e){try{let n=await g.fromDirectory(e.cwd,v(e)),r=se(n,e.files,e.cwd);return r.length===0?[{status:"skip",message:"No linter matches the inspected project files"}]:await Promise.all(r.map(async({entry:o,source:s})=>{let f=`${o.id} [${o.layer}] command ${JSON.stringify(o.config.check.command)}`;return F(e,s,async i=>{try{let a=await C(o.config,{projectRoot:e.cwd,filePath:i,env:e.env,signal:e.signal,processAccess:_(e)});return e.signal?.throwIfAborted(),a.ok?{status:"pass",message:`${f}: probe passed`,detail:o.sourcePath}:{status:"fail",message:`${f}: probe failed`,detail:a.failure??o.sourcePath}}catch(a){return e.signal?.throwIfAborted(),{status:"fail",message:`${f}: ${a instanceof Error?a.message:String(a)}`,detail:o.sourcePath}}})}))}catch(n){return e.signal?.throwIfAborted(),[{status:"fail",message:n instanceof Error?n.message:String(n)}]}}})}};async function oe(t){try{let e=await g.fromDirectory(t.cwd,v(t)),n=[],r=new Map;for(let[o,s]of t.detectedLanguages){let f=s.map(i=>e.resolveEntry(i,t.cwd)).find(i=>i!==void 0);f!==void 0&&(n.push({kind:"linter",languageId:o,toolId:f.id}),await z(t,f.config.check)||r.set(f.id,{id:`linter-${f.id}-unavailable`,message:`Configured linter ${f.id} cannot run ${JSON.stringify(f.config.check.command)}`}))}return{selections:n,actions:[...r.values()]}}catch(e){return t.signal?.throwIfAborted(),{actions:[{id:"linter-config-invalid",message:`Linter configuration cannot load: ${e instanceof Error?e.message:String(e)}`}]}}}l(oe,"inspectLinterSetup");function se(t,e,n){let r=new Map;for(let o of e){let s=t.resolveEntry(o,n);s!==void 0&&!r.has(s.id)&&r.set(s.id,{entry:s,source:o})}return[...r.values()]}l(se,"applicableLinters");async function ae(t){await ce(t)}l(ae,"registerLint");async function ce(t,e){let n=new Map,r=l((i,a=!1)=>{let d=JSON.stringify([i,a]),m=n.get(d);return m===void 0&&(m=e?e.loadRegistry(i,a):fe(i,a),n.set(d,m)),m},"registryFor"),o=l(async(i,a)=>{if(e)return e.resolveProject(i,a);if(i.includes("://")||a.includes("://"))throw Object.assign(new Error("Linter requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});let d=await I(a,i,"linters",p);return d===void 0?void 0:{projectRoot:d,external:d!==le.resolve(a)}},"resolveProject"),s={kind:"linter",name:"pi-agent-ide-lint",priority:200,extensions:["*"],detect:l(async i=>(await r(i.cwd),!0),"detect"),async lint(i,a){let d=await o(i.filePath,a.cwd);if(d===void 0)return{ok:!0,diagnostics:[]};let m=await r(d.projectRoot,d.external);return W(m,e?.run).lint(i,{cwd:d.projectRoot})}},f={protocol:P,apiVersion:5,id:"lint",setup(i){i.addTool(s),i.addDiagnosticSource({id:"lint",async diagnose(a,d){let m=await o(a,d.cwd);if(m===void 0)return{status:"unavailable",diagnostics:[],reason:"No linter project found for this file"};let k=await r(m.projectRoot,m.external);d.signal.throwIfAborted();let y=k.resolve(a,m.projectRoot);if(!y)return{status:"unavailable",diagnostics:[],reason:"No linter configured for this file"};let L=S(y.check.command),w=await(e?.run??C)(y,{projectRoot:m.projectRoot,filePath:a,signal:d.signal});return!w.ok&&w.diagnostics.length===0?{status:"unavailable",diagnostics:[],reason:w.failure??"Lint check failed",source:L}:{status:"ready",diagnostics:w.diagnostics,source:L}}})}};await Promise.all([D(t,f),j(t,G)])}l(ce,"registerLintWithOwner");async function fe(t,e){let n=e?t:process.env.PI_AGENT_IDE_CONFIG_DIR??t;return g.fromDirectory(n,{includeGlobal:!e,requireBuiltInEvidence:!0})}l(fe,"loadRegistry");export{p as a,g as b,C as c,ae as d,ce as e};
@@ -0,0 +1 @@
1
+ import{d as S,e as b}from"./chunk-FYOU4RBH.js";import{a as h}from"./chunk-EI7MMDWY.js";import z from"node:path";import{pathToFileURL as R}from"node:url";function x(e,n){let r=new Map;for(let t of e){let i=r.get(t.source)??[];i.push(t),r.set(t.source,i)}let a=new Set,u=e.length,s=[...r].sort(([t,i],[m,d])=>d.length-i.length||t.localeCompare(m));for(let[t,i]of s){if(u<=n)break;a.add(t),u-=i.length-1}let c=[],o=n,l=[...r].sort(([t],[i])=>Number(a.has(t))-Number(a.has(i))||t.localeCompare(i));for(let[t,i]of l){if(!a.has(t)){if(i.length>o)continue;c.push({kind:"detailed",source:t,matches:i}),o-=i.length;continue}if(o<1)continue;o--;let m=new Map;for(let f of i){let p=m.get(f.lineText);p===void 0?m.set(f.lineText,{matchCount:1,first:f}):p.matchCount++}let d=[...m].sort(([f,p],[T,w])=>w.matchCount-p.matchCount||f.localeCompare(T)).map(([f,p])=>({text:f,...p})),C=r.size===1?Math.min(o,d.length-1):0,N=d.slice(0,1+C);o-=C,c.push({kind:"compacted",source:t,matchCount:i.length,uniqueLineCount:m.size,groups:N})}return c.sort((t,i)=>t.source.localeCompare(i.source)),{files:c}}h(x,"planSearchPresentation");function L(e,n,r,a,u,s=50){let c=x(n,s),o=new Set(n.map(t=>t.source)).size,l=c.files.map(t=>t.kind==="detailed"?P(t.source,t.matches,a):{path:F(t.source,a),link:R(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups.map(({text:i,matchCount:m})=>({text:i,matchCount:m})),lines:[]});return{...u!==void 0&&{sessionId:u},query:e,matchCount:n.length,fileCount:o,...c.files.length<o?{omittedFileCount:o-l.length,omittedMatchCount:n.length-l.reduce((t,i)=>t+i.matchCount,0)}:{},complete:r,files:l}}h(L,"createSearchToolDetails");function U(e,n){return{fileCount:new Set(e.flatMap(r=>r.matches.map(a=>a.source))).size,groups:e.map(r=>{let u=L(r.identifier,r.matches.slice(0,S.previewMatches),r.complete,n).files.map(s=>{let c=s.lines.map(o=>{let l=Math.max(0,(o.ranges[0]?.from??0)-64),t=Math.min(o.text.length,(o.ranges[0]?.to??0)+64),i=l>0?"\u2026":"",m=o.ranges.filter(d=>d.from>=l&&d.to<=t).map(d=>({from:d.from-l+i.length,to:d.to-l+i.length}));return{...o,text:i+o.text.slice(l,t)+(t<o.text.length?"\u2026":""),ranges:m,matchCount:m.length}});return{...s,lines:c,matchCount:c.reduce((o,l)=>o+l.matchCount,0)}});return{identifier:r.identifier,files:u}})}}h(U,"createFuzzyPresentation");function k(e){return g(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(n=>g(n)&&typeof n.identifier=="string"&&Array.isArray(n.files)&&n.files.every(M))}h(k,"isFuzzyPresentation");function W(e){if(!g(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||e.omittedFileCount!==void 0&&!y(e.omittedFileCount)||e.omittedMatchCount!==void 0&&!y(e.omittedMatchCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!b(e.fuzzy)||e.fuzzyPresentation!==void 0&&!k(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(M))return!1;let n=e.files;return e.fileCount===n.length+(e.omittedFileCount??0)&&e.matchCount===n.reduce((r,a)=>r+a.matchCount,0)+(e.omittedMatchCount??0)}h(W,"isSearchToolDetails");function P(e,n,r){let a=new Map;for(let s of n){let c=a.get(s.lineNumber);if(c!==void 0&&c.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let o=c??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};o.ranges.push({from:s.startColumn,to:s.endLineNumber===void 0?s.endColumn:s.lineText.length}),a.set(s.lineNumber,o)}let u=[...a.values()].sort((s,c)=>s.lineNumber-c.lineNumber).map(s=>{let c=[...s.ranges].sort((o,l)=>o.from-l.from||o.to-l.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:c.length,ranges:c}});return{path:F(e,r),link:R(e).href,matchCount:n.length,lines:u}}h(P,"createSearchResultFile");function M(e){if(!g(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(A))return!1;let n=e.lines,r=e.groups,a=new Set(n.flatMap(u=>u.logicalMatchIds??[]));return(r===void 0||Array.isArray(r)&&r.every(u=>g(u)&&typeof u.text=="string"&&y(u.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(n.length===0||(a.size>0?a.size===e.matchCount:e.matchCount===n.reduce((u,s)=>u+s.matchCount,0)))}h(M,"isSearchResultFile");function A(e){return g(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(n=>typeof n=="string"))&&e.ranges.every(n=>I(n,e.text))}h(A,"isSearchResultLine");function I(e,n){return g(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=n.length}h(I,"isSearchResultRange");function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}h(g,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}h(y,"isCount");function F(e,n){if(e.includes("://"))return e;let r=z.relative(n,e);return r.length>0&&!r.startsWith("..")&&!z.isAbsolute(r)?r:e}h(F,"displaySource");export{x as a,L as b,U as c,W as d};
@@ -0,0 +1 @@
1
+ import{a as m,b as S}from"./chunk-ZXO4D5UB.js";import"./chunk-VMLPXSMK.js";import{a as u,b as w,c as g}from"./chunk-WQIMM4SU.js";import"./chunk-FHRHYY4M.js";import{g as o}from"./chunk-4IWEKRSP.js";import{a as R,c as y}from"./chunk-MPNE25CY.js";import{c as l}from"./chunk-W7CASEO3.js";import"./chunk-NNCZYO4Q.js";import"./chunk-FYOU4RBH.js";import"./chunk-7PVDTMEM.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-MDD5ORB6.js";import"./chunk-MLFJU2US.js";import"./chunk-OMNKD7WW.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DDH3FP4G.js";import"./chunk-756K3LJY.js";import"./chunk-VDJSH3DQ.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{readFile as P}from"node:fs/promises";import{Type as i}from"typebox";import{Value as v}from"typebox/value";var L=i.Object({url:i.String(),status:i.Integer({minimum:200,maximum:599}),statusText:i.String(),headers:i.Array(i.Tuple([i.String(),i.String()])),body:i.String()}),O=new Set(["INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED"]),b;async function I(n,s,r,f){f?.throwIfAborted(),b??=P(new URL("./web-http-worker.py",new URL("../src/backend/web-http.ts",import.meta.url).href),"utf8");try{let e=await m(n,"python3",["-c",await b,JSON.stringify({url:s.href,timeoutSeconds:30})],r,{signal:f,timeoutMs:3e4,maxBytes:33554432});if(e.exitCode!==0)throw new o("HTTP_FAILED",r,"not-applied");let t;try{t=JSON.parse(e.stdout.toString("utf8"))}catch{throw new o("INVALID_RESPONSE",r,"not-applied")}if(typeof t=="object"&&t!==null&&"error"in t)throw new o(typeof t.error=="string"&&O.has(t.error)?t.error:"INVALID_RESPONSE",r,"not-applied");if(!v.Check(L,t))throw new o("INVALID_RESPONSE",r,"not-applied");let c=Buffer.from(t.body,"base64");if(c.toString("base64")!==t.body||c.length>16*1024*1024)throw new o("INVALID_RESPONSE",r,"not-applied");let p;try{let d=new URL(t.url);if(!["http:","https:"].includes(d.protocol)||d.username||d.password)throw new Error("Invalid native HTTP redirect");p=new Response([204,205,304].includes(t.status)?null:c,{status:t.status,statusText:t.statusText,headers:t.headers}),Object.defineProperty(p,"url",{value:d.href})}catch{throw new o("INVALID_RESPONSE",r,"not-applied")}return p}catch(e){throw e instanceof o?new o(e.code,r,e.effect):e}}a(I,"fetchSshWebResponse");function T(n){if(!/^web:/iu.test(n))return;let s=/^web:ssh:\/\/([a-z0-9._-]+)\/(https?:\/\/.+)$/iu.exec(n);if(!s?.[1]||!s[2])throw new o("INVALID_SOURCE",n,"not-applied");let r;try{r=new URL(s[2])}catch{throw new o("INVALID_SOURCE",n,"not-applied")}if(r.username||r.password)throw new o("INVALID_SOURCE",n,"not-applied");return{target:s[1],url:r,source:`web:ssh://${s[1]}/${r.href}`}}a(T,"parseSshWebSource");function E(n,s){return{id:"ssh-web",async tryResolve(r,f){try{let e=T(r);if(!e)return{kind:"not-handled"};f.signal?.throwIfAborted();let t=s.resolve(`ssh://${e.target}/`);if(!t)throw new o("UNSUPPORTED_SOURCE",e.source,"not-applied");let p=await R(n,{fetch:a(async(d,h)=>I(t.backend.target,e.url,e.source,h?.signal??void 0),"fetch"),browser:{load(d,h){return S(t.backend.target,d,e.source,h)}}}).tryResolve(e.url.href,f);return p.kind!=="resolved"?p:{kind:"resolved",resource:{...p.resource,source:e.source}}}catch(e){return{kind:"failed",error:e instanceof o?new o(e.code,r,e.effect):e}}}}}a(E,"createSshWebResolver");async function k(n){let s=new g(await w(u(l())));await y(n,r=>E(r,s))}a(k,"registerOwnedWeb");export{k as default};
@@ -0,0 +1,9 @@
1
+ import{a as Ae}from"./chunk-RIJRPAL2.js";import{a as Ee}from"./chunk-SRFWT562.js";import{a as Ie,b as Re}from"./chunk-USG6WHAT.js";import"./chunk-AMIIOWFL.js";import{b as Ce}from"./chunk-LF325WYO.js";import{a as X,c as xe}from"./chunk-ZXO4D5UB.js";import"./chunk-VMLPXSMK.js";import{a as Pe,b as Se,c as ke}from"./chunk-WQIMM4SU.js";import{a as De}from"./chunk-FHRHYY4M.js";import{a as K,g as D}from"./chunk-4IWEKRSP.js";import{c as ve}from"./chunk-W7CASEO3.js";import{a as ye,b as we,c as be}from"./chunk-57F5GTHO.js";import"./chunk-B25LXXNV.js";import{d as me,e as L}from"./chunk-7D7PXIVV.js";import{a as he}from"./chunk-BXGMMZT3.js";import{a as H,b as de,c as pe,d as le,e as ue,g as fe}from"./chunk-MLFJU2US.js";import"./chunk-DDH3FP4G.js";import{d as ge}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as He,readFile as Ke,writeFile as Xe}from"node:fs/promises";async function Oe(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await He(me(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:d}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,d,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:d}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,d,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:d}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,d,t,o)&&e.push(f)}return e}s(Oe,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Ke(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
2
+ `;return t===i?!1:(o?await o.writeText(n,i,t,e):await Xe(n,i,{encoding:"utf8",signal:e}),!0)}s(q,"writeJson");function Te(n,r){let t=new Set,o;for(let e of n.trim().split(/\s+/u).filter(Boolean))if(["--apply","--no-apply","--agent"].includes(e))t.add(e);else if(e.startsWith("ssh://")&&o===void 0)o=e;else throw new TypeError("Use /pi-agent-ide-doctor [ssh://target/path] [--apply | --no-apply] [--agent]");if(t.has("--apply")&&t.has("--no-apply"))throw new TypeError("Choose --apply or --no-apply, not both");return{cwd:o??r,flags:t}}s(Te,"parseDoctorArguments");var z=class{static{s(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(r){let t=this.plugins.get(r.id);if(t!==void 0)return t;let o=this.queue.then(async()=>{let e=!0,i=[],a=[],u=[],f=[],h={addLanguage:s(d=>{V(d,i,r.id,"language",()=>e)},"addLanguage"),addToolRecipe:s(d=>{V(d,a,r.id,"tool recipe",()=>e)},"addToolRecipe"),addSetupCheck:s(d=>{V(d,u,r.id,"setup check",()=>e)},"addSetupCheck"),addCheck:s(d=>{V(d,f,r.id,"check",()=>e)},"addCheck")};try{await r.setup(h)}finally{e=!1}je(this.languages,i,"language"),je(this.recipes,a,"tool recipe"),this.languages.push(...i),this.recipes.push(...a),this.setupChecks.push(...u),this.checks.push(...f)});return this.plugins.set(r.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(r.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function $e(n,r){let t=[],o=[];for(let e of n.setupChecks)try{let i=await e.value.inspect(r);t.push(...(i.selections??[]).map(a=>({...a,pluginId:e.pluginId}))),o.push(...(i.actions??[]).map(a=>({...a,pluginId:e.pluginId})))}catch{}return{selections:t,actions:o}}s($e,"runContributedSetupChecks");async function Ne(n,r){let t=[];for(let o of n.checks)try{t.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(r)})}catch(e){t.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:e instanceof Error?e.message:String(e)}]})}return t}s(Ne,"runContributedChecks");function je(n,r,t){for(let o of r){let e=n.find(i=>i.value.id===o.value.id)?.pluginId;if(e!==void 0)throw new Error(`${t} ${o.value.id} is already owned by doctor plugin ${e}`)}}s(je,"assertAvailable");function V(n,r,t,o,e){if(!e())throw new Error(`Doctor plugin ${t} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(r.some(i=>i.value.id===n.id))throw new Error(`Doctor plugin ${t} registered ${o} ${n.id} twice`);r.push({pluginId:t,value:n})}s(V,"add");import it from"node:path";import{readFile as Qe}from"node:fs/promises";async function Le(n,r,t,o=process.env,e,i){e?.throwIfAborted();let a=t.filter(({value:g})=>g.languages.some(y=>r.has(y))),u=a.map(g=>g.value),f=i?await i.evidence(u,e):await he(n,u,void 0,e),h=await qe(n,e,i),d=[...new Set(u.flatMap(g=>g.executables))],m=i?await i.executableAvailability(d.map(g=>({command:[g]})),e):void 0;if(e?.throwIfAborted(),m&&(m.length!==d.length||m.some(g=>typeof g!="boolean")))throw new TypeError("Invalid Doctor executable availability report");let w=[];for(let g of a){e?.throwIfAborted();let y=g.value,C=[],I=1,b=f.get(y.id),O=b?.config;O!==void 0&&(I+=6,C.push(`project config: ${O}`)),h.has(`${y.kind}:${y.id}`)&&(I+=6,C.push("Pi Agent IDE config"));let p=b?.dependency;p!==void 0&&(I+=4,C.push(`project dependency: ${p}`));let c=m?y.executables.find(l=>m[d.indexOf(l)]===!0):await Ze(n,y.executables,o,e);c!==void 0&&(I+=3,C.push(`executable: ${c}`)),w.push({pluginId:g.pluginId,recipe:y,score:I,evidence:C,...c&&{executable:c}})}return w.sort((g,y)=>y.score-g.score||g.recipe.id.localeCompare(y.recipe.id))}s(Le,"discoverRecipeCandidates");function _e(n,r,t=[]){let o=new Map,e=new Map(t.map(i=>[`${i.kind}:${i.languageId}`,i.toolId]));for(let i of r)for(let a of["formatter","linter","lsp"]){let u=e.get(`${a}:${i}`),f=u===void 0?4:7,h=n.filter(m=>m.recipe.kind===a&&m.recipe.languages.includes(i)&&m.executable!==void 0&&m.recipe.id!==u&&m.score>=f),d=h[0];d!==void 0&&(h.filter(m=>m.score===d.score).length>1||o.set(`${d.recipe.kind}:${d.recipe.id}`,d))}return[...o.values()]}s(_e,"selectSuggestedRecipes");async function Ze(n,r,t,o){for(let e of r)if(await ge(e,n,t,o))return e}s(Ze,"firstExecutable");async function qe(n,r,t){let o=new Set;for(let[e,i,a]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{r?.throwIfAborted();let u=t?(await t.configPaths(e,r)).project:L(n,e),f=t?await t.readText(u,r):await Qe(u,{encoding:"utf8",signal:r});if(r?.throwIfAborted(),f===void 0)continue;let h=JSON.parse(f);if(typeof h!="object"||h===null||Array.isArray(h))continue;let m=h[i];if(typeof m=="object"&&m!==null&&!Array.isArray(m))for(let w of Object.keys(m))o.add(`${a}:${w}`)}catch(u){if(r?.throwIfAborted(),!(u instanceof SyntaxError)&&!(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT"))throw u}return o}s(qe,"managedRecipeIds");import{execFile as et}from"node:child_process";import{readdir as tt}from"node:fs/promises";import _ from"node:path";import{promisify as ot}from"node:util";var nt=ot(et),rt=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Ue(n,r){r?.throwIfAborted();try{let o=(await nt("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:r})).stdout.split("\0").filter(Boolean).map(e=>_.resolve(n,e)).filter(e=>!Fe(e));return r?.throwIfAborted(),o.length>0?o:await ee(n,r)}catch{return r?.throwIfAborted(),ee(n,r)}}s(Ue,"collectProjectFiles");function Be(n,r,t=process.platform){let o=new Map,e=t==="win32"?_.win32:_;for(let i of r){let a=new Set(i.extensions.map(d=>d.toLowerCase())),u=s(d=>t==="win32"?d.toLowerCase():d,"normalizeName"),f=new Set(i.fileNames?.map(u)),h=n.filter(d=>!d.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")&&(a.has(e.extname(d).toLowerCase())||f.has(u(e.basename(d)))));h.length>0&&o.set(i.id,h)}return o}s(Be,"detectProjectLanguages");async function ee(n,r){r?.throwIfAborted();let t=[];for(let o of await tt(n,{withFileTypes:!0})){if(o.isDirectory()&&rt.has(o.name))continue;let e=_.join(n,o.name);Fe(e)||(o.isDirectory()?t.push(...await ee(e,r)):o.isFile()&&t.push(e))}return t}s(ee,"walk");function Fe(n){return n.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")}s(Fe,"isManagedIdeConfig");function st(n,r){if(n.includes("://")&&!r||r&&r.source!==n)throw Object.assign(new Error(`Doctor requires the owner of ${n}`),{code:"UNSUPPORTED_SOURCE"})}s(st,"assertWorkspace");async function te(n,r,t=process.env,o,e){o?.throwIfAborted(),st(r,e);let i=e?await e.files(o):await Ue(r,o);o?.throwIfAborted();let a=Be(i,n.languages.map(w=>w.value),e?.platform),u=new Set(a.keys()),f={cwd:r,files:i,detectedLanguageIds:u,detectedLanguages:a,env:e?{...e.toolPaths}:t,signal:o,workspace:e},[h,d]=await Promise.all([Le(r,u,n.recipes,e?{...e.toolPaths}:t,o,e),$e(n,f)]);o?.throwIfAborted();let m=new Map;for(let w of u)for(let g of["formatter","linter","lsp"]){if(d.selections.some(b=>b.languageId===w&&b.kind===g))continue;let y=h.filter(b=>b.recipe.kind===g&&b.recipe.languages.includes(w)),C=s(b=>b.score-(b.executable===void 0?0:3),"nativeScore"),I=Math.max(1,...y.map(C));for(let b of y){if(b.executable!==void 0||C(b)!==I||I<=1)continue;let O=`${g}-${b.recipe.id}-unavailable`;m.set(O,{id:O,pluginId:b.pluginId,message:`Native project setup selects ${b.recipe.id}, but its executable is unavailable. Install ${b.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:r,files:i,detectedLanguages:a,candidates:h,selections:d.selections,actions:[...d.actions,...m.values()],suggestions:_e(h,u,d.selections)}}s(te,"inspectDoctorSetup");async function Y(n,r,t=process.env,o,e){let i=await te(n,r,t,o,e),a=new Set(i.detectedLanguages.keys()),u={cwd:r,files:i.files,detectedLanguageIds:a,detectedLanguages:i.detectedLanguages,env:e?{...e.toolPaths}:t,signal:o,workspace:e},f=await Ne(n,u);o?.throwIfAborted();let h=[{status:"pass",message:`Project: ${r}`},i.files.length>0?{status:"pass",message:`${i.files.length} project files inspected`}:{status:"warn",message:"No project files found"},a.size>0?{status:"pass",message:`Detected: ${[...a].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...i,sections:[{title:"Project",pluginId:"doctor",findings:h},...f]}}s(Y,"runDoctor");function M(n){let r=["Pi Agent IDE doctor",""];for(let t of n.sections){r.push(`${t.title} (${t.pluginId})`);for(let o of t.findings)r.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&r.push(` \`${o.detail}\``);r.push("")}if(n.actions.length>0){r.push("Setup needs attention");for(let t of n.actions)r.push(` ${t.message} [${t.pluginId}]`);r.push("")}if(n.suggestions.length>0){r.push("Suggested configuration");for(let t of n.suggestions){let o=t.evidence.length>0?` \u2014 ${t.evidence.join(", ")}`:"";r.push(` ${t.recipe.kind.padEnd(9)} ${t.recipe.id} [${t.pluginId}]${o}`)}r.push("")}return r.join(`
3
+ `).trimEnd()}s(M,"formatDoctorReport");function oe(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(r=>r.findings.some(t=>t.status==="fail"))}s(oe,"doctorNeedsWork");function Me(n){let r=n.candidates.map(t=>({owner:t.pluginId,id:t.recipe.id,kind:t.recipe.kind,languages:t.recipe.languages,evidence:t.evidence,documentation:t.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",M(n),"","Relevant registered recipes:",JSON.stringify(r,null,2),"",`Project root: ${n.cwd.includes("://")?n.cwd:it.resolve(n.cwd)}`].join(`
4
+ `)}s(Me,"buildDoctorAgentPrompt");import{createHash as at}from"node:crypto";var ct="doctor",ne=3;function We(n,r){let t=ye(n,dt(r));t!==void 0&&t.catch(()=>{})}s(We,"registerDoctorTipProvider");function dt(n){return{protocol:we,apiVersion:be,id:ct,async getTip(r){let t=await n(r),o=pt(t);if(o.length===0)return;let e=o.slice(0,ne).map(i=>`\u2022 ${i.message}`);return o.length>ne&&e.push(`\u2022 ${o.length-ne} more`),{id:`doctor-setup-${lt(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...e,"Run /pi-agent-ide-doctor"].join(`
5
+ `)}}}}s(dt,"createDoctorTipProvider");function pt(n){let r=n.actions.map(o=>({id:`action:${o.pluginId}:${o.id}`,message:o.message})),t=n.suggestions.map(o=>{let e=o.recipe.languages.filter(a=>n.detectedLanguages.has(a)).join(", "),i={debugger:"debugging",formatter:"formatting",linter:"linting",lsp:"language support"}[o.recipe.kind];return{id:`suggestion:${o.pluginId}:${o.recipe.kind}:${o.recipe.id}`,message:`Use ${o.recipe.name} for ${e} ${i}`}});return[...r,...t].sort((o,e)=>o.id.localeCompare(e.id))}s(pt,"setupItems");function lt(n){return at("sha256").update(n.map(r=>`${r.id}\0${r.message}`).join("\0")).digest("hex").slice(0,12)}s(lt,"fingerprint");async function Je(n,r){let t=new z;We(n,async i=>(await t.waitForPlugins(),te(t.snapshot(),i.cwd,process.env,i.signal)));let o,e=n.events.on(ue,i=>{if(!fe(i))throw new Error("Invalid doctor plugin registration request");i.accept(t.registerPlugin(i.plugin))});n.on("session_shutdown",e),n.registerCommand("pi-agent-ide-doctor",{description:"Check and configure this project or an explicit ssh://target/path",handler:s(async(i,a)=>{let{cwd:u,flags:f}=Te(i,a.cwd),h=await r?.(u);await t.waitForPlugins();let d=await Y(t.snapshot(),u,process.env,void 0,h);if(re(n,M(d)),d.suggestions.length>0&&!f.has("--no-apply")&&(f.has("--apply")||a.hasUI&&await a.ui.confirm("Apply suggested configuration?","Add detected tools to .pi/pi-agent-ide/. Existing entries and native tool settings are kept."))){let g=await Oe(u,d.suggestions,h),y=g.length===0?"Pi Agent IDE configs are already up to date":`Updated ${g.length} Pi Agent IDE config ${g.length===1?"file":"files"}`;a.ui.notify(y,"info"),d=await Y(t.snapshot(),u,process.env,void 0,h),re(n,M(d))}if(!oe(d)&&!f.has("--agent"))return;(f.has("--agent")||a.hasUI&&await a.ui.confirm("Ask the agent to finish setup?","The agent will receive this redacted report and relevant plugin recipes."))&&(o={cwd:u,workspace:h},n.sendUserMessage(Me(d)))},"handler")}),n.on("agent_end",async(i,a)=>{let u=o;if(u===void 0)return;o=void 0;let f=await Y(t.snapshot(),u.cwd,process.env,void 0,u.workspace);re(n,`Doctor recheck after agent setup
6
+
7
+ ${M(f)}`),oe(f)?a.ui.notify("Pi Agent IDE setup still needs attention","warning"):a.ui.notify("Pi Agent IDE setup is ready","info")}),n.events.emit(le,{protocol:de,apiVersion:pe}),await t.waitForPlugins()}s(Je,"registerDoctorWithOwner");function re(n,r){n.sendMessage({customType:"pi-agent-ide-doctor",content:r,display:!0},{triggerTurn:!1})}s(re,"sendReport");import{readFile as Ve}from"node:fs/promises";import U from"node:path";import{Type as E}from"typebox";import{Value as ie}from"typebox/value";var ut=E.Object({directory:E.String(),device:E.String({pattern:"^[0-9]+$"}),inode:E.String({pattern:"^[0-9]+$"}),containerCreated:E.Boolean(),containerDevice:E.String({pattern:"^[0-9]+$"}),containerInode:E.String({pattern:"^[0-9]+$"})});async function ze(n,r,t){t?.throwIfAborted();let o=n.resolve(r);if(!o)throw new D("UNSUPPORTED_SOURCE",r,"not-applied");let e=o.location,i=o.backend;if((await i.stat(e.path,{signal:t})).kind!=="directory")throw new D("NOT_DIRECTORY",e.source,"not-applied");let a=s(p=>{let c=n.resolve(p);if(!c||c.location.target!==e.target)throw new D("UNSUPPORTED_SOURCE",p,"not-applied");return c.location.path},"resolve"),u=await X({...i.target,workspace:e.path},"python3",["-c","import json,os,sys; keys=json.loads(sys.argv[1]); print(json.dumps({k:os.environ[k] for k in keys if k in os.environ}))",JSON.stringify(H)],e.source,{signal:t,timeoutMs:5e3,maxBytes:128*1024});if(u.exitCode!==0)throw new D("DEPENDENCY_UNAVAILABLE",e.source,"not-applied");let f=JSON.parse(u.stdout.toString("utf8")),h=E.Object(Object.fromEntries(H.map(p=>[p,E.Optional(E.String({maxLength:4096}))])),{additionalProperties:!1});if(!ie.Check(h,f))throw new D("INVALID_RESPONSE",e.source,"not-applied");let d=Ie(n),m=Ae(n),w=Ee(n,e.source),g=new Map,y=s(async(p,c,l)=>{let P=await Ve(new URL(`./${p}`,new URL("../src/backend/doctor-workspace.ts",import.meta.url).href),{encoding:"utf8",signal:l}),S=await X(i.target,"python3",["-c",P,...c],e.source,{signal:l,timeoutMs:3e4,maxBytes:32*1024*1024});if(S.exitCode!==0)throw new D("DOCTOR_FAILED",e.source,"not-applied");return JSON.parse(S.stdout.toString("utf8"))},"executeWorker"),C=s(async(p,c,l)=>{l?.throwIfAborted();let P=await Ve(new URL("./doctor-probe-worker.py",new URL("../src/backend/doctor-workspace.ts",import.meta.url).href),{encoding:"utf8",signal:l}),S=new AbortController,j=l?AbortSignal.any([l,S.signal]):S.signal,$=setTimeout(()=>S.abort(new D("TIMEOUT",e.source,"not-applied")),3e4),R,k=!1,T,x;try{R=await De(i.target,"python3",["-c",P,JSON.stringify({operation:"create",source:p})],i.target.workspace,{signal:j});let v=0,B=s(A=>(v+=A.length,v<=128*1024?!0:(S.abort(new D("BYTE_LIMIT",e.source,"not-applied")),!1)),"consume");R.stderr.on("data",A=>{B(A)});let G=R,W=new Promise((A,Ye)=>{let F=Buffer.alloc(0),se=!1;G.stdout.on("data",ae=>{if(!B(ae)||se)return;F=Buffer.concat([F,ae]);let ce=F.indexOf(`
8
+ `);if(!(ce<0)){se=!0;try{A(JSON.parse(F.subarray(0,ce).toString("utf8")))}catch(Ge){Ye(Ge)}F=Buffer.alloc(0)}})}),J=await Promise.race([W,R.completion.then(()=>{throw new D("PROBE_FAILED",e.source,"not-applied")})]);if(l?.throwIfAborted(),!ie.Check(ut,J))throw new D("PROBE_FAILED",e.source,"not-applied");if(x=J,await R.write(Buffer.from(`retain
9
+ `)),await R.end(),(await R.completion).exitCode!==0)throw new D("PROBE_FAILED",e.source,"not-applied")}catch(v){k=!0,T=l?.aborted?l.reason:S.signal.aborted?S.signal.reason:v}finally{clearTimeout($)}try{let v=await R?.stop();if(v?.exitCode===0&&x&&c(x),v?.exitCode===2)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}catch(v){throw new AggregateError(k?[T,v]:[v],"Doctor allocation cleanup failed",{cause:v})}if(k)throw T},"allocateProbe"),I=new Map,b=s(async p=>{for(;;){let c=I.get(p);if(c?.cleanup){await c.cleanup;continue}let l=c??{users:0};return l.users++,I.set(p,l),l}},"acquireContainer"),O=s(async(p,c)=>{c.users--,c.users===0&&(c.cleanup=Promise.resolve().then(async()=>{if(c.created&&await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove-container",...c.created})])!==null)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}).finally(()=>{I.get(p)===c&&I.delete(p)}),await c.cleanup)},"releaseContainer");return{source:e.source,platform:"linux",toolPaths:f,async probeBrowser(p){return await xe({...i.target,workspace:e.path},e.source,p),{ok:!0,detail:"Target Playwright and Chromium started without navigation"}},async files(p){let c=await y("doctor-inventory-worker.py",[e.path],p);if(!ie.Check(E.Array(E.String()),c))throw new D(typeof c=="object"&&c!==null&&"error"in c&&c.error==="BYTE_LIMIT"?"BYTE_LIMIT":"INVENTORY_FAILED",e.source,"not-applied");return c.map(l=>{let P=U.posix.resolve(e.path,l);if(U.posix.isAbsolute(l)||!(P.startsWith(`${e.path}/`)||e.path==="/"))throw new D("INVALID_RESPONSE",e.source,"not-applied");return K(e.target,P).source})},async readText(p,c){try{let l=await i.read(a(p),{signal:c}),P=l.bytes.toString("utf8");return g.set(p,{content:P,version:l.version}),P}catch(l){if(l instanceof D&&l.code==="ENOENT")return;throw l}},async writeText(p,c,l,P){let S=g.get(p);if(l!==void 0&&(!S||S.content!==l))throw new D("CONFLICT",p,"not-applied");await i.write(a(p),Buffer.from(c),l===void 0?null:S?.version??null,{signal:P})},configPaths:s((p,c)=>d.paths(e.source,p,c),"configPaths"),async exists(p,c){try{return await i.stat(a(p),{signal:c}),!0}catch(l){if(l instanceof D&&l.code==="ENOENT")return!1;throw l}},evidence:s((p,c)=>Re(i,e.path,p,c),"evidence"),executableAvailability:s((p,c)=>Ce(i,e.path,p,c),"executableAvailability"),run:s((p,c,l)=>m.run(p,{projectRoot:e.source,filePath:c,signal:l}),"run"),async withProbeCopy(p,c,l){l?.throwIfAborted();let P=a(p),S=U.posix.join(U.posix.dirname(P),".tmp"),j=await b(S),$,R=U.posix.basename(P),k=[],T;try{let v=j.allocation,B={};j.allocation=new Promise(A=>{B.resolve=A});let G=N(B.resolve);try{await v,l?.throwIfAborted(),await C(P,A=>{$=A,A.containerCreated&&(j.created={container:S,device:A.containerDevice,inode:A.containerInode})},l)}finally{G()}let W=U.posix.join(N($).directory,R),J=await i.lstat(P,{signal:l});await i.copy(P,W,J.revision,null,{signal:l}),l?.throwIfAborted(),k.push({value:await c(K(e.target,W).source)})}catch(v){T=v}let x=[];if($)try{if(await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove",...$,name:R})])!==null)throw new D("PROBE_CLEANUP_FAILED",p,"unknown")}catch(v){x.push(v)}try{await O(S,j)}catch(v){x.push(v)}if(x.length>0)throw new AggregateError(k.length===0?[T,...x]:x,"Doctor probe cleanup failed",{cause:x[0]});if(k.length===0)throw T;return N(k[0]).value},start:s((p,c,l)=>w.start({rootUri:e.source,command:p,env:c,signal:l}),"start"),toNativeUri:s(p=>w.toServerUri(p),"toNativeUri"),fromNativeUri:s(p=>w.fromServerUri(p),"fromNativeUri")}}s(ze,"createSshDoctorWorkspace");async function ft(n){let r=new ke(await Se(Pe(ve())));await Je(n,t=>t.startsWith("ssh://")?ze(r,t):Promise.resolve(void 0))}s(ft,"registerOwnedDoctor");export{ft as default};
@@ -0,0 +1 @@
1
+ import{a as r}from"./chunk-EI7MMDWY.js";import{readFile as i}from"node:fs/promises";import a from"node:path";var s="pi-agent-ide-documentation",l=1,c=`${s}/core/ready`,d=`${s}/document/register`;function g(e){let o=new Map;return async n=>{let t=o.get(n.id);return t===void 0&&(t=e(n.id),o.set(n.id,t),t.catch(()=>o.delete(n.id))),{...n,markdown:await t}}}r(g,"createPackagedAgentGuideLoader");var y=g(async e=>i(a.join(await m(),"docs","agent-guides",`${e}.md`),"utf8"));async function m(){let e=import.meta.dirname;for(;;){let o=a.join(e,"package.json");try{if(JSON.parse(await i(o,"utf8")).name==="pi-agent-ide")return e}catch{}let n=a.dirname(e);if(n===e)throw new Error("Cannot locate the pi-agent-ide package root");e=n}}r(m,"findHostPackageRoot");function A(e,o){let n=r(()=>e.events.emit(d,{documents:o}),"announce"),t=e.events.on(c,()=>{n(),t()});e.on("session_shutdown",t),n()}r(A,"connectAgentDocumentation");export{s as a,l as b,c,d,g as e,y as f,A as g};
@@ -1 +1 @@
1
- import{g as d}from"./chunk-PJL3UVMJ.js";import{a as p}from"./chunk-EI7MMDWY.js";import l from"node:path";async function y(e,o,t={},r){r?.throwIfAborted();for(let n of Object.keys(t))if(!/^[A-Za-z_][A-Za-z\d_]*$/u.test(n))throw new TypeError("Invalid remote process environment key");let i=await e.execute("python3",["-c",'import os; print(os.environ.get("PATH", os.defpath), end="")'],o,{signal:r});if(i.exitCode!==0)throw new d("DEPENDENCY_UNAVAILABLE",e.target.id,"not-applied");return{...t,PATH:[...["node_modules/.bin",".venv/bin","venv/bin","vendor/bin"].map(n=>l.posix.join(o,n)),t.PATH??i.stdout].join(":")}}p(y,"sshProjectEnvironment");async function v(e,o,t,r){r?.throwIfAborted();let i=t.map(s=>{for(let h of Object.keys(s.env??{}))if(!/^[A-Za-z_][A-Za-z\d_]*$/u.test(h))throw new TypeError("Invalid remote process environment key");return{command:s.command[0]?.replaceAll("{project}",o)??"",path:s.env?.PATH}}),n=await e.execute("python3",["-c","import json,os,shutil,sys; candidates=json.loads(sys.argv[1]); root=sys.argv[2]; prefixes=[os.path.join(root,p) for p in ['node_modules/.bin','.venv/bin','venv/bin','vendor/bin']]; print(json.dumps([bool(shutil.which(c['command'],path=os.pathsep.join(prefixes+[c.get('path',os.environ.get('PATH',os.defpath))]))) for c in candidates]))",JSON.stringify(i),o],o,{signal:r});if(n.exitCode!==0)throw new d("DEPENDENCY_UNAVAILABLE",e.target.id,"not-applied");let a=JSON.parse(n.stdout.toString("utf8"));if(!Array.isArray(a)||a.length!==t.length||a.some(s=>typeof s!="boolean"))throw new d("INVALID_RESPONSE",e.target.id,"not-applied");return a}p(v,"sshProjectExecutableAvailability");export{y as a,v as b};
1
+ import{g as d}from"./chunk-4IWEKRSP.js";import{a as p}from"./chunk-EI7MMDWY.js";import l from"node:path";async function y(e,o,t={},r){r?.throwIfAborted();for(let n of Object.keys(t))if(!/^[A-Za-z_][A-Za-z\d_]*$/u.test(n))throw new TypeError("Invalid remote process environment key");let i=await e.execute("python3",["-c",'import os; print(os.environ.get("PATH", os.defpath), end="")'],o,{signal:r});if(i.exitCode!==0)throw new d("DEPENDENCY_UNAVAILABLE",e.target.id,"not-applied");return{...t,PATH:[...["node_modules/.bin",".venv/bin","venv/bin","vendor/bin"].map(n=>l.posix.join(o,n)),t.PATH??i.stdout].join(":")}}p(y,"sshProjectEnvironment");async function v(e,o,t,r){r?.throwIfAborted();let i=t.map(s=>{for(let h of Object.keys(s.env??{}))if(!/^[A-Za-z_][A-Za-z\d_]*$/u.test(h))throw new TypeError("Invalid remote process environment key");return{command:s.command[0]?.replaceAll("{project}",o)??"",path:s.env?.PATH}}),n=await e.execute("python3",["-c","import json,os,shutil,sys; candidates=json.loads(sys.argv[1]); root=sys.argv[2]; prefixes=[os.path.join(root,p) for p in ['node_modules/.bin','.venv/bin','venv/bin','vendor/bin']]; print(json.dumps([bool(shutil.which(c['command'],path=os.pathsep.join(prefixes+[c.get('path',os.environ.get('PATH',os.defpath))]))) for c in candidates]))",JSON.stringify(i),o],o,{signal:r});if(n.exitCode!==0)throw new d("DEPENDENCY_UNAVAILABLE",e.target.id,"not-applied");let a=JSON.parse(n.stdout.toString("utf8"));if(!Array.isArray(a)||a.length!==t.length||a.some(s=>typeof s!="boolean"))throw new d("INVALID_RESPONSE",e.target.id,"not-applied");return a}p(v,"sshProjectExecutableAvailability");export{y as a,v as b};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-FXPY3V4L.js";import"./chunk-FYOU4RBH.js";import"./chunk-7PVDTMEM.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-MPT3R4BL.js";import"./chunk-KN6VPARZ.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DDH3FP4G.js";import"./chunk-EI7MMDWY.js";export{a as default};
@@ -1 +1 @@
1
- import{d,e as u,f as a}from"./chunk-S72FVLUX.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(r,i){let s=t(()=>{let o,n={plugin:i,accept(f){if(o!==void 0)throw new Error(`Doctor plugin ${i.id} was accepted more than once`);o=f}};return r.events.emit(u,n),o},"announce"),e=t(()=>{},"unsubscribe");e=r.events.on(d,o=>{if(!a(o))throw new Error("Invalid doctor core readiness event");let n=s();if(n===void 0)throw new Error("Doctor core did not accept the plugin");e(),n.catch(()=>{})}),r.on("session_shutdown",e);let c=s();if(c!==void 0)return e(),c}t(E,"connectDoctorPlugin");export{E as a};
1
+ import{d,e as u,f as a}from"./chunk-MLFJU2US.js";import{a as t}from"./chunk-EI7MMDWY.js";function E(r,i){let s=t(()=>{let o,n={plugin:i,accept(f){if(o!==void 0)throw new Error(`Doctor plugin ${i.id} was accepted more than once`);o=f}};return r.events.emit(u,n),o},"announce"),e=t(()=>{},"unsubscribe");e=r.events.on(d,o=>{if(!a(o))throw new Error("Invalid doctor core readiness event");let n=s();if(n===void 0)throw new Error("Doctor core did not accept the plugin");e(),n.catch(()=>{})}),r.on("session_shutdown",e);let c=s();if(c!==void 0)return e(),c}t(E,"connectDoctorPlugin");export{E as a};
@@ -1 +1 @@
1
- import{a as e}from"./chunk-EI7MMDWY.js";var i=["PI_PYTHON_PATH","PI_JS_DEBUG_PATH","PI_ELIXIR_LS_DEBUG_PATH","PI_R_PATH","PI_LLDB_DAP_PATH","PI_DELVE_PATH","PI_KOTLIN_DEBUG_ADAPTER_PATH","PI_JULIA_DEBUG_PROJECT","PI_DART_PATH","PI_JULIA_PATH","PI_NETCOREDBG_PATH","PI_RUBY_DEBUG_PATH","PI_PHP_PATH","PI_PHP_DEBUG_PATH","PI_LUA_PATH","PI_LUA_DEBUG_PATH","PI_BASH_PATH","PI_BASH_DEBUG_PATH","PI_PWSH_PATH","PI_POWERSHELL_EDITOR_SERVICES_PATH"];var t="pi-agent-ide-doctor",n=1,s="pi-agent-ide-doctor/core/ready",l="pi-agent-ide-doctor/plugin/register";function c(o){return r(o)&&o.protocol===t&&o.apiVersion===n}e(c,"isDoctorCoreReady");function d(o){return!r(o)||typeof o.accept!="function"||!r(o.plugin)?!1:o.plugin.protocol===t&&o.plugin.apiVersion===n&&typeof o.plugin.id=="string"&&o.plugin.id.length>0&&typeof o.plugin.setup=="function"}e(d,"isDoctorPluginRegistrationRequest");function r(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}e(r,"isRecord");export{i as a,t as b,n as c,s as d,l as e,c as f,d as g};
1
+ import{a as e}from"./chunk-EI7MMDWY.js";var i=["PI_PYTHON_PATH","PI_JS_DEBUG_PATH","PI_ELIXIR_LS_DEBUG_PATH","PI_R_PATH","PI_LLDB_DAP_PATH","PI_DELVE_PATH","PI_KOTLIN_DEBUG_ADAPTER_PATH","PI_JULIA_DEBUG_PROJECT","PI_DART_PATH","PI_JULIA_PATH","PI_NETCOREDBG_PATH","PI_RUBY_DEBUG_PATH","PI_PHP_PATH","PI_PHP_DEBUG_PATH","PI_LUA_PATH","PI_LUA_DEBUG_PATH","PI_BASH_PATH","PI_BASH_DEBUG_PATH","PI_PWSH_PATH","PI_POWERSHELL_EDITOR_SERVICES_PATH"];var t="pi-agent-ide-doctor",n=1,s="pi-agent-ide-doctor/core/ready",c="pi-agent-ide-doctor/plugin/register";function l(o){return r(o)&&o.protocol===t&&o.apiVersion===n}e(l,"isDoctorCoreReady");function d(o){return!r(o)||typeof o.accept!="function"||!r(o.plugin)?!1:o.plugin.protocol===t&&o.plugin.apiVersion===n&&typeof o.plugin.id=="string"&&o.plugin.id.length>0&&typeof o.plugin.setup=="function"}e(d,"isDoctorPluginRegistrationRequest");function r(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}e(r,"isRecord");export{i as a,t as b,n as c,s as d,c as e,l as f,d as g};
@@ -0,0 +1,5 @@
1
+ import{a as z,d as g,f as _,g as U,h as M,i as w,j as O}from"./chunk-FYOU4RBH.js";import{d as L}from"./chunk-7PVDTMEM.js";import{a as H}from"./chunk-47SPPIXK.js";import{a as k,b as B}from"./chunk-VAXLSPPU.js";import{a as $}from"./chunk-MDD5ORB6.js";import{b as I,c as W}from"./chunk-MLFJU2US.js";import{d as C}from"./chunk-OMNKD7WW.js";import{a as T}from"./chunk-BU7IZLKB.js";import{a as x,b as P}from"./chunk-S5PL5DFQ.js";import{I as A,o as E}from"./chunk-DDH3FP4G.js";import{e as F}from"./chunk-756K3LJY.js";import{a}from"./chunk-EI7MMDWY.js";import{constants as J}from"node:fs";import{access as K}from"node:fs/promises";import y from"node:path";var Q=["google-chrome-stable","google-chrome","chromium","chromium-browser"],X=["/usr/bin/google-chrome-stable","/usr/bin/google-chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/opt/google/chrome/chrome"];function D(e={}){let t;return{async load(r,n){t??=v(e.executablePath,e.environment??process.env);let o=await t;n.signal?.throwIfAborted();let{chromium:i}=await import("playwright-core");n.signal?.throwIfAborted();let s=await i.launch({executablePath:o,headless:!0,chromiumSandbox:!1,timeout:n.timeoutMs}),l=a(()=>{s.close()},"closeOnAbort");n.signal?.addEventListener("abort",l,{once:!0});try{n.signal?.throwIfAborted();let c=await s.newPage(),u=await c.goto(r.href,{timeout:n.timeoutMs,waitUntil:"domcontentloaded"});if(u!==null&&!u.ok())throw new Error(`HTTP ${u.status()}: ${u.statusText()}`);await c.waitForLoadState("networkidle",{timeout:Math.min(n.timeoutMs,1500)}).catch(()=>{}),n.signal?.throwIfAborted(),await Z(c);let d={html:await c.content(),source:c.url()};return n.signal?.throwIfAborted(),d}catch(c){throw n.signal?.aborted===!0?ee(n.signal):new Error(`Browser read failed for ${r.href}: ${re(c)}`,{cause:c})}finally{n.signal?.removeEventListener("abort",l),await s.close().catch(()=>{})}}}}a(D,"createSystemBrowserHtmlLoader");async function v(e=process.env.PI_AGENT_IDE_BROWSER_PATH,t=process.env){if(e!==void 0&&e.trim().length>0){let r=y.resolve(e);if(await R(r))return r;throw new Error(`PI_AGENT_IDE_BROWSER_PATH is not executable: ${r}`)}for(let r of(t.PATH??"").split(y.delimiter).filter(Boolean))for(let n of Q){let o=y.join(r,n);if(await R(o))return o}for(let r of X)if(await R(r))return r;throw new Error("No system Chrome or Chromium executable was found. Install Chrome/Chromium or set PI_AGENT_IDE_BROWSER_PATH.")}a(v,"resolveSystemBrowserExecutable");async function Z(e){await e.locator("body *").evaluateAll(t=>{for(let r of t.toReversed()){let n=globalThis.getComputedStyle(r);(r.hasAttribute("hidden")||r.getAttribute("aria-hidden")==="true"||n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")&&r.remove()}})}a(Z,"removeHiddenElements");async function R(e){try{return await K(e,J.X_OK),!0}catch{return!1}}a(R,"isExecutable");function ee(e){return e.reason instanceof Error?e.reason:te()}a(ee,"abortReason");function te(){let e=new Error("The operation was aborted");return e.name="AbortError",e}a(te,"abortError");function re(e){return e instanceof Error?e.message:String(e)}a(re,"errorMessage");var N={protocol:I,apiVersion:W,id:"web-browser",setup(e){e.addCheck({id:"system-browser",title:"Browser web reads",async run(t){try{t.signal?.throwIfAborted();let r=t.workspace?await ne(t.workspace,t.signal):await F(await v(t.env.PI_AGENT_IDE_BROWSER_PATH,t.env),["--version"],t.cwd,t.env,t.signal);return t.signal?.throwIfAborted(),[r.ok?{status:"pass",message:"Chrome/Chromium is available",detail:r.detail}:{status:"warn",message:"Chrome/Chromium cannot start",detail:r.detail}]}catch(r){return t.signal?.throwIfAborted(),[{status:"warn",message:"Browser reads are unavailable",detail:r instanceof Error?r.message:String(r)}]}}})}};async function ne(e,t){if(!e.probeBrowser)throw new Error("Project owner does not provide a browser probe");return e.probeBrowser(t)}a(ne,"probeOwnerBrowser");var oe=4096;function V(e,t={}){let r=se(t);return{id:"web",async tryResolve(n,o){if(/^web:/iu.test(n)){let i=await t.owner?.tryResolve(n,o);return i!==void 0&&i.kind!=="not-handled"?i:{kind:"failed",error:new Error(`Target web execution is unavailable: ${n}`)}}return ae(n,e,r)}}}a(V,"createWebResolver");function se(e){let t=e.timeoutMs??3e4;if(!Number.isFinite(t)||t<=0)throw new TypeError("Web timeout must be a positive finite number");return{timeoutMs:t,fetchResource:e.fetch??globalThis.fetch,browser:e.browser??D(),autoBrowserFallback:e.autoBrowserFallback??!0}}a(se,"resolverSettings");function ae(e,t,r){let n;try{n=new URL(e)}catch(o){return we(e)?{kind:"failed",error:new TypeError(`Invalid HTTP source ${e}`,{cause:o})}:{kind:"not-handled"}}return n.protocol!=="http:"&&n.protocol!=="https:"?{kind:"not-handled"}:{kind:"resolved",resource:{source:n.href,read({signal:o}){return ie(n,t,r,o)}}}}a(ae,"resolveHttpSource");async function ie(e,t,r,n){let o=G(n,r.timeoutMs),i=!0;try{o.signal.throwIfAborted();let s=await r.fetchResource(e,{method:"GET",redirect:"follow",signal:o.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; Pi-LPT/1.0; +https://github.com/alexshpunt/sasha-pi)",Accept:"text/html,application/xhtml+xml,application/pdf,application/json,text/plain,image/*,*/*;q=0.8","Accept-Language":"en-US,en;q=0.5"}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let l=s.headers.get("content-type")??void 0;if(ue(l)&&!de(e)){let h=await me(s,oe,o.signal);return[{type:"text",text:fe(e,s,l,h)}]}let c=new Uint8Array(await s.arrayBuffer());o.signal.throwIfAborted();let d={source:s.url.length===0?e.href:s.url,bytes:c,...l!==void 0&&{mediaType:l}};i=ge(c,l);let m=await t.convert(d,{signal:o.signal});if(o.signal.throwIfAborted(),r.autoBrowserFallback&&i&&q(m))throw new Error("HTTP read returned empty HTML content");return m}catch(s){if(n?.throwIfAborted(),!r.autoBrowserFallback||!i)throw s;o.dispose();try{return await ce(e,t,r,n)}catch(l){throw n?.throwIfAborted(),new Error(`HTTP read failed (${j(s)}) and browser fallback failed: ${j(l)}`,{cause:l})}}finally{o.dispose()}}a(ie,"readWebContent");async function ce(e,t,r,n){let o=G(n,r.timeoutMs);try{o.signal.throwIfAborted();let i=await le(e,t,r,o.signal);if(o.signal.throwIfAborted(),q(i))throw new Error("Browser read returned empty content");return i}finally{o.dispose()}}a(ce,"readBrowserContent");async function le(e,t,r,n){let o=await r.browser.load(e,{signal:n,timeoutMs:r.timeoutMs});return n.throwIfAborted(),t.convert({source:o.source,bytes:new TextEncoder().encode(o.html),mediaType:"text/html; charset=utf-8"},{signal:n})}a(le,"loadAndConvertBrowser");function ue(e){if(e===void 0)return!1;let t=e.split(";",1)[0]?.trim().toLowerCase()??"";return!(t.startsWith("text/")||t.startsWith("image/")||t==="application/json"||t.endsWith("+json")||t==="application/xml"||t.endsWith("+xml")||t==="application/xhtml+xml"||t==="application/pdf")}a(ue,"isUnsupportedBinaryMediaType");function de(e){return/\.(?:avif|bmp|gif|jpe?g|pdf|png|webp)$/iu.test(e.pathname)}a(de,"hasSupportedDocumentExtension");async function me(e,t,r){if(e.body===null)return new Uint8Array;let n=e.body.getReader(),o=[],i=0;try{for(;i<t;){r.throwIfAborted();let c=await n.read();if(c.done)break;let u=t-i,d=c.value.subarray(0,u);if(o.push(d),i+=d.length,c.value.length>u)break}}finally{await n.cancel().catch(()=>{})}let s=new Uint8Array(i),l=0;for(let c of o)s.set(c,l),l+=c.length;return s}a(me,"readBoundedBody");function fe(e,t,r,n){let o=["Unsupported binary response","Read cannot convert this Content-Type. Showing response metadata and a byte preview, not document text.",`URL: ${e.href}`,`HTTP: ${t.status} ${t.statusText}`.trimEnd(),`Content-Type: ${r??"unknown"}`],i=t.headers.get("content-disposition"),s=i===null?void 0:he(i);s!==void 0&&o.push(`Filename: ${s}`);let l=t.headers.get("content-length");l!==null&&o.push(`Content-Length: ${l}`);let c=[...t.headers].filter(([u])=>!pe(u)&&u!=="content-type"&&u!=="content-length").sort(([u],[d])=>u.localeCompare(d)).map(([u,d])=>`${u}: ${d}`);return c.length>0&&o.push("","Headers:",...c),o.push("",`Preview: first ${n.length} bytes (hex).`,be(n)),o.join(`
2
+ `)}a(fe,"formatUnsupportedBinaryResponse");function he(e){let t=/filename\*=UTF-8''([^;]+)/iu.exec(e)?.[1];if(t!==void 0)try{return decodeURIComponent(t).replaceAll(/[\r\n]/gu,"")}catch{return t.replaceAll(/[\r\n]/gu,"")}return/filename=(?:"([^"]+)"|([^;]+))/iu.exec(e)?.slice(1).find(Boolean)?.trim()}a(he,"attachmentFilename");function pe(e){return["content-location","link","location","refresh","set-cookie"].includes(e.toLowerCase())}a(pe,"isSensitiveRedirectHeader");function be(e){if(e.length===0)return"(empty body)";let t=[];for(let r=0;r<e.length;r+=16){let n=e.subarray(r,r+16),o=[...n].map(s=>s.toString(16).padStart(2,"0")).join(" "),i=[...n].map(s=>s>=32&&s<=126?String.fromCodePoint(s):".").join("");t.push(`${r.toString(16).padStart(8,"0")} ${o.padEnd(47)} |${i}|`)}return t.join(`
3
+ `)}a(be,"formatHexPreview");function ge(e,t){let r=t?.split(";",1)[0]?.trim().toLowerCase();if(r==="text/html"||r==="application/xhtml+xml")return!0;let n=new TextDecoder("utf8").decode(e.subarray(0,1024));return/^\u{FEFF}?\s*(?:<!doctype\s+html\b|<(?:article|body|head|html)\b)/iu.test(n)}a(ge,"isHtml");function q(e){return e.every(t=>t.type==="text"&&t.text.trim().length===0)}a(q,"isEmptyTextContent");function G(e,t){let r=new AbortController,n=a(()=>{r.abort(ye(e))},"abortFromParent"),o=setTimeout(()=>{r.abort(ve(t))},t);return o.unref(),e?.aborted===!0?n():e?.addEventListener("abort",n,{once:!0}),{signal:r.signal,dispose(){clearTimeout(o),e?.removeEventListener("abort",n)}}}a(G,"createOperationSignal");function we(e){return/^https?:/iu.test(e)}a(we,"claimsHttpScheme");function ye(e){return e?.reason instanceof Error?e.reason:Re()}a(ye,"abortReason");function Re(){let e=new Error("The operation was aborted");return e.name="AbortError",e}a(Re,"abortError");function ve(e){let t=new Error(`Web read timed out after ${e}ms`);return t.name="TimeoutError",t}a(ve,"timeoutError");function j(e){return e instanceof Error?e.message:String(e)}a(j,"errorMessage");function Y(e){return{id:"web",readResources:a(t=>t.path!==void 0&&/^https?:/iu.test(t.path)?[t.path]:[],"readResources"),async tryResolve(t,r){let n=t.path;if(n===void 0||!/^(?:https?:|web:)/iu.test(n))return{kind:"not-handled"};if(t.include!==void 0||t.exclude!==void 0)return{kind:"failed",error:new Error("File include/exclude globs do not apply to a web page.")};let o=Ae(t),i=await e.tryResolve(n,r);if(i.kind!=="resolved")return i;if(i.resource.read===void 0)return{kind:"failed",error:new Error(`Cannot read ${n}`)};let s=await i.resource.read({signal:r.signal});if(s.some(m=>m.type!=="text"))return{kind:"failed",error:new Error(`Web search requires text content: ${n}`)};let l=s.map(m=>m.type==="text"?m.text:"").join(`
4
+ `),c=[],u=t.limit??50;for(let[m,h]of l.split(/\r\n|\n|\r/u).entries()){r.signal?.throwIfAborted();for(let f of h.matchAll(o)){if(f[0].length===0)continue;let p=f.index,b=p+f[0].length;if(!(t.wholeWord===!0&&(new RegExp("\\p{L}|\\p{N}|_","u").test(h[p-1]??"")||new RegExp("\\p{L}|\\p{N}|_","u").test(h[b]??"")))){if(c.length===u)return{kind:"resolved",payload:{source:n,matches:c,complete:!1}};c.push({source:n,lineNumber:m+1,startColumn:p,endColumn:b,matchedText:f[0],lineText:h})}}}let d=c.length===0&&_(t.query)?Se(l,n,t.query,r.signal):void 0;return{kind:"resolved",payload:{source:n,matches:c,complete:!0,...d===void 0?{}:{fuzzy:d}}}},toScriptData(t){let r=t;return{...L(r.matches,r.complete),...r.fuzzy===void 0?{}:{fuzzy:{...r.fuzzy,candidates:r.fuzzy.candidates.map(n=>w(n))}}}},renderResult(t,r,n){let o=t.details;return z(o.matches,o.complete,n,r.expanded,void 0,["Web page \xB7 read-only",...o.complete?[]:["Limit reached \xB7 incomplete results"]])},format(t){let r=t,n=r.matches.length===0?`No matches in ${r.source}`:`${r.matches.length}${r.complete?"":"+"} matches in ${r.source}${r.complete?"":" (limit reached)"}`,o=[n];r.fuzzy?.status==="skipped"&&o.push(`Possible-name fallback skipped: ${r.fuzzy.message}`),r.fuzzy?.candidates.length&&o.push("Possible names \u2014 spelling suggestions, not equivalent behavior.",...r.fuzzy.candidates.map(s=>O(w(s))));let i=Buffer.byteLength(n);for(let s of r.matches){let l=`${r.source}:${s.lineNumber}:${s.startColumn+1} ${Ee(s)}`;if(i+=Buffer.byteLength(l)+1,i>48*1024){o.push("Output shortened. Narrow the query or lower the limit.");break}o.push(l)}return{content:[{type:"text",text:o.join(`
5
+ `)}],details:r}}}}a(Y,"createWebSearchResolver");function Se(e,t,r,n){n?.throwIfAborted();let o=performance.now(),i=new U;if(i.addText(e),i.limited)return{status:"skipped",message:"name collection reached its byte or unique-name budget",candidates:[]};let s=[];for(let l of M(r,i.names)){if(n?.throwIfAborted(),performance.now()-o>g.timeoutMs)return{status:"skipped",message:"extra search reached its time budget",candidates:[]};let c=new RegExp(l.identifier.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),"gu"),u=[],d=!0,m=0;e:for(let[h,f]of e.split(/\r\n|\n|\r/u).entries()){if(performance.now()-o>g.timeoutMs)return{status:"skipped",message:"extra search reached its time budget",candidates:[]};n?.throwIfAborted();for(let p of f.matchAll(c)){let b=p.index,S=b+p[0].length;if(!(/[\p{L}\p{N}_$]/u.test(f[b-1]??"")||/[\p{L}\p{N}_$]/u.test(f[S]??""))){if(m+=Buffer.byteLength(f),u.length===g.matchesPerCandidate||m>g.verificationBytes){d=!1;break e}u.push({source:t,lineNumber:h+1,startColumn:b,endColumn:S,matchedText:p[0],lineText:f})}}}u.length>0&&s.push({...l,matches:u,complete:d})}return s.length===0?void 0:{status:"ready",candidates:s}}a(Se,"searchFuzzyText");function Ee(e){let t=Math.max(0,e.startColumn-64),r=Math.min(e.lineText.length,e.startColumn+192);return`${t>0?"\u2026":""}${e.lineText.slice(t,r)}${r<e.lineText.length?"\u2026":""}`}a(Ee,"previewMatch");function Ae(e){let t=e.query,r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t,n=t.startsWith("regex:")?t.slice(6):r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(n,e.caseSensitive===!0?"gu":"giu")}a(Ae,"searchPattern");var xe={provider:"web",capability:"read"},Pe=C({kind:"markdown",label:"WEB"});async function Te(e){await Ce(e)}a(Te,"registerWeb");async function Ce(e,t){let r=A(e,xe),n=V(r,{owner:t?.(r)}),o={protocol:x,apiVersion:P,id:"web",setup(s){s.addHandler({stage:"pre-read",handler(l){let c=l.request.path;if(c===void 0||!/^(?:https?:\/\/|web:ssh:\/\/)/iu.test(c)||!l.request.views?.some(d=>/^(?:image|sequence)(?::|$)/u.test(d)))return{kind:"continue",context:l};let u="Website image and sequence views are not supported. Omit these views to read website content.";return{kind:"return",result:{content:[{type:"text",text:u}],details:{source:c,resolvedBy:"web",failure:{code:"UNSUPPORTED_CAPABILITY",source:c,resolverId:"web",message:u}},isError:!0}}}}),s.addResolver({resolver:n,renderResult:Pe,preserveTruncatedOutput:!0}),s.describe({path:a(()=>E(t?"HTTP(S) URL \u2014 fetched locally; web:ssh://<target>/https://\u2026 \u2014 fetched on that SSH target.":"HTTP(S) URL \u2014 remote content.",r.listDescriptions()),"path")})}},i={protocol:k,apiVersion:B,id:"web",setup(s){s.addResolver({resolver:Y(n),priority:-100}),s.describe("HTTP(S) Search reuses converted page text for zero-result identifier spelling suggestions. Candidate groups carry the URL and line ranges, never editable SEARCH references.")}};await Promise.all([T(e,o),H(e,i),Promise.resolve($(e,N))])}a(Ce,"registerWebWithOwner");export{V as a,Te as b,Ce as c};
@@ -0,0 +1 @@
1
+ import{a as d}from"./chunk-GXL4NMHR.js";import{c as s,d as l,e as c}from"./chunk-PQWANILR.js";import{a as i}from"./chunk-VDJSH3DQ.js";import{a as t}from"./chunk-EI7MMDWY.js";var o=class extends i{static{t(this,"ConstantTextAnchor")}constructor(n,r){super(n,r)}};function p(){return{id:"file-position",description:"`begin` and `end` select the first and last existing lines.",renderFull(e){return e},renderCompact(e){return e==="begin"?"file start":"file end"},tryResolve(e,n){return Promise.resolve(a(e,n))}}}t(p,"createConstantTextAnchorResolver");function a(e,n){return e!=="begin"&&e!=="end"?{kind:"not-handled"}:n.lines.length===0?{kind:"failed",error:new Error(`${e} cannot resolve in an empty file`)}:{kind:"resolved",anchor:new o(e,e==="begin"?1:n.lines.length)}}t(a,"resolveConstantAnchor");async function T(e){await d(e,{protocol:s,apiVersion:l,id:"text-anchor-constant",setup(r){r.addAnchorResolver({resolver:p(),kind:c,type:"constant"})}})}t(T,"registerConstantTextAnchors");export{T as a};
@@ -1 +1 @@
1
- import{a as O}from"./chunk-QT3EAHOG.js";import{a as R}from"./chunk-SMIFCAAX.js";import{a as v,b as S}from"./chunk-VXP5BMW7.js";import{b as y}from"./chunk-RW2GTYQI.js";import{a as w,b as E,c as b}from"./chunk-RIJMXO43.js";import"./chunk-VMTOFEXF.js";import"./chunk-CPELC6JE.js";import{g as s}from"./chunk-PJL3UVMJ.js";import{a as p,b as k,d as C}from"./chunk-6EDOLYOV.js";import{c as g}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-LCWBVOII.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import{c as u,l as h,m as P}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";import T from"node:path";function A(i){let l=v(i),U=R(i),d=new Map;return{async resolveProject(r,o){if(r.startsWith("ssh://")||o.startsWith("ssh://")){let e=i.resolve(r,o);if(!e)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let t=i.resolve(o);if(t&&t.location.target!==e.location.target)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");return O(e.backend,e.location.path,t?.location.path,"formatters",p)}if(r.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let n=await u(o,r,"formatters",p);return n===void 0?void 0:{cwd:n,external:n!==T.resolve(o)}},async loadRegistry(r,o){let n=JSON.stringify([r,o]),e=d.get(n);if(!e){let t=i.resolve(r);e=k.fromDirectory(r,{includeGlobal:!o,requireBuiltInEvidence:!0,...t?{layerAccess:l,executableAvailability:c(a=>y(t.backend,t.location.path,a),"executableAvailability"),recipeEvidence:c(a=>S(t.backend,t.location.path,a),"recipeEvidence")}:{}}),d.set(n,e)}return e},async run(r,o,n){let e=i.resolve(n);if(!e){if(n.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",n,"not-applied");return P(r,{projectRoot:o,filePath:n})}let t=await e.backend.read(e.location.path),a=await h(r.run,{projectRoot:o,filePath:n,processAccess:U}),m=await e.backend.read(e.location.path);if(!a.ok)return{ok:!1,changed:!m.bytes.equals(t.bytes)};if(r.output==="stdout"){if(m.version!==t.version)throw new s("CONFLICT",n,"not-applied");let f=Buffer.from(a.stdout);return f.equals(t.bytes)||await e.backend.write(e.location.path,f,t.version),{ok:!0,changed:!f.equals(t.bytes)}}return{ok:!0,changed:!m.bytes.equals(t.bytes)}}}}c(A,"createOwnedFormatterRuntime");async function F(i){let l=new b(await E(w(g())));await C(i,A(l))}c(F,"registerOwnedFormatter");export{A as createOwnedFormatterRuntime,F as default};
1
+ import{a as O}from"./chunk-H3GEEOOL.js";import{a as R}from"./chunk-RIJRPAL2.js";import{a as v,b as S}from"./chunk-USG6WHAT.js";import{b as y}from"./chunk-LF325WYO.js";import"./chunk-VMLPXSMK.js";import{a as w,b as E,c as b}from"./chunk-WQIMM4SU.js";import"./chunk-FHRHYY4M.js";import{g as s}from"./chunk-4IWEKRSP.js";import{a as p,b as k,d as C}from"./chunk-5PC5INOL.js";import{c as g}from"./chunk-W7CASEO3.js";import"./chunk-B25LXXNV.js";import{c as u,l as h,m as P}from"./chunk-7D7PXIVV.js";import"./chunk-BXGMMZT3.js";import"./chunk-MDD5ORB6.js";import"./chunk-MLFJU2US.js";import"./chunk-DDH3FP4G.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import{a as c}from"./chunk-EI7MMDWY.js";import T from"node:path";function A(i){let l=v(i),U=R(i),d=new Map;return{async resolveProject(r,o){if(r.startsWith("ssh://")||o.startsWith("ssh://")){let e=i.resolve(r,o);if(!e)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let t=i.resolve(o);if(t&&t.location.target!==e.location.target)throw new s("UNSUPPORTED_SOURCE",r,"not-applied");return O(e.backend,e.location.path,t?.location.path,"formatters",p)}if(r.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",r,"not-applied");let n=await u(o,r,"formatters",p);return n===void 0?void 0:{cwd:n,external:n!==T.resolve(o)}},async loadRegistry(r,o){let n=JSON.stringify([r,o]),e=d.get(n);if(!e){let t=i.resolve(r);e=k.fromDirectory(r,{includeGlobal:!o,requireBuiltInEvidence:!0,...t?{layerAccess:l,executableAvailability:c(a=>y(t.backend,t.location.path,a),"executableAvailability"),recipeEvidence:c(a=>S(t.backend,t.location.path,a),"recipeEvidence")}:{}}),d.set(n,e)}return e},async run(r,o,n){let e=i.resolve(n);if(!e){if(n.includes("://")||o.includes("://"))throw new s("UNSUPPORTED_SOURCE",n,"not-applied");return P(r,{projectRoot:o,filePath:n})}let t=await e.backend.read(e.location.path),a=await h(r.run,{projectRoot:o,filePath:n,processAccess:U}),m=await e.backend.read(e.location.path);if(!a.ok)return{ok:!1,changed:!m.bytes.equals(t.bytes)};if(r.output==="stdout"){if(m.version!==t.version)throw new s("CONFLICT",n,"not-applied");let f=Buffer.from(a.stdout);return f.equals(t.bytes)||await e.backend.write(e.location.path,f,t.version),{ok:!0,changed:!f.equals(t.bytes)}}return{ok:!0,changed:!m.bytes.equals(t.bytes)}}}}c(A,"createOwnedFormatterRuntime");async function F(i){let l=new b(await E(w(g())));await C(i,A(l))}c(F,"registerOwnedFormatter");export{A as createOwnedFormatterRuntime,F as default};
@@ -0,0 +1,6 @@
1
+ import{a as Y}from"./chunk-5BGWNYQS.js";import{c as D}from"./chunk-FYOU4RBH.js";import{m as k}from"./chunk-VDJSH3DQ.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a as u}from"./chunk-EI7MMDWY.js";import{createHash as Me}from"node:crypto";import{open as Be,readFile as Ie}from"node:fs/promises";import b from"node:path";import{spawn as Te}from"node:child_process";import{stat as Re}from"node:fs/promises";import E from"node:path";import{createInterface as ke}from"node:readline";import{existsSync as Se}from"node:fs";import ye from"node:os";import Z from"node:path";function ee(e=process.env.PI_CODING_AGENT_DIR??Z.join(ye.homedir(),".pi","agent"),t=process.platform){let n=Z.join(e,"bin",t==="win32"?"rg.exe":"rg");return Se(n)?n:"rg"}u(ee,"resolveRipgrepExecutable");function z(e,t=!1){let n=L(e);return $(n)?J(P(new I(e,n).parse(),t)):t?e:G(e)}u(z,"compileSearchQuery");function Q(e,t=!1){let n=L(e);return $(n)?P(new I(e,n).parse(),t):void 0}u(Q,"compileSearchCondition");function A(e,t){if(e.kind==="term")return t(e.value);let n=A(e.left,t);if(e.kind==="or")return n||A(e.right,t);let r=A(e.right,t);return n&&(e.kind==="not"?!r:r)}u(A,"satisfiesSearchCondition");function ne(e){if($(L(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(G).join("|")})`:void 0}u(ne,"compileSearchFallbackQuery");function $(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}u($,"containsBooleanSyntax");var I=class{static{u(this,"BooleanQueryParser")}#e;#r;#a=0;constructor(t,n){this.#e=t,this.#r=n}parse(){let t=this.#o(),n=this.#t();if(n.type!=="end"){let r=n.type==="right"?"unexpected ')'.":`unexpected ${we(n)}.`;throw T(n.offset,r)}return t}#o(){let t=this.#n();for(;this.#t().type==="or";){let n=this.#i(),r=this.#s(`after ${n.value}`);t={kind:"or",left:t,right:this.#c(r)}}return t}#n(){return this.#c(this.#s())}#c(t){let n=t;for(;;){let r=this.#t();if(r.type==="and"||r.type==="not"){this.#i();let o=this.#s(`after ${r.value}`);n={kind:r.type,left:n,right:o};continue}if(r.type==="term"||r.type==="left"){n={kind:"and",left:n,right:this.#s()};continue}return n}}#s(t){let n=this.#t();if(n.type==="term")return this.#i(),{kind:"term",value:n.value,quoted:n.quoted};if(n.type==="left"){if(this.#i(),this.#t().type==="right"||this.#t().type==="end")throw T(this.#t().offset,"expected a term after '('.");let o=this.#o();if(this.#t().type!=="right")throw T(this.#t().offset,"expected ')'.");return this.#i(),o}if(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw T(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw T(n.offset,`expected a term${r}.`)}#t(){return this.#r[this.#a]??{type:"end",value:"",offset:this.#e.length}}#i(){let t=this.#t();return this.#a+=1,t}};function L(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&be(e,n)){t.push({type:"left",value:r,offset:n}),n+=1;continue}if(r===")"){t.push({type:"right",value:r,offset:n}),n+=1;continue}if(te(e,n)){let i=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+i),offset:n}),n+=i;continue}if(r==="'"||r==='"'){let i=n,l=r,s="";for(n+=1;n<e.length&&e.charAt(n)!==l;)e.charAt(n)==="\\"&&(e.charAt(n+1)===l||e.charAt(n+1)==="\\")&&(n+=1),s+=e.charAt(n++);if(n>=e.length)throw T(i,`unterminated ${l==="'"?"single":"double"}-quoted term.`);if(n+=1,s.length===0)throw T(i,"quoted terms must not be empty.");t.push({type:"term",value:s,offset:i,quoted:!0});continue}let o=n;for(;n<e.length;){let i=e.charAt(n);if(/\s/u.test(i)||i===")"||te(e,n))break;i==="\\"&&n+1<e.length?n+=2:i==="["||i==="("?n=U(e,n)??n+1:n+=1}let a=e.slice(o,n);t.push({type:xe(a),value:a,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}u(L,"tokenize");function te(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}u(te,"isBooleanPipe");function U(e,t){let n=e.charAt(t)==="["?"]":")",r=t+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===n)return r+1;if(n===")"&&(o==="("||o==="[")){let a=U(e,r);if(a===void 0)return;r=a}else r+=1}}}u(U,"regexBlockEnd");function be(e,t){let n=U(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:$(L(r))}u(be,"isBooleanGroup");function xe(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}u(xe,"operatorType");function we(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}u(we,"quoteToken");function T(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}u(T,"syntaxError");function P(e,t){return e.kind==="term"?{kind:"term",value:t&&!e.quoted?e.value:G(e.value)}:{kind:e.kind,left:P(e.left,t),right:P(e.right,t)}}u(P,"compileTerms");function J(e){if(e.kind==="term")return e.value;let t=J(e.left);return e.kind==="not"?t:`(?:${t}|${J(e.right)})`}u(J,"matchPattern");function G(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}u(G,"escapeRegex");function ie(e){if(e.multiline===!0){if(e.condition!==void 0)throw new Error("Boolean conditions check single lines and cannot be combined with multiline. Use one regex with multiline instead.");return}if(/\r|\n/u.test(e.query))throw new Error("A pattern with line breaks requires multiline: true.")}u(ie,"assertSupportedPattern");function ae(e){return e.multiline===!0?["--multiline","--multiline-dotall"]:[]}u(ae,"multilineArguments");async function K(e,t,n,r,o){if(e.query.length===0)throw new Error("Search query must not be empty.");return ie(e),e.condition!==void 0?se(e,(a,i)=>re(a,t,n,i,void 0,o),n):re(e,t,n,void 0,r,o)}u(K,"searchText");async function ve(e,t,n,r){if(n===void 0&&(e.path?.includes("://")||t.includes("://")))throw new Error("No search environment owns this scope.");let o=n?.resolve(t,oe(e.path??"."))??E.resolve(t,oe(e.path??".")),a=n===void 0?(await Re(o)).isDirectory():await n.isDirectory(o,r);return{cwd:a?o:n?.dirname(o)??E.dirname(o),target:a?".":`./${n?.basename(o)??E.basename(o)}`,arguments:["--no-config","--no-ignore-parent","--color=never",...D(e.include).flatMap(i=>["--glob",i]),...D(e.exclude).flatMap(i=>["--glob",`!${i}`])]}}u(ve,"ripgrepScope");async function Ce(e,t,n,r){if(ie(e),e.condition!==void 0)return se(e,async(a,i)=>{let l=await Ce(a,t,n,r);for(let s of l.matches)i?.(s.source,s.lineNumber);return l},r);let o=await j(["--json","--no-config","--color=never","--with-filename","--line-number",...e.regex===!0?["--engine","auto"]:["--fixed-strings"],e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...ae(e),"--",e.query,"-"],n,r,void 0,void 0,t.length===0?`
2
+ `:t);return t.length===0?{...o,matches:o.matches.filter(a=>a.lineNumber===1&&a.startColumn===0&&a.endColumn===0)}:o}u(Ce,"searchTextContent");async function re(e,t,n,r,o,a){let i=await ve(e,t,a,n),l=i.cwd,s=["--json","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...ae(e),...i.arguments,"--",e.query,i.target];if(e.regex!==!0)return j(["--fixed-strings",...s],l,n,r,o,void 0,a);try{return await j(["--engine","auto",...s],l,n,r,o,void 0,a)}catch(c){if(!Ee(c))throw c instanceof Error&&/PCRE2 is not available|does not support PCRE2/iu.test(c.message)?new Error("This regex requires PCRE2. Install ripgrep with PCRE2 support or simplify the regex.",{cause:c}):c;try{return await j(["--engine","default",...s],l,n,r,o,void 0,a)}catch(d){throw n?.aborted?d:new AggregateError([c,d],"Regex exceeded the PCRE2 match limit and cannot run with the default engine. Narrow the search or simplify the regex.",{cause:d})}}}u(re,"searchPattern");async function se(e,t,n){let r=e.condition;if(r===void 0)throw new Error("Boolean search requires a line condition.");let o=new Set;function a(m){if(m.kind==="term"){o.add(m.value);return}a(m.left),a(m.right)}u(a,"collect"),a(r);let{condition:i,...l}=e,s=new Map,c=u(m=>JSON.stringify([m.source,m.lineNumber]),"lineKey");for(let m of o){n?.throwIfAborted();let g=new Set;await t({...l,query:m,regex:!0,wholeWord:!1},(w,x)=>g.add(JSON.stringify([w,x]))),s.set(m,g)}let d=await t(l),h=new Set,f=d.matches.filter(m=>{let g=c(m);return h.has(g)||!A(r,w=>s.get(w)?.has(g)===!0)?!1:(h.add(g),!0)});return{...d,matches:f}}u(se,"searchBoolean");function j(e,t,n,r,o,a,i){return i!==void 0?Ae(e,t,i,n,r,o):new Promise((l,s)=>{let c=Te(ee(),e,{stdio:["pipe","pipe","pipe"],cwd:t}),d=0,h=!1;o!==void 0&&c.stdout.on("data",p=>{d+=p.length,d>o.bytes&&(h=!0,c.kill())});let f=ke({input:c.stdout});c.stdin.on("error",()=>{}),c.stdin.end(a);let m=[],g="",w,x=u(()=>{c.kill()},"abort"),C=u(()=>{n?.removeEventListener("abort",x),f.close()},"cleanup");c.stderr.setEncoding("utf8"),c.stderr.on("data",p=>{g+=p}),f.on("line",p=>{if(!(h||w!==void 0||p.length===0))try{let S=JSON.parse(p);if(S.type!=="match")return;if(r!==void 0){let{path:B,line_number:X}=S.data;B.text!==void 0&&Number.isSafeInteger(X)&&r(E.resolve(t,B.text),X);return}for(let B of ce(S,t)){if(o!==void 0&&m.length===o.matches){h=!0,c.kill();break}m.push(B)}}catch(S){w=S,c.kill()}}),c.once("error",p=>{C(),s(p)}),c.once("close",p=>{if(C(),n?.aborted===!0){let S=new Error("Search was aborted.");S.name="AbortError",s(S);return}if(w!==void 0){s(new Error("Unable to parse ripgrep search output.",{cause:w}));return}if(!h&&p!==0&&p!==1){s(new Error(g.trim()||`ripgrep exited with code ${String(p)}.`));return}m.sort(le),l({matches:m,complete:!h})}),n?.addEventListener("abort",x,{once:!0}),n?.aborted===!0&&x()})}u(j,"runRipgrep");async function Ae(e,t,n,r,o,a){let i=[],l=new AbortController,s=u(()=>l.abort(r?.reason),"abort");r?.addEventListener("abort",s,{once:!0}),r?.aborted&&s();let c=0,d={limited:!1};try{let h=await n.runLines(e,t,f=>{if(d.limited||!f.length)return;if(c+=Buffer.byteLength(f)+1,a!==void 0&&c>a.bytes){d.limited=!0,l.abort();return}let m=JSON.parse(f);if(m.type==="match"){if(o!==void 0){let g=m.data.path.text;g!==void 0&&Number.isSafeInteger(m.data.line_number)&&o(n.resolve(t,g),m.data.line_number);return}for(let g of ce(m,t,n)){if(a!==void 0&&i.length>=a.matches){d.limited=!0,l.abort();break}i.push(g)}}},l.signal);if(h.code!==0&&h.code!==1)throw new Error(h.stderr.trim()||"Ripgrep failed.")}catch(h){if(r?.throwIfAborted(),!d.limited)throw h}finally{r?.removeEventListener("abort",s)}return r?.throwIfAborted(),i.sort(le),{matches:i,complete:!d.limited}}u(Ae,"runOwnedRipgrep");function Ee(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}u(Ee,"isPcre2MatchLimitError");function ce(e,t,n){let r=e.data.path.text,o=e.data.lines.text;if(r===void 0||o===void 0||!Number.isSafeInteger(e.data.line_number))return[];let a=o.split(`
3
+ `).map(c=>c.replace(/\r$/u,"")),i=Buffer.from(o),l=u(c=>{let d=i.subarray(0,c).toString("utf8");return{lineIndex:d.split(`
4
+ `).length-1,column:d.length-d.lastIndexOf(`
5
+ `)-1}},"position"),s=[];for(let c of e.data.submatches){if(c.start<0||c.end<c.start||c.end>i.length)continue;let d=l(c.start),h=l(c.end);s.push({source:n?.resolve(t,r)??E.resolve(t,r),lineNumber:e.data.line_number+d.lineIndex,startColumn:d.column,...h.lineIndex===d.lineIndex?{}:{endLineNumber:e.data.line_number+h.lineIndex},endColumn:h.column,matchedText:h.lineIndex===d.lineIndex?(a[d.lineIndex]??"").slice(d.column,h.column):i.subarray(c.start,c.end).toString("utf8"),lineText:a[d.lineIndex]??""})}return s}u(ce,"matchesFromEvent");function oe(e){return e.startsWith("@")?e.slice(1):e}u(oe,"stripFilePrefix");function le(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}u(le,"compareMatches");function at(e){let t=z(e.query),n=z(e.query,!0),r=ne(e.query),o=[],a=Q(e.query),i=Q(e.query,!0);return(n!==t||JSON.stringify(a)!==JSON.stringify(i))&&o.push({query:n,mode:"regex",condition:i}),e.multiline!==!0&&r!==void 0&&r!==t&&r!==n&&o.push({query:r,mode:"words"}),{...e,query:t,regex:!0,condition:a,fallbacks:o}}u(at,"createSearchRecipe");async function V(e,t,n,r){let o=e.query,a=await K(e,t,n,void 0,r),i=[];for(let l of e.fallbacks??[]){if(a.matches.length>0||!a.complete)break;n?.throwIfAborted();try{a=await K({...e,query:l.query,regex:!0,condition:l.condition},t,n,void 0,r),o=l.query,i.push(l.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words. Use these matches as location hints; refine the query before editing.")}catch(s){if(l.mode!=="regex"||!Ne(s)||n?.aborted)throw s;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...a,query:o,notices:i}}u(V,"runSearchRecipe");function Ne(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}u(Ne,"isRegexSyntaxError");var Pe=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,fe=4;function gt(e,t,n,r){return me(e,t,n,r).slice(0,fe)}u(gt,"createSearchSessionId");function me(e,t,n,r){let o=n===void 0?We(t.map(s=>s.source)):R(n),a=t.map(s=>({match:s,source:s.source.includes("://")?R(s.source):b.relative(o,b.resolve(s.source))})).sort((s,c)=>s.source.localeCompare(c.source)||q(s.match,c.match)).map(({match:s,source:c})=>[c,s.lineNumber,s.startColumn,s.endLineNumber??s.lineNumber,s.endColumn,s.matchedText,s.lineText]),{limit:i,...l}=pe(r??{query:e,regex:!0},o);return Me("sha256").update(JSON.stringify([e,o,l,a])).digest("hex").toUpperCase()}u(me,"createSearchSessionIdentity");function $e(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let n=fe;n<=e.length;n+=1){let r=e.slice(0,n);if(!t.has(r))return r}throw new Error("Could not allocate a unique search session id.")}u($e,"allocateSearchSessionId");function pe(e,t){return{query:e.query,path:Fe(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,multiline:e.multiline===!0,limit:e.limit??50,regex:e.regex===!0,condition:e.condition,fallbacks:e.fallbacks??[]}}u(pe,"normalizeRecipe");var F=class extends Error{static{u(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},ue=class{constructor(t=me,n,r){this.createIdentity=t;this.resultTargets=n;this.readSource=r}static{u(this,"SearchSessionStore")}#e=new Map;#r=new Map;async register(t,n,r,o,a,i={query:t,regex:!0},l,s,c){let d=n.map(p=>({...p,source:R(p.source)})).sort(q),h=this.readSource,f=h===void 0?void 0:(p,S)=>h(p,o,S),m=await de(d,a,s,c,f),g=this.createIdentity(t,d,o,i),x=this.#r.get(g)??$e(g,new Set(this.#e.keys())),C={id:x,query:t,matches:d,complete:r,contentBySource:m,read:f,...Le(this.resultTargets,x,d,m,o,r,(p,S)=>_(p,S,c,f)),...s===void 0?{}:{snapshotByteBudget:s},recipe:i,environment:c,...l!==void 0&&{refresh:l},cwd:R(o)};return this.#r.set(g,x),this.#e.set(x,C),C}async registerIfCurrent(t,n,r,o,a,i,l,s,c){try{return await this.register(t,n,r,o,a,i,l,s,c)}catch(d){if(d instanceof F)return;throw d}}async observeAfterEdit(t,n){let r=new Set(t.flatMap(a=>{let i=typeof a=="string"?N(a):void 0;return i===void 0?[]:[i.id]})),o=[];for(let a of r){let i=this.#e.get(a);if(i===void 0)continue;let l={sessionId:a,query:i.recipe.originalQuery??i.query,scope:pe(i.recipe,i.cwd)};try{let s=i.refresh===void 0?await V(i.recipe,i.cwd,n,i.environment):await i.refresh(n);o.push({...l,matches:s.matches.length,complete:s.complete,notices:s.notices})}catch(s){o.push({...l,error:s instanceof Error?s.message:String(s)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
6
+ `),renderFull(t){return t},renderCompact(t){let n=N(t);return n===void 0?"selected result":n.selector==="all"?n.mode==="match"?"all matches":"all lines":n.mode==="match"?`match ${String(n.selector)}`:`line ${String(n.selector)}`},tryResolve:u((t,n)=>this.#a(t,n.source,n.signal),"tryResolve")}}async resolveSearchScope(t,n){if(!t.startsWith("SEARCH#"))return;let r=await this.#o(t,n.cwd,n.signal,!0);if(r.kind!=="resolved")throw new Error(r.kind==="rejected"?r.rejection.reason:"Invalid Search reference.");let o=y(N(t)),a=y(this.#e.get(o.id));return{complete:!0,targets:r.targets.map(i=>{if(i.expectedContent===void 0)throw new Error("Search snapshot is unavailable.");return{source:i.source,expectedContent:i.expectedContent,ranges:i.ranges??[],readCurrent:u(async l=>{let s=await O(i.source,l,a.environment,a.read);if(s===void 0)throw new Error("Search source is unavailable.");return s},"readCurrent")}})}}resourceResolver(){return{id:"search-targets",tryResolve:u((t,n)=>this.#o(t,n.cwd),"tryResolve")}}async#a(t,n,r){let o=N(t);if(o===void 0)return{kind:"not-handled"};let a=this.#e.get(o.id);if(a===void 0)return M();if(o.selector==="all"&&!a.complete)return v();let i=R(n),l=a;if(o.selector==="all"){if(a.refreshedComplete?.complete===!0)l=a.refreshedComplete;else if(a.refreshedComplete!==void 0&&(l=await this.#n(a,r),!l.complete))return v()}let s=H(l,o.selector,o.mode),c=s.filter(f=>f.source===i);if(c.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await O(i,r,a.environment,a.read);if(d===void 0)return M(y(c[0]).lineNumber);if(o.selector==="all"&&d!==l.contentBySource.get(i)){if(l=await this.#n(a,r),!l.complete)return v();s=H(l,o.selector,o.mode),c=s.filter(f=>f.source===i)}if(c.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==a.contentBySource.get(i))return M(y(c[0]).lineNumber);let h=k(i,d);return{kind:"resolved",anchor:new Y(t,i,c.map(f=>W(h,f,o.mode)))}}async#o(t,n,r,o=!1){let a=N(t);if(a===void 0)return{kind:"not-handled"};let i=this.#e.get(a.id);if(i===void 0||i.cwd!==R(n))return M();if(a.selector==="all"&&!i.complete)return v();let l=i;if(a.selector==="all"){if(i.refreshedComplete?.complete===!0)l=i.refreshedComplete;else if(i.refreshedComplete!==void 0&&(l=await this.#n(i,r),!l.complete))return v();let h=new Set(H(l,a.selector,a.mode).map(f=>f.source));for(let f of h)if(await O(f,r,i.environment,i.read)!==l.contentBySource.get(f)){if(l=await this.#n(i,r),!l.complete)return v();break}}let s=H(l,a.selector,a.mode);if(a.selector!=="all"){let h=s[0]?.source;if(h!==void 0&&await O(h,r,i.environment,i.read)!==l.contentBySource.get(h))return M(s[0]?.lineNumber)}let c=new Map;for(let h of s){let f=c.get(h.source)??[];f.push(W(k(h.source,l.contentBySource.get(h.source)??h.lineText),h,a.mode)),c.set(h.source,f)}let d=[...c].map(([h,f])=>({source:h,ranges:f,expectedContent:l.contentBySource.get(h)}));return d.length===0&&!(o&&a.selector==="all")?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:d}}async#n(t,n){let r=t.refresh===void 0?await V(t.recipe,t.cwd,n,t.environment):await t.refresh(n),o=r.matches.map(i=>({...i,source:R(i.source)})).sort(q),a={matches:o,complete:r.complete,contentBySource:await de(o,n,t.snapshotByteBudget,t.environment,t.read)};return this.#e.set(t.id,{...t,refreshedComplete:a}),a}};function Le(e,t,n,r,o,a,i){if(e===void 0)return{};let l=new Map([...r].map(([c,d])=>[c,k(c,d)])),s=n.map(c=>({source:c.source,expectedContent:y(r.get(c.source)),ranges:[W(y(l.get(c.source)),c,"match")],readCurrent:u(d=>i(c.source,d),"readCurrent")}));for(let[c,d]of n.slice(0,100).entries()){let h=e.register([{...y(s[c]),ranges:[W(y(l.get(d.source)),d,"line")]}],o);e.registerSearchReference(`SEARCH#${t}:${c+1}:line`,h,o)}return{target:e.register(s,o,a),matchTargets:s.slice(0,100).map(c=>e.register([c],o,a))}}u(Le,"registerResultReferences");function N(e){let t=Pe.exec(e);if(t!==null)return{id:y(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}u(N,"parseSearchAnchor");function H(e,t,n){let r=t==="all"?e.matches:[e.matches[t-1]].filter(je);if(n==="match"||t!=="all")return r;let o=new Set;return r.flatMap(a=>{let i=k(a.source,e.contentBySource.get(a.source)??a.lineText),l=ge(a);return i.lines.slice(a.lineNumber-1,l).flatMap(s=>{let c=`${a.source}\0${String(s.lineNumber)}`;return o.has(c)?[]:(o.add(c),[{...a,lineNumber:s.lineNumber,endLineNumber:s.lineNumber,startColumn:0,endColumn:s.content.length,lineText:s.content,matchedText:s.content}])})})}u(H,"selectMatches");function je(e){return e!==void 0}u(je,"isMatch");function ge(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}u(ge,"lastContainingLine");function W(e,t,n){if(n==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let r=ge(t),o=y(e.lines[r-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:r+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}u(W,"selectionRange");function He(e,t){let n=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,n).map(r=>{let o=r.lineNumber===t.lineNumber?t.startColumn:0,a=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,a)+(r.lineNumber===n?"":r.lineEnding)}).join("")}u(He,"matchedSourceText");async function de(e,t,n,r,o){let a=[...new Set(e.map(s=>s.source))];if(n!==void 0){let s=new Map,c=n;for(let d of a){let h=await Oe(d,c,t,r,o);c-=Buffer.byteLength(h),he(d,h,e),s.set(d,h)}return s}let i=await Promise.allSettled(a.map(async s=>{let c=await _(s,t,r,o);return he(s,c,e),[s,c]})),l=new Map;for(let s of i){if(s.status==="rejected")throw s.reason;l.set(...s.value)}return l}u(de,"snapshotContents");function he(e,t,n){let r=k(e,t);for(let o of n.filter(a=>a.source===e))if(r.lines[o.lineNumber-1]?.content!==o.lineText||He(r,o)!==o.matchedText)throw new F(e)}u(he,"validateSnapshot");async function Oe(e,t,n,r,o){if(n?.throwIfAborted(),e.includes("://")){let i=await _(e,n,r,o);if(Buffer.byteLength(i)>t)throw new Error("Candidate snapshot byte budget reached.");return i}let a=await Be(e,"r");try{let i=await a.stat();if(!i.isFile()||i.size>t)throw new Error("Candidate snapshot byte budget reached.");let l=Buffer.alloc(Math.min(i.size+1,t+1)),s=0;for(;s<l.length;){n?.throwIfAborted();let c=await a.read(l,s,l.length-s,s);if(c.bytesRead===0)break;s+=c.bytesRead}if(n?.throwIfAborted(),s>i.size||s>t)throw new Error("Candidate file grew during snapshot capture.");return l.subarray(0,s).toString("utf8")}finally{await a.close()}}u(Oe,"readBoundedSnapshot");async function O(e,t,n,r){try{return await _(e,t,n,r)}catch{return}}u(O,"readCurrent");function R(e){return e.includes("://")?e:b.resolve(e)}u(R,"canonicalSource");function Fe(e,t){return t.includes("://")?t:e.includes("://")?new URL(t,e.endsWith("/")?e:e+"/").href:b.resolve(e,t)}u(Fe,"resolveScope");async function _(e,t,n,r){if(t?.throwIfAborted(),r!==void 0)return r(e,t);if(n!==void 0)return n.readText(e,t);if(e.includes("://"))throw new Error("No search snapshot owner for this source.");return Ie(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}u(_,"readOwnedText");function M(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}u(M,"staleAnchor");function v(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}u(v,"missingCompleteAnchor");function We(e){if(e.length===0)return".";let t=b.dirname(b.resolve(y(e[0])));for(let n of e.slice(1)){let r=b.resolve(n);for(;!_e(t,r);){let o=b.dirname(t);if(o===t)return t;t=o}}return t}u(We,"commonSourceDirectory");function _e(e,t){let n=b.relative(e,t);return n!==".."&&!n.startsWith(`..${b.sep}`)&&!b.isAbsolute(n)}u(_e,"isWithin");function q(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}u(q,"compareMatches");export{ee as a,K as b,ve as c,Ce as d,at as e,V as f,gt as g,me as h,$e as i,F as j,ue as k};
@@ -1,6 +1,6 @@
1
- import{e as I}from"./chunk-PS2B6THP.js";import{i as S,o as h,t as $,u as A}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as u}from"./chunk-EI7MMDWY.js";function we(e,n){let{lines:t,truncation:r,...i}=e,o=t?.map(a=>{let l=[a.lineNumber,$(a.content,n),a.lineEnding];return(a.presentation!==void 0||a.metadata!==void 0)&&l.push(a.presentation),a.metadata!==void 0&&l.push(a.metadata),l}),{content:s,...d}=r??{};return{...i,...o===void 0?{}:{storedLines:o},...r===void 0?{}:{truncation:d,truncatedText:$(s??"",n)}}}u(we,"compactReadDetails");function z(e,n){let t=e;if(t.storedLines===void 0&&t.truncatedText===void 0)return e;let{storedLines:r,truncatedText:i,truncation:o,...s}=t;return{...s,...r===void 0?{}:{lines:r.map(([d,a,l,f,c])=>({lineNumber:d,content:A(a,n),lineEnding:l,...f==null?{}:{presentation:f},...c==null?{}:{metadata:c}}))},...o===void 0?{}:{truncation:{...o,content:A(i??"",n)}}}}u(z,"restoreReadDetails");import p from"node:path";import{homedir as G}from"node:os";import{createReadToolDefinition as X,getReadmePath as J}from"@earendil-works/pi-coding-agent";import{Text as Z}from"@earendil-works/pi-tui";var D=X(process.cwd()),K=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function M(e,n=process.cwd()){if(typeof e!="object"||e===null)return;let t=e,r=t.path;if(typeof r!="string"||r.length===0||r.includes("#")||!p.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||t.views!==void 0&&(!Array.isArray(t.views)||t.views.length>0)||t.offset!==void 0&&(typeof t.offset!="number"||!Number.isInteger(t.offset)||t.offset<1)||t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1))return;let i=r.startsWith("~/")?p.join(G(),r.slice(2)):r,o=p.resolve(n,i),s=p.basename(o),d=p.relative(p.dirname(J()),o),a=!p.isAbsolute(d)&&(d==="README.md"||d.startsWith(`docs${p.sep}`)||d.startsWith(`examples${p.sep}`));if(!(s!=="SKILL.md"&&!K.has(s)&&!a))return{path:r,...t.offset===void 0?{}:{offset:t.offset},...t.limit===void 0?{}:{limit:t.limit}}}u(M,"nativeReadArguments");function P(e,n){return{...e,args:n,lastComponent:e.lastComponent instanceof Z?e.lastComponent:void 0}}u(P,"nativeReadContext");import{getLanguageFromPath as N,getMarkdownTheme as Y,highlightCode as W,keyHint as Q}from"@earendil-works/pi-coding-agent";import{Container as L,Markdown as _,Text as ee,truncateToWidth as v,visibleWidth as R,wrapTextWithAnsi as T}from"@earendil-works/pi-tui";var x=12;function te(e,n,t){let r=typeof n=="number"?n:void 0,i=typeof t=="number"?t:void 0;if(r===void 0&&i===void 0)return{pathSuffix:"",qualifiers:[],details:[]};if(e==="inherited source"||e.includes("#")){let a=r??1,l=i===void 0?String(a):`${a}-${a+i-1}`;return{pathSuffix:"",qualifiers:[{text:`relative lines ${l}`}],details:[{label:"relative lines",value:l}]}}if(r!==void 0&&r<0)return{pathSuffix:"",qualifiers:[{text:`tail ${Math.abs(r)}`},...i===void 0?[]:[{text:`limit ${i}`}]],details:[{label:"tail",value:String(Math.abs(r))},...i===void 0?[]:[{label:"limit",value:String(i)}]]};let s=Math.max(1,r??1),d=i===void 0?String(s):`${s}-${s+i-1}`;return{pathSuffix:`:${d}`,qualifiers:[],details:[{label:"lines",value:d}]}}u(te,"readWindowPresentation");function We(e,n,t){let r=M(e,t.cwd);if(r!==void 0)return w(D.renderCall)(r,n,P(t,r));if(typeof e.path=="string"&&e.path.startsWith("shell:"))return new L;let i=typeof e.path=="string"?e.path:"inherited source",o=te(i,e.offset,e.limit),s=Array.isArray(e.views)?e.views.filter(l=>typeof l=="string"):[],d=[...o.qualifiers,...s.length===0?[]:[{text:`views ${s.join(",")}`}]],a=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...o.details,...s.length===0?[]:[{label:"views",value:s.join(",")}]];return I(t.lastComponent,{tool:"read",primary:{text:`${i}${o.pathSuffix}`,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:d,details:a,expanded:t.expanded},n)}u(We,"renderReadCall");function je(e){let n=new WeakMap;return(t,r,i,o)=>{let s=e.nativeResources?M(o.args,o.cwd):void 0;if(s!==void 0&&!r.isPartial)return w(D.renderResult)({...t,details:{truncation:k(t.details).truncation}},r,i,P(o,s));if(r.isPartial||o.isError){let c=O(t),m=o.isError?"error":"dim";return new ee(i.fg(m,c),0,0)}let d=k(t.details).diagnosticCheck;if(d?.complete&&d.count===0)return new L;if(!me(t))return o.lastComponent instanceof L?o.lastComponent:new L;let a=n.get(t);a===void 0&&(a=z(k(t.details),O(t)),n.set(t,a));let f=(o.lastComponent instanceof C?o.lastComponent:void 0)??new C({result:t,details:a,options:e,expanded:r.expanded,theme:i});return f.update({result:t,details:a,options:e,expanded:r.expanded,theme:i}),f}}u(je,"createReadResultRenderer");var C=class{constructor(n){this.state=n}static{u(this,"ReadResultPanel")}cached;update(n){this.state.result===n.result&&this.state.details===n.details&&this.state.options===n.options&&this.state.expanded===n.expanded&&this.state.theme===n.theme||(this.state=n,this.invalidate())}render(n){if(this.cached?.width===n)return this.cached.lines;if(n<8){let c=[v(B(this.state,n),Math.max(1,n))];return this.cached={width:n,lines:c},c}let t=n-2,r=Math.max(1,t-2),i=oe(this.state,r),o=se(i.state,r).flatMap(c=>T(c,r)),s=ue(o,this.state.expanded,this.state.theme,i.hasHiddenRows),d=[le(this.state,t,this.state.theme)],a=this.state.details.diagnosticStatus;if(a)for(let c of a.split(/\r\n|\r|\n/u))for(let m of T(this.state.theme.fg("muted",g(c)),r))d.push(b(m,t,this.state.theme));for(let c of this.state.details.viewWarnings??[])for(let m of T(this.state.theme.fg("warning",g(c)),r))d.push(b(m,t,this.state.theme));for(let c of s)for(let m of T(c,r))d.push(b(m,t,this.state.theme));let l=fe(this.state.details,this.state.theme);l!==void 0&&d.push(b(l,t,this.state.theme)),d.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(t)}\u256F`));let f=d.map(c=>v(c,n));return this.cached={width:n,lines:f},f}invalidate(){this.cached=void 0}},ne=100,re=x,ie=4;function oe(e,n){if(e.expanded)return{state:e,hasHiddenRows:!1};let t=H(e.details);if(t!==void 0&&t.length>ne)return{state:{...e,details:{...e.details,lines:t.slice(0,re)}},hasHiddenRows:!0};if(t!==void 0)return{state:e,hasHiddenRows:!1};let r=Math.max(x,n*x*ie),i=e.result.content.map(s=>s.type!=="text"||s.text.length<=r?s:{...s,text:s.text.slice(0,r)}),o=i.some((s,d)=>{let a=e.result.content[d];return s.type==="text"&&a?.type==="text"&&s.text.length<a.text.length});return o?{state:{...e,result:{...e.result,content:i}},hasHiddenRows:o}:{state:e,hasHiddenRows:!1}}u(oe,"compactRenderInput");function se(e,n){let t=H(e.details),r=pe(e.result,t,e.details,!e.expanded);if(e.options.kind==="markdown"||ge(e.details,t,e.options.kind)){let a=new _(r,0,0,Y());return E(a.render(n),e.theme)}if(e.options.kind==="code-view"){let a=t===void 0?y(r).map(l=>j(l,e.theme,!1)):U(t)?ae(t,!e.expanded,e.theme):de(t,e.theme);return E(a,e.theme)}let i=t!==void 0&&U(t),o=t===void 0||i?y(r).map(g):t.map(({content:a})=>g(a)),s=q(e.details,t),d=s===void 0?o.map(a=>e.theme.fg("toolOutput",a)):i?F(t,s,!e.expanded,e.theme):W(o.join(`
2
- `),s);return E(d,e.theme)}u(se,"renderContentRows");function F(e,n,t,r){return e.flatMap(i=>{let o=g(i.content),s=W(o,n)[0]??r.fg("toolOutput",o),d=!1,a=h({source:"",content:i.content,lines:[i]},{compact:t});return y(a).map(l=>{if(!d&&o.length>0){let f=l.indexOf(o);if(f>=0)return d=!0,`${r.fg("toolOutput",l.slice(0,f))}${s}${r.fg("toolOutput",l.slice(f+o.length))}`}return r.fg("toolOutput",l)})})}u(F,"renderHighlightedPresentedLines");function ae(e,n,t){return e.flatMap(r=>{let i=S(r);if(i===void 0){let s=h({source:"",content:r.content,lines:[r]},{compact:n});return y(s).map(d=>j(d,t,!1))}let o=N(i.source);if(o===void 0){let s=h({source:"",content:r.content,lines:[r]},{compact:n});return y(s).map(d=>t.fg("toolOutput",d))}return F([r],o,n,t)})}u(ae,"renderPresentedCodeViewLines");function de(e,n){return e.map(t=>{let r=S(t);if(r===void 0)return j(t.content,n);let i=N(r.source),o=g(V(t.content));return i===void 0?n.fg("toolOutput",o):W(o,i)[0]??n.fg("toolOutput",o)})}u(de,"renderCodeViewLines");function V(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}u(V,"stripScopeMarkers");function j(e,n,t=!0){let r=g(t?V(e):e);return/^#{2,3}\s/u.test(r)?n.fg("mdHeading",n.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?n.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?n.fg("accent",n.bold(r)):/^\s*[-*]\s/u.test(r)?n.fg("mdListBullet",r):n.fg("toolOutput",r)}u(j,"renderCodeViewLabel");function ue(e,n,t,r=!1){if(n||e.length<=x&&!r)return e;let i=e.slice(0,x-1),o=e.length-i.length,s=r?"more rows":`${String(o)} more ${o===1?"row":"rows"}`;return[...i,`${t.fg("dim",`\u2026 ${s} \xB7 `)}${Q("app.tools.expand","to expand")}`]}u(ue,"compactRows");function le(e,n,t){let r=u(s=>t.fg("borderMuted",s),"frame"),i=v(` ${B(e,Math.max(1,n-1))} `,Math.max(0,n-1),""),o="\u2500".repeat(Math.max(0,n-R(i)-1));return`${r("\u256D\u2500")}${i}${r(`${o}\u256E`)}`}u(le,"renderTopBorder");function B(e,n){let t=e.options.label??Re(q(e.details,H(e.details))),r=e.details.source??"read result",i=ce(e.details),o=e.theme.fg("accent",e.theme.bold(t)),s=i===void 0?"":e.theme.fg("dim",` \xB7 ${i}`),d=Math.max(1,n-R(o)-R(s)-2),a=xe(r,d);return`${o} ${e.theme.fg("muted",a)}${s}`}u(B,"readTitle");function ce(e){if(!(e.startLine===void 0||e.endLine===void 0||e.totalLines===void 0||e.totalLines<=0))return`${String(e.startLine)}\u2013${String(e.endLine)} / ${String(e.totalLines)}`}u(ce,"sourceRange");function fe(e,n){let t=e.truncation;if(t?.firstLineExceedsLimit===!0)return n.fg("warning","First source line is larger than the saved read limit");if(t?.truncated===!0)return n.fg("warning",`Saved result contains ${String(t.outputLines)} of ${String(t.totalLines)} rendered rows`)}u(fe,"readStatus");function b(e,n,t){let r=Math.max(0,n-2),i=v(e,r),o=` ${i}${" ".repeat(Math.max(0,r-R(i)))} `,s=t.fg("borderMuted","\u2502");return`${s}${o}${s}`}u(b,"framed");function pe(e,n,t,r){if(n!==void 0)return h({source:t.source??"",content:"",lines:n},{compact:r});let i=O(e),o=t.viewWarnings?.join(`
1
+ import{e as I}from"./chunk-PS2B6THP.js";import{i as w,o as h,t as $,u as A}from"./chunk-VDJSH3DQ.js";import{a as S}from"./chunk-ZC65Z3CK.js";import{a as u}from"./chunk-EI7MMDWY.js";function we(e,n){let{lines:t,truncation:r,...i}=e,o=t?.map(a=>{let l=[a.lineNumber,$(a.content,n),a.lineEnding];return(a.presentation!==void 0||a.metadata!==void 0)&&l.push(a.presentation),a.metadata!==void 0&&l.push(a.metadata),l}),{content:s,...d}=r??{};return{...i,...o===void 0?{}:{storedLines:o},...r===void 0?{}:{truncation:d,truncatedText:$(s??"",n)}}}u(we,"compactReadDetails");function z(e,n){let t=e;if(t.storedLines===void 0&&t.truncatedText===void 0)return e;let{storedLines:r,truncatedText:i,truncation:o,...s}=t;return{...s,...r===void 0?{}:{lines:r.map(([d,a,l,f,c])=>({lineNumber:d,content:A(a,n),lineEnding:l,...f==null?{}:{presentation:f},...c==null?{}:{metadata:c}}))},...o===void 0?{}:{truncation:{...o,content:A(i??"",n)}}}}u(z,"restoreReadDetails");import p from"node:path";import{homedir as G}from"node:os";import{createReadToolDefinition as X,getReadmePath as J}from"@earendil-works/pi-coding-agent";import{Text as Z}from"@earendil-works/pi-tui";var D=X(process.cwd()),K=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function M(e,n=process.cwd()){if(typeof e!="object"||e===null)return;let t=e,r=t.path;if(typeof r!="string"||r.length===0||r.includes("#")||!p.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||t.views!==void 0&&(!Array.isArray(t.views)||t.views.length>0)||t.offset!==void 0&&(typeof t.offset!="number"||!Number.isInteger(t.offset)||t.offset<1)||t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1))return;let i=r.startsWith("~/")?p.join(G(),r.slice(2)):r,o=p.resolve(n,i),s=p.basename(o),d=p.relative(p.dirname(J()),o),a=!p.isAbsolute(d)&&(d==="README.md"||d.startsWith(`docs${p.sep}`)||d.startsWith(`examples${p.sep}`));if(!(s!=="SKILL.md"&&!K.has(s)&&!a))return{path:r,...t.offset===void 0?{}:{offset:t.offset},...t.limit===void 0?{}:{limit:t.limit}}}u(M,"nativeReadArguments");function P(e,n){return{...e,args:n,lastComponent:e.lastComponent instanceof Z?e.lastComponent:void 0}}u(P,"nativeReadContext");import{getLanguageFromPath as N,getMarkdownTheme as Y,highlightCode as W,keyHint as Q}from"@earendil-works/pi-coding-agent";import{Container as L,Markdown as _,Text as ee,truncateToWidth as v,visibleWidth as R,wrapTextWithAnsi as T}from"@earendil-works/pi-tui";var x=12;function te(e,n,t){let r=typeof n=="number"?n:void 0,i=typeof t=="number"?t:void 0;if(r===void 0&&i===void 0)return{pathSuffix:"",qualifiers:[],details:[]};if(e==="inherited source"||e.includes("#")){let a=r??1,l=i===void 0?String(a):`${a}-${a+i-1}`;return{pathSuffix:"",qualifiers:[{text:`relative lines ${l}`}],details:[{label:"relative lines",value:l}]}}if(r!==void 0&&r<0)return{pathSuffix:"",qualifiers:[{text:`tail ${Math.abs(r)}`},...i===void 0?[]:[{text:`limit ${i}`}]],details:[{label:"tail",value:String(Math.abs(r))},...i===void 0?[]:[{label:"limit",value:String(i)}]]};let s=Math.max(1,r??1),d=i===void 0?String(s):`${s}-${s+i-1}`;return{pathSuffix:`:${d}`,qualifiers:[],details:[{label:"lines",value:d}]}}u(te,"readWindowPresentation");function We(e,n,t){let r=M(e,t.cwd);if(r!==void 0)return S(D.renderCall)(r,n,P(t,r));if(typeof e.path=="string"&&e.path.startsWith("shell:"))return new L;let i=typeof e.path=="string"?e.path:"inherited source",o=te(i,e.offset,e.limit),s=Array.isArray(e.views)?e.views.filter(l=>typeof l=="string"):[],d=[...o.qualifiers,...s.length===0?[]:[{text:`views ${s.join(",")}`}]],a=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...o.details,...s.length===0?[]:[{label:"views",value:s.join(",")}]];return I(t.lastComponent,{tool:"read",primary:{text:`${i}${o.pathSuffix}`,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:d,details:a,expanded:t.expanded},n)}u(We,"renderReadCall");function je(e){let n=new WeakMap;return(t,r,i,o)=>{let s=e.nativeResources?M(o.args,o.cwd):void 0;if(s!==void 0&&!r.isPartial)return S(D.renderResult)({...t,details:{truncation:k(t.details).truncation}},r,i,P(o,s));if(r.isPartial||o.isError){let c=O(t),m=o.isError?"error":"dim";return new ee(i.fg(m,c),0,0)}let d=k(t.details).diagnosticCheck;if(d?.complete&&d.count===0)return new L;if(!me(t))return o.lastComponent instanceof L?o.lastComponent:new L;let a=n.get(t);a===void 0&&(a=z(k(t.details),O(t)),n.set(t,a));let f=(o.lastComponent instanceof C?o.lastComponent:void 0)??new C({result:t,details:a,options:e,expanded:r.expanded,theme:i});return f.update({result:t,details:a,options:e,expanded:r.expanded,theme:i}),f}}u(je,"createReadResultRenderer");var C=class{constructor(n){this.state=n}static{u(this,"ReadResultPanel")}cached;update(n){this.state.result===n.result&&this.state.details===n.details&&this.state.options===n.options&&this.state.expanded===n.expanded&&this.state.theme===n.theme||(this.state=n,this.invalidate())}render(n){if(this.cached?.width===n)return this.cached.lines;if(n<8){let c=[v(B(this.state,n),Math.max(1,n))];return this.cached={width:n,lines:c},c}let t=n-2,r=Math.max(1,t-2),i=oe(this.state,r),o=se(i.state,r).flatMap(c=>T(c,r)),s=ue(o,this.state.expanded,this.state.theme,i.hasHiddenRows),d=[le(this.state,t,this.state.theme)],a=this.state.details.diagnosticStatus;if(a)for(let c of a.split(/\r\n|\r|\n/u))for(let m of T(this.state.theme.fg("muted",g(c)),r))d.push(b(m,t,this.state.theme));for(let c of this.state.details.viewWarnings??[])for(let m of T(this.state.theme.fg("warning",g(c)),r))d.push(b(m,t,this.state.theme));for(let c of s)for(let m of T(c,r))d.push(b(m,t,this.state.theme));let l=fe(this.state.details,this.state.theme);l!==void 0&&d.push(b(l,t,this.state.theme)),d.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(t)}\u256F`));let f=d.map(c=>v(c,n));return this.cached={width:n,lines:f},f}invalidate(){this.cached=void 0}},ne=100,re=x,ie=4;function oe(e,n){if(e.expanded)return{state:e,hasHiddenRows:!1};let t=H(e.details);if(t!==void 0&&t.length>ne)return{state:{...e,details:{...e.details,lines:t.slice(0,re)}},hasHiddenRows:!0};if(t!==void 0)return{state:e,hasHiddenRows:!1};let r=Math.max(x,n*x*ie),i=e.result.content.map(s=>s.type!=="text"||s.text.length<=r?s:{...s,text:s.text.slice(0,r)}),o=i.some((s,d)=>{let a=e.result.content[d];return s.type==="text"&&a?.type==="text"&&s.text.length<a.text.length});return o?{state:{...e,result:{...e.result,content:i}},hasHiddenRows:o}:{state:e,hasHiddenRows:!1}}u(oe,"compactRenderInput");function se(e,n){let t=H(e.details),r=pe(e.result,t,e.details,!e.expanded);if(e.options.kind==="markdown"||ge(e.details,t,e.options.kind)){let a=new _(r,0,0,Y());return E(a.render(n),e.theme)}if(e.options.kind==="code-view"){let a=t===void 0?y(r).map(l=>j(l,e.theme,!1)):U(t)?ae(t,!e.expanded,e.theme):de(t,e.theme);return E(a,e.theme)}let i=t!==void 0&&U(t),o=t===void 0||i?y(r).map(g):t.map(({content:a})=>g(a)),s=q(e.details,t),d=s===void 0?o.map(a=>e.theme.fg("toolOutput",a)):i?F(t,s,!e.expanded,e.theme):W(o.join(`
2
+ `),s);return E(d,e.theme)}u(se,"renderContentRows");function F(e,n,t,r){return e.flatMap(i=>{let o=g(i.content),s=W(o,n)[0]??r.fg("toolOutput",o),d=!1,a=h({source:"",content:i.content,lines:[i]},{compact:t});return y(a).map(l=>{if(!d&&o.length>0){let f=l.indexOf(o);if(f>=0)return d=!0,`${r.fg("toolOutput",l.slice(0,f))}${s}${r.fg("toolOutput",l.slice(f+o.length))}`}return r.fg("toolOutput",l)})})}u(F,"renderHighlightedPresentedLines");function ae(e,n,t){return e.flatMap(r=>{let i=w(r);if(i===void 0){let s=h({source:"",content:r.content,lines:[r]},{compact:n});return y(s).map(d=>j(d,t,!1))}let o=N(i.source);if(o===void 0){let s=h({source:"",content:r.content,lines:[r]},{compact:n});return y(s).map(d=>t.fg("toolOutput",d))}return F([r],o,n,t)})}u(ae,"renderPresentedCodeViewLines");function de(e,n){return e.map(t=>{let r=w(t);if(r===void 0)return j(t.content,n);let i=N(r.source),o=g(V(t.content));return i===void 0?n.fg("toolOutput",o):W(o,i)[0]??n.fg("toolOutput",o)})}u(de,"renderCodeViewLines");function V(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}u(V,"stripScopeMarkers");function j(e,n,t=!0){let r=g(t?V(e):e);return/^#{2,3}\s/u.test(r)?n.fg("mdHeading",n.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?n.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?n.fg("accent",n.bold(r)):/^\s*[-*]\s/u.test(r)?n.fg("mdListBullet",r):n.fg("toolOutput",r)}u(j,"renderCodeViewLabel");function ue(e,n,t,r=!1){if(n||e.length<=x&&!r)return e;let i=e.slice(0,x-1),o=e.length-i.length,s=r?"more rows":`${String(o)} more ${o===1?"row":"rows"}`;return[...i,`${t.fg("dim",`\u2026 ${s} \xB7 `)}${Q("app.tools.expand","to expand")}`]}u(ue,"compactRows");function le(e,n,t){let r=u(s=>t.fg("borderMuted",s),"frame"),i=v(` ${B(e,Math.max(1,n-1))} `,Math.max(0,n-1),""),o="\u2500".repeat(Math.max(0,n-R(i)-1));return`${r("\u256D\u2500")}${i}${r(`${o}\u256E`)}`}u(le,"renderTopBorder");function B(e,n){let t=e.options.label??Re(q(e.details,H(e.details))),r=e.details.source??"read result",i=ce(e.details),o=e.theme.fg("accent",e.theme.bold(t)),s=i===void 0?"":e.theme.fg("dim",` \xB7 ${i}`),d=Math.max(1,n-R(o)-R(s)-2),a=xe(r,d);return`${o} ${e.theme.fg("muted",a)}${s}`}u(B,"readTitle");function ce(e){if(!(e.startLine===void 0||e.endLine===void 0||e.totalLines===void 0||e.totalLines<=0))return`${String(e.startLine)}\u2013${String(e.endLine)} / ${String(e.totalLines)}`}u(ce,"sourceRange");function fe(e,n){let t=e.truncation;if(t?.firstLineExceedsLimit===!0)return n.fg("warning","First source line is larger than the saved read limit");if(t?.truncated===!0)return n.fg("warning",`Saved result contains ${String(t.outputLines)} of ${String(t.totalLines)} rendered rows`)}u(fe,"readStatus");function b(e,n,t){let r=Math.max(0,n-2),i=v(e,r),o=` ${i}${" ".repeat(Math.max(0,r-R(i)))} `,s=t.fg("borderMuted","\u2502");return`${s}${o}${s}`}u(b,"framed");function pe(e,n,t,r){if(n!==void 0)return h({source:t.source??"",content:"",lines:n},{compact:r});let i=O(e),o=t.viewWarnings?.join(`
3
3
  `),s=o===void 0?i:i===o?"":i.startsWith(`${o}
4
4
  `)?i.slice(o.length+1):i,d=t.diagnosticStatus;return d!==void 0&&(s=s===d?"":s.startsWith(`${d}
5
5
  `)?s.slice(d.length+1):s),t.truncation===void 0&&!(t.totalLines!==void 0&&t.endLine!==void 0&&t.endLine<t.totalLines)?s:s.replace(/\n\n\[(?:Showing lines|Output truncated|\d+ more lines in source)[\s\S]*\]$/u,"")}u(pe,"cleanText");function U(e){return e.some(n=>n.presentation!==void 0)}u(U,"hasPresentation");function y(e){let n=e.split(/\r\n|\r|\n/u);return n.at(-1)===""&&/(?:\r\n|\r|\n)$/u.test(e)&&n.pop(),n}u(y,"splitTextRows");function O(e){return e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
6
- `)}u(O,"textBlocks");function H(e){return e.lines}u(H,"readLines");function k(e){return typeof e=="object"&&e!==null?e:{}}u(k,"readDetails");function me(e){return e.content.some(n=>n.type==="text")}u(me,"hasTextContent");function q(e,n){let r=n?.map(S).find(i=>i!==void 0)?.source??e.source;return r===void 0?void 0:N(he(r))}u(q,"languageFor");function ge(e,n,t){return t==="source"&&q(e,n)==="markdown"}u(ge,"isMarkdownSource");function he(e){try{let n=new URL(e);return n.protocol==="file:"?n.pathname:`${n.pathname}${n.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}u(he,"normalizeSourcePath");function g(e){let n="";for(let t of e.replaceAll(" "," ".repeat(4))){let r=w(t.codePointAt(0));n+=r<32||r===127?"\uFFFD":t}return n}u(g,"normalizeText");function Re(e){return e===void 0?"TEXT":{javascript:"JS",json:"JSON",markdown:"MD",python:"PY",rust:"RS",typescript:"TS"}[e]??e.slice(0,4).toUpperCase()}u(Re,"languageLabel");function E(e,n){return e.length===0?[n.fg("dim","Empty content")]:[...e]}u(E,"nonEmptyRows");function xe(e,n){return R(e)<=n?e:n<=1?"\u2026":`\u2026${e.slice(-(n-1))}`}u(xe,"truncateFromStart");export{we as a,x as b,We as c,je as d};
6
+ `)}u(O,"textBlocks");function H(e){return e.lines}u(H,"readLines");function k(e){return typeof e=="object"&&e!==null?e:{}}u(k,"readDetails");function me(e){return e.content.some(n=>n.type==="text")}u(me,"hasTextContent");function q(e,n){let r=n?.map(w).find(i=>i!==void 0)?.source??e.source;return r===void 0?void 0:N(he(r))}u(q,"languageFor");function ge(e,n,t){return t==="source"&&q(e,n)==="markdown"}u(ge,"isMarkdownSource");function he(e){try{let n=new URL(e);return n.protocol==="file:"?n.pathname:`${n.pathname}${n.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}u(he,"normalizeSourcePath");function g(e){let n="";for(let t of e.replaceAll(" "," ".repeat(4))){let r=S(t.codePointAt(0));n+=r<32||r===127?"\uFFFD":t}return n}u(g,"normalizeText");function Re(e){return e===void 0?"TEXT":{javascript:"JS",json:"JSON",markdown:"MD",python:"PY",rust:"RS",typescript:"TS"}[e]??e.slice(0,4).toUpperCase()}u(Re,"languageLabel");function E(e,n){return e.length===0?[n.fg("dim","Empty content")]:[...e]}u(E,"nonEmptyRows");function xe(e,n){return R(e)<=n?e:n<=1?"\u2026":`\u2026${e.slice(-(n-1))}`}u(xe,"truncateFromStart");export{we as a,x as b,We as c,je as d};
@@ -0,0 +1,28 @@
1
+ import{a as Se,b as Te,c as be}from"./chunk-PBQDHYNX.js";import{a as we}from"./chunk-L2B4DTVS.js";import{a as he,b as ye,c as O}from"./chunk-WQIMM4SU.js";import"./chunk-4IWEKRSP.js";import{c as ge}from"./chunk-W7CASEO3.js";import{a as me}from"./chunk-FYOU4RBH.js";import{d as de}from"./chunk-7PVDTMEM.js";import{a as ce}from"./chunk-47SPPIXK.js";import{a as le,b as ue}from"./chunk-VAXLSPPU.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{d as fe}from"./chunk-TSQ6FBTB.js";import"./chunk-VDJSH3DQ.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import dt from"node:path";import{stripVTControlCharacters as ct}from"node:util";import{truncateLine as mt}from"@earendil-works/pi-coding-agent";import{Text as E}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as ve,DEFAULT_MAX_LINES as xe,formatSize as lt,truncateTail as ut}from"@earendil-works/pi-coding-agent";function $(t){return ut(t,{maxBytes:ve-4096,maxLines:xe-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(a=>a!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
+ `)}
3
+ output:${r.length===0?" (empty)":`
4
+ ${r}`}`;let i=e.truncatedBy==="lines"?`${xe} line output budget`:`${lt(ve)} output budget`,s=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
+ `)}
6
+ output:
7
+ ${s}${r.length===0?"":`
8
+ ${r}`}`}l(D,"formatAgentTerminalSnapshot");var pt=500;function Re(t,e,n,r,i){let s=e?"background":"wait",a=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${F(n)} \xB7 ${s}`)}`;return new E(`${a}
9
+ ${i.fg("accent",X(r.family))} ${t}`,0,0)}l(Re,"renderRunCall");function Pe(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
+ `),0,0)}l(Pe,"renderTerminalActionResult");function Ee(t,e,n,r,i){let s=[ht(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(a=>` ${i.fg("dim",a)}`)),new E(s.join(`
11
+ `),0,0)}l(Ee,"renderTerminalAction");function k(t,e,n,r){let i=Ce(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 Ae(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 a=N(t.output??"",C),o=[...a.omission===void 0?[]:[` ${n.fg("muted",a.omission)}`],...a.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(o.join(`
13
+ `),0,0)}if(e==="full"){let s=Ce(t,Number.POSITIVE_INFINITY,n).slice(2);return new E(s.join(`
14
+ `),0,0)}let r=N(t.output??"",C),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(s=>` ${n.fg("dim",s)}`)];return i.push(I(t,(s,a)=>n.fg(s,a))),new E(i.join(`
15
+ `),0,0)}l(Ae,"renderRunResult");function ke(t,e){let n=l((a,o)=>e?.fg(a,o)??o,"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)}`],s=ft(t.output,2);return s.length>0&&i.push(...s.map(a=>` ${n("dim",V(a,90))}`)),i.push(I(t,n)),i.join(`
16
+ `)}l(ke,"renderActiveTerminal");function Ce(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":F(t.cwd),a=t.shellFamily??"posix",o=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",X(a))} ${t.command??""}`],u=N(t.output??"",e);return u.omission!==void 0&&o.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&o.push(...u.lines.map(d=>` ${n.fg("dim",d)}`)),o.push(I(t,(d,c)=>n.fg(d,c))),o}l(Ce,"terminalCardLines");function ft(t,e){return N(t,e).lines}l(ft,"outputTail");function N(t,e){let n=$(ct(t).replaceAll("\r","")),r=n.content.split(`
17
+ `).map(u=>mt(u.trimEnd(),pt).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),a=Math.max(0,n.totalLines-n.outputLines),o=s+a;return{lines:r.slice(s),...n.truncated||o>0?{omission:o>0?`\u2026 ${o} earlier lines`:"\u2026 earlier output omitted"}:{}}}l(N,"outputWindow");function I(t,e){let n=t.status??"running",r=gt(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,yt(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}l(I,"statusLine");function gt(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}l(gt,"statusIcon");function X(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}l(X,"promptMarker");function ht(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":F(t.cwd),i=t.background===!0?"background":"wait",s=V(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}l(ht,"terminalIdentity");function F(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${dt.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 yt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(yt,"formatElapsed");function $e(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=>ke(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($e,"terminalProcessProvider");import{setTimeout as vt}from"node:timers/promises";var wt="#d8dee9",Y="#111418",St=["#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:s}=await import("@napi-rs/canvas"),a=Math.max(0,Math.min(i.rows-1,n?.start??0)),o=Math.max(1,Math.min(i.rows-a,n?.count??i.rows)),u=i.cols*9+24,d=o*18+24,c=s(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<o;g+=1){let S=p.getLine(h+a+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||Tt(m,x,y,g)}}return i.status==="running"&&p.cursorY>=a&&p.cursorY<a+o&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-a)*18+18-2,9,2)),c.toBuffer("image/png").toString("base64")}l(K,"renderTerminalScreen");function Tt(t,e,n,r){let i=Ie(e,"foreground"),s=Ie(e,"background");e.isInverse()&&([i,s]=[s,i]);let a=12+n*9,o=12+r*18;s!==Y&&(t.fillStyle=s,t.fillRect(a,o,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,a,o),e.isUnderline()&&t.fillRect(a,o+18-2,9*Math.max(1,e.getWidth()),1))}l(Tt,"drawCell");function Ie(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?wt:Y;let i=n?t.isFgRGB():t.isBgRGB(),s=n?t.getFgColor():t.getBgColor();return i?`#${s.toString(16).padStart(6,"0")}`:bt(s)}l(Ie,"cellColor");function bt(t){let e=St[t];if(e!==void 0)return e;if(t>=232){let o=8+(t-232)*10;return Le(o,o,o)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),s=n%6,a=l(o=>o===0?0:55+o*40,"channel");return Le(a(r),a(i),a(s))}l(bt,"ansiColor");function Le(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}l(Le,"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[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 s=i.get("duration")??2,a=i.get("interval")??.5,o=i.get("scale")??1;if(!(o>0&&o<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(s>0&&s<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(a>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(s/a)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:s,interval:a,scale:o}}l(xt,"parseTerminalVisualView");async function De(t,e){let n=new Map,r=new Map,i={protocol:te,apiVersion:ne,id:"terminal",setup(a){a.addResolver({resolver:Rt(e),preserveTruncatedOutput:!0,renderResult(o,u,d){let c=o.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")}}),a.addHandler({stage:"pre-read",async handler(o){let u=o.request.path;if(u===void 0||!v(u))return{kind:"continue",context:o};let d;try{d=xt(o.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:o};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){o.resolverContext.signal?.throwIfAborted(),h>0&&await vt(d.interval*1e3,void 0,{signal:o.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))}}}})}},s={protocol:ie,apiVersion:oe,id:"terminal",setup(a){a.addResolver({resolver:Pt(e)}),a.tool("write").addHandler({stage:"text-pre-edit",handler:l(async o=>(_e(o.input,e,n),await Me(o.input,e,r),Et(o,Z)),"handler")}),a.tool("insert").addHandler({stage:"text-pre-edit",handler:l(async o=>(await Me(o.input,e,r),_e(o.input,e,n),At(o)),"handler")});for(let o of["write","insert","delete"])a.addToolRenderer({tool:o,matches:l((u,d)=>It(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)),Ee(h.snapshot??{},o,Oe(o,m),[],d)},renderResult(u,d,c){let m=$t(u.details);return Pe(m.action,m.changedLines,c)}})}};await Promise.all([re(t,i),pe(t,s)]),t.on("tool_result",async(a,o)=>{if(!R(a.input))return;let u=a.input.path;if(a.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:a.details},_(a.toolName),{status:"error",errors:[q(w,"UNSUPPORTED_OPERATION",u)],data:{operation:"replace",effect:"not-applied",files:[{source:u,effect:"not-applied"}]}})}if(a.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:[]}},_(a.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}},_(a.toolName),{status:"error",errors:[q(T,"TERMINAL_DELETE_FAILED",u)],data:{operation:"delete",effect:"unknown",files:[{source:u,effect:"unknown"}]}}))}if(a.toolName!=="write"&&a.toolName!=="insert"||a.isError)return;let d=a.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=a.toolName,S=Oe(g,a.input),y=e.screenChangeRegion(c,m,6),x=[{type:"text",text:`Sent ${S} to ${c.source}.`}];return o.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:a.isError,...a.structuredContent===void 0?{}:{structuredContent:a.structuredContent}}})}l(De,"registerTerminalResources");function Rt(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:kt(r)}]}}}}}}l(Rt,"createReadResolver");function Pt(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=Ct(r),s=i.indexOf(Z),a=i.indexOf(J);if(s>=0){await t.write(n.source,i.slice(s+Z.length));return}if(a>=0){await t.sendKeys(n.source,i.slice(a+J.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}l(Pt,"createInputResolver");function Et(t,e){return!R(t.input)||!Ne(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}l(Et,"transformWriteInput");function At(t){if(!R(t.input)||!Ne(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(At,"transformInsertInput");function kt(t){return D(t)}l(kt,"formatSnapshot");function Ct(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}l(Ct,"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 Ne(t){return typeof t=="string"&&v(t)}l(Ne,"isShellSourceValue");function $t(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($t,"terminalActionDetails");async 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&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}l(Me,"rememberScreen");function _e(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(_e,"rememberOutputEnd");function Oe(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(Oe,"terminalInputLabel");function It(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(It,"isTerminalRenderValue");function R(t){return typeof t=="object"&&t!==null}l(R,"isRecord");async function Fe(t,e){await ce(t,{protocol:le,apiVersion:ue,id:"terminal",setup(r){r.addResolver({resolver:Lt(e),priority:100})}})}l(Fe,"registerTerminalSearch");function Lt(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=Mt(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
+ `)}
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,s=Q(i)?B(i.payload):B(void 0);return me(s.matches,!1,r,n.expanded===!0,void 0,[`Retained terminal output \xB7 ${s.snapshot.status} \xB7 read-only`])}}}l(Lt,"terminalSearchResolver");function Mt(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[s,a]of t.output.replaceAll("\r","").split(`
23
+ `).entries()){let o=e.caseSensitive===!0?a:a.toLocaleLowerCase(),u=0;for(;r.length<i;){let d=o.indexOf(n,u);if(d<0)break;let c=d+n.length;(e.wholeWord!==!0||_t(o,d,c))&&r.push({source:t.source,lineNumber:s+1,startColumn:d,endColumn:c,matchedText:a.slice(d,c),lineText:a}),u=Math.max(c,d+1)}if(r.length>=i)break}return r}l(Mt,"findTerminalMatches");function _t(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}l(_t,"isWordBoundary");function B(t){if(!Ot(t))throw new TypeError("Invalid terminal search result");return t}l(B,"parsePayload");function Ot(t){return Q(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&Q(t.snapshot)&&typeof t.snapshot.source=="string"}l(Ot,"isTerminalSearchPayload");function Q(t){return typeof t=="object"&&t!==null}l(Q,"isRecord");import{spawn as Nt}from"node:child_process";import{closeSync as Ft,mkdirSync as Bt,openSync as Wt,rmSync as jt,writeSync as Ut}from"node:fs";import Ht from"node:os";import Ue from"node:path";import{createRequire as Gt}from"node:module";import{randomUUID as qt}from"node:crypto";import{stripVTControlCharacters as Vt}from"node:util";import{StringDecoder as Xt}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 We(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=Be.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:l(a=>["/d","/s","/c",a],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:l(a=>["-NoLogo","-NoProfile","-Command",a],"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(We,"resolveShellProfile");function je(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(je,"shellSyntaxGuidance");var qe=Gt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),He=1e6,Yt=100,Kt=30,zt=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=en){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(tn(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:s}=n,a;try{let u=qe("node-pty"),d={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:rn(nn()),...globalThis.process.platform==="win32"?{useConptyDll:!0}:{}};a=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 o={...n,process:a};return this.#e.set(r,o),a.onData(u=>this.#c(o,u)),globalThis.process.platform==="win32"&&o.screen.onData(u=>{if(!P(o.status))try{a.write(u)}catch{}}),a.onExit(({exitCode:u,signal:d})=>{P(o.status)||(o.endedAt=Date.now(),o.exitCode=u,d!==0&&(o.signal=d),o.status=o.status==="stopping"?"stopped":u===0?"completed":"failed",(u===124||u===137)&&(o.completionReason="timeout"),this.#n(o.id),o.resolveCompletion(o),this.#t(o),this.#a(o))}),this.#t(o),o}#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=an(n);this.#o.set(n,Wt(r,"a",384));let i=e.cols??Yt,s=e.rows??Kt,a=Qt(i,s),o=l(d=>{},"resolveCompletion"),u=new Promise(d=>{o=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:s,fullOutputPath:r,screen:a,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:o,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 s=l(()=>i.abort(),"abortStartup");e.signal?.addEventListener("abort",s,{once:!0}),e.signal?.aborted&&s();try{let a=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",s)),o={...r,remote:{target:e.remote.location.target,process:a}};this.#e.set(o.id,o);let u=new Xt("utf8");a.stdout.on("data",c=>this.#c(o,u.write(c))),a.stderr.resume();let d=l(()=>{this.#c(o,u.end()),o.endedAt=Date.now(),this.#n(o.id),o.resolveCompletion(o),this.#t(o),this.#a(o)},"finish");return a.completion.then(({exitCode:c})=>{o.exitCode=c,c<0&&(o.signal=-c),o.status=o.status==="stopping"?"stopped":c===0?"completed":"failed",(c===124||c===137)&&(o.completionReason="timeout"),d()},c=>{o.status="lost",o.error=j(c),d()}),this.#t(o),o}catch(a){let o={...r,status:"failed",endedAt:Date.now(),error:j(a)};return this.#e.set(o.id,o),this.#n(o.id),o.resolveCompletion(o),queueMicrotask(()=>this.#a(o)),o}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,s)=>{let a=l(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",a,{once:!0}),r.completion.then(o=>{n?.removeEventListener("abort",a),i(o)},s)})}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(s=>{let a=!1,o,u=l(p=>{a||(p!==void 0&&P(r.status)&&(p=void 0),a=!0,clearTimeout(c),clearInterval(m),n.signal?.removeEventListener("abort",d),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#t(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),d=l(()=>u("aborted"),"onAbort"),c=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Jt(r)){o=void 0;return}o??=Date.now(),Date.now()-o>=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,s;for(;Date.now()<r;){let a=e.outputStart+e.output.length;if(a!==i)i=a,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=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),s=Math.max(1,Math.min(e.rows,r)),a=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),o=-1;for(let c=0;c<=e.rows-s;c+=1){let m=0;for(let p=c;p<c+s;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>o&&(o=m,a=c)}let u=e.screen.buffer.active;return{lines:i.slice(a,a+s).map((c,m)=>{if(a+m!==u.cursorY)return c;let h=c.padEnd(u.cursorX," ");return`${h.slice(0,u.cursorX)}\u258C${h.slice(u.cursorX)}`}),startRow:a}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),s=[];for(let a=0;a<e.rows;a+=1){let o=r.getLine(i+a)?.translateToString(!0).trimEnd();o!==void 0&&o.length>0&&s.push(o)}return s.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,on(n))}async stop(e,n="stopped"){let r=this.required(e);return P(r.status)||(r.status="stopping",this.#t(r),await Ge(r,!1),await Promise.race([r.completion.then(()=>!0),ee(zt).then(()=>!1)])||(await Ge(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),jt(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=[],s=Math.max(0,r.baseY);for(let a=s;a<s+n.rows;a+=1)i.push(r.getLine(a)?.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=Vt(n),i=this.#o.get(e.id);if(i!==void 0&&Ut(i,r),e.output+=r,e.output.length>He){let s=e.output.length-He;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#t(e)}#n(e){let n=this.#o.get(e);n!==void 0&&(Ft(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 Jt(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(Jt,"looksInteractive");function Qt(t,e){let{Terminal:n}=qe("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}l(Qt,"createScreen");function en(){return qt().replaceAll("-","").slice(0,12)}l(en,"defaultSessionId");function tn(t){return t.startsWith("shell:")?t.slice(6):t}l(tn,"normalizeSessionId");function P(t){return t!=="running"&&t!=="stopping"}l(P,"isTerminalStatus");function nn(){return process.env}l(nn,"processEnvironment");function rn(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(rn,"cleanEnvironment");function on(t){return t.split(/[\s,]+/u).filter(Boolean).map(sn).join("")}l(on,"encodeTerminalKeys");function sn(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"),s=r.has("alt")||r.has("meta"),a=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 s?`\x1B${m}`:m}let o={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!s&&!a&&o[n]!==void 0)return o[n];if(s&&!i&&!a&&o[n]!==void 0)return`\x1B${o[n]}`;let d={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(d!==void 0)return!i&&!s&&!a?`\x1B[${d}`:`\x1B[1;${1+(a?1:0)+(s?2:0)+(i?4:0)}${d}`;if(s&&!i&&n.length===1)return`\x1B${a?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}l(sn,"encodeTerminalKey");async function Ge(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=Nt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}l(Ge,"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 an(t){let e=Ue.join(Ht.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Bt(e,{recursive:!0,mode:448}),Ue.join(e,`${t}.log`)}l(an,"createOutputLog");import{AgentSession as ln}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function Ve(t){let e=ln.prototype,n=e[U]??un(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}l(Ve,"observeQueuedSteering");function un(t){let e=t.prompt,n=t.steer,r=new Set,i=l(u=>{for(let d of[...r])d(u)},"notify"),s=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"),a=l(async function(...u){let d=await n.apply(this,u);return d==="queued"&&i(this),d},"steer");t.prompt=s,t.steer=a;let o={listeners:r,restore:l(()=>{t[U]===o&&(t.prompt===s&&(t.prompt=e),t.steer===a&&(t.steer=n),delete t[U])},"restore")};return t[U]=o,o}l(un,"installObservers");import ze from"node:path";import{stripVTControlCharacters as cn}from"node:util";import{defineTool as mn}from"@earendil-works/pi-coding-agent";import{Type as b}from"typebox";import{Text as pn}from"@earendil-works/pi-tui";import{open as dn}from"node:fs/promises";import{Type as f}from"typebox";var Xe=1024*1024,Ye=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 Ke(t){let e=await dn(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=l(async(o,u)=>{let d=Buffer.alloc(u),c=0;for(;c<u;){let m=await e.read(d,c,u-c,o+c);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");c+=m.bytesRead}return d},"readRange"),i,s,a=n>Xe;if(!a)i=(await r(0,n)).toString("utf8"),s=[{start:0,end:n}];else{let o=Xe/2,u=await r(0,o),d=await r(n-o,o),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,s=[{start:0,end:Buffer.byteLength(c)},{start:n-o+m,end:n}]}return{output:i,truncated:a,full_output_path:t.fullOutputPath,output_ranges:s,...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(Ke,"structuredShellResult");var fn=l(t=>b.Object({command:b.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${je(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",s=new O([]),a){let o=new Set,u=process.platform==="win32"?"powershell":"bash",d=fn(n);return t.registerTool(mn({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:Ye,async execute(c,m,p,h,g){r.bind(g);let S=a?.(c,g),y=s.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:ze.resolve(g.cwd,m.cwd),shell:n});if(w.origin??=S,m.background===!0&&w.status!=="failed")return await gn(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;o.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{o.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 pn(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:ze.resolve(process.cwd(),c.cwd):process.cwd();return Re(g,c.background===!0,y,S?W:n,m)},renderResult(c,m,p){return Ae(c.details,m.expanded?"full":i,p)}})),()=>{for(let c of o)c.abort()}}l(Ze,"registerTerminalTools");function Je(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(Je,"terminalPreview");async function H(t){return{...Je(t),structuredContent:await Ke(t)}}l(H,"terminalResult");async function gn(t,e,n){await new Promise(r=>{let i=!1,s,a=l(()=>{},"unsubscribe"),o=l(()=>{i||(i=!0,clearTimeout(s),a(),r())},"finish"),u=l(()=>{let d=t.snapshot(e);n?.(Je(d)),(cn(d.output).replaceAll("\r","").split(`
24
+ `).filter(m=>m.length>0).length>=C||d.status!=="running")&&o()},"publish");a=t.onDidChange(d=>{d.id===e.id&&u()}),s=setTimeout(o,2e3),u()})}l(gn,"captureInitialBackgroundPreview");import{Box as tt,Container as nt}from"@earendil-works/pi-tui";var hn=120,yn=12e4,G=class{constructor(e,n,r=yn){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:s},a)=>Qe(i.details,s,a)),e.registerMessageRenderer("terminal-completion",(i,{expanded:s},a)=>et(i.details,s,a)),e.registerEntryRenderer("terminal-stale-display",(i,{expanded:s},a)=>Qe(i.data,s,a)),e.registerEntryRenderer("terminal-completion-display",(i,{expanded:s},a)=>et(i.data,s,a)),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:Tn(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(s=>!s.completionDelivered);if(this.#l.clear(),this.#s||n.length===0)return;for(let s of n)s.completionDelivered=!0;let r=n.map(s=>this.#n(s));this.pi.sendMessage({customType:"terminal-completion",display:!1,content:Sn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"});let i=new Map;for(let s of r){let a=this.#t(s).parentToolCallId,o=i.get(a)??[];o.push(s),i.set(a,o)}for(let[s,a]of i)this.pi.appendEntry("terminal-completion-display",{sessions:a,...s===void 0?{}:{parentToolCallId:s}})},hn)))}};function Qe(t,e,n){let r=new nt;rt(t)&&r.addChild(k(t,e,n,"stale \xB7 inspect session"));let i=new tt(1,1,s=>n.bg("toolPendingBg",s));return i.addChild(r),i}l(Qe,"renderStale");function et(t,e,n){let r=new nt;for(let s of wn(t))r.addChild(k(s,e,n));let i=new tt(1,1,s=>n.bg("toolSuccessBg",s));return i.addChild(r),i}l(et,"renderCompletion");function wn(t){return!ot(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(rt)}l(wn,"completionSnapshots");function rt(t){return ot(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(rt,"isTerminalSessionSnapshot");function Sn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
+ ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,s=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${it(n.elapsedMs)}
26
+ ${s||"(no output)"}`}).join(`
27
+ `)}`}l(Sn,"formatCompletionMessage");function Tn(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${it(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
+ ${e||"(no output)"}`}l(Tn,"formatStaleMessage");function it(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}l(it,"formatElapsed");function ot(t){return typeof t=="object"&&t!==null}l(ot,"isRecord");function st(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(st,"registerTerminalOrigins");function at(t){return t==="full"||t==="disabled"?t:"compact"}l(at,"toolPresentation");async function bn(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(c=>({tool:c,resourcePrefixes:["shell:"]}))]})]);let n=Te("terminal",L)??new L,r=We(),i=new O(await ye(he(ge()))),s=new G(t,n),a=we(t).add($e(n));await Promise.all([De(t,n),Fe(t,n)]);let o=Ze(t,n,r,s,at(e?.preferences["ui.terminal"]),i,st(t)),u="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.";fe(t,{version:1,id:"terminal",tools:["bash","powershell"],schemas:{read:{parameters:{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."}},search:{promptGuidelines:["path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."]},write:{parameters:{path:"shell:<session> types into that terminal.",content:"For shell:<session>, exact input; Enter is not added."},promptGuidelines:[u]},insert:{parameters:{path:"shell:<session> sends keys to that terminal.",anchor:"Omit for shell:<session>.",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."},promptGuidelines:[u]},delete:{parameters:{path:"shell:<session> ends that session."},promptGuidelines:[u]}}});let d=l(()=>{},"removeSteeringObserver");t.on("session_start",(c,m)=>{s.bind(m),d(),d=Ve(p=>{p.sessionManager===m.sessionManager&&o()})}),t.on("agent_settled",(c,m)=>s.onAgentSettled(m)),t.on("session_shutdown",async c=>{if(d(),s.dispose(),a(),c.reason!=="quit"){Se("terminal",n);return}be("terminal",n),await n.dispose()})}l(bn,"registerTerminal");export{bn as default};