pi-agent-ide 0.7.3 → 0.8.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 (734) hide show
  1. package/CHANGELOG.md +48 -35
  2. package/README.md +70 -19
  3. package/dist/chunk-246NTPOS.js +1 -0
  4. package/dist/chunk-2ITKAXHO.js +1 -0
  5. package/dist/chunk-3WO2NOEQ.js +1 -0
  6. package/dist/{chunk-ZTYWHL2F.js → chunk-47SPPIXK.js} +1 -1
  7. package/dist/chunk-4HWKBCBH.js +1 -0
  8. package/dist/chunk-4W7GH3T7.js +10 -0
  9. package/dist/{chunk-JMVDFOTQ.js → chunk-57F5GTHO.js} +1 -1
  10. package/dist/chunk-6EDOLYOV.js +1 -0
  11. package/dist/chunk-756K3LJY.js +1 -0
  12. package/dist/chunk-7LOVUWNI.js +1 -0
  13. package/dist/chunk-A64JRDZK.js +1 -0
  14. package/dist/chunk-AIT3YWR5.js +3 -0
  15. package/dist/chunk-AKNHSDGV.js +1 -0
  16. package/dist/chunk-AUL5FGGK.js +2 -0
  17. package/dist/chunk-BB4A5UI3.js +5 -0
  18. package/dist/chunk-BQAKA3FU.js +1 -0
  19. package/dist/chunk-BR7GRH4A.js +5 -0
  20. package/dist/chunk-BXGMMZT3.js +1 -0
  21. package/dist/{chunk-ZIWPKIBZ.js → chunk-D4IA2MTA.js} +1 -1
  22. package/dist/chunk-DUUOCBS3.js +3 -0
  23. package/dist/chunk-DXONCYWF.js +3 -0
  24. package/dist/chunk-E2PHA4SQ.js +1 -0
  25. package/dist/{chunk-H445SHSJ.js → chunk-EMRJP6EM.js} +1 -1
  26. package/dist/chunk-GEMDU6XW.js +1 -0
  27. package/dist/chunk-GNACBJM3.js +1 -0
  28. package/dist/chunk-HCK7OIQ3.js +1 -0
  29. package/dist/chunk-HFJGCYFO.js +11 -0
  30. package/dist/chunk-ID4RJIVZ.js +9 -0
  31. package/dist/chunk-IMGIDBCC.js +1 -0
  32. package/dist/chunk-JKMXND6V.js +1 -0
  33. package/dist/chunk-L2B4DTVS.js +1 -0
  34. package/dist/chunk-LAJQSHEI.js +4 -0
  35. package/dist/chunk-LEKC4GQK.js +5 -0
  36. package/dist/chunk-LLRUJD62.js +1 -0
  37. package/dist/{chunk-2ZMMRINH.js → chunk-M4TVRCMZ.js} +1 -1
  38. package/dist/chunk-MKEC3U2M.js +4 -0
  39. package/dist/chunk-N56WAVYA.js +1 -0
  40. package/dist/chunk-OFILFO6D.js +1 -0
  41. package/dist/chunk-OI3HBIPK.js +2 -0
  42. package/dist/{chunk-S6QRG3TQ.js → chunk-OM4LYD3S.js} +1 -1
  43. package/dist/{chunk-WLZIUMJL.js → chunk-PRLIHLCS.js} +1 -1
  44. package/dist/chunk-Q5X6OXNS.js +2 -0
  45. package/dist/chunk-R2U5WXYR.js +1 -0
  46. package/dist/chunk-S72FVLUX.js +1 -0
  47. package/dist/chunk-SWA5B5B2.js +9 -0
  48. package/dist/chunk-T4FTT3U4.js +1 -0
  49. package/dist/chunk-T7MWQQIF.js +3 -0
  50. package/dist/chunk-TGC2ZACO.js +1 -0
  51. package/dist/chunk-TOYN4W4F.js +1 -0
  52. package/dist/chunk-TXG2H7YQ.js +9 -0
  53. package/dist/{chunk-QFTBY67N.js → chunk-UEVGZUII.js} +3 -3
  54. package/dist/{chunk-7UGNGK7Y.js → chunk-VAXLSPPU.js} +1 -1
  55. package/dist/chunk-VDP5CQHM.js +3 -0
  56. package/dist/chunk-VMGZMXEM.js +10 -0
  57. package/dist/chunk-VNTY7BKC.js +1 -0
  58. package/dist/chunk-W3YFF6OO.js +1 -0
  59. package/dist/chunk-W7M3V7FR.js +28 -0
  60. package/dist/chunk-WMHSVEIT.js +29 -0
  61. package/dist/chunk-WPBQ45ZL.js +1 -0
  62. package/dist/chunk-WXGTU2M6.js +1 -0
  63. package/dist/chunk-XSIKDVAR.js +25 -0
  64. package/dist/chunk-YHREORHH.js +2 -0
  65. package/dist/chunk-YJ6T3PEP.js +1 -0
  66. package/dist/chunk-YTYLS2UM.js +1 -0
  67. package/dist/chunk-Z2QGNTGQ.js +1 -0
  68. package/dist/{chunk-QDLTO5PH.js → chunk-ZAWRSA7N.js} +1 -1
  69. package/dist/chunk-ZV5ETNLQ.js +1 -0
  70. package/dist/entry-0.js +1 -1
  71. package/dist/entry-1.js +1 -1
  72. package/dist/entry-10.js +1 -1
  73. package/dist/entry-11.js +1 -1
  74. package/dist/entry-13.js +1 -1
  75. package/dist/entry-14.js +1 -1
  76. package/dist/entry-15.js +1 -1
  77. package/dist/entry-16.js +1 -1
  78. package/dist/entry-17.js +1 -1
  79. package/dist/entry-18.js +1 -0
  80. package/dist/entry-2.js +1 -1
  81. package/dist/entry-20.js +1 -1
  82. package/dist/entry-21.js +1 -1
  83. package/dist/entry-22.js +1 -1
  84. package/dist/entry-23.js +1 -1
  85. package/dist/entry-24.js +1 -1
  86. package/dist/entry-25.js +1 -2
  87. package/dist/entry-26.js +1 -1
  88. package/dist/entry-27.js +2 -2
  89. package/dist/entry-28.js +1 -1
  90. package/dist/entry-29.js +4 -1
  91. package/dist/entry-30.js +1 -1
  92. package/dist/entry-31.js +1 -17
  93. package/dist/entry-32.js +1 -1
  94. package/dist/entry-33.js +18 -3
  95. package/dist/entry-34.js +1 -1
  96. package/dist/entry-35.js +1 -1
  97. package/dist/entry-36.js +1 -4
  98. package/dist/entry-37.js +1 -9
  99. package/dist/entry-38.js +1 -1
  100. package/dist/entry-39.js +1 -1
  101. package/dist/entry-4.js +1 -1
  102. package/dist/entry-40.js +1 -1
  103. package/dist/entry-41.js +1 -1
  104. package/dist/entry-42.js +1 -1
  105. package/dist/entry-43.js +1 -1
  106. package/dist/entry-44.js +1 -1
  107. package/dist/entry-45.js +1 -25
  108. package/dist/entry-46.js +1 -1
  109. package/dist/entry-47.js +25 -1
  110. package/dist/entry-48.js +1 -1
  111. package/dist/entry-49.js +1 -1
  112. package/dist/entry-50.js +1 -3
  113. package/dist/entry-51.js +1 -13
  114. package/dist/entry-52.js +3 -1
  115. package/dist/entry-53.js +13 -1
  116. package/dist/entry-54.js +1 -1
  117. package/dist/entry-55.js +1 -1
  118. package/dist/entry-56.js +1 -1
  119. package/dist/entry-57.js +1 -1
  120. package/dist/entry-58.js +1 -1
  121. package/dist/entry-59.js +1 -1
  122. package/dist/entry-6.js +1 -1
  123. package/dist/entry-60.js +1 -1
  124. package/dist/entry-61.js +1 -0
  125. package/dist/entry-62.js +1 -1
  126. package/dist/entry-64.js +1 -1
  127. package/dist/entry-65.js +0 -1
  128. package/dist/entry-66.js +1 -1
  129. package/dist/entry-67.js +1 -1
  130. package/dist/entry-68.js +1 -1
  131. package/dist/entry-69.js +1 -1
  132. package/dist/entry-7.js +1 -1
  133. package/dist/entry-70.js +1 -1
  134. package/dist/entry-71.js +1 -0
  135. package/dist/entry-72.js +1 -1
  136. package/dist/entry-74.js +1 -1
  137. package/dist/entry-75.js +0 -1
  138. package/dist/entry-76.js +1 -1
  139. package/dist/entry-77.js +1 -80
  140. package/dist/entry-78.js +1 -19
  141. package/dist/entry-79.js +80 -2
  142. package/dist/entry-8.js +1 -1
  143. package/dist/entry-80.js +22 -1
  144. package/dist/entry-81.js +2 -1
  145. package/dist/entry-82.js +1 -5
  146. package/dist/entry-83.js +1 -3
  147. package/dist/entry-84.js +1 -1
  148. package/dist/entry-85.js +3 -1
  149. package/dist/entry-86.js +1 -1
  150. package/dist/entry-87.js +1 -0
  151. package/dist/entry-88.js +1 -0
  152. package/dist/pi-agent-ide.js +53 -24
  153. package/docs/agent-guides/debugger.md +2 -0
  154. package/docs/agent-guides/editing.md +1 -1
  155. package/docs/agent-guides/search-code.md +7 -2
  156. package/docs/agent-guides/ssh.md +58 -0
  157. package/docs/agent-guides/vision.md +6 -0
  158. package/docs/configuration.md +51 -5
  159. package/docs/development.md +1 -13
  160. package/docs/extensions.md +1 -1
  161. package/docs/releases.md +1 -1
  162. package/docs/settings-help.md +39 -0
  163. package/docs/tools.md +22 -14
  164. package/docs/user-hooks.md +7 -3
  165. package/node_modules/pi-agent-doctor/package.json +10 -9
  166. package/node_modules/pi-agent-doctor/runtime/entry-25.js +1 -0
  167. package/node_modules/pi-agent-doctor/src/evidence.ts +49 -4
  168. package/node_modules/pi-agent-doctor/src/executable.ts +46 -16
  169. package/node_modules/pi-agent-doctor/src/fixtures/executable-probe.ts +78 -0
  170. package/node_modules/pi-agent-doctor/src/fixtures/probe-executable-wait.mjs +10 -0
  171. package/node_modules/pi-agent-doctor/src/plugin-protocol.ts +6 -0
  172. package/node_modules/pi-agent-doctor/src/project-probes.ts +73 -0
  173. package/node_modules/pi-agent-doctor/src/workspace.ts +106 -0
  174. package/node_modules/pi-agent-documentation/package.json +2 -2
  175. package/node_modules/pi-agent-documentation/runtime/entry-26.js +1 -0
  176. package/node_modules/pi-agent-filesystem/package.json +8 -8
  177. package/node_modules/pi-agent-filesystem/src/resolver.ts +23 -7
  178. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  179. package/node_modules/pi-agent-filesystem-jq/index.ts +33 -6
  180. package/node_modules/pi-agent-filesystem-jq/package.json +6 -7
  181. package/node_modules/pi-agent-filesystem-jq/src/jq.ts +67 -0
  182. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  183. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-30.js +2 -0
  184. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  185. package/node_modules/pi-agent-ide-ast/package.json +15 -41
  186. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +2 -1
  187. package/node_modules/pi-agent-ide-ast/src/ast/outline.ts +10 -3
  188. package/node_modules/pi-agent-ide-ast/src/ast/read-text.ts +4 -1
  189. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +3 -3
  190. package/node_modules/pi-agent-ide-ast/src/doctor-plugin.ts +13 -10
  191. package/node_modules/pi-agent-ide-ast/src/extension.ts +17 -1
  192. package/node_modules/pi-agent-ide-ast/src/outline-resolver.ts +32 -4
  193. package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  194. package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +1 -1
  195. package/node_modules/pi-agent-ide-ast/src/search-presentation.ts +4 -3
  196. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +100 -42
  197. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +3 -2
  198. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +2 -1
  199. package/node_modules/pi-agent-ide-changes/index.ts +10 -2
  200. package/node_modules/pi-agent-ide-changes/package.json +10 -11
  201. package/node_modules/pi-agent-ide-changes/runtime/entry-34.js +1 -0
  202. package/node_modules/pi-agent-ide-changes/src/change-anchor.ts +7 -2
  203. package/node_modules/pi-agent-ide-changes/src/changes/change-service.ts +18 -1
  204. package/node_modules/pi-agent-ide-changes/src/changes/change-types.ts +3 -0
  205. package/node_modules/pi-agent-ide-changes/src/changes/git-changes-backend.ts +59 -7
  206. package/node_modules/pi-agent-ide-changes/src/changes/git-paths.ts +49 -0
  207. package/node_modules/pi-agent-ide-changes/src/current-change-presenter.ts +10 -2
  208. package/node_modules/pi-agent-ide-changes/src/doctor-plugin.ts +13 -14
  209. package/node_modules/pi-agent-ide-changes/src/last-text-transaction-store.ts +2 -1
  210. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +47 -11
  211. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +6 -1
  212. package/node_modules/pi-agent-ide-formatter/index.ts +14 -2
  213. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  214. package/node_modules/pi-agent-ide-formatter/src/doctor-plugin.ts +47 -35
  215. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +41 -11
  216. package/node_modules/pi-agent-ide-formatter/src/registry.ts +9 -28
  217. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  218. package/node_modules/pi-agent-ide-lint/index.ts +35 -4
  219. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  220. package/node_modules/pi-agent-ide-lint/runtime/entry-38.js +2 -0
  221. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +14 -10
  222. package/node_modules/pi-agent-ide-lint/src/doctor-plugin.ts +47 -39
  223. package/node_modules/pi-agent-ide-lint/src/registry.ts +9 -25
  224. package/node_modules/pi-agent-ide-lsp/index.ts +107 -25
  225. package/node_modules/pi-agent-ide-lsp/package.json +10 -13
  226. package/node_modules/pi-agent-ide-lsp/runtime/entry-39.js +2 -0
  227. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +6 -2
  228. package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +5 -1
  229. package/node_modules/pi-agent-ide-lsp/src/diagnostic-source.ts +5 -3
  230. package/node_modules/pi-agent-ide-lsp/src/doctor-plugin.ts +27 -11
  231. package/node_modules/pi-agent-ide-lsp/src/lsp/abort.ts +62 -0
  232. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +245 -103
  233. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +26 -45
  234. package/node_modules/pi-agent-ide-lsp/src/lsp/diagnostic-adapters.ts +1 -1
  235. package/node_modules/pi-agent-ide-lsp/src/lsp/document-uri.ts +40 -0
  236. package/node_modules/pi-agent-ide-lsp/src/lsp/file-watchers.ts +8 -1
  237. package/node_modules/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +24 -17
  238. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +255 -56
  239. package/node_modules/pi-agent-ide-lsp/src/lsp/navigation.ts +51 -11
  240. package/node_modules/pi-agent-ide-lsp/src/lsp/owner-transport.ts +67 -0
  241. package/node_modules/pi-agent-ide-lsp/src/lsp/registry.ts +149 -18
  242. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +79 -31
  243. package/node_modules/pi-agent-ide-lsp/src/lsp/symbols.ts +15 -12
  244. package/node_modules/pi-agent-ide-lsp/src/lsp/workspace-owner.ts +16 -0
  245. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +67 -46
  246. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +50 -19
  247. package/node_modules/pi-agent-image/package.json +3 -3
  248. package/node_modules/pi-agent-invariant/package.json +2 -2
  249. package/node_modules/pi-agent-pdf/package.json +3 -4
  250. package/node_modules/pi-agent-read/package.json +12 -12
  251. package/node_modules/pi-agent-read/runtime/entry-45.js +0 -1
  252. package/node_modules/pi-agent-read/runtime/entry-47.js +2 -0
  253. package/node_modules/pi-agent-read/src/api/tools/read.ts +4 -2
  254. package/node_modules/pi-agent-read/src/core/extension.ts +4 -1
  255. package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +143 -69
  256. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +25 -1
  257. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +67 -44
  258. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +8 -3
  259. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +20 -5
  260. package/node_modules/pi-agent-resource/package.json +2 -2
  261. package/node_modules/pi-agent-resource/src/content-conversion/content-host.ts +75 -16
  262. package/node_modules/pi-agent-resource/src/index.ts +3 -0
  263. package/node_modules/pi-agent-resource/src/resource-error.ts +17 -0
  264. package/node_modules/pi-agent-resource/src/resource.ts +23 -0
  265. package/node_modules/pi-agent-resource/src/result-targets.ts +25 -2
  266. package/node_modules/pi-agent-resource/src/validation.ts +2 -1
  267. package/node_modules/pi-agent-search/package.json +9 -9
  268. package/node_modules/pi-agent-search/runtime/entry-50.js +0 -1
  269. package/node_modules/pi-agent-search/runtime/entry-51.js +1 -0
  270. package/node_modules/pi-agent-search/runtime/entry-52.js +2 -0
  271. package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  272. package/node_modules/pi-agent-search/src/api/presentation.ts +10 -2
  273. package/node_modules/pi-agent-search/src/api/search-parameters.ts +7 -3
  274. package/node_modules/pi-agent-search/src/api/search.ts +51 -2
  275. package/node_modules/pi-agent-search/src/core/extension.ts +2 -3
  276. package/node_modules/pi-agent-search/src/core/search-core.ts +98 -8
  277. package/node_modules/pi-agent-search-text/index.ts +37 -1
  278. package/node_modules/pi-agent-search-text/package.json +14 -12
  279. package/node_modules/pi-agent-search-text/runtime/entry-53.js +1 -0
  280. package/node_modules/pi-agent-search-text/runtime/entry-56.js +1 -0
  281. package/node_modules/pi-agent-search-text/src/doctor-plugin.ts +10 -5
  282. package/node_modules/pi-agent-search-text/src/file-search.ts +26 -3
  283. package/node_modules/pi-agent-search-text/src/fuzzy-search.ts +54 -3
  284. package/node_modules/pi-agent-search-text/src/resolvers.ts +22 -5
  285. package/node_modules/pi-agent-search-text/src/scoped-search.ts +4 -5
  286. package/node_modules/pi-agent-search-text/src/search-backend.ts +123 -17
  287. package/node_modules/pi-agent-search-text/src/search-recipe.ts +5 -1
  288. package/node_modules/pi-agent-search-text/src/search-result.ts +1 -0
  289. package/node_modules/pi-agent-search-text/src/search-session.ts +166 -31
  290. package/node_modules/pi-agent-text/package.json +3 -3
  291. package/node_modules/pi-agent-text/src/text-document.ts +2 -0
  292. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  293. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -6
  294. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  295. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-62.js +2 -0
  296. package/node_modules/pi-agent-text-anchor-line-hash/src/read-handler.ts +3 -1
  297. package/node_modules/pi-agent-text-editor/package.json +26 -34
  298. package/node_modules/pi-agent-text-editor/runtime/entry-77.js +0 -1
  299. package/node_modules/pi-agent-text-editor/runtime/entry-78.js +1 -0
  300. package/node_modules/pi-agent-text-editor/src/api/delete-guard.ts +29 -2
  301. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +3 -0
  302. package/node_modules/pi-agent-text-editor/src/api/file-operations.ts +55 -0
  303. package/node_modules/pi-agent-text-editor/src/api/file-transfers.ts +41 -0
  304. package/node_modules/pi-agent-text-editor/src/api/mutation-guard.ts +2 -0
  305. package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  306. package/node_modules/pi-agent-text-editor/src/api/native-files.ts +127 -0
  307. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +20 -1
  308. package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +1 -0
  309. package/node_modules/pi-agent-text-editor/src/core/delete-policy.ts +93 -85
  310. package/node_modules/pi-agent-text-editor/src/core/extension.ts +15 -2
  311. package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +81 -0
  312. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +70 -25
  313. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +123 -27
  314. package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +30 -1
  315. package/node_modules/pi-agent-text-editor/src/core/file-transfers.ts +147 -105
  316. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  317. package/node_modules/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  318. package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +91 -14
  319. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +74 -9
  320. package/node_modules/pi-agent-text-editor/src/core/temporary-directories.ts +49 -25
  321. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  322. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +122 -39
  323. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  324. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +307 -32
  325. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +85 -31
  326. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  327. package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +4 -1
  328. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -8
  329. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-80.js +2 -0
  330. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +139 -27
  331. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  332. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +2 -0
  333. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  334. package/node_modules/pi-agent-tool-call-interception/runtime/entry-82.js +1 -0
  335. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  336. package/node_modules/pi-agent-tool-ui/runtime/entry-83.js +1 -0
  337. package/node_modules/pi-agent-web/index.ts +28 -4
  338. package/node_modules/pi-agent-web/package.json +8 -11
  339. package/node_modules/pi-agent-web/src/doctor-plugin.ts +21 -6
  340. package/node_modules/pi-agent-web/src/resolver.ts +12 -2
  341. package/node_modules/pi-agent-web/src/search.ts +2 -1
  342. package/node_modules/pi-agent-web-html/package.json +3 -5
  343. package/node_modules/pi-agent-web-image/package.json +4 -4
  344. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  345. package/node_modules/pi-agent-web-pdf/runtime/entry-87.js +2 -0
  346. package/node_modules/pi-agent-web-text/package.json +4 -4
  347. package/node_modules/pi-agent-web-text/runtime/entry-88.js +2 -0
  348. package/package.json +43 -39
  349. package/skills/configure-agent-ide/SKILL.md +38 -0
  350. package/src/api/content.ts +6 -0
  351. package/src/api/doctor-runtime.ts +80 -0
  352. package/src/api/doctor.ts +6 -0
  353. package/src/api/hooks.ts +3 -0
  354. package/src/api/plugin-protocol.ts +11 -1
  355. package/src/api/tips.ts +3 -0
  356. package/src/api/tool-config.ts +143 -24
  357. package/src/backend/config.ts +85 -0
  358. package/src/backend/configured-process.ts +59 -0
  359. package/src/backend/dap-java-transport.ts +112 -0
  360. package/src/backend/dap-java-worker.py +218 -0
  361. package/src/backend/dap-node-transport.ts +112 -0
  362. package/src/backend/dap-powershell-worker.py +44 -0
  363. package/src/backend/dap-r-worker.py +210 -0
  364. package/src/backend/dap-tcp-transport.ts +42 -0
  365. package/src/backend/dap-tcp-worker.py +125 -0
  366. package/src/backend/dap-transport.ts +69 -0
  367. package/src/backend/dap-unix-worker.py +63 -0
  368. package/src/backend/debugger-registration.ts +62 -0
  369. package/src/backend/debugger-workspace-owner.ts +413 -0
  370. package/src/backend/doctor-inventory-worker.py +54 -0
  371. package/src/backend/doctor-probe-worker.py +140 -0
  372. package/src/backend/doctor-registration.ts +18 -0
  373. package/src/backend/doctor-workspace.ts +381 -0
  374. package/src/backend/file-operation-resolver.ts +58 -0
  375. package/src/backend/file-revision.ts +13 -0
  376. package/src/backend/file-transfer.ts +302 -0
  377. package/src/backend/file-watch-worker.py +119 -0
  378. package/src/backend/formatter-registration.ts +114 -0
  379. package/src/backend/git-registration.ts +60 -0
  380. package/src/backend/identity.ts +47 -0
  381. package/src/backend/index.ts +12 -0
  382. package/src/backend/lint-registration.ts +102 -0
  383. package/src/backend/lsp-file-watchers.ts +220 -0
  384. package/src/backend/lsp-registration.ts +83 -0
  385. package/src/backend/lsp-transport.ts +87 -0
  386. package/src/backend/lsp-workspace-owner.ts +50 -0
  387. package/src/backend/object-transfer.ts +299 -0
  388. package/src/backend/owned-command.ts +105 -0
  389. package/src/backend/owned-process-stop.ts +36 -0
  390. package/src/backend/owned-read-command.ts +20 -0
  391. package/src/backend/process-environment.ts +77 -0
  392. package/src/backend/process-metadata-worker.py +98 -0
  393. package/src/backend/process-metadata.ts +99 -0
  394. package/src/backend/recipe-evidence-worker.py +26 -0
  395. package/src/backend/recipe-evidence.ts +77 -0
  396. package/src/backend/registration.ts +124 -0
  397. package/src/backend/registry.ts +29 -0
  398. package/src/backend/resource-resolver.ts +147 -0
  399. package/src/backend/search-environment.ts +100 -0
  400. package/src/backend/ssh-channel-worker.py +306 -0
  401. package/src/backend/ssh-channel.ts +376 -0
  402. package/src/backend/ssh-transfer-worker.py +99 -0
  403. package/src/backend/ssh-transport.ts +54 -0
  404. package/src/backend/ssh-worker.py +730 -0
  405. package/src/backend/ssh.ts +610 -0
  406. package/src/backend/tool-config-access.ts +63 -0
  407. package/src/backend/tool-project.ts +71 -0
  408. package/src/backend/vision-capture-worker.py +319 -0
  409. package/src/backend/vision-capture.ts +165 -0
  410. package/src/backend/vision-registration.ts +104 -0
  411. package/src/backend/web-browser-worker.mjs +182 -0
  412. package/src/backend/web-browser.ts +128 -0
  413. package/src/backend/web-http-worker.py +62 -0
  414. package/src/backend/web-http.ts +79 -0
  415. package/src/backend/web-owner.ts +68 -0
  416. package/src/backend/web-registration.ts +14 -0
  417. package/src/code-view/diagnostic-view.ts +2 -2
  418. package/src/code-view/reference.ts +9 -0
  419. package/src/composite/builtin-extensions.ts +9 -14
  420. package/src/composite/module-labels.ts +1 -0
  421. package/src/composite/nested-tool-rendering.ts +26 -6
  422. package/src/composite/preferences.ts +13 -0
  423. package/src/composite/settings-documentation.ts +59 -0
  424. package/src/composite/settings-help.ts +106 -0
  425. package/src/composite/text-results.ts +50 -22
  426. package/src/core/diagnostic-store.ts +32 -10
  427. package/src/core/ide-core.ts +22 -2
  428. package/src/doctor/arguments.ts +19 -0
  429. package/src/doctor/config-writer.ts +72 -29
  430. package/src/doctor/discovery.ts +53 -15
  431. package/src/doctor/extension.ts +27 -10
  432. package/src/doctor/run.ts +42 -7
  433. package/src/documentation/extension.ts +12 -0
  434. package/src/documentation/search.ts +166 -0
  435. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
  436. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  437. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +33 -6
  438. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -7
  439. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts +67 -0
  440. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  441. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-30.js +2 -0
  442. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  443. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-31.js +2 -0
  444. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-27.js +2 -0
  445. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/src/resolver.ts +23 -7
  446. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -4
  447. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -11
  448. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -5
  449. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  450. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  451. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-87.js +2 -0
  452. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  453. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-88.js +2 -0
  454. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-84.js +2 -0
  455. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/doctor-plugin.ts +21 -6
  456. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +12 -2
  457. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +2 -1
  458. package/src/extensions/pi-agent-read/package.json +12 -12
  459. package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
  460. package/src/extensions/pi-agent-read/runtime/entry-46.js +1 -0
  461. package/src/extensions/pi-agent-read/runtime/entry-47.js +2 -0
  462. package/src/extensions/pi-agent-read/src/api/tools/read.ts +4 -2
  463. package/src/extensions/pi-agent-read/src/core/extension.ts +4 -1
  464. package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +143 -69
  465. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +25 -1
  466. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +67 -44
  467. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +8 -3
  468. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +20 -5
  469. package/src/extensions/pi-agent-search/package.json +9 -9
  470. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +37 -1
  471. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -12
  472. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-53.js +1 -0
  473. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +1 -0
  474. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-56.js +1 -0
  475. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/doctor-plugin.ts +10 -5
  476. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +26 -3
  477. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/fuzzy-search.ts +54 -3
  478. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +22 -5
  479. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +4 -5
  480. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +123 -17
  481. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +5 -1
  482. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +1 -0
  483. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +166 -31
  484. package/src/extensions/pi-agent-search/runtime/entry-50.js +0 -1
  485. package/src/extensions/pi-agent-search/runtime/entry-51.js +1 -0
  486. package/src/extensions/pi-agent-search/runtime/entry-52.js +2 -0
  487. package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +1 -1
  488. package/src/extensions/pi-agent-search/src/api/presentation.ts +10 -2
  489. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +7 -3
  490. package/src/extensions/pi-agent-search/src/api/search.ts +51 -2
  491. package/src/extensions/pi-agent-search/src/core/extension.ts +2 -3
  492. package/src/extensions/pi-agent-search/src/core/search-core.ts +98 -8
  493. package/src/extensions/pi-agent-text-editor/package.json +26 -34
  494. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  495. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -6
  496. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  497. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-61.js +1 -0
  498. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-62.js +2 -0
  499. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/src/read-handler.ts +3 -1
  500. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -8
  501. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-80.js +2 -0
  502. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +139 -27
  503. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  504. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-81.js +2 -0
  505. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +0 -1
  506. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +1 -0
  507. package/src/extensions/pi-agent-text-editor/runtime/entry-79.js +2 -0
  508. package/src/extensions/pi-agent-text-editor/src/api/delete-guard.ts +29 -2
  509. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +3 -0
  510. package/src/extensions/pi-agent-text-editor/src/api/file-operations.ts +55 -0
  511. package/src/extensions/pi-agent-text-editor/src/api/file-transfers.ts +41 -0
  512. package/src/extensions/pi-agent-text-editor/src/api/mutation-guard.ts +2 -0
  513. package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +2 -2
  514. package/src/extensions/pi-agent-text-editor/src/api/native-files.ts +127 -0
  515. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +20 -1
  516. package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +1 -0
  517. package/src/extensions/pi-agent-text-editor/src/core/delete-policy.ts +93 -85
  518. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +15 -2
  519. package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +81 -0
  520. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +70 -25
  521. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +123 -27
  522. package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +30 -1
  523. package/src/extensions/pi-agent-text-editor/src/core/file-transfers.ts +147 -105
  524. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
  525. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/grouped-replacements.ts +18 -9
  526. package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +91 -14
  527. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +74 -9
  528. package/src/extensions/pi-agent-text-editor/src/core/temporary-directories.ts +49 -25
  529. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +16 -8
  530. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +122 -39
  531. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +7 -4
  532. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +307 -32
  533. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +85 -31
  534. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +22 -1
  535. package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +4 -1
  536. package/src/pi-agent-ide.ts +14 -2
  537. package/src/plugins/pi-agent-ide-ast/package.json +15 -41
  538. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +2 -1
  539. package/src/plugins/pi-agent-ide-ast/src/ast/outline.ts +10 -3
  540. package/src/plugins/pi-agent-ide-ast/src/ast/read-text.ts +4 -1
  541. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +3 -3
  542. package/src/plugins/pi-agent-ide-ast/src/doctor-plugin.ts +13 -10
  543. package/src/plugins/pi-agent-ide-ast/src/extension.ts +17 -1
  544. package/src/plugins/pi-agent-ide-ast/src/outline-resolver.ts +32 -4
  545. package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +2 -2
  546. package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +1 -1
  547. package/src/plugins/pi-agent-ide-ast/src/search-presentation.ts +4 -3
  548. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +100 -42
  549. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +3 -2
  550. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +2 -1
  551. package/src/plugins/pi-agent-ide-changes/index.ts +10 -2
  552. package/src/plugins/pi-agent-ide-changes/package.json +10 -11
  553. package/src/plugins/pi-agent-ide-changes/runtime/entry-34.js +1 -0
  554. package/src/plugins/pi-agent-ide-changes/src/change-anchor.ts +7 -2
  555. package/src/plugins/pi-agent-ide-changes/src/changes/change-service.ts +18 -1
  556. package/src/plugins/pi-agent-ide-changes/src/changes/change-types.ts +3 -0
  557. package/src/plugins/pi-agent-ide-changes/src/changes/git-changes-backend.ts +59 -7
  558. package/src/plugins/pi-agent-ide-changes/src/changes/git-paths.ts +49 -0
  559. package/src/plugins/pi-agent-ide-changes/src/current-change-presenter.ts +10 -2
  560. package/src/plugins/pi-agent-ide-changes/src/doctor-plugin.ts +13 -14
  561. package/src/plugins/pi-agent-ide-changes/src/last-text-transaction-store.ts +2 -1
  562. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +47 -11
  563. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +6 -1
  564. package/src/plugins/pi-agent-ide-debugger/index.ts +62 -25
  565. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +3 -1
  566. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +33 -0
  567. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +150 -171
  568. package/src/plugins/pi-agent-ide-debugger/src/process-provider.ts +2 -0
  569. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +152 -58
  570. package/src/plugins/pi-agent-ide-debugger/src/workspace-owner.ts +28 -0
  571. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +4 -1
  572. package/src/plugins/pi-agent-ide-formatter/index.ts +14 -2
  573. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  574. package/src/plugins/pi-agent-ide-formatter/src/doctor-plugin.ts +47 -35
  575. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +41 -11
  576. package/src/plugins/pi-agent-ide-formatter/src/registry.ts +9 -28
  577. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  578. package/src/plugins/pi-agent-ide-lint/index.ts +35 -4
  579. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  580. package/src/plugins/pi-agent-ide-lint/runtime/entry-38.js +2 -0
  581. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +14 -10
  582. package/src/plugins/pi-agent-ide-lint/src/doctor-plugin.ts +47 -39
  583. package/src/plugins/pi-agent-ide-lint/src/registry.ts +9 -25
  584. package/src/plugins/pi-agent-ide-lsp/index.ts +107 -25
  585. package/src/plugins/pi-agent-ide-lsp/package.json +10 -13
  586. package/src/plugins/pi-agent-ide-lsp/runtime/entry-39.js +2 -0
  587. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +6 -2
  588. package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +5 -1
  589. package/src/plugins/pi-agent-ide-lsp/src/diagnostic-source.ts +5 -3
  590. package/src/plugins/pi-agent-ide-lsp/src/doctor-plugin.ts +27 -11
  591. package/src/plugins/pi-agent-ide-lsp/src/lsp/abort.ts +62 -0
  592. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +245 -103
  593. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +26 -45
  594. package/src/plugins/pi-agent-ide-lsp/src/lsp/diagnostic-adapters.ts +1 -1
  595. package/src/plugins/pi-agent-ide-lsp/src/lsp/document-uri.ts +40 -0
  596. package/src/plugins/pi-agent-ide-lsp/src/lsp/file-watchers.ts +8 -1
  597. package/src/plugins/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +24 -17
  598. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +255 -56
  599. package/src/plugins/pi-agent-ide-lsp/src/lsp/navigation.ts +51 -11
  600. package/src/plugins/pi-agent-ide-lsp/src/lsp/owner-transport.ts +67 -0
  601. package/src/plugins/pi-agent-ide-lsp/src/lsp/registry.ts +149 -18
  602. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +79 -31
  603. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbols.ts +15 -12
  604. package/src/plugins/pi-agent-ide-lsp/src/lsp/workspace-owner.ts +16 -0
  605. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +67 -46
  606. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +50 -19
  607. package/src/plugins/pi-agent-ide-processes/src/registry.ts +8 -1
  608. package/src/plugins/pi-agent-ide-terminal/index.ts +7 -0
  609. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +5 -1
  610. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +5 -2
  611. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +161 -42
  612. package/src/plugins/pi-agent-ide-terminal/src/shell-profile.ts +7 -0
  613. package/src/plugins/pi-agent-ide-terminal/src/shell-result.ts +11 -0
  614. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +33 -8
  615. package/src/plugins/pi-agent-ide-terminal/src/types.ts +5 -0
  616. package/src/plugins/pi-agent-ide-vision/index.ts +170 -9
  617. package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +47 -0
  618. package/src/plugins/pi-agent-ide-vision/src/vision.ts +42 -1
  619. package/src/post-edit/gate.ts +4 -1
  620. package/src/tips/core.ts +5 -2
  621. package/src/tips/extension.ts +30 -2
  622. package/src/tips/persistence.ts +29 -27
  623. package/src/tips/setup-hint.ts +19 -0
  624. package/src/toolchain/types.ts +2 -0
  625. package/dist/chunk-3YK4XMWB.js +0 -0
  626. package/dist/chunk-5JELU6RV.js +0 -7
  627. package/dist/chunk-6U5OU77O.js +0 -3
  628. package/dist/chunk-7LD2OQH3.js +0 -14
  629. package/dist/chunk-BMOJTJJJ.js +0 -3
  630. package/dist/chunk-BYZSBXUK.js +0 -2
  631. package/dist/chunk-CEX73RI5.js +0 -28
  632. package/dist/chunk-DZWTKF2K.js +0 -1
  633. package/dist/chunk-EOKEQ3YH.js +0 -25
  634. package/dist/chunk-HZ5BNF3A.js +0 -1
  635. package/dist/chunk-IG56UGSO.js +0 -2
  636. package/dist/chunk-KVHDMIZS.js +0 -3
  637. package/dist/chunk-M5IVSCR2.js +0 -1
  638. package/dist/chunk-M5MJP7Z2.js +0 -1
  639. package/dist/chunk-MGCHOGQD.js +0 -1
  640. package/dist/chunk-N34ATN52.js +0 -1
  641. package/dist/chunk-NHKPP2AI.js +0 -28
  642. package/dist/chunk-NRZO5KJT.js +0 -9
  643. package/dist/chunk-OB46OPMZ.js +0 -1
  644. package/dist/chunk-Q6CZ6GBR.js +0 -3
  645. package/dist/chunk-QIK2E64R.js +0 -1
  646. package/dist/chunk-SBP3ABH4.js +0 -5
  647. package/dist/chunk-STBJO3Z3.js +0 -2
  648. package/dist/chunk-T6LX2RX5.js +0 -1
  649. package/dist/chunk-TXOTNK6B.js +0 -11
  650. package/dist/chunk-WZI4YC2O.js +0 -1
  651. package/dist/entry-19.js +0 -1
  652. package/docs/research/apply-native-capability-matrix.md +0 -174
  653. package/docs/research/apply-read-latency.md +0 -221
  654. package/docs/research/codemode-write-context.md +0 -56
  655. package/docs/research/lpt-393-fuzzy-results/file.json +0 -152
  656. package/docs/research/lpt-393-fuzzy-results/repo.json +0 -122
  657. package/docs/research/lpt-393-search-fuzzy-fallback.md +0 -97
  658. package/docs/research/native-codemode-batch-decision.md +0 -31
  659. package/docs/research/native-codemode-batching.md +0 -65
  660. package/node_modules/pi-agent-doctor/runtime/entry-19.js +0 -1
  661. package/node_modules/pi-agent-filesystem/runtime/entry-25.js +0 -2
  662. package/node_modules/pi-agent-filesystem-image/runtime/entry-26.js +0 -2
  663. package/node_modules/pi-agent-ide-ast/runtime/entry-30.js +0 -1
  664. package/node_modules/pi-agent-ide-formatter/runtime/entry-34.js +0 -2
  665. package/node_modules/pi-agent-image/runtime/entry-38.js +0 -1
  666. package/node_modules/pi-agent-invariant/runtime/entry-39.js +0 -1
  667. package/node_modules/pi-agent-search/runtime/entry-47.js +0 -1
  668. package/node_modules/pi-agent-search-text/runtime/entry-51.js +0 -2
  669. package/node_modules/pi-agent-search-text/runtime/entry-52.js +0 -1
  670. package/node_modules/pi-agent-text-anchor-constant/runtime/entry-56.js +0 -2
  671. package/node_modules/pi-agent-text-editor/runtime/entry-62.js +0 -1
  672. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-78.js +0 -2
  673. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +0 -1
  674. package/node_modules/pi-agent-tool-ui/runtime/entry-81.js +0 -1
  675. package/node_modules/pi-agent-web/runtime/entry-82.js +0 -2
  676. package/node_modules/pi-agent-web-html/runtime/entry-83.js +0 -2
  677. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-26.js +0 -2
  678. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-27.js +0 -2
  679. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-25.js +0 -2
  680. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +0 -2
  681. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-84.js +0 -2
  682. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +0 -2
  683. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  684. package/src/extensions/pi-agent-read/runtime/entry-42.js +0 -1
  685. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-51.js +0 -2
  686. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-52.js +0 -1
  687. package/src/extensions/pi-agent-search/runtime/entry-47.js +0 -1
  688. package/src/extensions/pi-agent-search/runtime/entry-48.js +0 -1
  689. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-56.js +0 -2
  690. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-57.js +0 -1
  691. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +0 -2
  692. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-79.js +0 -2
  693. package/src/extensions/pi-agent-text-editor/runtime/entry-61.js +0 -1
  694. package/src/extensions/pi-agent-text-editor/runtime/entry-62.js +0 -1
  695. package/src/plugins/pi-agent-ide-ast/runtime/entry-30.js +0 -1
  696. package/src/plugins/pi-agent-ide-ast/runtime/entry-31.js +0 -2
  697. package/src/plugins/pi-agent-ide-formatter/runtime/entry-34.js +0 -2
  698. /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-24.js +0 -0
  699. /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem}/runtime/entry-27.js +0 -0
  700. /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-28.js +0 -0
  701. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-29.js +0 -0
  702. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-text}/runtime/entry-31.js +0 -0
  703. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-32.js +0 -0
  704. /package/node_modules/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-33.js +0 -0
  705. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-35.js +0 -0
  706. /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-36.js +0 -0
  707. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-37.js +0 -0
  708. /package/node_modules/{pi-agent-pdf → pi-agent-image}/runtime/entry-40.js +0 -0
  709. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-41.js +0 -0
  710. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-42.js +0 -0
  711. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-46.js +0 -0
  712. /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-48.js +0 -0
  713. /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-55.js +0 -0
  714. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text}/runtime/entry-57.js +0 -0
  715. /package/node_modules/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-58.js +0 -0
  716. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-59.js +0 -0
  717. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-60.js +0 -0
  718. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-61.js +0 -0
  719. /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor}/runtime/entry-79.js +0 -0
  720. /package/node_modules/{pi-agent-web-image → pi-agent-web}/runtime/entry-84.js +0 -0
  721. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-85.js +0 -0
  722. /package/node_modules/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-86.js +0 -0
  723. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-image}/runtime/entry-28.js +0 -0
  724. /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-jq}/runtime/entry-29.js +0 -0
  725. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-html}/runtime/entry-85.js +0 -0
  726. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-image}/runtime/entry-86.js +0 -0
  727. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-exact → pi-agent-text-anchor-constant}/runtime/entry-58.js +0 -0
  728. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-59.js +0 -0
  729. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-exact}/runtime/entry-60.js +0 -0
  730. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-32.js +0 -0
  731. /package/src/plugins/{pi-agent-ide-changes → pi-agent-ide-ast}/runtime/entry-33.js +0 -0
  732. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-changes}/runtime/entry-35.js +0 -0
  733. /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-formatter}/runtime/entry-36.js +0 -0
  734. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-languages}/runtime/entry-37.js +0 -0
@@ -0,0 +1,5 @@
1
+ import{a as se}from"./chunk-E2PHA4SQ.js";import{a as oe}from"./chunk-L2B4DTVS.js";import{b as O}from"./chunk-2ITKAXHO.js";import{c as re}from"./chunk-JKMXND6V.js";import{a as $}from"./chunk-BQAKA3FU.js";import"./chunk-WXGTU2M6.js";import{a as ee,b as te,c as ne}from"./chunk-LLRUJD62.js";import"./chunk-Q5X6OXNS.js";import{g as y}from"./chunk-4HWKBCBH.js";import"./chunk-VDP5CQHM.js";import{a as Q}from"./chunk-47SPPIXK.js";import{a as J,b as K}from"./chunk-VAXLSPPU.js";import{c as Z}from"./chunk-W7CASEO3.js";import{e as z,f as F}from"./chunk-T7I2VX3J.js";import{a as H}from"./chunk-YJ6T3PEP.js";import{b as B,c as _}from"./chunk-S72FVLUX.js";import{a as X}from"./chunk-PS2B6THP.js";import{a as G}from"./chunk-BU7IZLKB.js";import{a as j,b as Y}from"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import{a as d}from"./chunk-EI7MMDWY.js";var ie={protocol:B,apiVersion:_,id:"vision",setup(e){e.addCheck({id:"target-graphics",title:"Target screen capture readiness",async run(t){if(!t.workspace)return[];try{if(t.signal?.throwIfAborted(),!t.workspace.probeCapture)throw new Error("Project owner does not provide a capture readiness probe");let n=await t.workspace.probeCapture(t.signal);return t.signal?.throwIfAborted(),[{status:n.display.ok?"pass":"warn",message:"Native display connection",detail:n.display.detail},{status:n.window.ok?"pass":"warn",message:"Trusted native window identity",detail:n.window.detail}]}catch(n){return t.signal?.throwIfAborted(),[{status:"warn",message:"Native capture readiness is unavailable",detail:n instanceof Error?n.message:String(n)}]}}})}};import{execFile as be}from"node:child_process";import Pe from"node:os";import{promisify as ve}from"node:util";import{createCanvas as ae,loadImage as Se}from"@napi-rs/canvas";var v=ve(be),k=20*1024*1024,de={durationSeconds:2,intervalSeconds:.5,scale:.5},q=new Set;function D(e,t){let n=t.list().find(r=>r.owned===!0&&r.remote?.target===e.target&&r.remote.pid===e.pid&&r.remote.identity===e.identity&&(r.status==="running"||r.status==="stopping"||r.status==="paused"));return n?{...e,owned:!0,source:n.source}:{...e,owned:!1,source:void 0}}d(D,"withRemoteProcessOwnership");function le(e){let t=V({mode:"sequence",durationSeconds:Number(e.durationSeconds??2),intervalSeconds:Number(e.intervalSeconds??.5),scale:Number(e.scale??.5)});de={durationSeconds:t.durationSeconds,intervalSeconds:t.intervalSeconds,scale:t.scale},q=new Set((e.allowedExecutables??"").split(",").map(n=>n.trim().toLowerCase()).filter(Boolean))}d(le,"configureVision");function C(){return de}d(C,"getVisionDefaults");function ue(e){let t=e.includes("\\")?e.slice(e.lastIndexOf("\\")+1):e,n=t.trim().split(/\s+/u)[0]??"",r=n.slice(n.lastIndexOf("/")+1);return q.has((e.includes("\\")?t:r).toLowerCase())}d(ue,"isExecutableAllowed");function pe(e){return q.has(e.slice(e.lastIndexOf("/")+1).toLowerCase())}d(pe,"isNativeExecutableAllowed");function we(e,t){let n=e?.filter(u=>/^(?:image|sequence)(?::|$)/u.test(u))??[];if(n.length===0)return;if(n.length>1)throw new Error("Use only one image or sequence view");let r=n[0],s=r.indexOf(":"),c=r.slice(0,s<0?void 0:s),a={};if(s>=0&&xe(r.slice(s+1),a),c==="image"&&(a.duration!==void 0||a.interval!==void 0))throw new Error("duration and interval are supported only by the sequence view");return V({mode:c,durationSeconds:a.duration??t.durationSeconds,intervalSeconds:a.interval??t.intervalSeconds,scale:a.scale??t.scale,...a.region===void 0?{}:{region:a.region}})}d(we,"parseVisionView");function xe(e,t){if(e.length===0)throw new Error("View parameters cannot be empty");let n=e.split(",");for(let r=0;r<n.length;r+=1){let s=n[r],c=s.indexOf("=");if(c<=0)throw new Error(`Invalid view parameter ${s}`);let a=s.slice(0,c),u=s.slice(c+1);if(a==="region"){let o=[u,n[r+1],n[r+2],n[r+3]].map(Number);if(o.some(w=>!Number.isFinite(w)))throw new Error("region requires x,y,width,height values");t.region={x:o[0],y:o[1],width:o[2],height:o[3]},r+=3;continue}if(a!=="duration"&&a!=="interval"&&a!=="scale")throw new Error(`Unknown view parameter ${a}`);let i=Number(u);if(!Number.isFinite(i))throw new Error(`View parameter ${a} must be a number`);if(t[a]!==void 0)throw new Error(`Duplicate view parameter ${a}`);t[a]=i}}d(xe,"parseViewParameters");function me(e){if(!e.startsWith("display:"))return;if(e==="display:")return 0;let t=/^display:#(\d+)$/u.exec(e);if(t===null)throw new Error("Display sources use display: or display:#N with a zero-based index");let n=Number(t[1]);if(!Number.isSafeInteger(n))throw new Error("Display sources use display: or display:#N with a zero-based index");return n}d(me,"parseDisplaySource");async function T(e){let t=new Map(e.list().flatMap(s=>s.remote!==void 0||s.pid===void 0?[]:[[s.pid,s]]));if(process.platform!=="linux"&&process.platform!=="darwin")return[...t].map(([s,c])=>({pid:s,command:c.description,owned:!0,source:c.source,host:"local"}));let{stdout:n}=await v("ps",["-eo","pid=,ppid=,lstart=,args="],{maxBuffer:4*1024*1024}),r=n.split(`
2
+ `).flatMap(s=>{let c=/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/u.exec(s);if(c===null)return[];let a=Number(c[1]),u=t.get(a);return[{pid:a,parentPid:Number(c[2]),started:c[3],command:c[4]??"",owned:u!==void 0,host:"local",...u===void 0?{}:{source:u.source}}]});return M()?[...r,...await Ie()]:r}d(T,"listProcesses");async function Ie(){try{let{stdout:e}=await v("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command","Get-Process | Select-Object Id,ProcessName,Path,StartTime | ConvertTo-Json -Compress"],{maxBuffer:4194304}),t=JSON.parse(e);return(Array.isArray(t)?t:[t]).flatMap(r=>{if(typeof r!="object"||r===null||!("Id"in r)||typeof r.Id!="number")return[];let s="ProcessName"in r&&typeof r.ProcessName=="string"?r.ProcessName:"Windows process",c="Path"in r&&typeof r.Path=="string"?r.Path:void 0,a="StartTime"in r&&typeof r.StartTime=="string"?r.StartTime:void 0;return[{pid:r.Id,command:c??s,owned:!1,host:"windows",...a===void 0?{}:{started:a}}]})}catch{return[]}}d(Ie,"listWindowsProcesses");async function W(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Process PID must be a positive integer");let n=(await T(t)).find(r=>r.pid===e);if(n===void 0)throw new Error(`Process ${e} is not running`);return n}d(W,"readProcess");function V(e){let t=e.scale??1;if(!(t>0&&t<=1))throw new Error("Image scale must be greater than 0 and at most 1");let n=e.durationSeconds??0,r=e.intervalSeconds??1;if(e.mode==="sequence"){if(!(n>0&&n<=10))throw new Error("Sequence duration must be greater than 0 and at most 10 seconds");if(!(r>0))throw new Error("Sequence interval must be greater than 0 seconds");if(Math.floor(n/r)+1>20)throw new Error("Sequence capture is limited to 20 frames")}if(e.region!==void 0){let{x:s,y:c,width:a,height:u}=e.region;if(s<0||c<0||a<=0||u<=0||s+a>1||c+u>1)throw new Error("Image region x,y,width,height must fit within normalized bounds 0..1")}if(e.cellIndex!==void 0&&e.cellSize===void 0)throw new Error("Image offset requires limit to set the square grid cell size");if(e.cellSize!==void 0&&(!Number.isSafeInteger(e.cellSize)||e.cellSize<=0))throw new Error("Image limit must be a positive integer pixel size");if(e.cellIndex!==void 0&&(!Number.isSafeInteger(e.cellIndex)||e.cellIndex<0))throw new Error("Image offset must be a zero-based cell index");return e}d(V,"validateVisionOptions");async function I(e,t,n){let r=V(t),s=r.mode==="image"?1:Math.floor(r.durationSeconds/r.intervalSeconds)+1,c=[],a=0;for(let u=0;u<s;u+=1){n?.throwIfAborted(),u>0&&await Ne(r.intervalSeconds*1e3,n);let i=await e();if(a+=i.byteLength,a>k)throw new Error("Captured images exceed the 20MB aggregate limit");for(let o of await Ee(i,r))c.push({type:"image",data:Buffer.from(o).toString("base64"),mimeType:"image/png"})}return c}d(I,"captureImages");async function Ee(e,t){let n=await Se(e),r=t.region??{x:0,y:0,width:1,height:1},s=Math.round(r.x*n.width),c=Math.round(r.y*n.height),a=Math.max(1,Math.round(r.width*n.width)),u=Math.max(1,Math.round(r.height*n.height)),i=t.scale??1,o=Math.max(1,Math.round(a*i)),w=Math.max(1,Math.round(u*i)),f=ae(o,w);if(f.getContext("2d").drawImage(n,s,c,a,u,0,0,o,w),t.cellSize===void 0)return[await f.encode("png")];let m=Math.ceil(o/t.cellSize),l=Math.ceil(w/t.cellSize),p=t.cellIndex??0;if(p>=m*l)throw new Error(`Image cell offset ${p} exceeds the ${m}x${l} grid`);let g=p%m,N=Math.floor(p/m),A=g*t.cellSize,b=N*t.cellSize,P=Math.min(t.cellSize,o-A),x=Math.min(t.cellSize,w-b),L=ae(P,x);return L.getContext("2d").drawImage(f,A,b,P,x,0,0,P,x),[await L.encode("png")]}d(Ee,"selectImage");function Ae(e,t){return e&&t==="windows"}d(Ae,"usesWindowsHostWindowCapture");function fe(){return{async captureWindow(e,t,n){if(n?.throwIfAborted(),Ae(M(),t))return Re(e,n);if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Window capture is unsupported on ${process.platform}`);let{Window:r}=await import("node-screenshots"),s;try{s=r.all()}catch(u){throw new Error(`Desktop window enumeration is unavailable: ${ce(u)}`,{cause:u})}let c=s.find(u=>{try{return u.pid()===e}catch{return!1}});if(c===void 0)throw new Error(`No capturable desktop window belongs to PID ${e}`);let a=await c.captureImage();return n?.throwIfAborted(),new Uint8Array(await a.toPng())},async captureDisplay(e,t){if(t?.throwIfAborted(),M())return De(e,t);if(process.platform!=="linux"&&process.platform!=="darwin"&&process.platform!=="win32")throw new Error(`Display capture is unsupported on ${process.platform}`);let{Monitor:n}=await import("node-screenshots"),r;try{r=n.all()}catch(a){throw new Error(`Desktop display enumeration is unavailable: ${ce(a)}`,{cause:a})}let s=r[e];if(s===void 0)throw new Error(`Display index ${e} is unavailable; found ${r.length} display(s)`);let c=await s.captureImage();return t?.throwIfAborted(),new Uint8Array(await c.toPng())},async captureUrl(e,t){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Web screenshots require an HTTP(S) URL");let{chromium:n}=await import("playwright-core"),r=await Ce(),s=await n.launch({executablePath:r,headless:!0,chromiumSandbox:!1,timeout:3e4}),c=d(()=>{s.close()},"abort");t?.addEventListener("abort",c,{once:!0});try{let a=await s.newPage({viewport:{width:1280,height:720}});return await a.goto(e.href,{waitUntil:"domcontentloaded",timeout:3e4}),await a.waitForLoadState("networkidle",{timeout:1500}).catch(()=>{}),t?.throwIfAborted(),new Uint8Array(await a.screenshot({type:"png",fullPage:!0}))}finally{t?.removeEventListener("abort",c),await s.close().catch(()=>{})}}}}d(fe,"createCaptureBackend");async function Re(e,t){let n=new URL("windows-window-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);t?.throwIfAborted();let{stdout:r}=await v("wslpath",["-w",n.pathname],{signal:t}),{stdout:s}=await v("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",r.trim(),"-ProcessId",String(e)],{encoding:"buffer",maxBuffer:k,signal:t});return new Uint8Array(s)}d(Re,"captureWslWindow");async function De(e,t){let n=new URL("windows-display-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);t?.throwIfAborted();let{stdout:r}=await v("wslpath",["-w",n.pathname],{signal:t}),{stdout:s}=await v("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",r.trim(),"-DisplayIndex",String(e)],{encoding:"buffer",maxBuffer:k,signal:t});return new Uint8Array(s)}d(De,"captureWslDisplay");function M(){return process.platform==="linux"&&(process.env.WSL_DISTRO_NAME!==void 0||Pe.release().toLowerCase().includes("microsoft"))}d(M,"isWsl");async function Ce(){let e=process.env.PI_AGENT_IDE_BROWSER_PATH;if(e!==void 0)return e;let{stdout:t}=await v("bash",["-lc","command -v google-chrome-stable || command -v google-chrome || command -v chromium || command -v chromium-browser"]),n=t.trim();if(n.length===0)throw new Error("No Chrome or Chromium executable was found; set PI_AGENT_IDE_BROWSER_PATH");return n}d(Ce,"resolveBrowser");function Ne(e,t){return new Promise((n,r)=>{let s=setTimeout(n,e),c=d(()=>{clearTimeout(s),r(t?.reason??new Error("Capture aborted"))},"abort");t?.addEventListener("abort",c,{once:!0}),s.unref()})}d(Ne,"delay");function ce(e){return e instanceof Error?e.message:String(e)}d(ce,"errorMessage");async function ye(e,t,n,r){F(e,[await z({id:"vision",description:"Window, display, image, and sequence capture",triggers:[{tool:"read",resourcePrefixes:["process:","window:","display:"]},{tool:"read",resourcePrefixes:["web:ssh://"],viewPrefixes:["image","sequence"]}]})]);let s=t?.preferences??{};le({durationSeconds:s["vision.sequenceDurationSeconds"],intervalSeconds:s["vision.sequenceIntervalSeconds"],scale:s["vision.imageScale"],allowedExecutables:s["vision.allowedExecutables"]});let c=oe(e),a=fe();await Promise.all([H(e,ie),G(e,{protocol:j,apiVersion:Y,id:"vision",setup(u){for(let i of["image","sequence"])u.addView({contentKind:"any",view:i,presenter:{id:`vision-${i}`,present:d(o=>o,"present")}});u.addHandler({stage:"pre-read",async handler(i){let o=i.request.path;if(o===void 0)return{kind:"continue",context:i};if(o.startsWith("window:ssh://")||o.startsWith("display:ssh://"))try{let l=o.startsWith("window:"),p=new URL(o.slice(l?7:8));if(p.username||p.password||p.port||p.search||(l?p.hash!==""||!/^\/[1-9][0-9]*$/u.test(p.pathname):p.pathname!=="/"||p.hash!==""&&!/^#\d+$/u.test(p.hash)))throw new Error(`Invalid target capture resource: ${o}`);if(!l&&e.getFlag("pi-agent-ide-vision-displays")!==!0)return h(o,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");if(!r)return h(o,`Target capture is unavailable: ${o}`);let g=Number(l?p.pathname.slice(1):p.hash.slice(1)||"0");if(!Number.isSafeInteger(g))throw new Error(`Invalid target capture resource: ${o}`);let N=await I(async()=>{if(!l)return r.captureDisplay(o,g,i.resolverContext.signal);let A=`process:ssh://${p.hostname}/${g}`,b=await n?.read(A,i.resolverContext.signal);if(!b||b.resource!==A||b.pid!==g||b.target!==p.hostname)throw new Error(`Target process identity is unavailable: ${o}`);let P=D(b,c),x=P.executable;if(!P.owned&&(!x||!pe(x))&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)throw new Error(`Window capture is denied for the target executable: ${o}`);return r.captureWindow(o,P,i.resolverContext.signal)},R(i.request),i.resolverContext.signal);return S(o,N)}catch(l){return h(o,E(l))}if(o.startsWith("web:")&&he(i.request))try{let l=r?.captureWeb?.bind(r);if(!l)return h(o,`Target web capture is unavailable: ${o}`);let p=await I(()=>l(o,i.resolverContext.signal),R(i.request),i.resolverContext.signal);return S(o,p)}catch(l){return h(o,E(l))}let w=me(o);if(w!==void 0){if(e.getFlag("pi-agent-ide-vision-displays")!==!0)return h(o,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");try{let l=await I(()=>a.captureDisplay(w,i.resolverContext.signal),R(i.request),i.resolverContext.signal);return S(o,l)}catch(l){return h(o,E(l))}}try{let l=await n?.read(o,i.resolverContext.signal);if(l)return S(o,[{type:"text",text:U(D(l,c))}])}catch(l){return h(o,E(l))}let f=ge(o,"process:");if(f!==void 0){let l=await W(f,c);return S(o,[{type:"text",text:U(l)}])}let m=ge(o,"window:");if(m!==void 0){let l=await W(m,c);if(!l.owned&&!ue(l.command)&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)return h(o,`Window capture for PID ${m} is denied because the process is neither Agent IDE-owned nor allowlisted by executable name. Enable --pi-agent-ide-vision-arbitrary-windows to allow it.`);try{let p=await I(()=>a.captureWindow(m,l.host,i.resolverContext.signal),R(i.request),i.resolverContext.signal);return S(o,p)}catch(p){return h(o,E(p))}}if(/^https?:\/\//iu.test(o)&&he(i.request)){let l=new URL(o);try{let p=await I(()=>a.captureUrl(l,i.resolverContext.signal),R(i.request),i.resolverContext.signal);return S(l.href,p)}catch(p){return h(l.href,E(p))}}return{kind:"continue",context:i}}}),u.describe({path:d(()=>`process:ssh://target/PID, window:ssh://target/PID and display:ssh://target/ select configured Linux SSH targets; missing target facilities fail without local fallback. web:ssh://target/https://\u2026 captures with target-installed Playwright/Chromium. process:PID \u2014 process metadata. window:PID \u2014 capture a window of an IDE-owned or allowlisted process${e.getFlag("pi-agent-ide-vision-arbitrary-windows")===!0?"; arbitrary windows are enabled":"; other processes require --pi-agent-ide-vision-arbitrary-windows"}. display: or display:#N \u2014 display capture with a zero-based index; ${e.getFlag("pi-agent-ide-vision-displays")===!0?"enabled":"requires --pi-agent-ide-vision-displays"}. HTTP(S) URLs accept image or sequence screenshots.`,"path"),views:d(()=>{let i=C();return`image or image:scale=S,region=X,Y,W,H \u2014 one screenshot. sequence or sequence:duration=D,interval=I,scale=S,region=X,Y,W,H \u2014 timed frames. Only one image/sequence view per request. duration and interval are seconds and only valid for sequence: 0 < D <= 10, I > 0, at most 20 frames (floor(D/I)+1). Scale satisfies 0 < S <= 1. Region uses normalized x,y,width,height: x,y >= 0, width,height > 0, and the rectangle must fit in 0..1; crop runs before scaling. Settings are optional; defaults: duration=${i.durationSeconds}, interval=${i.intervalSeconds}, scale=${i.scale}.`},"views"),offset:"For window:, display: and HTTP(S) image/sequence captures, a non-negative integer zero-based row-major grid cell index in the transformed image. Requires limit; omit to select cell 0 when limit is set.",limit:"For window:, display: and HTTP(S) image/sequence captures, a positive integer square grid cell size in output pixels. Omit both offset and limit for the bounded transformed image."})}}),Q(e,{protocol:J,apiVersion:K,id:"vision-processes",setup(u){u.addResolver({priority:-100,resolver:{id:"processes",readResources:d(i=>/^process:/iu.test(i.query)?void 0:[],"readResources"),toScriptData(i){return{kind:"custom",resolverId:"processes",value:{processes:i.map(w=>({pid:w.pid,command:w.command,...w.host==="ssh"?{host:w.host,target:w.target,resource:w.resource,identity:w.identity,owned:w.owned,parentPid:w.parentPid,started:w.started,executable:w.executable,...w.source===void 0?{}:{source:w.source}}:{}}))}}},async tryResolve(i,o){let w=/^process:(.*)$/isu.exec(i.query);if(w===null)return{kind:"not-handled"};let f=(w[1]??"").trim().toLowerCase(),m=i.path??o.cwd,l=await n?.list(m,o.signal);if(m.includes("://")&&l===void 0)throw new Error("Process scope has no resource owner");return{kind:"resolved",payload:(l?.map(g=>D(g,c))??await T(c)).filter(g=>f.length===0||String(g.pid)===f||g.command.toLowerCase().includes(f)).slice(0,Math.min(i.limit??50,100))}},renderResult(i,o,w){let f=i.details;return new X({summary:`${f.processes.length} processes shown`,rows:f.processes.length?f.processes.map(m=>({kind:"note",text:`${m.pid} ${m.command}`})):[{kind:"note",text:"No matching processes"}]},w,o.expanded)},format(i){let o=i;return{content:[{type:"text",text:o.length===0?"No matching processes.":o.map(U).join(`
3
+
4
+ `)}],details:{count:o.length,processes:o}}}}}),u.describe("process:<query> finds running processes by PID or command. Select a configured Linux target with an SSH path; its results retain process:ssh://target/PID, target and kernel start identity. Use process:PID for local metadata. Use window:ssh://target/PID for authorized target capture, never window:PID with a remote PID. Discovery alone does not grant capture or process control.")}})])}d(ye,"registerVisionWithOwner");function ge(e,t){if(!e.startsWith(t))return;let n=e.slice(t.length);if(!/^\d+$/u.test(n))throw new Error(`${t} sources require a numeric PID`);return Number(n)}d(ge,"prefixedPid");function R(e){return{...we(e.views,C())??{mode:"image",...C()},...e.limit===void 0?{}:{cellSize:e.limit},...e.offset===void 0?{}:{cellIndex:e.offset}}}d(R,"options");function he(e){return e.views?.some(t=>/^(?:image|sequence)(?::|$)/u.test(t))===!0}d(he,"requestsScreenshot");function S(e,t){return{kind:"return",result:{content:t,script:{kind:"native",source:e,blocks:t},details:{source:e,resolvedBy:"vision"}}}}d(S,"returned");function h(e,t){return{kind:"return",result:{content:[{type:"text",text:t}],details:{source:e,resolvedBy:"vision",failure:{code:"READ_FAILED",source:e,resolverId:"vision",message:t}},isError:!0}}}d(h,"failed");function E(e){return e instanceof Error?e.message:String(e)}d(E,"errorMessage");function U(e){return[`PID: ${e.pid}`,...e.host==="ssh"?[`Target: ${e.target}`,`Resource: ${e.resource}`,`Identity: ${e.identity}`]:[],`Command: ${e.command}`,`Owned by Agent IDE: ${e.owned?"yes":"no"}`,...e.host==="ssh"&&e.executable!==null?[`Executable: ${e.executable}`]:[],...e.parentPid===void 0?[]:[`Parent PID: ${e.parentPid}`],...e.started===void 0?[]:[`Started: ${e.started}`],...e.source===void 0?[]:[`Agent IDE source: ${e.source}`]].join(`
5
+ `)}d(U,"formatProcess");function $e(e){return{async read(t,n){if(!t.startsWith("process:ssh://"))return;let r=new URL(t.slice(8));if(r.username||r.password||r.port||r.search||r.hash||!/^\/[1-9][0-9]*$/u.test(r.pathname))throw new y("INVALID_SOURCE",t,"not-applied");try{let[s]=await $(e,`ssh://${r.hostname}/`,Number(r.pathname.slice(1)),n);if(!s)throw new y("ENOENT",t,"not-applied");return s}catch(s){throw s instanceof y?new y(s.code,t,s.effect):s}},async list(t,n){if(t.startsWith("ssh://"))return $(e,t,void 0,n)}}}d($e,"createSshProcessOwner");function Oe(e){return{captureWindow(t,n,r){if(!n.executable)throw new y("CAPABILITY_UNAVAILABLE",t,"not-applied");return O(e,t,{kind:"window",pid:n.pid,identity:n.identity,executable:n.executable},r)},async captureWeb(t,n){let r=se(t);if(!r)throw new y("INVALID_SOURCE",t,"not-applied");try{let s=e.resolve(`ssh://${r.target}/`);if(!s)throw new y("UNSUPPORTED_SOURCE",t,"not-applied");return await re(s.backend.target,r.url,t,n)}catch(s){throw s instanceof y?new y(s.code,t,s.effect):s}},captureDisplay(t,n,r){return O(e,t,{kind:"display",index:n},r)}}}d(Oe,"createSshCaptureOwner");async function Me(e,t){let n=new ne(await te(ee(Z())));await ye(e,t,$e(n),Oe(n))}d(Me,"registerOwnedVision");export{Oe as createSshCaptureOwner,$e as createSshProcessOwner,Me as default};
@@ -0,0 +1 @@
1
+ import{a as c}from"./chunk-EI7MMDWY.js";import{access as I,readFile as P,readdir as S}from"node:fs/promises";import w from"node:path";async function M(t,i,e,n){if(n?.throwIfAborted(),t.includes("://")&&!e)throw Object.assign(new Error("Project evidence requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});let a=new Map,b=c(o=>{let r=a.get(o);return r===void 0&&(r=e?e.readText(o,n):P(w.join(t,o),{encoding:"utf8",signal:n}),r=r.catch(d=>{if(n?.throwIfAborted(),e)throw d}),a.set(o,r)),r},"content"),l=await b("package.json");n?.throwIfAborted();let k=g(l),m=new Set;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let r=k?.[o];if(h(r))for(let d of Object.keys(r))m.add(d)}let R=await Promise.all(i.map(async o=>{let r;for(let s of o.configFiles??[]){n?.throwIfAborted();let u=await(e?e.hasMarker(s,n):E(t,s,n)).catch(f=>{throw n?.throwIfAborted(),f});if(n?.throwIfAborted(),u){r=s;break}}if(r===void 0)for(let[s,u]of Object.entries(o.configSections??{})){n?.throwIfAborted();let f=await b(s);if(n?.throwIfAborted(),f===void 0)continue;let y=s.endsWith(".json")?g(f):void 0;if(u.some(p=>y===void 0?f.split(/\r?\n/).some(j=>{let A=/^\s*\[([^\]]+)\]/.exec(j)?.[1]?.trim();return A===p||A?.startsWith(`${p}.`)===!0}):O(y,p)!==void 0)){r=s;break}}let d=o.dependencies?.find(s=>m.has(s));return[o.id,{score:(r===void 0?0:6)+(d===void 0?0:4),...r!==void 0&&{config:r},...d!==void 0&&{dependency:d}}]}));return n?.throwIfAborted(),new Map(R)}c(M,"inspectRecipeEvidence");async function E(t,i,e){if(e?.throwIfAborted(),t.includes("://"))throw Object.assign(new Error("Project marker requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});if(!i.includes("*"))try{return await I(w.join(t,i)),e?.throwIfAborted(),!0}catch{return e?.throwIfAborted(),!1}try{let n=await S(t);return e?.throwIfAborted(),n.some(a=>w.matchesGlob(a,i))}catch{return e?.throwIfAborted(),!1}}c(E,"hasProjectMarker");function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}c(h,"isRecord");function g(t){try{let i=JSON.parse(t??"");return h(i)?i:void 0}catch{return}}c(g,"parseJson");function O(t,i){let e=t;for(let n of i.split("."))e=h(e)?e[n]:void 0;return e}c(O,"jsonSection");export{M as a,E as b};
@@ -1 +1 @@
1
- import{c as S,d as C}from"./chunk-STBJO3Z3.js";import{a as h}from"./chunk-EI7MMDWY.js";import z from"node:path";import{pathToFileURL as x}from"node:url";function b(e,n){let r=new Map;for(let t of e){let i=r.get(t.source)??[];i.push(t),r.set(t.source,i)}let a=new Set,u=e.length,s=[...r].sort(([t,i],[d,m])=>m.length-i.length||t.localeCompare(d));for(let[t,i]of s){if(u<=n)break;a.add(t),u-=i.length-1}let c=[],o=n,l=[...r].sort(([t],[i])=>Number(a.has(t))-Number(a.has(i))||t.localeCompare(i));for(let[t,i]of l){if(!a.has(t)){if(i.length>o)continue;c.push({kind:"detailed",source:t,matches:i}),o-=i.length;continue}if(o<1)continue;o--;let d=new Map;for(let g of i)d.set(g.lineText,(d.get(g.lineText)??0)+1);let m=r.size===1?[...d].sort(([g,p],[F,w])=>w-p||g.localeCompare(F)).slice(0,o).map(([g,p])=>({text:g,matchCount:p})):[];o-=m.length,c.push({kind:"compacted",source:t,matchCount:i.length,uniqueLineCount:d.size,groups:m})}return c.sort((t,i)=>t.source.localeCompare(i.source)),{files:c}}h(b,"planSearchPresentation");function N(e,n,r,a,u,s=50){let c=b(n,s),o=new Set(n.map(t=>t.source)).size,l=c.files.map(t=>t.kind==="detailed"?L(t.source,t.matches,a):{path:M(t.source,a),link:x(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups,lines:[]});return{...u!==void 0&&{sessionId:u},query:e,matchCount:n.length,fileCount:o,...c.files.length<o?{omittedFileCount:o-l.length,omittedMatchCount:n.length-l.reduce((t,i)=>t+i.matchCount,0)}:{},complete:r,files:l}}h(N,"createSearchToolDetails");function $(e,n){return{fileCount:new Set(e.flatMap(r=>r.matches.map(a=>a.source))).size,groups:e.map(r=>{let u=N(r.identifier,r.matches.slice(0,S.previewMatches),r.complete,n).files.map(s=>{let c=s.lines.map(o=>{let l=Math.max(0,(o.ranges[0]?.from??0)-64),t=Math.min(o.text.length,(o.ranges[0]?.to??0)+64),i=l>0?"\u2026":"",d=o.ranges.filter(m=>m.from>=l&&m.to<=t).map(m=>({from:m.from-l+i.length,to:m.to-l+i.length}));return{...o,text:i+o.text.slice(l,t)+(t<o.text.length?"\u2026":""),ranges:d,matchCount:d.length}});return{...s,lines:c,matchCount:c.reduce((o,l)=>o+l.matchCount,0)}});return{identifier:r.identifier,files:u}})}}h($,"createFuzzyPresentation");function k(e){return f(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(n=>f(n)&&typeof n.identifier=="string"&&Array.isArray(n.files)&&n.files.every(R))}h(k,"isFuzzyPresentation");function E(e){if(!f(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||e.omittedFileCount!==void 0&&!y(e.omittedFileCount)||e.omittedMatchCount!==void 0&&!y(e.omittedMatchCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!C(e.fuzzy)||e.fuzzyPresentation!==void 0&&!k(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(R))return!1;let n=e.files;return e.fileCount===n.length+(e.omittedFileCount??0)&&e.matchCount===n.reduce((r,a)=>r+a.matchCount,0)+(e.omittedMatchCount??0)}h(E,"isSearchToolDetails");function L(e,n,r){let a=new Map;for(let s of n){let c=a.get(s.lineNumber);if(c!==void 0&&c.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let o=c??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};o.ranges.push({from:s.startColumn,to:s.endColumn}),a.set(s.lineNumber,o)}let u=[...a.values()].sort((s,c)=>s.lineNumber-c.lineNumber).map(s=>{let c=[...s.ranges].sort((o,l)=>o.from-l.from||o.to-l.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:c.length,ranges:c}});return{path:M(e,r),link:x(e).href,matchCount:n.length,lines:u}}h(L,"createSearchResultFile");function R(e){if(!f(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(P))return!1;let n=e.lines,r=e.groups,a=new Set(n.flatMap(u=>u.logicalMatchIds??[]));return(r===void 0||Array.isArray(r)&&r.every(u=>f(u)&&typeof u.text=="string"&&y(u.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(n.length===0||(a.size>0?a.size===e.matchCount:e.matchCount===n.reduce((u,s)=>u+s.matchCount,0)))}h(R,"isSearchResultFile");function P(e){return f(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(n=>typeof n=="string"))&&e.ranges.every(n=>A(n,e.text))}h(P,"isSearchResultLine");function A(e,n){return f(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=n.length}h(A,"isSearchResultRange");function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}h(f,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}h(y,"isCount");function M(e,n){let r=z.relative(n,e);return r.length>0&&!r.startsWith("..")&&!z.isAbsolute(r)?r:e}h(M,"displaySource");export{b as a,N as b,$ as c,E as d};
1
+ import{c as S,d as C}from"./chunk-OI3HBIPK.js";import{a as h}from"./chunk-EI7MMDWY.js";import z from"node:path";import{pathToFileURL as x}from"node:url";function b(e,n){let r=new Map;for(let t of e){let i=r.get(t.source)??[];i.push(t),r.set(t.source,i)}let a=new Set,u=e.length,s=[...r].sort(([t,i],[d,m])=>m.length-i.length||t.localeCompare(d));for(let[t,i]of s){if(u<=n)break;a.add(t),u-=i.length-1}let c=[],o=n,l=[...r].sort(([t],[i])=>Number(a.has(t))-Number(a.has(i))||t.localeCompare(i));for(let[t,i]of l){if(!a.has(t)){if(i.length>o)continue;c.push({kind:"detailed",source:t,matches:i}),o-=i.length;continue}if(o<1)continue;o--;let d=new Map;for(let g of i)d.set(g.lineText,(d.get(g.lineText)??0)+1);let m=r.size===1?[...d].sort(([g,p],[F,w])=>w-p||g.localeCompare(F)).slice(0,o).map(([g,p])=>({text:g,matchCount:p})):[];o-=m.length,c.push({kind:"compacted",source:t,matchCount:i.length,uniqueLineCount:d.size,groups:m})}return c.sort((t,i)=>t.source.localeCompare(i.source)),{files:c}}h(b,"planSearchPresentation");function N(e,n,r,a,u,s=50){let c=b(n,s),o=new Set(n.map(t=>t.source)).size,l=c.files.map(t=>t.kind==="detailed"?L(t.source,t.matches,a):{path:M(t.source,a),link:x(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups,lines:[]});return{...u!==void 0&&{sessionId:u},query:e,matchCount:n.length,fileCount:o,...c.files.length<o?{omittedFileCount:o-l.length,omittedMatchCount:n.length-l.reduce((t,i)=>t+i.matchCount,0)}:{},complete:r,files:l}}h(N,"createSearchToolDetails");function $(e,n){return{fileCount:new Set(e.flatMap(r=>r.matches.map(a=>a.source))).size,groups:e.map(r=>{let u=N(r.identifier,r.matches.slice(0,S.previewMatches),r.complete,n).files.map(s=>{let c=s.lines.map(o=>{let l=Math.max(0,(o.ranges[0]?.from??0)-64),t=Math.min(o.text.length,(o.ranges[0]?.to??0)+64),i=l>0?"\u2026":"",d=o.ranges.filter(m=>m.from>=l&&m.to<=t).map(m=>({from:m.from-l+i.length,to:m.to-l+i.length}));return{...o,text:i+o.text.slice(l,t)+(t<o.text.length?"\u2026":""),ranges:d,matchCount:d.length}});return{...s,lines:c,matchCount:c.reduce((o,l)=>o+l.matchCount,0)}});return{identifier:r.identifier,files:u}})}}h($,"createFuzzyPresentation");function k(e){return f(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(n=>f(n)&&typeof n.identifier=="string"&&Array.isArray(n.files)&&n.files.every(R))}h(k,"isFuzzyPresentation");function E(e){if(!f(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||e.omittedFileCount!==void 0&&!y(e.omittedFileCount)||e.omittedMatchCount!==void 0&&!y(e.omittedMatchCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!C(e.fuzzy)||e.fuzzyPresentation!==void 0&&!k(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(R))return!1;let n=e.files;return e.fileCount===n.length+(e.omittedFileCount??0)&&e.matchCount===n.reduce((r,a)=>r+a.matchCount,0)+(e.omittedMatchCount??0)}h(E,"isSearchToolDetails");function L(e,n,r){let a=new Map;for(let s of n){let c=a.get(s.lineNumber);if(c!==void 0&&c.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let o=c??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};o.ranges.push({from:s.startColumn,to:s.endColumn}),a.set(s.lineNumber,o)}let u=[...a.values()].sort((s,c)=>s.lineNumber-c.lineNumber).map(s=>{let c=[...s.ranges].sort((o,l)=>o.from-l.from||o.to-l.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:c.length,ranges:c}});return{path:M(e,r),link:x(e).href,matchCount:n.length,lines:u}}h(L,"createSearchResultFile");function R(e){if(!f(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(P))return!1;let n=e.lines,r=e.groups,a=new Set(n.flatMap(u=>u.logicalMatchIds??[]));return(r===void 0||Array.isArray(r)&&r.every(u=>f(u)&&typeof u.text=="string"&&y(u.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(n.length===0||(a.size>0?a.size===e.matchCount:e.matchCount===n.reduce((u,s)=>u+s.matchCount,0)))}h(R,"isSearchResultFile");function P(e){return f(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(n=>typeof n=="string"))&&e.ranges.every(n=>A(n,e.text))}h(P,"isSearchResultLine");function A(e,n){return f(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=n.length}h(A,"isSearchResultRange");function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}h(f,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}h(y,"isCount");function M(e,n){if(e.includes("://"))return e;let r=z.relative(n,e);return r.length>0&&!r.startsWith("..")&&!z.isAbsolute(r)?r:e}h(M,"displaySource");export{b as a,N as b,$ as c,E as d};
@@ -0,0 +1,3 @@
1
+ import{b as x}from"./chunk-T4FTT3U4.js";import{j as $}from"./chunk-ZPT5D4VP.js";import{a as m}from"./chunk-KINKBPPX.js";import{a as p}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";function D(e,n,t){let i=`${n}:`;if(!e.startsWith(i))return;let o=e.slice(i.length);if(o.length===0)throw new Error(`${n}: requires a file path.`);return x(o,t)}a(D,"resolveDiagnosticViewPath");function R(e,n){return`${e}:${n}`}a(R,"formatDiagnosticViewSource");function k(e,n,t,i={}){let o={complete:t.length>0&&t.every(d=>d.status==="ready"),count:t.reduce((d,u)=>d+u.diagnostics.length,0),sources:t.map(d=>d.source)},r=n.split(/\r\n|\r|\n/u),s=b(t,r.length);if(s.size===0)return{type:"text",diagnosticCheck:o,text:L(t)||"No completed diagnostic checks are available.",sourceLines:{}};let c=i.contextLines??5;if(!Number.isInteger(c)||c<0)throw new TypeError("Diagnostic contextLines must be a non-negative integer.");let l=new Set;for(let d of s.keys()){let u=Math.max(1,d-c),f=Math.min(r.length,d+c);for(let g=u;g<=f;g+=1)l.add(g)}let w=L(t),y=w?[w]:[],h={};for(let d of[...l].sort((u,f)=>u-f)){let u=r[d-1]??"",f=(s.get(d)??[]).map(({diagnostic:g,source:V})=>`<!-- ${V}: ${m(g,V)} -->`).join(" ");y.push(f.length===0?u:`${u} ${f}`),h[String(y.length)]={source:e,lineNumber:d,content:u}}return{type:"text",diagnosticCheck:o,text:y.join(`
2
+ `),sourceLines:h}}a(k,"createDiagnosticViewContent");function T(e,n){let t=b(n,e.lines.length,/[\r\n]$/u.test(e.content)),i=e.lines.map(o=>{let r=t.get(o.lineNumber);if(r===void 0)return o;let s=r.map(({diagnostic:c,source:l})=>`<!-- ${l}: ${m(c,l)}${c.line===o.lineNumber?"":` @${c.line}:${c.column}`} -->`).join(" ");return{...o,presentation:{...o.presentation,suffix:`${o.presentation?.suffix??""} ${s}`}}});return{...e,lines:i}}a(T,"addDiagnosticAnnotations");function L(e){return e.length>0&&e.every(n=>n.status==="ready"&&n.diagnostics.length===0)?`Checks completed (${e.map(n=>n.source).join(", ")}); no diagnostics found at this point.`:e.filter(n=>n.status&&n.status!=="ready").map(n=>`${n.source}: ${n.status}${n.reason?` (${n.reason})`:""}.`).join(" ")}a(L,"diagnosticStatus");function b(e,n,t=!1){let i=new Map;for(let{diagnostics:o,source:r}of e)for(let s of o){let c=t&&s.line===n+1?n:s.line;if(!Number.isInteger(s.line)||c<1||c>n)continue;let l=i.get(c)??[];l.push({diagnostic:s,source:r}),i.set(c,l)}return i}a(b,"diagnosticsByValidLine");function C(e){return{text:`${e.content}${e.suffix??""}`,...e.sourceLine!==void 0&&{sourceLine:e.sourceLine}}}a(C,"renderSourceViewLine");function v(e,n){if(e.length===0)return S([{text:"<empty-result>"}]);if(e.length===1&&p(e[0]).status==="failed"&&p(e[0]).path===""){let i=p(e[0]),o=n.recovery===void 0?[]:["","Recovery:",...n.recovery],r=n.includeNoChange===!0?["","No file was changed."]:[];return S([i.code??n.failureLabel,"",`Reason: ${i.error??n.unknownFailure??"unknown failure"}`,...r,...o].map(s=>({text:s})))}let t=[];for(let[i,o]of e.entries())i>0&&t.push({text:""},{text:""}),t.push(...M(o,n));return S(t)}a(v,"formatSourceViewResults");function N(){return e=>{let n=e.state;if(n?.contentKind!=="text")return{kind:"continue",context:e};let t=j(n.content[0]);if(t===void 0)return{kind:"continue",context:e};let i=n.text.lines.map(o=>{let r=t[String(o.lineNumber)];return r===void 0?o:$(o,r)});return{kind:"continue",context:{...e,state:{...n,text:{...n.text,lines:i}}}}}}a(N,"createSourceMappedTextReadHandler");function M(e,n){if(e.status==="failed")return[...e.heading===void 0?[`## file: ${e.path||"<unknown>"}`]:[`## ${e.heading}`,...e.details??[]],`${n.failureLabel} | ${e.error??n.unknownFailure??"unknown failure"}`].map(s=>({text:s}));let t=e.heading===void 0?[`## file: ${e.path}`]:[`## ${e.heading}`,...e.details??[]],i=e.continuation??"",o=e.warning===void 0?[]:[{text:""},{text:e.warning}];return[...t.map(r=>({text:r})),{text:`Lines: ${e.startLine}-${e.endLine} of ${e.totalLines}${i}`},{text:""},...e.renderedLines,...o]}a(M,"formatSourceViewBlock");function S(e){let n={};for(let[t,i]of e.entries())i.sourceLine!==void 0&&(n[String(t+1)]=i.sourceLine);return{type:"text",text:e.map(t=>t.text).join(`
3
+ `),sourceLines:n}}a(S,"sourceMappedContent");function j(e){if(typeof e!="object"||e===null||!("sourceLines"in e))return;let n=e.sourceLines;if(!(typeof n!="object"||n===null)){for(let t of Object.values(n))if(!B(t))return;return n}}a(j,"sourceLineMap");function B(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.source=="string"&&n.source.length>0&&Number.isInteger(n.lineNumber)&&(n.lineNumber??0)>0&&typeof n.content=="string"}a(B,"isTextSourceLine");export{D as a,R as b,k as c,T as d,L as e,C as f,v as g,N as h};
@@ -0,0 +1,3 @@
1
+ import{a as i}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as Se}from"node:async_hooks";function ie(){return{pending:new Set,active:new Se}}i(ie,"createSchedulerState");function be(r,e){return r===void 0||e===void 0?!0:r.some(t=>e.some(n=>(t.mode==="write"||n.mode==="write")&&(t.resource==="*"||n.resource==="*"||t.resource===n.resource||t.recursive===!0&&n.resource.startsWith(t.resource.endsWith("/")?t.resource:`${t.resource}/`)||n.recursive===!0&&t.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`))))}i(be,"conflicts");function Ee(r,e,t){if(e===void 0||!t&&e.some(o=>o.mode!=="read"))return!1;if(r===void 0)return!0;let n=new Map;for(let o of e){let s=o.group??o.resource;n.set(s,[...n.get(s)??[],o])}return[...n.values()].every(o=>o.some(s=>r.some(a=>(s.mode==="read"||a.mode==="write")&&(a.resource==="*"||s.resource===a.resource&&(s.recursive!==!0||a.recursive===!0)||a.recursive===!0&&s.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}i(Ee,"coveredAccess");async function xe(r,e){if(e===void 0)return await r;e.throwIfAborted();let t,n=new Promise((o,s)=>{t=i(()=>s(e.reason),"abort"),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([r,n])}finally{e.removeEventListener("abort",t)}}i(xe,"waitForDependencies");var $=class r{constructor(e=ie()){this.state=e}static{i(this,"ResourceScheduler")}run(e,t,n,o={}){let s=Promise.resolve(e),a=this.state.active.getStore();if(a?.open){let m=s.then(S=>{if(n?.throwIfAborted(),!Ee(a.accesses,S,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return S});a.nested??=new r;let y=a.nested.run(m,t,n,{allowNestedWrites:a.allowNestedWrites});return a.children.add(y),y.then(()=>a.children.delete(y),()=>a.children.delete(y)),y}let d=[...this.state.pending],c=s.catch(()=>{}),p,l=new Promise(m=>{p=m}),h={accesses:c,done:l};return this.state.pending.add(h),(async()=>{try{n?.throwIfAborted();let m=await xe(s.then(async S=>(await Promise.all(d.map(B=>Promise.race([B.done,B.accesses.then(Te=>be(S,Te)?B.done:void 0)]))),S)),n);n?.throwIfAborted();let y={accesses:m,children:new Set,open:!0,allowNestedWrites:o.allowNestedWrites===!0};try{return await this.state.active.run(y,t)}finally{for(;y.children.size>0;)await Promise.allSettled([...y.children]);y.open=!1}}finally{this.state.pending.delete(h),p()}})()}},Ae=Symbol.for("pi-agent-resource.resource-scheduler-state"),Oe=globalThis,ke=Oe[Ae]??=ie(),Ne=new $(ke);import{realpath as Pe,stat as je}from"node:fs/promises";import P from"node:path";import{fileURLToPath as Ie}from"node:url";async function ae(r,e,t){if(/^[a-z][a-z\d+.-]*:/iu.test(r)&&!/^[a-z]:[\\/]/iu.test(r)&&!r.startsWith("file:"))return[{resource:r,mode:t}];let n=P.resolve(e,r.startsWith("file:")?Ie(r):r),[o,s]=await Promise.allSettled([Pe(n),je(n,{bigint:!0})]),a;if(o.status==="fulfilled")a=o.value;else{let l=o.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l;let h=P.dirname(n);if(h===n)a=n;else{let y=(await ae(h,e,t)).find(S=>S.resource.startsWith("file:"));a=P.join(y?.resource.slice(5)??h,P.basename(n))}}let d=a.split(P.sep).join("/"),c=`file:${process.platform==="win32"?d.toLowerCase():d}`,p=[{resource:c,group:c,mode:t}];if(s.status==="fulfilled"){let l=s.value;l.isDirectory()&&(p[0]={resource:c,group:c,mode:t,recursive:!0}),l.ino!==0n&&p.push({resource:`inode:${l.dev}:${l.ino}`,group:c,mode:t,recursive:l.isDirectory()})}else{let l=s.reason;if(!(l instanceof Error)||!("code"in l)||l.code!=="ENOENT")throw l}return p}i(ae,"resourceAccesses");import{randomUUID as _e}from"node:crypto";import{mkdir as $e,mkdtemp as Ue,readFile as Le,rm as De,writeFile as He}from"node:fs/promises";import{tmpdir as We}from"node:os";import ce from"node:path";var K=class{static{i(this,"TempResourceStore")}resolver;#e=new Map;#n=new Set;#o;#t;#r;constructor(e={}){this.#o=e.parentDirectory??We(),this.resolver={id:"temp",tryResolve:i(t=>Promise.resolve(this.#c(t)),"tryResolve")}}save(e){return this.#s(e,!1)}saveFile(e){return this.#s(e,!0)}async#s(e,t){if(this.#r!==void 0)throw new Error("Temporary resource store is closed");let n=this.#i(e,t);this.#n.add(n);try{return await n}finally{this.#n.delete(n)}}dispose(){return this.#r??=this.#a(),this.#r}async#i(e,t){let n=await this.#d(),o=_e(),s=`temp:${o}`,a=ce.join(n,`${o}.txt`);return await He(a,e,{encoding:"utf8",flag:"wx",mode:384}),t||this.#e.set(s,a),t?a:s}async#a(){await Promise.allSettled(this.#n),this.#e.clear(),this.#t!==void 0&&await De(await this.#t,{recursive:!0,force:!0})}#c(e){return e.startsWith("temp:")?this.#r!==void 0||!this.#e.has(e)?{kind:"failed",error:new Error(`Temporary resource ${e} does not exist in this runtime`)}:{kind:"resolved",resource:{source:e,read:i(()=>this.#u(e),"read")}}:{kind:"not-handled"}}async#u(e){let t=this.#e.get(e);if(this.#r!==void 0||t===void 0)throw new Error(`Temporary resource ${e} does not exist in this runtime`);return[{type:"text",text:await Le(t,"utf8")}]}async#d(){return this.#t??=(async()=>(await $e(this.#o,{recursive:!0}),Ue(ce.join(this.#o,"pi-agent-read-"))))(),this.#t}};import{Type as g}from"typebox";import{Value as Ve}from"typebox/value";var U=g.Object({code:g.String(),message:g.String(),source:g.Optional(g.String())},{additionalProperties:!1});function ue(r){return{...g.Union([g.Object({status:g.Literal("success"),data:r,errors:g.Array(U,{maxItems:0})},{additionalProperties:!1}),g.Object({status:g.Union([g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U,{minItems:1})},{additionalProperties:!1})]),type:"object",properties:{status:g.Union([g.Literal("success"),g.Literal("error"),g.Literal("partial")]),data:g.Optional(r),errors:g.Array(U)},required:["status","errors"],additionalProperties:!1}}i(ue,"structuredResultSchema");var de=1024*1024;function q(r){let e=new Set,t=i(n=>{if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");e.add(n);for(let o of Array.isArray(n)?n:Object.values(n))t(o);e.delete(n)}},"visit");if(t(r),Buffer.byteLength(JSON.stringify(r))>de)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}i(q,"assertJsonData");function le(r,e="EXECUTION_FAILED",t){return{code:typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:e,message:r instanceof Error?r.message:String(r),...t===void 0?{}:{source:t}}}i(le,"resultError");function Me(r,e,t){try{if(q(t),!Ve.Check(ue(e),t))throw new TypeError("Result adapter returned data outside its public schema");return{...r,structuredContent:t,isError:t.status!=="success"}}catch(n){let o=le(n,"INVALID_STRUCTURED_RESULT"),s={status:"error",errors:[o]};return q(s),{...r,content:[...r.content,{type:"text",text:o.message}],structuredContent:s,isError:!0}}}i(Me,"withStructuredResult");var J=class extends Error{constructor(t,n,o,s){if(!/^[A-Z][A-Z0-9_]*$/u.test(t))throw new TypeError("Invalid resource failure code");super(`${t}: ${n}`,s);this.code=t;this.source=n;this.effect=o;this.name="ResourceError"}static{i(this,"ResourceError")}};function Fe(r,e){if(e.length===0)return;let t=r.trim();if(t.length===0||/[\r\n]/u.test(t))throw new TypeError("Content provider summary must be one non-empty line");return[t,...e.map(({description:n})=>n)].join(`
2
+ `)}i(Fe,"renderContentDescription");import{Type as f}from"typebox";import{Value as Qe}from"typebox/value";import{Type as u}from"typebox";import{Value as ze}from"typebox/value";var C={additionalProperties:!0},j=u.Function([],u.Unknown()),v=u.String({minLength:1}),Be=u.Object({type:u.Literal("text"),text:u.String(),textSignature:u.Optional(u.String())},C),Ke=u.Object({type:u.Literal("image"),data:u.String(),mimeType:u.String()},C),qe=u.Object({type:u.Literal("custom"),kind:v,data:u.Unknown()},C),Je=u.Array(u.Union([Be,Ke,qe]),{minItems:1}),fe=u.Union([u.Object({source:v,link:u.Optional(v),read:j,write:u.Optional(u.Never())},C),u.Object({source:v,link:u.Optional(v),read:u.Optional(u.Never()),write:j},C),u.Object({source:v,link:u.Optional(v),read:j,write:j},C)]),Ye=u.Object({id:v,tryResolve:j},C),Ge=u.Union([u.Object({kind:u.Literal("not-handled")},C),u.Object({kind:u.Literal("resolved"),resource:fe},C),u.Object({kind:u.Literal("failed"),error:u.Unknown()},C)]);function Y(r){return L(Je,r)?D(()=>r.every(e=>e.type!=="text"||!("textSignature"in e)||typeof e.textSignature=="string")):!1}i(Y,"isAgentContent");function pe(r){return L(fe,r)?D(()=>{let e=r,t=!("read"in e)||typeof e.read=="function",n=!("write"in e)||typeof e.write=="function",o=!("readBytes"in e)||typeof e.readBytes=="function";return t&&n&&o}):!1}i(pe,"isResource");function Xe(r){return L(Ye,r)}i(Xe,"isResourceResolver");function Ze(r){return L(Ge,r)?D(()=>{let e=r;return e.kind!=="resolved"||pe(e.resource)}):!1}i(Ze,"isResourceResolutionAttempt");function L(r,e){return D(()=>ze.Check(r,e))}i(L,"safeCheck");function D(r){try{return r()}catch{return!1}}i(D,"safeEvaluate");var R={additionalProperties:!0},et=f.Function([],f.Unknown()),H=f.String({minLength:1}),tt=f.Object({provider:H,capability:f.Union([f.Literal("read"),f.Literal("write")])},R),rt=f.Object({source:H,bytes:f.Unknown(),mediaType:f.Optional(f.String())},R),nt=f.Object({signal:f.Optional(f.Unknown())},R),ot=f.Object({id:H,description:H,tryConvert:et},R),st=f.Union([f.Object({kind:f.Literal("not-handled")},R),f.Object({kind:f.Literal("converted"),content:f.Unknown()},R),f.Object({kind:f.Literal("failed"),error:f.Unknown()},R)]),it=f.Object({target:f.Unknown(),converter:f.Unknown(),priority:f.Optional(f.Number())},R);function O(r){return k(tt,r)&&E(()=>r.provider.trim().length>0)}i(O,"isContentTarget");function G(r){return k(rt,r)?E(()=>{let e=r;return e.bytes instanceof Uint8Array&&(!("mediaType"in e)||typeof e.mediaType=="string")}):!1}i(G,"isContentInput");function X(r){return k(nt,r)?E(()=>{let e=r;return!("signal"in e)||e.signal instanceof AbortSignal}):!1}i(X,"isContentConversionContext");function ge(r){return k(ot,r)?E(()=>{let e=r;return e.id.trim().length>0&&e.description.trim().length>0&&!/[\r\n]/u.test(e.description)}):!1}i(ge,"isContentConverter");function Z(r){return k(st,r)?E(()=>{let e=r;return e.kind!=="converted"||Y(e.content)}):!1}i(Z,"isContentConversionAttempt");function b(r){return k(it,r)?E(()=>{let e=r;return O(e.target)&&ge(e.converter)&&(!("priority"in e)||typeof e.priority=="number"&&Number.isFinite(e.priority))}):!1}i(b,"isContentConverterRegistration");function k(r,e){return E(()=>Qe.Check(r,e))}i(k,"safeCheck");function E(r){try{return r()}catch{return!1}}i(E,"safeEvaluate");var W=class extends Error{static{i(this,"UnsupportedContentError")}source;target;constructor(e,t){super(`No content converter for ${e} in ${t.provider}/${t.capability}`),this.name="UnsupportedContentError",this.source=e,this.target=t}};function ee(r){if(!O(r))throw new TypeError("Invalid content target");let e={...r},t=[],n=i(()=>[...t].sort((o,s)=>o.priority-s.priority||o.order-s.order),"snapshotConverters");return{target:e,register(o){if(!b(o))throw new TypeError("Invalid content converter registration");if(!x(e,o.target))throw new Error(`Content converter ${o.converter.id} targets ${o.target.provider}/${o.target.capability}, not ${e.provider}/${e.capability}`);if(t.some(({converter:s})=>s.id===o.converter.id))throw new Error(`Content converter ${o.converter.id} is already registered for ${e.provider}/${e.capability}`);t.push({converter:o.converter,priority:o.priority??0,order:t.length})},listDescriptions(){return n().map(({converter:o})=>({id:o.id,description:o.description}))},async convert(o,s){if(!G(o))throw new TypeError("Invalid content input");if(!X(s))throw new TypeError("Invalid content conversion context");Q(s.signal);let a=n();for(let{converter:d}of a){Q(s.signal);let c=await d.tryConvert(o,s);if(Q(s.signal),!Z(c))throw new TypeError(`Content converter ${d.id} returned an invalid outcome`);if(c.kind!=="not-handled"){if(c.kind==="failed")throw c.error;return c.content}}throw new W(o.source,e)}}}i(ee,"createContentRunner");function x(r,e){return r.provider===e.provider&&r.capability===e.capability}i(x,"targetsEqual");function Q(r){r?.throwIfAborted()}i(Q,"throwIfAborted");import{Type as w}from"typebox";import{Value as at}from"typebox/value";var N="pi-agent-resource/content-conversion",V=2,I=`${N}/host/ready`,_=`${N}/converter/register`,he={additionalProperties:!0},ct=w.Function([],w.Unknown()),ut=w.Object({protocol:w.Literal(N),apiVersion:w.Literal(V),target:w.Unknown()},he),dt=w.Object({registration:w.Unknown(),accept:ct},he);function te(r){return me(ut,r)&&ne(()=>O(r.target))}i(te,"isContentHostReady");function re(r){return me(dt,r)&&ne(()=>b(r.registration))}i(re,"isContentConverterRegistrationRequest");function me(r,e){return ne(()=>at.Check(r,e))}i(me,"safeCheck");function ne(r){try{return r()}catch{return!1}}i(ne,"safeEvaluate");var ye="pi-agent-resource:content-host-lookup";function lt(r,e){let t;if(r.events.emit(ye,{target:e,accept(c){if(t)throw new Error("Multiple content hosts registered for one target");t=c}}),t)return Ce(r,t),t.host;let n=ee(e),o=r.events.on(_,c=>{if(!re(c))throw new Error("Invalid content converter registration request");if(!x(n.target,c.registration.target))return;let p;try{n.register(c.registration),p=Promise.resolve()}catch(l){p=Promise.reject(l instanceof Error?l:new Error("Content converter registration failed",{cause:l}))}c.accept(p)}),s={target:n.target,listDescriptions(){return n.listDescriptions()},convert(c,p){return n.convert(c,p)}},a=r.events.on(ye,c=>{if(!ft(c))throw new Error("Invalid content host lookup request");x(e,c.target)&&c.accept(d)}),d={host:s,owners:new Set,unsubscribe(){o(),a()}};return Ce(r,d),r.events.emit(I,{protocol:N,apiVersion:V,target:n.target}),s}i(lt,"createContentHost");function ft(r){return typeof r=="object"&&r!==null&&"target"in r&&typeof r.target=="object"&&r.target!==null&&"provider"in r.target&&typeof r.target.provider=="string"&&"capability"in r.target&&typeof r.target.capability=="string"&&"accept"in r&&typeof r.accept=="function"}i(ft,"isHostLookup");function Ce(r,e){e.owners.has(r)||(e.owners.add(r),r.on("session_shutdown",()=>{e.owners.delete(r),e.owners.size===0&&e.unsubscribe()}))}i(Ce,"retainOwner");function pt(r,e){if(!b(e))throw new TypeError("Invalid content converter registration");let t=i(()=>{let s,a={registration:e,accept(d){if(s!==void 0)throw new Error(`Content converter ${e.converter.id} registration was accepted more than once`);s=d}};return r.events.emit(_,a),s},"announce"),n=i(()=>{},"unsubscribe");n=r.events.on(I,s=>{if(!te(s))throw new Error("Invalid content conversion host readiness event");if(!x(e.target,s.target))return;let a=t();if(a===void 0)throw new Error(`${s.target.provider}/${s.target.capability} announced readiness without accepting content converter ${e.converter.id}`);n(),a.catch(()=>{})}),r.on("session_shutdown",n);let o=t();if(o!==void 0)return n(),o}i(pt,"connectContentConverter");import{createHash as ve,randomUUID as oe}from"node:crypto";import{statSync as gt}from"node:fs";import{readFile as ht}from"node:fs/promises";import T from"node:path";import{fileURLToPath as mt}from"node:url";import{Type as M}from"typebox";var yt=M.Union([M.String(),M.Array(M.String())]),A="RESULT#",Re="pi-agent-resource:result-targets",z=class{static{i(this,"ResultTargetStore")}#e=new Map;#n=new Map;#o=new Map;#t=new Map;clear(){this.#e.clear(),this.#n.clear(),this.#o.clear(),this.#t.clear()}register(e,t,n=!0){for(let s of e)this.refresh(s.source,t);let o=`${A}${oe()}`;return this.#e.set(o,{state:"ready",targets:se(e),complete:n,cwd:T.resolve(t)}),o}reserve(e){let t=`${A}${oe()}`;return this.#e.set(t,{state:"pending",cwd:T.resolve(e)}),t}confirm(e,t,n){let o=this.#e.get(e);if(o?.state!=="pending"||o.cwd!==T.resolve(n))throw new Error("Only a pending result in this worktree can be confirmed.");for(let s of t)this.refresh(s.source,n);this.#e.set(e,{state:"ready",cwd:o.cwd,targets:se(t),complete:!0})}reject(e,t){let n=this.#e.get(e);n?.state==="pending"&&this.#e.set(e,{state:"rejected",cwd:n.cwd,reason:t})}resolve(e,t){e=this.source(e,t);let n=this.#r(e),o=[],s=!0;for(let a of n){let d=this.#e.get(a);if(d===void 0)throw new Error("Result target expired or unknown; repeat Read/Search.");if(d.cwd!==T.resolve(t))throw new Error("Result target belongs to another worktree.");if(d.state==="pending")throw new Error("Result target is pending; its write has not been confirmed.");if(d.state==="rejected")throw new Error(d.reason);for(let c of d.targets)this.refresh(c.source,t);if(!this.#e.has(a))throw new Error("Result target expired after its snapshot changed; repeat Read/Search.");s&&=d.complete,o.push(...d.targets)}return{targets:se(o),complete:s}}resolveOrdered(e,t){let n=this.resolve(e,t),o=[],s=new Set;for(let a of new Set(this.#r(this.source(e,t))))for(let d of this.resolve(a,t).targets)for(let c of d.ranges){let p=JSON.stringify([d.source,c]);s.has(p)||(s.add(p),o.push({...d,ranges:[c]}))}return{targets:o,complete:n.complete}}async verify(e,t){try{await we(e,t)}catch(n){if(!t?.aborted)for(let o of e.targets)this.invalidate(o.source);throw n}}registerSearchReference(e,t,n){if(!/^SEARCH#[A-F\d]{4,64}:[1-9]\d*:(line|match)$/u.test(e))throw new Error("Only numbered Search references can alias a snapshot.");if(!this.#e.has(t))throw new Error("A Search reference needs a registered result target.");this.resolve(t,n),this.#n.set(e,t)}publish(e,t,n,o=[]){let s=oe();for(let p of o)this.refresh(p,n);let a=[];try{a=this.#r(e)}catch{}let d=`<system-result note="Internal reference; not part of the file. Do not edit."><uuid>${s}</uuid></system-result>
3
+ ${t}`,c=e!==null&&typeof e=="object"&&"status"in e&&e.status==="success";if(c&&"data"in e){let p=e.data;if(p!==null&&typeof p=="object"&&"matches"in p&&Array.isArray(p.matches)){let l=p.matches;for(let h of l){if(h===null||typeof h!="object"||!("target"in h)||typeof h.target!="string"||!this.#e.has(h.target)||!("references"in h))continue;let m=h.references;m!==null&&typeof m=="object"&&"match"in m&&typeof m.match=="string"&&/^SEARCH#[A-F\d]+:\d+:match$/u.test(m.match)&&this.#n.set(m.match,h.target)}}}return this.#t.set(s,{cwd:T.resolve(n),digest:ve("sha256").update(d).digest("hex"),consumable:c,references:a,resources:o}),d}source(e,t,n=!1){if(Array.isArray(e))return e.map(l=>this.source(l,t,n));if(typeof e!="string")return e;let o=this.#n.get(e);if(o)return this.source(o,t,n);let s=/^<system-result\b[^>]*><uuid>([a-f\d-]{36})<\/uuid><\/system-result>(?:\n|$)/u.exec(e),a=s?.[1]??(e.startsWith(A)?e.slice(A.length):e),d=/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/u.test(a);if(!s&&!d){if(e.startsWith("<system-result"))throw new Error("Invalid system result reference.");return e}let c=this.#t.get(a);if(!c&&!s&&e.startsWith(A)&&this.#e.has(e))return e;if(!c)throw new Error("Result reference expired or unknown. Run Read/Search again and use the new result.");if(c.cwd!==T.resolve(t))throw new Error("Result belongs to another worktree.");if(s&&ve("sha256").update(e).digest("hex")!==c.digest)throw new Error("Result text changed; pass the original result or its UUID.");for(let l of c.resources)this.refresh(l,t);if(!this.#t.has(a))throw new Error("Result reference expired. Run Read/Search again and use the new result.");if(!c.consumable)throw new Error("Only successful source results can be consumed.");for(let l of c.references)if(!this.#e.has(l))throw this.#t.delete(a),new Error("Result reference expired. Run Read/Search again and use the new result.");if(c.references.length===1)return c.references[0];if(c.references.length>1)return c.references;let p=c.resources.length===1?c.resources[0]:void 0;if(p&&(n===!0||n==="live"&&/^(?:shell|debug):/u.test(p)))return p;throw new Error("This result has no reusable text selection.")}invalidate(e){let t=new Set;for(let[n,o]of this.#e)o.state==="ready"&&o.targets.some(s=>F(s.source,o.cwd)===e)&&(this.#e.delete(n),t.add(n));for(let[n,o]of this.#t)(o.resources.some(s=>F(s,o.cwd)===e)||o.references.some(s=>t.has(s)))&&this.#t.delete(n)}refresh(e,t){let n=F(e,t),o=JSON.stringify([T.resolve(t),n]),s=Ct(e,t),a=this.#o.get(o);a&&a.stamp!==s&&this.invalidate(n),this.#o.set(o,{source:e,cwd:t,stamp:s})}refreshAll(){for(let e of[...this.#o.values()])this.refresh(e.source,e.cwd)}#r(e){if(typeof e=="string"&&e.startsWith(A))return[e];if(Array.isArray(e))return e.flatMap(n=>this.#r(n));if(e===null||typeof e!="object")throw new Error("Unsupported result input.");let t=e;if("status"in t){if(t.status!=="success")throw new Error("Only successful source results can be consumed.");return this.#r(t.data)}if(typeof t.target=="string"&&t.target.startsWith(A))return[t.target];if(t.kind==="resources"&&Array.isArray(t.resources))return this.#r(t.resources);throw new Error("This result has no supported source target; do not use preview text as a source.")}};function F(r,e){let t=r.startsWith("raw:")?r.slice(4):r;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(t)&&!t.startsWith("file:"))return t;if(t.startsWith("file:"))try{return mt(t)}catch{}return T.resolve(e,t)}i(F,"sourcePath");function Ct(r,e){try{let t=gt(F(r,e),{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}i(Ct,"fileStamp");async function we(r,e){let t=new Map;for(let n of r.targets){e?.throwIfAborted();let o=t.get(n.source);if(o===void 0&&(o=n.readCurrent===void 0?await ht(n.source,{encoding:"utf8",signal:e}):await n.readCurrent(e),e?.throwIfAborted(),t.set(n.source,o)),o!==n.expectedContent)throw new Error("Result target is stale; repeat Read/Search.")}}i(we,"verifyResultTargets");function se(r){let e=new Map;for(let t of r){let n=e.get(t.source);if(n!==void 0&&n.expectedContent!==t.expectedContent)throw new Error("Result targets refer to different snapshots of the same source.");let o=n??{source:t.source,expectedContent:t.expectedContent,...t.readCurrent===void 0?{}:{readCurrent:t.readCurrent},ranges:[],seen:new Set};for(let s of t.ranges){let a=JSON.stringify(s);o.seen.has(a)||(o.seen.add(a),o.ranges.push(structuredClone(s)))}e.set(t.source,o)}return[...e.values()].filter(t=>t.ranges.length>0).map(({seen:t,...n})=>({...n,ranges:n.ranges.sort((o,s)=>o.start.lineNumber-s.start.lineNumber||o.start.column-s.start.column||o.end.lineNumber-s.end.lineNumber||o.end.column-s.end.column)}))}i(se,"combineTargets");function vt(r){let e;if(r.events.emit(Re,{accept:i(o=>{e=o},"accept")}),e!==void 0)return e;let t=new z,n=r.events.on(Re,o=>{o!==null&&typeof o=="object"&&"accept"in o&&typeof o.accept=="function"&&o.accept(t)});return r.on("session_start",()=>{t.clear()}),r.on("session_shutdown",()=>{t.clear(),n()}),t}i(vt,"connectResultTargets");export{$ as a,Ne as b,ae as c,K as d,U as e,ue as f,de as g,q as h,le as i,Me as j,J as k,Fe as l,Y as m,pe as n,Xe as o,Ze as p,O as q,G as r,X as s,ge as t,Z as u,b as v,W as w,ee as x,x as y,N as z,V as A,I as B,_ as C,te as D,re as E,lt as F,pt as G,yt as H,z as I,we as J,vt as K};
@@ -0,0 +1 @@
1
+ import{a as f,b as u}from"./chunk-JKMXND6V.js";import{g as o}from"./chunk-4HWKBCBH.js";import{b as w}from"./chunk-VDP5CQHM.js";import{a as d}from"./chunk-EI7MMDWY.js";import{readFile as R}from"node:fs/promises";import{Type as i}from"typebox";import{Value as g}from"typebox/value";var y=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()}),b=new Set(["INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED"]),m;async function S(n,s,t,c){c?.throwIfAborted(),m??=R(new URL("./web-http-worker.py",new URL("../src/backend/web-http.ts",import.meta.url).href),"utf8");try{let e=await f(n,"python3",["-c",await m,JSON.stringify({url:s.href,timeoutSeconds:30})],t,{signal:c,timeoutMs:3e4,maxBytes:33554432});if(e.exitCode!==0)throw new o("HTTP_FAILED",t,"not-applied");let r;try{r=JSON.parse(e.stdout.toString("utf8"))}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}if(typeof r=="object"&&r!==null&&"error"in r)throw new o(typeof r.error=="string"&&b.has(r.error)?r.error:"INVALID_RESPONSE",t,"not-applied");if(!g.Check(y,r))throw new o("INVALID_RESPONSE",t,"not-applied");let h=Buffer.from(r.body,"base64");if(h.toString("base64")!==r.body||h.length>16*1024*1024)throw new o("INVALID_RESPONSE",t,"not-applied");let a;try{let p=new URL(r.url);if(!["http:","https:"].includes(p.protocol)||p.username||p.password)throw new Error("Invalid native HTTP redirect");a=new Response([204,205,304].includes(r.status)?null:h,{status:r.status,statusText:r.statusText,headers:r.headers}),Object.defineProperty(a,"url",{value:p.href})}catch{throw new o("INVALID_RESPONSE",t,"not-applied")}return a}catch(e){throw e instanceof o?new o(e.code,t,e.effect):e}}d(S,"fetchSshWebResponse");function I(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 t;try{t=new URL(s[2])}catch{throw new o("INVALID_SOURCE",n,"not-applied")}if(t.username||t.password)throw new o("INVALID_SOURCE",n,"not-applied");return{target:s[1],url:t,source:`web:ssh://${s[1]}/${t.href}`}}d(I,"parseSshWebSource");function D(n,s){return{id:"ssh-web",async tryResolve(t,c){try{let e=I(t);if(!e)return{kind:"not-handled"};c.signal?.throwIfAborted();let r=s.resolve(`ssh://${e.target}/`);if(!r)throw new o("UNSUPPORTED_SOURCE",e.source,"not-applied");let a=await w(n,{fetch:d(async(p,l)=>S(r.backend.target,e.url,e.source,l?.signal??void 0),"fetch"),browser:{load(p,l){return u(r.backend.target,p,e.source,l)}}}).tryResolve(e.url.href,c);return a.kind!=="resolved"?a:{kind:"resolved",resource:{...a.resource,source:e.source}}}catch(e){return{kind:"failed",error:e instanceof o?new o(e.code,t,e.effect):e}}}}}d(D,"createSshWebResolver");export{I as a,D as b};
@@ -1,2 +1,2 @@
1
- import{d as R}from"./chunk-ZIWPKIBZ.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as T}from"@earendil-works/pi-coding-agent";import{Text as $}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,C=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
1
+ import{d as R}from"./chunk-D4IA2MTA.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as T}from"@earendil-works/pi-coding-agent";import{Text as $}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,C=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
2
2
  `)),k.set(e.details,a)),e={...e,details:a}}if(r.isPartial||t.isError||!R(e.details)){let a=e.content[0],n=a?.type==="text"?a.text:"",i=t.isError?"error":r.isPartial?"dim":"toolOutput";return new $(o.fg(i,n),0,0)}let l=(t.lastComponent instanceof m?t.lastComponent:void 0)??new m(e.details,o,r.expanded);return l.updateSearch(e.details,o,r.expanded),l}c(v,"renderSearchResult");var m=class extends S{static{c(this,"SearchResultPanel")}constructor(r,o,t){super(z(r,t),o,t)}updateSearch(r,o,t){super.update(z(r,t),o,t)}};function z(e,r){let o=D(e,r).map(t=>t.kind==="file"?{kind:"source",label:t.file.path,link:t.file.link,count:t.file.matchCount}:t.kind==="line"?{kind:"line",...t.line}:t.kind==="candidate"?{kind:"note",text:t.identifier}:t.kind==="summary"?{kind:"note",text:t.text}:t.kind==="omitted"?{kind:"note",text:`\u2026 ${t.matches} more ${d(t.matches,"match","matches")} \xB7 ${T("app.tools.expand")} to expand`}:{kind:"note",text:"No matches found"});return{summary:P(e),rows:o}}c(z,"searchModel");function D(e,r){let o=e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0,t=e.files.length===0?o?[]:[{kind:"empty"}]:e.files.flatMap(n=>[{kind:"file",file:n},...n.uniqueLineCount===void 0?n.lines.map(i=>({kind:"line",file:n,line:i})):[{kind:"summary",text:`${String(n.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(n.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(e.fuzzy!==void 0&&(e.fuzzy.status==="skipped"?t.push({kind:"summary",text:"Fuzzy search unavailable"}):e.fuzzy.candidates.length>0&&t.push(...e.fuzzy.candidates.flatMap(n=>{let i=e.fuzzyPresentation?.groups.find(u=>u.identifier===n.identifier)?.files??[],h=i.reduce((u,f)=>u+f.matchCount,0);return[{kind:"candidate",identifier:n.identifier},...i.length===0?[]:[{kind:"summary",text:`Shown ${String(h)} of ${String(n.matchCount)}${n.selection.complete?"":"+"}`},...i.flatMap(u=>[{kind:"file",file:u},...u.lines.map(f=>({kind:"line",file:u,line:f}))])]]}))),(e.omittedFileCount??0)>0&&t.push({kind:"summary",text:`\u2026 ${e.omittedFileCount} more files (${e.omittedMatchCount} matches) \xB7 narrow path, include, or query`}),e.fuzzy!==void 0||r||t.length<=C)return t;let s=t.slice(0,C-1);for(;s.at(-1)?.kind==="file";)s.pop();let l=new Set(s.flatMap(n=>n.kind==="line"?n.line.logicalMatchIds??[]:[])),a=l.size>0?l.size:s.reduce((n,i)=>n+(i.kind==="line"?i.line.matchCount:0),0);return[...s,{kind:"omitted",matches:Math.max(0,e.matchCount-a)}]}c(D,"searchViewport");function P(e){if(e.matchCount===0&&e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0&&e.fuzzyPresentation!==void 0){let o=e.fuzzy.candidates.reduce((l,a)=>l+a.matchCount,0),t=e.fuzzy.candidates.every(l=>l.selection.complete)?"":"+",s=e.fuzzyPresentation.fileCount;return`0 exact \xB7 ${String(o)}${t} fuzzy ${d(o,"match","matches")} \xB7 ${String(s)}${t} ${d(s,"file","files")}`}return e.matchCount===0?e.complete?"No matches":"No matches \xB7 incomplete":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${d(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${d(e.fileCount,"file","files")}`}c(P,"searchSummary");function d(e,r,o){return e===1?r:o}c(d,"plural");export{w as a,v as b,m as c};
@@ -0,0 +1 @@
1
+ import{a as u,g as p}from"./chunk-4HWKBCBH.js";import{a as S}from"./chunk-BXGMMZT3.js";import{a as l}from"./chunk-EI7MMDWY.js";import d from"node:path";function k(m,n){return{async paths(i,s,a=n){a?.throwIfAborted();let r=m.resolve(i);if(!r)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");let f=await r.backend.execute("python3",["-c","import json,os;print(json.dumps({'home':os.environ.get('HOME',''),'agent':os.environ.get('PI_CODING_AGENT_DIR','')}))"],r.location.path,{signal:a});if(f.exitCode!==0)throw new p("CONFIG_ENVIRONMENT_FAILED",i,"not-applied");let o=JSON.parse(f.stdout.toString("utf8"));if(typeof o!="object"||o===null||!("home"in o)||!("agent"in o)||typeof o.home!="string"||typeof o.agent!="string"||!o.home.startsWith("/"))throw new TypeError("Invalid remote configuration environment");let c=o.agent.trim()?d.posix.resolve(r.location.path,o.agent.trim()):d.posix.join(o.home,".pi","agent");return{project:u(r.location.target,d.posix.join(r.location.path,".pi","pi-agent-ide",`${s}.json`)).source,global:u(r.location.target,d.posix.join(c,"extensions","pi-agent-ide",`${s}.json`)).source}},async readText(i,s=n){s?.throwIfAborted();let a=m.resolve(i);if(!a)throw new p("UNSUPPORTED_SOURCE",i,"not-applied");return(await a.backend.read(a.location.path,{signal:s})).bytes.toString("utf8")}}}l(k,"createSshToolConfigAccess");import{readFile as E}from"node:fs/promises";import g from"node:path";import{Type as t}from"typebox";import{Value as y}from"typebox/value";var w=t.Object({content:t.Record(t.String(),t.Union([t.String(),t.Null()])),markers:t.Record(t.String(),t.Boolean()),names:t.Array(t.String())});async function U(m,n,i,s){s?.throwIfAborted();let a=[...new Set(["package.json",...i.flatMap(e=>Object.keys(e.configSections??{}))])],r=[...new Set(i.flatMap(e=>e.configFiles??[]))];for(let e of[...a,...r]){let h=g.posix.relative(n,g.posix.resolve(n,e));if(h===".."||h.startsWith("../")||g.posix.isAbsolute(e))throw new p("UNSUPPORTED_SOURCE",n,"not-applied")}let f=await E(new URL("./recipe-evidence-worker.py",new URL("../src/backend/recipe-evidence.ts",import.meta.url).href),{encoding:"utf8",signal:s}),o=await m.execute("python3",["-c",f,n,JSON.stringify({files:a,markers:r.filter(e=>!e.includes("*")),listNames:r.some(e=>e.includes("*"))})],n,{signal:s});if(o.exitCode!==0)throw new p("EVIDENCE_FAILED",n,"not-applied");let c=JSON.parse(o.stdout.toString("utf8"));if(y.Check(t.Object({error:t.Literal("CONTENT_LIMIT")}),c))throw new p("CONTENT_LIMIT",n,"not-applied");if(!y.Check(w,c))throw new p("INVALID_RESPONSE",n,"not-applied");return S(n,i,{readText:l(e=>Promise.resolve(c.content[e]??void 0),"readText"),hasMarker:l(e=>Promise.resolve(e.includes("*")?c.names.some(h=>g.matchesGlob(h,e)):c.markers[e]===!0),"hasMarker")},s)}l(U,"inspectSshRecipeEvidence");export{k as a,U as b};
@@ -0,0 +1 @@
1
+ import{b as n}from"./chunk-E2PHA4SQ.js";import"./chunk-JKMXND6V.js";import"./chunk-WXGTU2M6.js";import{a as o,b as t,c as i}from"./chunk-LLRUJD62.js";import"./chunk-Q5X6OXNS.js";import"./chunk-4HWKBCBH.js";import{b as s}from"./chunk-AIT3YWR5.js";import"./chunk-VDP5CQHM.js";import"./chunk-47SPPIXK.js";import"./chunk-VAXLSPPU.js";import"./chunk-OI3HBIPK.js";import"./chunk-YTYLS2UM.js";import{c as r}from"./chunk-W7CASEO3.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-NNCZYO4Q.js";import"./chunk-IICJXZBU.js";import"./chunk-PS2B6THP.js";import"./chunk-BU7IZLKB.js";import"./chunk-S5PL5DFQ.js";import"./chunk-DXONCYWF.js";import"./chunk-ZPT5D4VP.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as e}from"./chunk-EI7MMDWY.js";async function g(a){let m=new i(await t(o(r())));await s(a,f=>n(f,m))}e(g,"registerOwnedWeb");export{g as default};
@@ -0,0 +1 @@
1
+ import{a as _}from"./chunk-7LOVUWNI.js";import{a as A}from"./chunk-WPBQ45ZL.js";import{a as W,g as n}from"./chunk-4HWKBCBH.js";import{a as u}from"./chunk-EI7MMDWY.js";import{Writable as M}from"node:stream";import{callbackify as N}from"node:util";import{fileURLToPath as $,pathToFileURL as G}from"node:url";import{readFile as x}from"node:fs/promises";import U from"node:path";import{createInterface as H}from"node:readline";import{fileURLToPath as j}from"node:url";import{Type as i}from"typebox";import{Value as B}from"typebox/value";var V=i.Union([i.Object({kind:i.Literal("ready")}),i.Object({kind:i.Literal("change"),path:i.String(),type:i.Union([i.Literal(1),i.Literal(2),i.Literal(3)])}),i.Object({kind:i.Literal("error"),code:i.Union([i.Literal("WATCH_FAILED"),i.Literal("WATCH_LIMIT"),i.Literal("WATCH_OVERFLOW")])})]);function J(h,s){let c=U.posix.relative(h,s);return c===""||c!==".."&&!c.startsWith("../")&&!U.posix.isAbsolute(c)}u(J,"inside");function I(h,s,c,e){let r=h.resolve(s);if(!r)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");let d=!1,m=new Map,l=new Set,P=u(o=>d||o.closed,"closed"),p=u(o=>(o.closed=!0,o.channel&&(o.stopping??=o.channel.stop().then(()=>{})),o.stopping??Promise.resolve()),"release"),y={async register(o,w){if(d)throw new n("WATCH_DISPOSED",s,"not-applied");let E=w.map(L=>{let f=L.globPattern,S=typeof f=="string"?s:typeof f.baseUri=="string"?f.baseUri:f.baseUri.uri,g=S.startsWith("file://")?W(r.location.target,j(S)).source:S,v=h.resolve(g);if(!v||v.location.target!==r.location.target)throw new n("UNSUPPORTED_SOURCE",g,"not-applied");let O=L.kind??7;if(!Number.isInteger(O)||O<0||O>7)throw new TypeError("Invalid file watcher event mask");return{root:v.location.path,expression:typeof f=="string"?f:f.pattern,kind:O}});if(E.length===0){await y.unregister(o);return}let t={id:o,closed:!1,starting:Promise.resolve()};l.add(t),t.starting=(async()=>{let L=await x(new URL("./file-watch-worker.py",new URL("../src/backend/lsp-file-watchers.ts",import.meta.url).href),"utf8");if(P(t))throw new n("WATCH_DISPOSED",s,"not-applied");let f=await r.backend.startProcess("python3",["-u","-c",L,JSON.stringify([...new Set(E.map(k=>k.root))])],r.location.path);if(t.channel=f,f.stderr.resume(),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let S=H({input:f.stdout}),g=!1,v=!1;if(await new Promise((k,b)=>{let R=u(C=>{if(v||t.closed)return;v=!0;let a=new n(C,s,"not-applied");g?e(a):b(a),p(t).catch(e)},"fail");S.on("line",C=>{if(t.closed)return;let a;try{a=JSON.parse(C)}catch{R("INVALID_RESPONSE");return}if(!B.Check(V,a)){R("INVALID_RESPONSE");return}if(a.kind==="ready"){g=!0,k();return}if(a.kind==="error"){R(a.code);return}if(!g){R("INVALID_RESPONSE");return}if(m.get(o)!==t)return;E.some(T=>{if(!J(T.root,a.path))return!1;let F=U.posix.relative(T.root,a.path);return(T.kind&(a.type===1?1:a.type===2?2:4))!==0&&U.matchesGlob(U.posix.isAbsolute(T.expression)?a.path:F,T.expression)})&&c({uri:W(r.location.target,a.path).source,type:a.type})}),f.completion.then(()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))},()=>{S.close(),g?t.closed||R("WATCH_FAILED"):b(new n("WATCH_FAILED",s,"not-applied"))})}),P(t))throw await p(t),new n("WATCH_DISPOSED",s,"not-applied");let D=m.get(o);m.set(o,t),D&&await p(D)})();try{await t.starting}catch(L){throw await p(t),L}finally{l.delete(t)}},async unregister(o){let w=m.get(o);m.delete(o);let E=[...l].filter(t=>t.id===o);await Promise.all([...E,...w?[w]:[]].map(p)),await Promise.allSettled(E.map(t=>t.starting))},async dispose(){d=!0;let o=new Set([...m.keys(),...[...l].map(w=>w.id)]);await Promise.all([...o].map(w=>y.unregister(w)))}};return y}u(I,"createSshLspFileWatchers");function he(h,s){let c=h.resolve(s);if(!c)throw new n("UNSUPPORTED_SOURCE",s,"not-applied");return{async start(e){let r=h.resolve(e.rootUri);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e.rootUri,"not-applied");let d=e.command.map(p=>p.replaceAll("{project}",r.location.path));if(!d[0])throw new TypeError("Language server command is empty");let m=Object.entries(await A(r.backend,r.location.path,e.env,e.signal)).map(([p,y])=>`${p}=${y}`),l=await r.backend.startProcess("env",[...m,...d],r.location.path,{signal:e.signal}),P=new M({write:N(async(p,y)=>{await l.write(p)}),final:N(async()=>{await l.end()})});return{stdin:P,stdout:l.stdout,stderr:l.stderr,completion:l.completion,remote:{target:r.location.target,pid:l.pid},async stop(){try{await _(l,h,e.rootUri)}finally{P.destroy()}}}},fileWatchers(e,r,d){let m=h.resolve(e);if(!m||m.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return I(h,e,r,d)},toServerUri(e){if(!e.startsWith("ssh://")){if(e.startsWith("file://"))throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return e}let r=h.resolve(e);if(!r||r.location.target!==c.location.target)throw new n("UNSUPPORTED_SOURCE",e,"not-applied");return G(r.location.path).href},fromServerUri(e){return e.startsWith("file://")?W(c.location.target,$(e)).source:e}}}u(he,"createSshLspTransport");export{he as a};
@@ -0,0 +1,11 @@
1
+ import{d as M,h as N}from"./chunk-XH5WN5XA.js";import{a as _}from"./chunk-PRLIHLCS.js";import{h as w,i as P,j as B}from"./chunk-DXONCYWF.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as D}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as H,parse as W}from"partial-json";function O(o,e=H.ALL){if(!(!o||o.trim().length===0))try{let t=W(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(O,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),s=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),i=e.filterEntries?.(s,t)??s,d=new Set(i.map(c=>c.index));for(let c of s)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of i)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as U}from"@earendil-works/pi-ai";var K=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function $(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((s,i)=>{if(!s)return;let d=i.modelRegistry.getProvider(s.provider);if(!d)return;let u=r.get(s.provider);if(u){if(u.subscribers.add(a),u.api===s.api&&d.streamSimple===u.wrapper)return;u.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:u.wrapper});return}let m=d.streamSimple[K];if(m){if(m.subscribers.add(a),r.set(s.provider,m),m.api===s.api)return;m.api=s.api;let p=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...p,api:s.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,C,v)=>Q(c,p,C,v,g),"wrapper"),I={api:s.api,delegate:c,wrapper:b,subscribers:g};b[K]=I;let h=i.modelRegistry.getRegisteredProviderConfig(s.provider);o.registerProvider(s.provider,{...h,api:s.api,streamSimple:b}),r.set(s.provider,I)},"install");o.on("before_provider_request",(s,i)=>{a.context=i,l(i.model,i)}),o.on("turn_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("agent_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("session_start",(s,i)=>{a.context=i,l(i.model,i)}),o.on("model_select",(s,i)=>{a.context=i,l(s.model,i)}),o.on("session_shutdown",()=>{for(let[s,i]of r)i.subscribers.delete(a),i.subscribers.size===0&&o.unregisterProvider(s);r.clear(),a.context=void 0})}y($,"registerStreamingInterceptorProvider");function Q(o,e,t,n,r){let a=U(),l=new AbortController,s=n?.signal,i=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),I=y(()=>{l.abort()},"abortFromParent");return s&&(s.aborted?l.abort():s.addEventListener("abort",I,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(i)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),q(p,u);let C;for(let v of r){let x=v.context;if(x){let T=await v.processStreamEvent(p,x);C??=T}}if(b(p),J(p,m,c,g),a.push(structuredClone(p)),C){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let E of r)E.finalizeStreamInterception(p.contentIndex);i=!0,l.abort();let v=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,x={...d,content:d.content.filter((E,A)=>u.has(A)&&(v===void 0||A<=v||g.has(A))).map(E=>E.type==="toolCall"&&E.id===C.toolCallId?{...E,arguments:structuredClone(C.arguments)}:E)};V(a,b,x,u,m,c,g);let{errorMessage:T,...F}=x;a.push({type:"done",reason:"toolUse",message:{...F,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(i)return;let p=d,C=s?.aborted===!0?"aborted":"error",v={...p,stopReason:C,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:C,error:v}),a.end()}finally{s?.removeEventListener("abort",I)}})(),a}y(Q,"wrapStream");function q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(q,"rememberStartEvent");function J(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(J,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[s,i]of t.content.entries())if(n.has(s)){if(i.type==="text"&&!r.has(s)){let d={type:"text_end",contentIndex:s,content:i.text,partial:t};e(d),o.push(d)}else if(i.type==="thinking"&&!a.has(s)){let d={type:"thinking_end",contentIndex:s,content:i.thinking,partial:t};e(d),o.push(d)}else if(i.type==="toolCall"&&!l.has(s)){let d={type:"toolcall_end",contentIndex:s,toolCall:i,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Y,"emptyAssistantMessage");var X="agentic-ide-partial-tool-recovery",z="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
2
+ `)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",s=r.content.flatMap(i=>i.type==="text"?[i.text]:[]).join(`
3
+ `);return B({content:r.content,details:a},_(t.toolName),{status:"error",errors:[P(s,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role==="toolResult"){let r=this.toolCallRecords.get(t.message.toolCallId),a=r?.blockExecution?r.guardResult:void 0;if(a){this.toolCallRecords.delete(t.message.toolCallId);let l=a.details;l!==void 0&&w(l);let s=this.toolCallBatchEntryIndexes.get(t.message.toolCallId);return s!==void 0&&this.completedBatchEntryIndexes.add(s),{message:{...t.message,content:a.content,...l!==void 0&&{details:l},isError:!0}}}}if(t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=O(a,D.OBJ|D.ARR)??{},s=te(a),i=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:i,toolName:n,args:l,complete:s!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!s&&Object.keys(l).length===0)return;let u=s!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=s??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:i,batchEntries:this.getBatchEntries(i),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let s=!this.completeArgumentContentIndices.has(e.contentIndex),i;s&&(this.completeArgumentContentIndices.add(e.contentIndex),i=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),i}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(z,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=ee(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let s={content:[{type:"text",text:e.message.content}],details:M(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:s,...r&&{blockExecution:!0}}),s}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,i=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(i))for(let d of i)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,s=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],i=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:s,blockedToolCallIds:i,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?oe(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function j(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(j,"toolStreamEventKey");function ee(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(ee,"abortReason");function te(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(te,"parseCompleteArguments");function ne(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(i=>f.IsObjectNotArray(i.data)?i.data:i),a=n===void 0?r:r.filter(i=>i.path===n),s=(a.length>0?a:r).flatMap(i=>{let d=i.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(s)]}y(ne,"freshAnchorsAfterRecovery");function re(o,e){let n=o.indexOf(`
4
+
5
+ Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
6
+
7
+ Current nearby anchors:
8
+ ${e.map(a=>` ${a}`).join(`
9
+ `)}`}y(re,"replaceCurrentAnchors");function oe(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(u=>`${u.index} (${u.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=ne(e),s=l.length>0&&f.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,i=l.length>0?re(o.message.content,l):o.message.content,d=l.length>0&&f.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:X,content:`${i}
10
+
11
+ [RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:s,recovery:d}}}}y(oe,"makeRecoveryResult");var G=new WeakMap;function L(o){let e=G.get(o);if(e)return e;let t=new k(o);return G.set(o,t),$(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(L,"coordinatorFor");function ae(o,e){L(o).register(e)}y(ae,"registerToolCallInterceptor");function se(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on(z,n=>{!f.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!N(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(se,"registerToolCallAnnotationSink");function xe(o,e){L(o).registerBlockedCallSink(e)}y(xe,"registerBlockedToolCallSink");export{ae as a,se as b,xe as c};
@@ -0,0 +1,9 @@
1
+ import{a as Ae}from"./chunk-N56WAVYA.js";import{a as Ee}from"./chunk-HCK7OIQ3.js";import"./chunk-7LOVUWNI.js";import{a as Ie,b as Re}from"./chunk-GEMDU6XW.js";import{b as Ce}from"./chunk-WPBQ45ZL.js";import{a as xe}from"./chunk-2ITKAXHO.js";import{a as X,d as ke}from"./chunk-JKMXND6V.js";import"./chunk-BQAKA3FU.js";import"./chunk-WXGTU2M6.js";import{a as Pe,b as Se,c as Oe}from"./chunk-LLRUJD62.js";import{a as De}from"./chunk-Q5X6OXNS.js";import{a as K,g as D}from"./chunk-4HWKBCBH.js";import{c as ve}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-DXONCYWF.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as ue,b as fe,c as ge}from"./chunk-57F5GTHO.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(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 Ke(le(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:p}=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,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=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,p,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:p}=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,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(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 Qe(n,i,{encoding:"utf8",signal:e}),!0)}s(q,"writeJson");function je(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(je,"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(p=>{V(p,i,r.id,"language",()=>e)},"addLanguage"),addToolRecipe:s(p=>{V(p,a,r.id,"tool recipe",()=>e)},"addToolRecipe"),addSetupCheck:s(p=>{V(p,u,r.id,"setup check",()=>e)},"addSetupCheck"),addCheck:s(p=>{V(p,f,r.id,"check",()=>e)},"addCheck")};try{await r.setup(h)}finally{e=!1}$e(this.languages,i,"language"),$e(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 Ne(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(Ne,"runContributedSetupChecks");async function Le(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(Le,"runContributedChecks");function $e(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($e,"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 st from"node:path";import{readFile as Ze}from"node:fs/promises";async function _e(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 de(n,u,void 0,e),h=await et(n,e,i),p=[...new Set(u.flatMap(g=>g.executables))],m=i?await i.executableAvailability(p.map(g=>({command:[g]})),e):void 0;if(e?.throwIfAborted(),m&&(m.length!==p.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 c=b?.dependency;c!==void 0&&(I+=4,C.push(`project dependency: ${c}`));let d=m?y.executables.find(l=>m[p.indexOf(l)]===!0):await qe(n,y.executables,o,e);d!==void 0&&(I+=3,C.push(`executable: ${d}`)),w.push({pluginId:g.pluginId,recipe:y,score:I,evidence:C,...d&&{executable:d}})}return w.sort((g,y)=>y.score-g.score||g.recipe.id.localeCompare(y.recipe.id))}s(_e,"discoverRecipeCandidates");function Ue(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),p=h[0];p!==void 0&&(h.filter(m=>m.score===p.score).length>1||o.set(`${p.recipe.kind}:${p.recipe.id}`,p))}return[...o.values()]}s(Ue,"selectSuggestedRecipes");async function qe(n,r,t,o){for(let e of r)if(await pe(e,n,t,o))return e}s(qe,"firstExecutable");async function et(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 Ze(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(et,"managedRecipeIds");import{execFile as tt}from"node:child_process";import{readdir as ot}from"node:fs/promises";import _ from"node:path";import{promisify as nt}from"node:util";var rt=nt(tt),it=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Be(n,r){r?.throwIfAborted();try{let o=(await rt("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=>!Me(e));return r?.throwIfAborted(),o.length>0?o:await ee(n,r)}catch{return r?.throwIfAborted(),ee(n,r)}}s(Be,"collectProjectFiles");function Fe(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(p=>p.toLowerCase())),u=s(p=>t==="win32"?p.toLowerCase():p,"normalizeName"),f=new Set(i.fileNames?.map(u)),h=n.filter(p=>!p.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")&&(a.has(e.extname(p).toLowerCase())||f.has(u(e.basename(p)))));h.length>0&&o.set(i.id,h)}return o}s(Fe,"detectProjectLanguages");async function ee(n,r){r?.throwIfAborted();let t=[];for(let o of await ot(n,{withFileTypes:!0})){if(o.isDirectory()&&it.has(o.name))continue;let e=_.join(n,o.name);Me(e)||(o.isDirectory()?t.push(...await ee(e,r)):o.isFile()&&t.push(e))}return t}s(ee,"walk");function Me(n){return n.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")}s(Me,"isManagedIdeConfig");function at(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(at,"assertWorkspace");async function te(n,r,t=process.env,o,e){o?.throwIfAborted(),at(r,e);let i=e?await e.files(o):await Be(r,o);o?.throwIfAborted();let a=Fe(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,p]=await Promise.all([_e(r,u,n.recipes,e?{...e.toolPaths}:t,o,e),Ne(n,f)]);o?.throwIfAborted();let m=new Map;for(let w of u)for(let g of["formatter","linter","lsp"]){if(p.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:p.selections,actions:[...p.actions,...m.values()],suggestions:Ue(h,u,p.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 Le(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 We(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:st.resolve(n.cwd)}`].join(`
4
+ `)}s(We,"buildDoctorAgentPrompt");import{createHash as ct}from"node:crypto";var dt="doctor",ne=3;function Je(n,r){let t=ue(n,pt(r));t!==void 0&&t.catch(()=>{})}s(Je,"registerDoctorTipProvider");function pt(n){return{protocol:fe,apiVersion:ge,id:dt,async getTip(r){let t=await n(r),o=lt(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-${ut(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...e,"Run /pi-agent-ide-doctor"].join(`
5
+ `)}}}}s(pt,"createDoctorTipProvider");function lt(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(lt,"setupItems");function ut(n){return ct("sha256").update(n.map(r=>`${r.id}\0${r.message}`).join("\0")).digest("hex").slice(0,12)}s(ut,"fingerprint");async function Ve(n,r){let t=new z;Je(n,async i=>(await t.waitForPlugins(),te(t.snapshot(),i.cwd,process.env,i.signal)));let o,e=n.events.on(we,i=>{if(!be(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}=je(i,a.cwd),h=await r?.(u);await t.waitForPlugins();let p=await Y(t.snapshot(),u,process.env,void 0,h);if(re(n,M(p)),p.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 Te(u,p.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"),p=await Y(t.snapshot(),u,process.env,void 0,h),re(n,M(p))}if(!oe(p)&&!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(We(p)))},"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(ye,{protocol:he,apiVersion:me}),await t.waitForPlugins()}s(Ve,"registerDoctorWithOwner");function re(n,r){n.sendMessage({customType:"pi-agent-ide-doctor",content:r,display:!0},{triggerTurn:!1})}s(re,"sendReport");import{readFile as ze}from"node:fs/promises";import U from"node:path";import{Type as E}from"typebox";import{Value as ie}from"typebox/value";var ft=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 Ye(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(c=>{let d=n.resolve(c);if(!d||d.location.target!==e.target)throw new D("UNSUPPORTED_SOURCE",c,"not-applied");return d.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(c=>[c,E.Optional(E.String({maxLength:4096}))])),{additionalProperties:!1});if(!ie.Check(h,f))throw new D("INVALID_RESPONSE",e.source,"not-applied");let p=Ie(n),m=Ae(n),w=Ee(n,e.source),g=new Map,y=s(async(c,d,l)=>{let P=await ze(new URL(`./${c}`,new URL("../src/backend/doctor-workspace.ts",import.meta.url).href),{encoding:"utf8",signal:l}),S=await X(i.target,"python3",["-c",P,...d],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(c,d,l)=>{l?.throwIfAborted();let P=await ze(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,x=!1,T,k;try{R=await De(i.target,"python3",["-c",P,JSON.stringify({operation:"create",source:c})],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,Ge)=>{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(He){Ge(He)}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(ft,J))throw new D("PROBE_FAILED",e.source,"not-applied");if(k=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){x=!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&&k&&d(k),v?.exitCode===2)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}catch(v){throw new AggregateError(x?[T,v]:[v],"Doctor allocation cleanup failed",{cause:v})}if(x)throw T},"allocateProbe"),I=new Map,b=s(async c=>{for(;;){let d=I.get(c);if(d?.cleanup){await d.cleanup;continue}let l=d??{users:0};return l.users++,I.set(c,l),l}},"acquireContainer"),O=s(async(c,d)=>{d.users--,d.users===0&&(d.cleanup=Promise.resolve().then(async()=>{if(d.created&&await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove-container",...d.created})])!==null)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}).finally(()=>{I.get(c)===d&&I.delete(c)}),await d.cleanup)},"releaseContainer");return{source:e.source,platform:"linux",toolPaths:f,probeCapture:s(c=>xe({...i.target,workspace:e.path},e.source,c),"probeCapture"),async probeBrowser(c){return await ke({...i.target,workspace:e.path},e.source,c),{ok:!0,detail:"Target Playwright and Chromium started without navigation"}},async files(c){let d=await y("doctor-inventory-worker.py",[e.path],c);if(!ie.Check(E.Array(E.String()),d))throw new D(typeof d=="object"&&d!==null&&"error"in d&&d.error==="BYTE_LIMIT"?"BYTE_LIMIT":"INVENTORY_FAILED",e.source,"not-applied");return d.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(c,d){try{let l=await i.read(a(c),{signal:d}),P=l.bytes.toString("utf8");return g.set(c,{content:P,version:l.version}),P}catch(l){if(l instanceof D&&l.code==="ENOENT")return;throw l}},async writeText(c,d,l,P){let S=g.get(c);if(l!==void 0&&(!S||S.content!==l))throw new D("CONFLICT",c,"not-applied");await i.write(a(c),Buffer.from(d),l===void 0?null:S?.version??null,{signal:P})},configPaths:s((c,d)=>p.paths(e.source,c,d),"configPaths"),async exists(c,d){try{return await i.stat(a(c),{signal:d}),!0}catch(l){if(l instanceof D&&l.code==="ENOENT")return!1;throw l}},evidence:s((c,d)=>Re(i,e.path,c,d),"evidence"),executableAvailability:s((c,d)=>Ce(i,e.path,c,d),"executableAvailability"),run:s((c,d,l)=>m.run(c,{projectRoot:e.source,filePath:d,signal:l}),"run"),async withProbeCopy(c,d,l){l?.throwIfAborted();let P=a(c),S=U.posix.join(U.posix.dirname(P),".tmp"),j=await b(S),$,R=U.posix.basename(P),x=[],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(),x.push({value:await d(K(e.target,W).source)})}catch(v){T=v}let k=[];if($)try{if(await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove",...$,name:R})])!==null)throw new D("PROBE_CLEANUP_FAILED",c,"unknown")}catch(v){k.push(v)}try{await O(S,j)}catch(v){k.push(v)}if(k.length>0)throw new AggregateError(x.length===0?[T,...k]:k,"Doctor probe cleanup failed",{cause:k[0]});if(x.length===0)throw T;return N(x[0]).value},start:s((c,d,l)=>w.start({rootUri:e.source,command:c,env:d,signal:l}),"start"),toNativeUri:s(c=>w.toServerUri(c),"toNativeUri"),fromNativeUri:s(c=>w.fromServerUri(c),"fromNativeUri")}}s(Ye,"createSshDoctorWorkspace");async function gt(n){let r=new Oe(await Se(Pe(ve())));await Ve(n,t=>t.startsWith("ssh://")?Ye(r,t):Promise.resolve(void 0))}s(gt,"registerOwnedDoctor");export{gt as default};
@@ -0,0 +1 @@
1
+ import{a as v}from"./chunk-BXGMMZT3.js";import{b as E,c as A,d as j}from"./chunk-756K3LJY.js";import{a as h}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import F from"cross-spawn";import{access as M,readFile as P,writeFile as D}from"node:fs/promises";import _ from"node:os";import l from"node:path";import{fileURLToPath as U}from"node:url";var N=1;function se(e){return l.win32.basename(h(e[0]))}a(se,"configuredExecutableName");async function ae(e,o,n,r,i){i?.throwIfAborted();let s=l.resolve(e),t=l.resolve(s,o),c=r.filter(d=>H(d,t));if(X(s,t))return s;let f=l.dirname(t);for(;;){if(i?.throwIfAborted(),await Q(S(f,n),i)||[...(await v(f,c,void 0,i)).values()].some(p=>p.score>0))return f;let u=l.dirname(f);if(u===f)return;f=u}}a(ae,"resolveExternalToolProjectRoot");function G(e){return l.join(e,".pi","pi-agent-ide")}a(G,"projectIdeConfigDirectory");function S(e,o){return l.join(G(e),`${o}.json`)}a(S,"projectIdeConfigPath");function B(e,o,n={}){let i=(n.environment??process.env).PI_CODING_AGENT_DIR?.trim(),s=i===void 0||i.length===0?l.join(n.homeDirectory??_.homedir(),".pi","agent"):l.resolve(i);return{project:S(e,o),global:l.join(s,"extensions","pi-agent-ide",`${o}.json`),builtIn:U(new URL(`tool-config/${o}.json`,new URL("../src/api/tool-config.ts",import.meta.url).href))}}a(B,"resolveToolConfigPaths");async function le(e,o,n,r={}){let i=r.signal;i?.throwIfAborted();let s=r.layerAccess;if(e.includes("://")&&!s)throw Object.assign(new Error("No config owner for this project"),{code:"UNSUPPORTED_SOURCE"});let t={...B(e,o,r),...s?await s.paths(e,o,i):{}},c=[{layer:"project",sourcePath:t.project,optional:!0},...r.includeGlobal===!1?[]:[{layer:"global",sourcePath:t.global,optional:!0}],{layer:"built-in",sourcePath:t.builtIn,optional:!1}],f=[],d=new Set;for(let u of c){i?.throwIfAborted();let p=await z(u,o,n,u.layer!=="built-in"&&s?m=>s.readText(m,i):void 0,i);for(let[m,C]of Object.entries(p))d.has(m)||(d.add(m),f.push({id:m,config:C,layer:u.layer,sourcePath:u.sourcePath}))}return{entries:f,paths:t}}a(le,"loadLayeredToolConfig");function J(e,o,n){let r=l.extname(o).toLowerCase();if(e.extensions.every(t=>!(L(t)===r||t==="*"))&&!e.fileNames?.some(t=>process.platform==="win32"?t.toLowerCase()===l.basename(o).toLowerCase():t===l.basename(o)))return!1;let i=l.relative(n,o).split(l.sep).join("/"),s=a(t=>t?.some(c=>l.matchesGlob(i,c))??!1,"matches");return(e.include===void 0||s(e.include))&&!s(e.exclude)}a(J,"matchesConfiguredFile");function ce(e,o,n,r,i){let s=l.resolve(i,r),t=e.filter(d=>J(d.config,s,i)),c=t.find(d=>d.layer!=="built-in");if(c!==void 0)return c;let f=Math.max(0,...t.map(d=>n.get(d.id)?.score??0));return t.find(d=>o.has(d.id)&&(n.get(d.id)?.score??0)===f)}a(ce,"selectConfiguredEntry");async function q(e,o,n=process.env,r){r?.throwIfAborted(),w(e,"process");let i=h(e.command[0]).replaceAll("{project}",o),s=k(e,o,n);return j(i,o,s,r)}a(q,"hasConfiguredExecutable");async function fe(e,o,n,r){if(r.signal?.throwIfAborted(),e.includes("://")&&!r.executableAvailability)throw Object.assign(new Error("Tool probes require their resource owner"),{code:"UNSUPPORTED_SOURCE"});let i=r.executableAvailability?await r.executableAvailability(o.map(t=>t.config),r.signal):await Promise.all(o.map(t=>q(t.config,e,r.environment??process.env,r.signal)));if(r.signal?.throwIfAborted(),i.length!==o.length||i.some(t=>typeof t!="boolean"))throw new TypeError("Invalid tool executable availability report");let s=r.recipeEvidence?await r.recipeEvidence(n,r.signal):await v(e,n,void 0,r.signal);return r.signal?.throwIfAborted(),{available:new Set(o.filter((t,c)=>i[c]===!0&&(!r.requireBuiltInEvidence||(s.get(t.id)?.score??0)>0)).map(t=>t.id)),evidence:s}}a(fe,"toolRuntimeEvidence");async function V(e,o){if(w(e,"process"),o.processAccess)return o.processAccess.run(e,o);if(o.projectRoot.includes("://")||o.filePath.includes("://"))throw Object.assign(new Error("No process owner for this resource"),{code:"UNSUPPORTED_SOURCE"});let n=e.command.map(f=>W(f,o)),r=h(n[0]),i=n.slice(1),s=e.cwd==="file"?l.dirname(o.filePath):o.projectRoot,t=e.successExitCodes??[0],c=k(e,o.projectRoot,o.env??process.env);return new Promise((f,d)=>{let u=F(r,i,{cwd:s,env:c,signal:o.signal,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]}),p="",m="",C=h(u.stdout),x=h(u.stderr),T=!1,R=setTimeout(()=>{T=!0,u.kill("SIGKILL")},e.timeoutMs??3e4);C.setEncoding("utf8"),x.setEncoding("utf8"),C.on("data",g=>{p+=g}),x.on("data",g=>{m+=g}),u.on("error",g=>{clearTimeout(R),d(g)}),u.on("close",g=>{clearTimeout(R),f({ok:!T&&g!==null&&t.includes(g),exitCode:g,stdout:p,stderr:m})})})}a(V,"runConfiguredProcess");async function de(e,o){let n=await P(o.filePath,"utf8"),r=await V(e.run,o);if(!r.ok)return{ok:!1,changed:await P(o.filePath,"utf8")!==n};e.output==="stdout"&&r.stdout!==n&&await D(o.filePath,r.stdout,"utf8");let i=await P(o.filePath,"utf8");return{ok:!0,changed:n!==i}}a(de,"runConfiguredFormatter");function ue(e){let o=$(e,"formatters");for(let[n,r]of Object.entries(o.entries)){let i=y(r,`formatter ${n}`);if(O(i,`formatter ${n}`),w(i.run,`formatter ${n}.run`),i.output!=="in-place"&&i.output!=="stdout")throw new Error(`formatter ${n}.output must be in-place or stdout`)}return e}a(ue,"parseFormattersConfig");function ge(e){let o=$(e,"linters"),n=new Set(["pi-json","eslint-json","sarif","checkstyle","gcc","clang","regex"]);for(let[r,i]of Object.entries(o.entries)){let s=y(i,`linter ${r}`);O(s,`linter ${r}`),w(s.check,`linter ${r}.check`),s.fix!==void 0&&w(s.fix,`linter ${r}.fix`);let t=y(s.diagnostics,`linter ${r}.diagnostics`);if(!n.has(String(t.format)))throw new Error(`linter ${r} has an unsupported diagnostics format`);if(t.columnBase!==void 0&&(t.format!=="regex"||t.columnBase!==0&&t.columnBase!==1))throw new Error(`linter ${r} columnBase must be 0 or 1 for regex diagnostics`);if(t.format==="regex"&&typeof t.pattern!="string")throw new Error(`linter ${r} regex diagnostics require pattern`)}return e}a(ge,"parseLintersConfig");function $(e,o){let n=y(e,"tool config");if(n.version!==N)throw new Error(`tool config version must be ${N}`);return{entries:y(n[o],o)}}a($,"configRoot");function O(e,o){b(e.extensions,`${o}.extensions`,!1),e.fileNames!==void 0&&b(e.fileNames,`${o}.fileNames`,!1),e.include!==void 0&&b(e.include,`${o}.include`,!1),e.exclude!==void 0&&b(e.exclude,`${o}.exclude`,!0)}a(O,"assertMatcher");function w(e,o){let n=y(e,o);if(b(n.command,`${o}.command`,!1),n.cwd!==void 0&&n.cwd!=="project"&&n.cwd!=="file")throw new Error(`${o}.cwd must be project or file`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||Number(n.timeoutMs)<=0))throw new Error(`${o}.timeoutMs must be positive`);if(n.successExitCodes!==void 0&&(!Array.isArray(n.successExitCodes)||n.successExitCodes.some(r=>!Number.isInteger(r))))throw new Error(`${o}.successExitCodes must contain integers`);if(n.env!==void 0){let r=y(n.env,`${o}.env`);if(Object.values(r).some(i=>typeof i!="string"))throw new Error(`${o}.env values must be strings`)}}a(w,"assertProcessConfig");function b(e,o,n){if(!Array.isArray(e)||!n&&e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error(`${o} must be ${n?"an":"a non-empty"} array of strings`)}a(b,"assertStringArray");function y(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${o} must be an object`);return e}a(y,"configRecord");function L(e){return e.startsWith(".")?e.toLowerCase():`.${e.toLowerCase()}`}a(L,"normalizeExtension");async function z(e,o,n,r,i){i?.throwIfAborted();let s;try{s=r?await r(e.sourcePath):await P(e.sourcePath,{encoding:"utf8",signal:i})}catch(t){if(i?.throwIfAborted(),e.optional&&K(t))return{};throw new Error(`Cannot read ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}i?.throwIfAborted();try{return n(JSON.parse(s))}catch(t){throw new Error(`Invalid ${e.layer} ${o} config at ${e.sourcePath}: ${I(t)}`,{cause:t})}}a(z,"readToolConfigLayer");function K(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}a(K,"isMissingFile");function I(e){return e instanceof Error?e.message:String(e)}a(I,"errorMessage");function k(e,o,n){return A(o,{...E(n),...E(e.env??{})})}a(k,"createConfiguredProcessEnvironment");function W(e,o){let n=l.relative(o.projectRoot,o.filePath);return e.replaceAll("{project}",o.projectRoot).replaceAll("{fileDir}",l.dirname(o.filePath)).replaceAll("{relativeFile}",n).replaceAll("{file}",o.filePath)}a(W,"expandPlaceholders");function H(e,o){let n=l.extname(o).toLowerCase(),r=l.basename(o),i=a((s,t=[])=>s.some(c=>L(c)===n)||t.some(c=>c===r),"matches");return e.formatter?i(e.formatter.extensions,e.formatter.fileNames):e.linter?i(e.linter.extensions,e.linter.fileNames):e.lsp?i(Object.values(e.lsp.languageIds).flat(),Object.values(e.lsp.fileNames??{}).flat()):!1}a(H,"recipeMatchesFile");async function Q(e,o){o?.throwIfAborted();try{return await M(e),o?.throwIfAborted(),!0}catch{return o?.throwIfAborted(),!1}}a(Q,"fileExists");function X(e,o){let n=l.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}a(X,"isPathInside");export{N as a,se as b,ae as c,G as d,S as e,B as f,le as g,J as h,ce as i,q as j,fe as k,V as l,de as m,ue as n,ge as o,k as p,H as q};
@@ -0,0 +1 @@
1
+ import{a as d}from"./chunk-WXGTU2M6.js";import{g as n}from"./chunk-4HWKBCBH.js";import{a as p}from"./chunk-EI7MMDWY.js";import{readFile as h}from"node:fs/promises";import{Type as m}from"typebox";import{Value as g}from"typebox/value";async function f(s,a,e,o,t){return d(s,a,e,o,{...t,effect:"not-applied"})}p(f,"readOwnedSshCommand");var S=m.Object({html:m.String(),source:m.String()}),u=new Set(["CAPABILITY_UNAVAILABLE","INVALID_SOURCE","BYTE_LIMIT","TIMEOUT","HTTP_FAILED","BROWSER_FAILED","CANCELLED"]),l;async function B(s,a,e,o){let t=await w(s,a,e,o,"html");if(!g.Check(S,t)||Buffer.byteLength(t.html,"utf8")>16*1024*1024)throw new n("INVALID_RESPONSE",e,"not-applied");let r=new URL(t.source);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw new n("INVALID_RESPONSE",e,"not-applied");return t}p(B,"readSshBrowserPage");async function N(s,a,e,o){let t=await w(s,a,e,{signal:o,timeoutMs:3e4},"image");if(typeof t!="object"||t===null||!("png"in t)||typeof t.png!="string")throw new n("INVALID_RESPONSE",e,"not-applied");let r=Buffer.from(t.png,"base64");if(r.toString("base64")!==t.png||r.length>20*1024*1024||!r.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex")))throw new n("INVALID_RESPONSE",e,"not-applied");return r}p(N,"captureSshBrowserImage");async function R(s,a,e){let o=await w(s,new URL("about:blank"),a,{signal:e,timeoutMs:3e4},"probe");if(!g.Check(m.Object({ready:m.Literal(!0)}),o))throw new n("INVALID_RESPONSE",a,"not-applied")}p(R,"probeSshBrowser");async function w(s,a,e,o,t){o.signal?.throwIfAborted(),l??=h(new URL("./web-browser-worker.mjs",new URL("../src/backend/web-browser.ts",import.meta.url).href),"utf8");try{let r=await f(s,"node",["--input-type=module","-e",await l,JSON.stringify({kind:t,url:a.href,timeoutMs:o.timeoutMs})],e,{signal:o.signal,timeoutMs:o.timeoutMs,maxBytes:33554432});if(r.exitCode!==0)throw new n("BROWSER_FAILED",e,"not-applied");let i;try{i=JSON.parse(r.stdout.toString("utf8"))}catch{throw new n("INVALID_RESPONSE",e,"not-applied")}if(typeof i=="object"&&i!==null&&"error"in i)throw new n(typeof i.error=="string"&&u.has(i.error)?i.error:"INVALID_RESPONSE",e,"not-applied");return i}catch(r){throw r instanceof n?new n(r.code==="ENOENT"?"CAPABILITY_UNAVAILABLE":r.code,e,r.effect):r}}p(w,"runBrowser");export{f as a,B as b,N as c,R as d};
@@ -0,0 +1 @@
1
+ import{a as n}from"./chunk-EI7MMDWY.js";var s=class{static{n(this,"AgentIdeProcessRegistry")}#t=new Map;#n=new Set;#e=new Map;add(e){return this.#e.get(e.id)?.(),this.#t.set(e.id,e),this.#e.set(e.id,e.onDidChange(()=>this.#s())),this.#s(),()=>{this.#t.get(e.id)===e&&(this.#e.get(e.id)?.(),this.#e.delete(e.id),this.#t.delete(e.id),this.#s())}}list(){return[...this.#t.values()].flatMap(e=>e.list())}onDidChange(e){return this.#n.add(e),()=>this.#n.delete(e)}dispose(){for(let e of this.#e.values())e();this.#e.clear(),this.#t.clear(),this.#n.clear()}#s(){for(let e of this.#n)e()}},i=new WeakMap;function r(t){let e=i.get(t);return e===void 0&&(e=new s,i.set(t,e)),e}n(r,"agentIdeProcessRegistry");export{r as a};
@@ -0,0 +1,4 @@
1
+ import{a as re,b as ie,c as oe}from"./chunk-DEP55R35.js";import{a as ee,b as te,c as ne}from"./chunk-R2U5WXYR.js";import{e as B,f as W}from"./chunk-T7I2VX3J.js";import{a as V}from"./chunk-YJ6T3PEP.js";import{b as M,c as _}from"./chunk-S72FVLUX.js";import{a as J}from"./chunk-M4TVRCMZ.js";import{c as Z,d as Y}from"./chunk-TGC2ZACO.js";import{a as K}from"./chunk-BU7IZLKB.js";import{a as z,b as Q}from"./chunk-S5PL5DFQ.js";import{H as q,f as X,i as R,j as S}from"./chunk-DXONCYWF.js";import{a as F}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import we from"node:path";var ae={protocol:M,apiVersion:_,id:"changes",setup(n){n.addSetupCheck({id:"git",async inspect(e){return await ee(e,e.workspace?`${e.cwd}/.git`:we.join(e.cwd,".git"))?await ne(e,"git")?{}:{actions:[{id:"git-unavailable",message:"Git integration is unavailable because Git was not found"}]}:{}}}),n.addCheck({id:"git",title:"Git changes",async run(e){let t=await te(e,"git",["--version"]);return[t.ok?{status:"pass",message:"Git is available",detail:t.detail}:{status:"warn",message:"Git is not available; change anchors and index tools are disabled",detail:t.detail}]}})}};import{mkdtemp as be,rm as Te,writeFile as Ee}from"node:fs/promises";import Ce from"node:os";import C from"node:path";import b from"node:path";var x=/^[a-z][a-z0-9+.-]*:\/\//iu;function T(n,e){if(x.test(n))return E(n).href;if(!x.test(e))return b.resolve(e,n);let t=E(e);return t.pathname=b.posix.resolve(decodeURIComponent(t.pathname),n).split("/").map(encodeURIComponent).join("/"),t.href}s(T,"resolveGitSource");function se(n,e){if(!x.test(n)&&!x.test(e))return b.relative(n,e);if(!x.test(n)||!x.test(e))return;let t=E(n),r=E(e);if(t.host===r.host)return b.posix.relative(decodeURIComponent(t.pathname),decodeURIComponent(r.pathname))}s(se,"relativeGitSource");function m(n,e){let t=T(n,e);if(!x.test(t))return b.dirname(t);let r=E(t);return r.pathname=b.posix.dirname(decodeURIComponent(r.pathname)).split("/").map(encodeURIComponent).join("/"),r.href}s(m,"gitSourceDirectory");function E(n){let e=new URL(n);if(e.protocol!=="ssh:"||e.username||e.password||e.port||e.search||e.hash)throw new Error(`Unsupported Git resource: ${n}`);return e}s(E,"remoteUrl");var v=class n{constructor(e,t){this.executor=e;this.repositoryRoot=t}static{s(this,"GitChangesBackend")}static async create(e,t,r){let o=await e.exec("git",["rev-parse","--show-toplevel"],{cwd:t,...r!==void 0&&{signal:r}});return o.code!==0?{status:"unavailable",reason:"no-worktree",message:o.stderr.trim()||"not inside a Git worktree"}:{status:"ready",backend:new n(e,T(o.stdout.trim(),t))}}async readTrackedFile(e,t,r){let o=T(e,t),i=se(this.repositoryRoot,o);return i===void 0||i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i)?{status:"unavailable",reason:"outside-worktree",message:`${o} is outside ${this.repositoryRoot}`}:this.readTrackedRepositoryFile(i.split(C.sep).join("/"),r)}async readTrackedRepositoryFile(e,t){let r=await this.git(["rev-parse","--verify","HEAD"],t);if(r.code!==0)return{status:"unavailable",reason:"missing-head",message:r.stderr.trim()||"Git HEAD does not exist"};let o=await this.git(["--literal-pathspecs","ls-tree","-z","HEAD","--",e],t);if(o.code!==0)return{status:"unavailable",reason:"head-file-lookup-failed",message:o.stderr.trim()||`could not inspect HEAD:${e}`};let i=ke(o.stdout);if(i===void 0)return{status:"untracked"};let d=await this.readBlob(i.blob,"HEAD",e,t);if(d.status!=="found")return d;let c=await this.git(["--literal-pathspecs","ls-files","--stage","-z","--",e],t);if(c.code!==0)return{status:"unavailable",reason:"index-file-lookup-failed",message:c.stderr.trim()||`could not inspect the index entry for ${e}`};let a=ve(c.stdout);if(a.some(({stage:u})=>u!==0))return{status:"unavailable",reason:"conflicted",message:`${e} has unresolved Git index entries`};let l=a.find(({stage:u})=>u===0),f="";if(l!==void 0){let u=await this.readBlob(l.blob,"index",e,t);if(u.status!=="found")return u;f=u.text}return{status:"found",head:r.stdout.trim(),repositoryPath:e,repositoryRoot:this.repositoryRoot,headText:d.text,indexText:f,indexMode:l?.mode??i.mode,indexExists:l!==void 0}}async writeIndexFile(e,t,r,o,i){if(i&&this.executor.writeIndex&&await this.executor.writeIndex({repositoryPath:e,mode:t,text:r,...i},{cwd:this.repositoryRoot,...o!==void 0&&{signal:o}}))return;if(this.repositoryRoot.startsWith("ssh://"))throw new Error("Remote Git index writes require a guarded owner index writer");let d=await be(C.join(Ce.tmpdir(),"pi-agent-index-")),c=C.join(d,"content");try{await Ee(c,r,"utf8");let a=await this.git(["hash-object","-w",`--path=${e}`,c],o);if(a.code!==0||a.stdout.trim().length===0)throw new Error(a.stderr.trim()||`could not write a Git blob for ${e}`);let l=await this.git(["update-index","--add","--cacheinfo",t,a.stdout.trim(),e],o);if(l.code!==0)throw new Error(l.stderr.trim()||`could not update the Git index entry for ${e}`)}finally{await Te(d,{recursive:!0,force:!0})}}async readBlob(e,t,r,o){let i=await this.git(["cat-file","blob",e],o);return i.code!==0?{status:"unavailable",reason:t==="HEAD"?"head-file-lookup-failed":"index-file-lookup-failed",message:i.stderr.trim()||`could not read ${t}:${r}`}:{status:"found",text:i.stdout}}git(e,t){return this.executor.exec("git",e,{cwd:this.repositoryRoot,...t!==void 0&&{signal:t}})}};function ke(n){let e=n.split("\0",1)[0];if(e===void 0||e.length===0)return;let t=e.indexOf(" ");if(t===-1)return;let[r,o,i]=e.slice(0,t).split(" ",3);return r===void 0||o!=="blob"||i===void 0?void 0:{mode:r,blob:i,path:e.slice(t+1)}}s(ke,"parseTreeEntry");function ve(n){return n.split("\0").filter(Boolean).flatMap(e=>{let t=e.indexOf(" ");if(t===-1)return[];let[r,o,i]=e.slice(0,t).split(" ",3),d=Number(i);return r===void 0||o===void 0||!Number.isInteger(d)?[]:[{mode:r,blob:o,stage:d,path:e.slice(t+1)}]})}s(ve,"parseIndexEntries");function de(n){return{exec:s((e,t,r)=>{if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(r.cwd))throw new Error(`No Git executor owns ${r.cwd}`);return n.exec(e,t,r)},"exec")}}s(de,"extensionGitExecutor");var h=class n{constructor(e){this.git=e}static{s(this,"ChangeService")}static async create(e,t,r){let o=await v.create(e,t,r);return o.status==="unavailable"?o:{status:"ready",service:new n(o.backend)}}async inspect(e){if(e.worktreeText.includes("\0"))return{status:"unavailable",reason:"binary",message:"worktree file contains binary content"};let t=await this.git.readTrackedFile(e.source,e.cwd,e.signal);if(t.status!=="found")return t.status==="untracked"?{status:"not-applicable",reason:"untracked"}:t;if(t.headText.includes("\0")||t.indexText.includes("\0"))return{status:"unavailable",reason:"binary",message:"Git file state contains binary content"};let r=re(t.repositoryPath,t.headText,t.indexText,e.worktreeText);return r.length===0?{status:"not-applicable",reason:"clean"}:{status:"applicable",head:t.head,repositoryRoot:t.repositoryRoot,repositoryPath:t.repositoryPath,groups:r}}async changeIndex(e,t,r){let o=await this.inspect(e);if(o.status!=="applicable")return o;let i=o.groups.find(l=>l.selector===t);if(i===void 0)return H(t,o.groups.map(({selector:l})=>l));let d=r==="stage"?"staged":"unstaged";if(i.state===d)return{status:"unchanged",state:d,group:i};let c=w(i.segments[0]),a={expectedWorktreeText:e.worktreeText,head:o.head,repositoryPath:o.repositoryPath,headStart:c.headStart,headEnd:c.headEnd,replacementText:r==="stage"?c.worktreeText:c.headText};try{await this.applyIndexUpdate(a,e.signal)}catch(l){return{status:"unavailable",reason:"index-write-failed",message:ce(l),failure:l instanceof Error?l:new Error(ce(l))}}return{status:"applied",state:d,group:i}}async prepareUndo(e,t){let r=await this.inspect(e);if(r.status!=="applicable")return r;let o=r.groups.find(a=>a.selector===t);if(o===void 0)return H(t,r.groups.map(({selector:a})=>a));let i=ie(e.worktreeText,o);if(i===void 0)return H(t,r.groups.map(({selector:a})=>a));let d=w(o.segments[0]),c=o.state==="unstaged"?void 0:{head:r.head,repositoryPath:r.repositoryPath,headStart:d.headStart,headEnd:d.headEnd,replacementText:d.headText,expectedWorktreeText:i};return{status:"applied",worktreeText:i,group:o,...c!==void 0&&{indexUpdate:c}}}async applyIndexUpdate(e,t){let r=await this.git.readTrackedRepositoryFile(e.repositoryPath,t);if(r.status!=="found")throw new Error(r.status==="untracked"?`${e.repositoryPath} is no longer tracked by HEAD`:r.message);if(r.head!==e.head)throw new Error(`Git HEAD changed while updating ${e.repositoryPath}`);let o=oe(r.headText,r.indexText,e.headStart,e.headEnd,e.replacementText);o!==r.indexText&&await this.git.writeIndexFile(e.repositoryPath,r.indexMode,o,t,{expectedHead:r.head,expectedIndexText:r.indexText,expectedIndexMode:r.indexMode,expectedIndexExists:r.indexExists,...e.expectedWorktreeText!==void 0&&{expectedWorktreeText:e.expectedWorktreeText}})}};function H(n,e){return{status:"unavailable",reason:"stale-selector",message:`${n} is not available in the current file state`,availableSelectors:e}}s(H,"staleSelector");function ce(n){return n instanceof Error?n.message:String(n)}s(ce,"errorMessage");var I="pi-agent-ide-changes/change",Ie=/^CHANGE#[0-9A-F]{4,64}$/,Ge=/^[A-Za-z][A-Za-z\d+.-]*:\/\//,D=class extends F{static{s(this,"ChangeTextAnchor")}constructor(e){super(e.selector,e.currentStartLine)}};function ue(n){return{resolver:Pe(s(async t=>{if(Ge.test(t.source)&&!t.source.startsWith("ssh://"))return;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")throw new Error(r.message);return r.service.inspect({source:t.source,worktreeText:t.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}})},"inspect"))}}s(ue,"createChangeAnchorRegistration");function Pe(n){return{id:"git-change",description:"Use the complete `CHANGE#HASH` shown beside a current Git change.",renderFull(e){return e},renderCompact(e){return e},async tryResolve(e,t){if(!Ie.test(e))return{kind:"not-handled"};try{let r=await n(t);if(r===void 0)return{kind:"not-handled"};if(r.status==="unavailable")return{kind:"failed",error:new Error(r.message)};let o=r.status==="applicable"?r.groups.find(i=>i.selector===e):void 0;return o===void 0?{kind:"rejected",rejection:{code:"stale",reason:`Change anchor ${e} is stale or unknown`}}:{kind:"resolved",anchor:new D(o)}}catch(r){return{kind:"failed",error:r}}}}}s(Pe,"createChangeAnchorResolver");import{diffLines as Ae}from"diff";var Re="filesystem";function le(n){return{id:"current-git-changes",async present(e,t){if(t.purpose!=="read"||t.resolvedBy!==Re&&!t.source.startsWith("ssh://"))return e;let r=await h.create(n,m(t.source,t.cwd),t.signal);if(r.status!=="ready")return e;let o=await r.service.inspect({source:t.source,worktreeText:e.content,cwd:t.cwd,...t.signal!==void 0&&{signal:t.signal}});return o.status!=="applicable"?e:Se(e,o.groups)}}}s(le,"createCurrentChangePresenter");function Se(n,e){let t=new Map;for(let r of e)He(n,r,t);return{...n,references:e.map(r=>({value:r.selector,kind:"change",state:r.state})),lines:n.lines.map(r=>$e(r,t.get(r.lineNumber)))}}s(Se,"presentChangeGroups");function He(n,e,t){let r=w(e.segments[0]),o=Ae(r.headText,r.worktreeText),i=e.currentStartLine,d,c;for(let a of o){let l=Le(a.value);if(a.removed){let f=Ue(n,i),u=U(t,f.lineNumber),p=f.after?u.after:u.before;for(let j of l){let y={kind:"synthetic",rows:p,index:p.length};p.push({marker:"-",prefix:"|",content:j}),d??=y,c=y}continue}if(a.added){for(let f of l){let u=U(t,i),p={kind:"current",lineNumber:i};u.added=!0,d??=p,c=p,i++}continue}i+=l.length}if(d!==void 0&&c!==void 0){let a=`${e.selector} \xB7 ${e.state}`;De(d,c)?$(t,d,`<!-- change: ${a} -->`):($(t,d,`<!-- change-begin: ${a} -->`),$(t,c,`<!-- change-end: ${a} -->`))}}s(He,"presentChangeGroup");function De(n,e){return n.kind==="current"&&e.kind==="current"?n.lineNumber===e.lineNumber:n.kind==="synthetic"&&e.kind==="synthetic"?n.rows===e.rows&&n.index===e.index:!1}s(De,"sameTarget");function $(n,e,t){if(e.kind==="current"){U(n,e.lineNumber).annotations.push(t);return}let r=w(e.rows[e.index]);e.rows[e.index]={...r,suffix:`${r.suffix??""} ${t}`}}s($,"annotateTarget");function $e(n,e){if(e===void 0)return n;let t=e.annotations.length===0?"":` ${e.annotations.join(" ")}`;return{...n,presentation:{...n.presentation,...e.added&&{marker:"+"},before:[...n.presentation?.before??[],...e.before],after:[...e.after,...n.presentation?.after??[]],suffix:`${n.presentation?.suffix??""}${t}`}}}s($e,"presentLine");function U(n,e){let t=n.get(e);if(t!==void 0)return t;let r={before:[],after:[],annotations:[],added:!1};return n.set(e,r),r}s(U,"presentationsFor");function Ue(n,e){return e<=n.lines.length?{lineNumber:Math.max(1,e),after:!1}:{lineNumber:n.lines.length,after:!0}}s(Ue,"placementFor");function Le(n){if(n.length===0)return[];let e=n.split(/\r\n|\r|\n/u);return e.at(-1)===""&&e.pop(),e}s(Le,"splitLines");var G=class{static{s(this,"IndexMutationQueue")}tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}};import{createHash as Ne}from"node:crypto";import{realpathSync as Oe}from"node:fs";import pe from"node:path";import{fileURLToPath as je}from"node:url";var A=class{static{s(this,"LastTextTransactionStore")}#e=new Map;observe(e){let t=ge(e.resourceSource,e.cwd);if(e.postProcessing==="final"){let r=this.#e.get(t),o=e.beforePostProcessing??e.before;r&&r.afterDigest===P(o.content)?this.#e.set(t,{...r,afterDigest:P(e.after.content)}):this.#e.delete(t);return}if(e.intent!=="edit"||!e.existed||e.before.content===e.after.content){this.#e.delete(t);return}this.#e.set(t,{before:e.before.content,afterDigest:P(e.after.content)})}restore(e,t,r){let o=ge(e,t),i=this.#e.get(o);if(i===void 0)throw new Error(`No last text transaction is available for ${e}.`);if(i.afterDigest!==P(r))throw this.#e.delete(o),new Error(`${e} changed after its last text transaction; refusing to overwrite newer text.`);return i.before}};function ge(n,e){return n.startsWith("file://")?fe(je(new URL(n))):/^[a-z][a-z\d+.-]*:/iu.test(n)?n:fe(pe.resolve(e,n))}s(ge,"sourceKey");function fe(n){try{return Oe.native(n)}catch{return pe.normalize(n)}}s(fe,"canonicalFile");function P(n){return Ne("sha256").update(n).digest("hex")}s(P,"textDigest");import{readFile as Fe}from"node:fs/promises";import{defineTool as Me,withFileMutationQueue as _e}from"@earendil-works/pi-coding-agent";import{Text as Be}from"@earendil-works/pi-tui";import{Type as g}from"typebox";var L=g.Object({action:g.Union([g.Literal("stage"),g.Literal("unstage")]),change:g.String(),file:g.String(),state:g.Optional(g.Union([g.Literal("staged"),g.Literal("unstaged")])),effect:g.Union([g.Literal("applied"),g.Literal("not-applied"),g.Literal("unknown")]),unchanged:g.Optional(g.Boolean())},{additionalProperties:!1}),We=X(L),k=g.Object({file:g.String({description:"Path to the tracked text file"}),change:g.String({description:"Complete CHANGE#HASH anchor shown by read",pattern:"^CHANGE#[0-9A-F]{4,64}$"})},{additionalProperties:!1}),Ve=g.Object({file:{...k.properties.file,description:"Path to a tracked text file in the current Git worktree. Relative paths resolve from the workspace."},change:{...k.properties.change,description:'Select one complete current CHANGE#HASH anchor returned by read with views: ["changes"].'}},{additionalProperties:!1});function me(n,e,t){n.registerTool(he("stage",e,t)),n.registerTool(he("unstage",e,t))}s(me,"registerIndexChangeTools");function he(n,e,t){let r=ze(n,e,t),o=n==="stage"?"Staged":"Unstaged",i=n==="stage"?{...k,properties:{file:{...k.properties.file,description:"Path to the tracked text file, absolute or relative to the current working directory."},change:{...k.properties.change,description:'Use the complete current CHANGE#HASH anchor shown by read with views: ["changes"].'}}}:Ve;return Me({name:n,exposure:"deferred",namespace:{name:"ide_git",description:"Stage or unstage selected Git changes without changing worktree files."},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},label:n,promptSnippet:`${o.slice(0,-1)} a selected Git change`,description:n==="stage"?"Use stage to add one selected Git change to the index without changing the worktree file.":"Use unstage to remove one selected Git change from the index. Worktree content is kept.",parameters:i,outputSchema:We,...n==="stage"&&{renderResult(d,c,a){return new Be(a.fg("toolOutput",d.content.flatMap(l=>l.type==="text"?[l.text]:[]).join(`
2
+ `)),0,0)}},async execute(d,c,a,l,f){try{let u=await r(c,a,f);return S(u,L,{status:"success",data:{...u.details,effect:u.details.unchanged?"not-applied":"applied"},errors:[]})}catch(u){if(a?.aborted)throw u;let p=R(u,"INDEX_CHANGE_FAILED",c.file);return S({content:[{type:"text",text:p.message}],details:{action:n,change:c.change,file:N(c.file,f.cwd)}},L,{status:"error",data:{action:n,change:c.change,file:N(c.file,f.cwd),effect:xe(u)},errors:[p]})}}})}s(he,"createIndexChangeTool");function ze(n,e,t){let r=n==="stage"?"staged":"unstaged",o=n==="stage"?"Staged":"Unstaged";return async(i,d,c)=>{let a=N(i.file,c.cwd);return _e(a,()=>t.run(async()=>{let l=e.readText?await e.readText(a,d):await Fe(a,"utf8"),f=await h.create(e,m(a,c.cwd),d);if(f.status!=="ready")throw new Error(n==="stage"?`Cannot stage ${i.file}: ${f.message}`:f.message);let u=await f.service.changeIndex({source:a,worktreeText:l,cwd:c.cwd,...d!==void 0&&{signal:d}},i.change,n);if(u.status==="unavailable"){if("failure"in u&&u.failure!==void 0){if(n==="stage"&&u.reason==="index-write-failed"){let y=R(u.failure,"INDEX_CHANGE_FAILED",i.file);throw Object.assign(new Error(`${y.message}
3
+ The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`,{cause:u.failure}),{effect:xe(u.failure)})}throw u.failure}throw n==="stage"&&u.reason==="stale-selector"?Object.assign(new Error(`${u.message}. Read ${i.file} with views: ["changes"] and use a current CHANGE# anchor.`),{effect:"not-applied"}):n==="stage"&&u.reason==="index-write-failed"&&!d?.aborted?new Error(`${u.message}
4
+ The index may have changed. Read ${i.file} with views: ["changes"] before retrying.`):Object.assign(new Error(n==="stage"&&u.reason!=="index-write-failed"?`Cannot stage ${i.file}: ${u.message}`:u.message),{effect:"not-applied"})}if(u.status==="not-applicable"){if(n==="stage"){let y=u.reason==="clean"?"the worktree text matches HEAD":"the file is not present in HEAD";throw new Error(`Cannot stage ${i.file}: ${y}.`)}throw new Error(`${n} is not applicable to ${a}: ${u.reason}`)}let p=u.status==="unchanged";return{content:[{type:"text",text:p?`${i.change} is already ${r} in ${i.file}.`:`${o} ${i.change} in ${i.file}.`}],details:{action:n,change:i.change,file:a,state:r,unchanged:p}}}))}}s(ze,"createIndexChangeExecutor");function N(n,e){let t=n.startsWith("@")?n.slice(1):n;return T(t,e)}s(N,"resolveFile");function xe(n){return n!==null&&typeof n=="object"&&"effect"in n&&(n.effect==="applied"||n.effect==="not-applied")?n.effect:"unknown"}s(xe,"publicationEffect");import{diffChars as Qe}from"diff";import{Type as O}from"typebox";var Ke=O.Object({file:O.Optional({...q,description:"File path or one whole-file source result. Partial and multi-file selections are rejected. Omit file to use the supplied CHANGE anchor's file or the last resolved source."}),change:O.String({description:`Use a complete current CHANGE#HASH anchor from read with views: ["changes"] to restore that change to HEAD in both worktree and index. Use last to restore the file's latest saved text-editor transaction.`,pattern:"^(?:CHANGE#[0-9A-F]{4,64}|last)$"})},{additionalProperties:!1});function ye(n,e,t){return{name:"undo",description:"Use undo to restore one selected uncommitted Git change or a file's latest text-editor transaction.",promptSnippet:"Restore a Git change or latest text edit",parameters:Ke,intent:"restore",source:{field:"file",inherited:!0},anchors:[{field:"change",sourceField:"file",kinds:[I],nonAnchorValues:["last"]}],async mutate(r,o){let i=r.sourceFor("file"),d,c;if(o.change==="last")d=e.restore(i,r.cwd,r.sourceDocument.content);else{await r.resolveAnchor("change");let a=await h.create(n,m(i,r.cwd),r.signal);if(a.status!=="ready")throw new Error(a.message);let l=await a.service.prepareUndo({source:i,worktreeText:r.sourceDocument.content,cwd:r.cwd,...r.signal!==void 0&&{signal:r.signal}},o.change);if(l.status!=="applied")throw l.status==="unavailable"?new Error(l.message):new Error(`Undo is not applicable to ${i}: ${l.reason}`);if(d=l.worktreeText,l.indexUpdate!==void 0){let f=l.indexUpdate;c=s(()=>t.run(()=>a.service.applyIndexUpdate(f,r.signal)),"afterWrite")}}return{edits:new Map([[i,{changes:Xe(r.sourceDocument.content,d),action:"edited"}]]),...c!==void 0&&{afterWrite:c}}}}}s(ye,"createUndoMutationTool");function Xe(n,e){let t=[],r=0,o,i=0,d="",c=s(()=>{o!==void 0&&(t.push({from:o,to:o+i,insert:d}),o=void 0,i=0,d="")},"flush");for(let a of Qe(n,e)){if(!a.added&&!a.removed){c(),r+=a.value.length;continue}o??=r,a.removed?(r+=a.value.length,i+=a.value.length):d+=a.value}return c(),t}s(Xe,"createTextChanges");function qe(n){return Ze(n,de(n))}s(qe,"registerGitChanges");async function Ze(n,e){W(n,[await B({id:"git-changes",description:"Git change anchors, staging, and safe undo",triggers:["stage","unstage","undo"].map(a=>({tool:a}))})]);let t=new A,r=new G,o=le(e),i=ue(e),d={protocol:z,apiVersion:Q,id:"current-git-changes",setup(a){a.addView({view:"changes",presenter:o}),a.describe({views:"changes \u2014 uncommitted edits in tracked files, staged/unstaged state, and CHANGE# anchors for stage, unstage and undo."})}},c={protocol:Z,apiVersion:Y,id:"current-git-changes",setup(a){a.addAnchorResolver({...i,kind:I,type:"auxiliary"}),a.onDidEdit(l=>{t.observe(l)}),a.addMutationTool(ye(e,t,r)),a.addTextPresenter({presenter:o})}};await Promise.all([V(n,ae),K(n,d),J(n,c)]),me(n,e,r)}s(Ze,"registerGitChangesWithExecutor");export{qe as a,Ze as b};
@@ -0,0 +1,5 @@
1
+ import{a as o}from"./chunk-EI7MMDWY.js";import{readFile as l}from"node:fs/promises";var i=256*1024;async function c(e){if(e.includes("://"))throw new Error("URI outlines require an owned text snapshot, not a local file read.");let t=await l(e);if(t.byteLength>i)throw new Error(`File exceeds the ${i}-byte AST outline limit: ${e}`);if(t.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${e}`);let n=t.toString("utf8").replaceAll(`\r
2
+ `,`
3
+ `),r=n.endsWith(`
4
+ `)?n.slice(0,-1):n,s=r.length===0?[]:r.split(`
5
+ `);return{content:n,lines:s}}o(c,"readTextFile");export{i as a,c as b};
@@ -0,0 +1 @@
1
+ import{b as d,g,h as c}from"./chunk-4HWKBCBH.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readFile as p}from"node:fs/promises";import a from"node:path";import{Type as i}from"typebox";import{Value as f}from"typebox/value";var S=i.Object({targets:i.Array(i.Object({id:i.String(),host:i.String(),workspace:i.String(),configFile:i.Optional(i.String({minLength:1}))},{additionalProperties:!1}))},{additionalProperties:!1});function T(o){return{globalPath:a.join(a.dirname(o.globalPath),"ssh.json"),projectPath:a.join(a.dirname(o.projectPath),"ssh.json")}}s(T,"resolveSshConfigPaths");async function j(o){let r=await h(o.globalPath),t=await h(o.projectPath),e=new Map(r.map(n=>[n.id,n]));for(let n of t)e.set(n.id,n);return[...e.values()]}s(j,"readSshTargets");async function h(o){let r;try{r=await p(o,"utf8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return[];throw new Error(`Cannot read SSH settings at ${o}`,{cause:t})}try{let t=JSON.parse(r);if(!f.Check(S,t))throw new Error("Invalid settings");return u(t,o)}catch{throw new Error(`Invalid SSH settings at ${o}`)}}s(h,"readScope");function u(o,r){let t=new Set;return o.targets.map(e=>{if(t.has(e.id))throw new Error("Duplicate target");t.add(e.id);let n={id:e.id,host:e.host,workspace:e.workspace,...e.configFile===void 0?{}:{configFile:a.resolve(a.dirname(r),e.configFile)}};return new c(n).target})}s(u,"validateScope");var l=class{static{s(this,"SshBackendRegistry")}#t=new Map;constructor(r){for(let t of r){if(this.#t.has(t.id))throw new TypeError(`Duplicate SSH target: ${t.id}`);this.#t.set(t.id,new c(t))}}resolve(r,t){let e=d(r,t);if(!e)return;let n=this.#t.get(e.target);if(!n)throw new g("UNKNOWN_TARGET",e.source,"not-applied");return{location:e,backend:n}}};export{T as a,j as b,l as c};
@@ -1 +1 @@
1
- import{e as u,f as E,k as a}from"./chunk-HZ5BNF3A.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
1
+ import{g as u,h as E,m as a}from"./chunk-TGC2ZACO.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
@@ -0,0 +1,4 @@
1
+ import{a as v,b as O,c as _,d as z}from"./chunk-TOYN4W4F.js";import{a as F}from"./chunk-YJ6T3PEP.js";import{b as T,c as N}from"./chunk-S72FVLUX.js";import{a as M}from"./chunk-K5G4FDXD.js";import{a as j}from"./chunk-ZAWRSA7N.js";import{a as R,b}from"./chunk-OFILFO6D.js";import{b as P,c as E,g as D,i as S,k as I,l as $,o as A}from"./chunk-IMGIDBCC.js";import{a as u}from"./chunk-ZC65Z3CK.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 D(e,"linters",i=>A(i).linters,n),{available:o,evidence:s}=await I(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 S(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 $(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:T,apiVersion:N,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 z(e,s,async i=>{try{let a=await C(o.config,{projectRoot:e.cwd,filePath:i,env:e.env,signal:e.signal,processAccess:O(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 _(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 E(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:R,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=P(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([j(t,f),F(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};