pi-agent-ide 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (395) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +2 -2
  3. package/dist/{chunk-AWXVJ5AC.js → chunk-2RTCSZB3.js} +1 -1
  4. package/dist/{chunk-QEJGED4V.js → chunk-3HYXQ4YA.js} +1 -1
  5. package/dist/chunk-3JO7QFIL.js +1 -0
  6. package/dist/{chunk-5J43L2RL.js → chunk-4NIFBFFR.js} +1 -1
  7. package/dist/{chunk-BSICWXMH.js → chunk-64M3SQPG.js} +1 -1
  8. package/dist/{chunk-3BBJZSMS.js → chunk-7LD2OQH3.js} +1 -1
  9. package/dist/chunk-7LZKOHH2.js +1 -0
  10. package/dist/chunk-AJRIASPQ.js +2 -0
  11. package/dist/chunk-EAZGN5ND.js +7 -0
  12. package/dist/{chunk-GIRAEVUJ.js → chunk-F5YZG77W.js} +1 -1
  13. package/dist/chunk-FK42RSF4.js +1 -0
  14. package/dist/{chunk-WJTHY6AG.js → chunk-FXNKMNSJ.js} +1 -1
  15. package/dist/chunk-GBLKIB6O.js +2 -0
  16. package/dist/{chunk-KUPHNMUK.js → chunk-KBP3QUDT.js} +1 -1
  17. package/dist/{chunk-VBICI5YA.js → chunk-KR36BT5E.js} +1 -1
  18. package/dist/chunk-OE7QVAI2.js +5 -0
  19. package/dist/chunk-PNU3E7IO.js +3 -0
  20. package/dist/chunk-PS2B6THP.js +3 -0
  21. package/dist/{chunk-HPUAIWIH.js → chunk-PYPPV2F5.js} +1 -1
  22. package/dist/{chunk-FUG2TEKI.js → chunk-QFTBY67N.js} +2 -2
  23. package/dist/chunk-S5LXX32D.js +28 -0
  24. package/dist/chunk-SQKAXYIR.js +2 -0
  25. package/dist/chunk-VCGNVTXQ.js +1 -0
  26. package/dist/chunk-XYS4FSCC.js +12 -0
  27. package/dist/{chunk-FBOW7XOV.js → chunk-YRF7OATP.js} +1 -1
  28. package/dist/entry-11.js +1 -1
  29. package/dist/entry-13.js +1 -1
  30. package/dist/entry-14.js +1 -1
  31. package/dist/entry-15.js +1 -1
  32. package/dist/entry-17.js +1 -1
  33. package/dist/entry-25.js +1 -1
  34. package/dist/entry-26.js +1 -1
  35. package/dist/entry-28.js +1 -1
  36. package/dist/entry-29.js +1 -1
  37. package/dist/entry-30.js +1 -1
  38. package/dist/entry-31.js +13 -11
  39. package/dist/entry-33.js +1 -1
  40. package/dist/entry-37.js +6 -6
  41. package/dist/entry-42.js +1 -1
  42. package/dist/entry-44.js +1 -1
  43. package/dist/entry-45.js +13 -13
  44. package/dist/entry-46.js +1 -1
  45. package/dist/entry-49.js +1 -1
  46. package/dist/entry-50.js +3 -6
  47. package/dist/entry-51.js +11 -9
  48. package/dist/entry-52.js +1 -1
  49. package/dist/entry-53.js +1 -1
  50. package/dist/entry-54.js +1 -1
  51. package/dist/entry-56.js +1 -1
  52. package/dist/entry-58.js +1 -1
  53. package/dist/entry-60.js +1 -1
  54. package/dist/entry-61.js +0 -1
  55. package/dist/entry-62.js +1 -0
  56. package/dist/entry-63.js +0 -1
  57. package/dist/entry-64.js +1 -0
  58. package/dist/entry-65.js +1 -1
  59. package/dist/entry-66.js +1 -1
  60. package/dist/entry-67.js +1 -1
  61. package/dist/entry-68.js +1 -1
  62. package/dist/entry-69.js +1 -1
  63. package/dist/entry-70.js +1 -1
  64. package/dist/entry-71.js +0 -1
  65. package/dist/entry-72.js +1 -0
  66. package/dist/entry-73.js +0 -1
  67. package/dist/entry-74.js +1 -0
  68. package/dist/entry-75.js +1 -1
  69. package/dist/entry-76.js +1 -1
  70. package/dist/entry-77.js +67 -1
  71. package/dist/entry-78.js +14 -325
  72. package/dist/entry-79.js +2 -18
  73. package/dist/entry-80.js +1 -2
  74. package/dist/entry-81.js +1 -1
  75. package/dist/entry-82.js +5 -1
  76. package/dist/entry-83.js +3 -5
  77. package/dist/entry-84.js +1 -3
  78. package/dist/entry-85.js +1 -1
  79. package/dist/entry-86.js +1 -1
  80. package/dist/pi-agent-ide.js +5 -5
  81. package/docs/agent-guides/editing.md +20 -4
  82. package/docs/agent-guides/git-changes.md +1 -1
  83. package/docs/agent-guides/read-resources.md +9 -1
  84. package/docs/agent-guides/search-code.md +38 -1
  85. package/docs/agent-guides/select-code.md +194 -0
  86. package/docs/configuration.md +12 -17
  87. package/docs/development.md +2 -1
  88. package/docs/releases.md +1 -1
  89. package/docs/research/apply-native-capability-matrix.md +174 -0
  90. package/docs/research/apply-read-latency.md +2 -0
  91. package/docs/research/lpt-393-fuzzy-results/file.json +152 -0
  92. package/docs/research/lpt-393-fuzzy-results/repo.json +122 -0
  93. package/docs/research/lpt-393-search-fuzzy-fallback.md +97 -0
  94. package/docs/research/native-codemode-batch-decision.md +2 -0
  95. package/docs/research/native-codemode-batching.md +1 -1
  96. package/docs/structured-results.md +32 -5
  97. package/docs/tools.md +6 -2
  98. package/docs/user-hooks.md +1 -1
  99. package/node_modules/pi-agent-doctor/package.json +1 -1
  100. package/node_modules/pi-agent-documentation/package.json +1 -1
  101. package/node_modules/pi-agent-filesystem/package.json +7 -7
  102. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  103. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  104. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  105. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  106. package/node_modules/pi-agent-ide-ast/package.json +15 -10
  107. package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
  108. package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
  109. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +5 -1
  110. package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +204 -0
  111. package/node_modules/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
  112. package/node_modules/pi-agent-ide-ast/src/extension.ts +4 -2
  113. package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
  114. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +107 -21
  115. package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +104 -0
  116. package/node_modules/pi-agent-ide-ast/src/select-schema.ts +384 -0
  117. package/node_modules/pi-agent-ide-ast/src/selection-region.ts +41 -0
  118. package/node_modules/pi-agent-ide-ast/src/source-text.ts +92 -0
  119. package/node_modules/pi-agent-ide-ast/src/text-selection.ts +214 -0
  120. package/node_modules/pi-agent-ide-ast/src/tool-select.ts +251 -0
  121. package/node_modules/pi-agent-ide-changes/index.ts +2 -18
  122. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  123. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
  124. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
  125. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  126. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  127. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  128. package/node_modules/pi-agent-ide-lsp/index.ts +2 -2
  129. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  130. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
  131. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
  132. package/node_modules/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
  133. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
  134. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
  135. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +88 -45
  136. package/node_modules/pi-agent-image/package.json +2 -2
  137. package/node_modules/pi-agent-invariant/package.json +1 -1
  138. package/node_modules/pi-agent-pdf/package.json +2 -2
  139. package/node_modules/pi-agent-read/package.json +7 -7
  140. package/node_modules/pi-agent-read/src/api/read-parameters.ts +2 -2
  141. package/node_modules/pi-agent-read/src/api/tools/read.ts +4 -0
  142. package/node_modules/pi-agent-read/src/core/extension.ts +11 -0
  143. package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
  144. package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +2 -0
  145. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +8 -1
  146. package/node_modules/pi-agent-resource/package.json +1 -1
  147. package/node_modules/pi-agent-resource/src/index.ts +10 -0
  148. package/node_modules/pi-agent-resource/src/result-targets.ts +233 -0
  149. package/node_modules/pi-agent-search/package.json +5 -5
  150. package/node_modules/pi-agent-search/src/api/fuzzy.ts +208 -0
  151. package/node_modules/pi-agent-search/src/api/presentation.ts +68 -0
  152. package/node_modules/pi-agent-search/src/api/search-parameters.ts +9 -3
  153. package/node_modules/pi-agent-search/src/api/search-scope.ts +22 -0
  154. package/node_modules/pi-agent-search/src/api/search.ts +28 -0
  155. package/node_modules/pi-agent-search/src/api/structured-result.ts +69 -14
  156. package/node_modules/pi-agent-search/src/core/extension.ts +56 -16
  157. package/node_modules/pi-agent-search/src/core/search-core.ts +9 -1
  158. package/node_modules/pi-agent-search-text/index.ts +3 -1
  159. package/node_modules/pi-agent-search-text/package.json +7 -6
  160. package/node_modules/pi-agent-search-text/src/fuzzy-search.ts +164 -0
  161. package/node_modules/pi-agent-search-text/src/resolvers.ts +161 -30
  162. package/node_modules/pi-agent-search-text/src/scoped-search.ts +103 -0
  163. package/node_modules/pi-agent-search-text/src/search-backend.ts +104 -17
  164. package/node_modules/pi-agent-search-text/src/search-renderer.ts +89 -292
  165. package/node_modules/pi-agent-search-text/src/search-result.ts +77 -0
  166. package/node_modules/pi-agent-search-text/src/search-session.ts +96 -11
  167. package/node_modules/pi-agent-text/package.json +2 -2
  168. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  169. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  170. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  171. package/node_modules/pi-agent-text-editor/index.ts +0 -5
  172. package/node_modules/pi-agent-text-editor/package.json +26 -31
  173. package/node_modules/pi-agent-text-editor/runtime/entry-77.js +1 -0
  174. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
  175. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
  176. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
  177. package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
  178. package/node_modules/pi-agent-text-editor/src/core/extension.ts +12 -2
  179. package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
  180. package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +1 -1
  181. package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
  182. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
  183. package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
  184. package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +199 -19
  185. package/node_modules/pi-agent-text-editor/src/core/result-input.ts +22 -0
  186. package/node_modules/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
  187. package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
  188. package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +109 -11
  189. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
  190. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
  191. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +211 -223
  192. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -6
  193. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
  194. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
  195. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
  196. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
  197. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
  198. package/node_modules/pi-agent-text-editor-renderer/index.ts +1 -72
  199. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  200. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
  201. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
  202. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  203. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  204. package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +1 -0
  205. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  206. package/node_modules/pi-agent-tool-ui/src/index.ts +7 -0
  207. package/node_modules/pi-agent-tool-ui/src/result-panel.ts +298 -0
  208. package/node_modules/pi-agent-web/index.ts +3 -0
  209. package/node_modules/pi-agent-web/package.json +8 -8
  210. package/node_modules/pi-agent-web/runtime/entry-82.js +2 -0
  211. package/node_modules/pi-agent-web/src/search.ts +111 -2
  212. package/node_modules/pi-agent-web-html/package.json +3 -3
  213. package/node_modules/pi-agent-web-image/package.json +4 -4
  214. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  215. package/node_modules/pi-agent-web-text/package.json +4 -4
  216. package/package.json +35 -36
  217. package/src/composite/module-labels.ts +1 -1
  218. package/src/composite/preferences.ts +0 -5
  219. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  220. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  221. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  222. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  223. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  224. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +3 -0
  225. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
  226. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  227. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +2 -0
  228. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  229. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  230. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  231. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +2 -0
  232. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +111 -2
  233. package/src/extensions/pi-agent-read/package.json +7 -7
  234. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
  235. package/src/extensions/pi-agent-read/src/api/tools/read.ts +4 -0
  236. package/src/extensions/pi-agent-read/src/core/extension.ts +11 -0
  237. package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
  238. package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +2 -0
  239. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +8 -1
  240. package/src/extensions/pi-agent-search/package.json +5 -5
  241. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +3 -1
  242. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -6
  243. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/fuzzy-search.ts +164 -0
  244. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +161 -30
  245. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +103 -0
  246. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +104 -17
  247. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +89 -292
  248. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +77 -0
  249. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +96 -11
  250. package/src/extensions/pi-agent-search/src/api/fuzzy.ts +208 -0
  251. package/src/extensions/pi-agent-search/src/api/presentation.ts +68 -0
  252. package/src/extensions/pi-agent-search/src/api/search-parameters.ts +9 -3
  253. package/src/extensions/pi-agent-search/src/api/search-scope.ts +22 -0
  254. package/src/extensions/pi-agent-search/src/api/search.ts +28 -0
  255. package/src/extensions/pi-agent-search/src/api/structured-result.ts +69 -14
  256. package/src/extensions/pi-agent-search/src/core/extension.ts +56 -16
  257. package/src/extensions/pi-agent-search/src/core/search-core.ts +9 -1
  258. package/src/extensions/pi-agent-text-editor/index.ts +0 -5
  259. package/src/extensions/pi-agent-text-editor/package.json +26 -31
  260. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  261. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  262. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  263. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +1 -72
  264. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  265. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
  266. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
  267. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
  268. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  269. package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +1 -0
  270. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
  271. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
  272. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
  273. package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
  274. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +12 -2
  275. package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
  276. package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +1 -1
  277. package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
  278. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
  279. package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
  280. package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +199 -19
  281. package/src/extensions/pi-agent-text-editor/src/core/result-input.ts +22 -0
  282. package/src/extensions/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
  283. package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
  284. package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +109 -11
  285. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
  286. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
  287. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +211 -223
  288. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -6
  289. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
  290. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
  291. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
  292. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
  293. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
  294. package/src/pi-agent-ide.ts +0 -6
  295. package/src/plugins/pi-agent-ide-ast/package.json +15 -10
  296. package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
  297. package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
  298. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +5 -1
  299. package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +204 -0
  300. package/src/plugins/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
  301. package/src/plugins/pi-agent-ide-ast/src/extension.ts +4 -2
  302. package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
  303. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +107 -21
  304. package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +104 -0
  305. package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +384 -0
  306. package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +41 -0
  307. package/src/plugins/pi-agent-ide-ast/src/source-text.ts +92 -0
  308. package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +214 -0
  309. package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +251 -0
  310. package/src/plugins/pi-agent-ide-changes/index.ts +2 -18
  311. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  312. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
  313. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
  314. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  315. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  316. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  317. package/src/plugins/pi-agent-ide-lsp/index.ts +2 -2
  318. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  319. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
  320. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
  321. package/src/plugins/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
  322. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
  323. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
  324. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +88 -45
  325. package/src/plugins/pi-agent-ide-terminal/src/search.ts +10 -36
  326. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -1
  327. package/src/plugins/pi-agent-ide-vision/index.ts +19 -0
  328. package/dist/chunk-2P2OGO3G.js +0 -2
  329. package/dist/chunk-6EYWFBNG.js +0 -0
  330. package/dist/chunk-7AVXUV4A.js +0 -7
  331. package/dist/chunk-7WCZOO5I.js +0 -1
  332. package/dist/chunk-BAYETTZZ.js +0 -16
  333. package/dist/chunk-BVK5A7ED.js +0 -28
  334. package/dist/chunk-F7NVAC4Q.js +0 -0
  335. package/dist/chunk-FZBCKIJJ.js +0 -1
  336. package/dist/chunk-I5JLCFUX.js +0 -1
  337. package/dist/chunk-MIZAFRDR.js +0 -1
  338. package/dist/chunk-PJPA5EEE.js +0 -2
  339. package/dist/chunk-PXWDDBBC.js +0 -0
  340. package/dist/chunk-TQZBVOTT.js +0 -5
  341. package/dist/chunk-VWW3RLUX.js +0 -12
  342. package/dist/chunk-YHUTTZC6.js +0 -2
  343. package/dist/chunk-ZODCBFBL.js +0 -2
  344. package/dist/entry-87.js +0 -1
  345. package/docs/agent-guides/apply.md +0 -333
  346. package/node_modules/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
  347. package/node_modules/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
  348. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
  349. package/node_modules/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
  350. package/node_modules/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
  351. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
  352. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
  353. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +0 -276
  354. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
  355. package/node_modules/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
  356. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
  357. package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +0 -137
  358. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
  359. package/node_modules/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
  360. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
  361. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
  362. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  363. package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +0 -1
  364. package/node_modules/pi-agent-web-text/runtime/entry-87.js +0 -2
  365. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +0 -2
  366. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +0 -2
  367. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
  368. package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +0 -2
  369. package/src/extensions/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
  370. package/src/extensions/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
  371. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
  372. package/src/extensions/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
  373. package/src/extensions/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
  374. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
  375. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
  376. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +0 -276
  377. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
  378. package/src/extensions/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
  379. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
  380. package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +0 -137
  381. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
  382. package/src/extensions/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
  383. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
  384. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
  385. /package/node_modules/{pi-agent-text-editor → pi-agent-text-editor-renderer}/runtime/entry-78.js +0 -0
  386. /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
  387. /package/node_modules/{pi-agent-tool-call-interception → pi-agent-tool-ui}/runtime/entry-81.js +0 -0
  388. /package/node_modules/{pi-agent-web → pi-agent-web-html}/runtime/entry-83.js +0 -0
  389. /package/node_modules/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
  390. /package/node_modules/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
  391. /package/node_modules/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
  392. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
  393. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
  394. /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
  395. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
@@ -1,72 +1,115 @@
1
1
  import { searchSymbols } from "./lsp/symbol-search.js";
2
-
2
+ import path from "node:path";
3
+ import { selectionData, renderSearchMatches } from "pi-agent-search/api/search";
3
4
  import type { LspManager } from "./lsp/manager.js";
4
5
  import type { SymbolHit } from "./lsp/symbol-search.js";
5
- import type { SearchResolver } from "pi-agent-search/api/search";
6
+ import type { SearchPluginApi, SearchResolver } from "pi-agent-search/api/search";
6
7
 
8
+ /** Expose strict LSP discovery and explicit reference navigation as shared source targets. */
7
9
  export function createLspSearchResolver(
8
10
  managerFor: (cwd: string) => Promise<LspManager>,
11
+ registerSelection: SearchPluginApi["registerSelection"],
9
12
  ): SearchResolver {
10
13
  return {
11
14
  id: "symbols",
15
+ supportsResultScope: true,
12
16
  // Workspace symbol backends may read beyond the requested path.
13
17
  readResources: (request) => (request.query.startsWith("symbols:") ? undefined : []),
14
18
  toScriptData(payload) {
15
- const { query, hits } = payload as { query: string; hits: readonly SymbolHit[] };
16
- return {
17
- kind: "custom",
18
- resolverId: "symbols",
19
- value: {
20
- query,
21
- hits: hits.map((hit) => ({
22
- source: hit.filePath,
23
- lineNumber: hit.lineNumber,
24
- column: hit.column,
25
- kind: hit.kind,
26
- name: hit.name,
27
- })),
28
- },
29
- };
19
+ return (payload as { readonly data: unknown }).data;
30
20
  },
31
21
  async tryResolve(request, context) {
32
- if (!request.query.startsWith("symbols:")) {
33
- return { kind: "not-handled" };
34
- }
35
-
22
+ if (!request.query.startsWith("symbols:")) return { kind: "not-handled" };
36
23
  const query = request.query.slice("symbols:".length).trim();
37
-
38
- if (query.length === 0) {
24
+ if (query.length === 0)
39
25
  return { kind: "failed", error: new Error("symbols: query must not be empty") };
40
- }
41
-
42
26
  const manager = await managerFor(context.cwd);
43
- const hits = await searchSymbols(
44
- query,
45
- context.cwd,
46
- request.limit ?? 100,
47
- context.signal,
48
- request,
49
- manager,
27
+ const collect = (signal?: AbortSignal) =>
28
+ searchSymbols(
29
+ query,
30
+ context.cwd,
31
+ request.limit ?? 100,
32
+ signal,
33
+ { ...request, ...(context.scope === undefined ? {} : { resultScope: context.scope }) },
34
+ manager,
35
+ );
36
+ const found = await collect(context.signal);
37
+ const session = await registerSelection(
38
+ {
39
+ request,
40
+ matches: found.hits,
41
+ complete: found.complete,
42
+ refresh: async (signal) => {
43
+ const refreshed = await collect(signal);
44
+ return { matches: refreshed.hits, complete: refreshed.complete };
45
+ },
46
+ },
47
+ context,
50
48
  );
51
- return { kind: "resolved", payload: { query, hits } };
49
+ const data = selectionData(found.hits, found.complete, session.id, session);
50
+ return {
51
+ kind: "resolved",
52
+ payload: {
53
+ query,
54
+ hits: found.hits,
55
+ complete: found.complete,
56
+ navigation: request.navigation,
57
+ data: {
58
+ ...data,
59
+ matches: data.matches.map((match, index) => ({
60
+ ...match,
61
+ role: found.hits[index]?.role,
62
+ symbol: found.hits[index]?.symbol,
63
+ })),
64
+ },
65
+ },
66
+ };
52
67
  },
53
- format(payload) {
54
- const { query, hits } = payload as {
68
+ renderResult(result, options, theme) {
69
+ const data = result.details as {
70
+ hits: readonly SymbolHit[];
71
+ complete: boolean;
72
+ navigation?: "references";
73
+ cwd: string;
74
+ };
75
+ return renderSearchMatches(
76
+ data.hits,
77
+ data.complete,
78
+ theme,
79
+ options.expanded,
80
+ data.cwd,
81
+ data.navigation === "references"
82
+ ? ["LSP reference navigation · may leave input scope"]
83
+ : [],
84
+ data.hits.map((hit) => `${hit.role} ${hit.symbol.name}`),
85
+ );
86
+ },
87
+ format(payload, context) {
88
+ const result = payload as {
55
89
  readonly query: string;
56
90
  readonly hits: readonly SymbolHit[];
91
+ readonly complete: boolean;
92
+ readonly navigation?: "references";
57
93
  };
58
- const text =
59
- hits.length === 0
60
- ? "No symbols found."
61
- : hits
94
+ const heading =
95
+ result.navigation === "references"
96
+ ? "LSP reference navigation (may leave input scope)"
97
+ : "LSP symbols inside scope";
98
+ const lines =
99
+ result.hits.length === 0
100
+ ? ["No symbols found."]
101
+ : result.hits
102
+ .slice(0, 100)
62
103
  .map(
63
104
  (hit, index) =>
64
- `${String(index + 1)}. ${hit.filePath}:${String(hit.lineNumber)}:${String(
65
- hit.column,
66
- )} ${hit.kind} ${hit.name}`,
67
- )
68
- .join("\n");
69
- return { content: [{ type: "text", text }], details: { query, hits } };
105
+ `${String(index + 1)}. ${path.relative(context.cwd, hit.source)}:${String(hit.lineNumber)}:${String(hit.startColumn + 1)} ${hit.role} ${hit.symbol.name}`,
106
+ );
107
+ if (!result.complete) lines.push("Incomplete results; not a complete edit scope.");
108
+ if (result.hits.length > 100) lines.push("Preview shortened; full source targets retained.");
109
+ return {
110
+ content: [{ type: "text", text: [heading, ...lines].join("\n") }],
111
+ details: { ...result, cwd: context.cwd },
112
+ };
70
113
  },
71
114
  };
72
115
  }
@@ -5,12 +5,11 @@ import {
5
5
  type SearchPlugin,
6
6
  } from "pi-agent-search/api/plugin-protocol";
7
7
  import type { SearchRequest, SearchSelectionMatch } from "pi-agent-search/api/search";
8
- import { selectionData } from "pi-agent-search/api/search";
8
+ import { selectionData, renderSearchMatches } from "pi-agent-search/api/search";
9
+ import type { Theme } from "@earendil-works/pi-coding-agent";
9
10
 
10
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
- import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
12
12
 
13
- import { renderTerminalAction } from "#src/plugins/pi-agent-ide-terminal/src/renderer.js";
14
13
  import type { TerminalSessionManager } from "#src/plugins/pi-agent-ide-terminal/src/session-manager.js";
15
14
  import type { TerminalSessionSnapshot } from "#src/plugins/pi-agent-ide-terminal/src/types.js";
16
15
 
@@ -91,48 +90,23 @@ function terminalSearchResolver(manager: TerminalSessionManager) {
91
90
  renderResult(
92
91
  result: { details: unknown },
93
92
  options: { readonly expanded?: boolean },
94
- theme: Parameters<typeof renderTerminalAction>[4],
93
+ theme: Theme,
95
94
  ) {
96
95
  const details = result.details;
97
96
  const payload = isRecord(details) ? parsePayload(details.payload) : parsePayload(undefined);
98
- const content = renderTerminalAction(
99
- payload.snapshot,
100
- "search",
101
- JSON.stringify(payload.query),
102
- payload.matches.slice(-6).map((match) => `${match.lineNumber}: ${match.lineText}`),
97
+ return renderSearchMatches(
98
+ payload.matches,
99
+ false,
103
100
  theme,
101
+ options.expanded === true,
102
+ undefined,
103
+ [`Retained terminal output · ${payload.snapshot.status} · read-only`],
104
104
  );
105
- return new TerminalSearchPanel(content, options.expanded === true, theme);
106
105
  },
107
106
  };
108
107
  }
109
108
 
110
- const COMPACT_TERMINAL_SEARCH_ROWS = 12;
111
-
112
- /** Keep terminal search readable without changing the complete agent-facing result. */
113
- export class TerminalSearchPanel implements Component {
114
- public constructor(
115
- private readonly content: Component,
116
- private readonly expanded: boolean,
117
- private readonly theme: Parameters<typeof renderTerminalAction>[4],
118
- ) {}
119
-
120
- public render(width: number): string[] {
121
- const rows = this.content.render(width);
122
- if (this.expanded || rows.length <= COMPACT_TERMINAL_SEARCH_ROWS) return rows;
123
- const shown = COMPACT_TERMINAL_SEARCH_ROWS - 1;
124
- const omitted = String(rows.length - shown);
125
- const fullHint = `… ${omitted} visual rows omitted · ctrl+o to expand`;
126
- const hint =
127
- visibleWidth(fullHint) <= width ? fullHint : `… ${omitted} visual rows omitted · ctrl+o`;
128
- return [...rows.slice(0, shown), this.theme.fg("muted", truncateToWidth(hint, width))];
129
- }
130
-
131
- public invalidate(): void {
132
- this.content.invalidate();
133
- }
134
- }
135
-
109
+ /** Find literal matches in retained output without claiming a complete source scope. */
136
110
  export function findTerminalMatches(
137
111
  snapshot: TerminalSessionSnapshot,
138
112
  request: SearchRequest,
@@ -89,7 +89,7 @@ export function registerTerminalTools(
89
89
  label: profile.displayName,
90
90
  promptSnippet: `Execute ${profile.displayName} commands in synchronous or background terminal sessions`,
91
91
  promptGuidelines: [
92
- `Do not use ${toolName} commands or scripts to edit files. Use Apply or the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`,
92
+ `Do not use ${toolName} commands or scripts to edit files. Use the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`,
93
93
  ],
94
94
  description: `Use ${toolName} to execute a command in the user's configured ${profile.displayName} shell (${profile.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,
95
95
  parameters: runParameters,
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { ResultPanel } from "pi-agent-tool-ui";
2
3
  import { connectAgentDocumentation, loadPackagedAgentGuide } from "pi-agent-documentation";
3
4
 
4
5
  import type { BuiltinExtensionContext } from "#src/composite/selection.js";
@@ -166,6 +167,24 @@ export default async function registerVision(
166
167
  .slice(0, Math.min(request.limit ?? 50, 100));
167
168
  return { kind: "resolved" as const, payload: matches };
168
169
  },
170
+ renderResult(result, options, theme) {
171
+ const data = result.details as {
172
+ processes: Awaited<ReturnType<typeof listProcesses>>;
173
+ };
174
+ return new ResultPanel(
175
+ {
176
+ summary: `${data.processes.length} processes shown`,
177
+ rows: data.processes.length
178
+ ? data.processes.map((item) => ({
179
+ kind: "note",
180
+ text: `${item.pid} ${item.command}`,
181
+ }))
182
+ : [{ kind: "note", text: "No matching processes" }],
183
+ },
184
+ theme,
185
+ options.expanded,
186
+ );
187
+ },
169
188
  format(payload) {
170
189
  const processes = payload as Awaited<ReturnType<typeof listProcesses>>;
171
190
  return {
@@ -1,2 +0,0 @@
1
- import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as ae}from"node:async_hooks";function X(){return{pending:new Set,active:new ae}}o(X,"createSchedulerState");function ue(e,t){return e===void 0||t===void 0?!0:e.some(n=>t.some(r=>(n.mode==="write"||r.mode==="write")&&(n.resource==="*"||r.resource==="*"||n.resource===r.resource||n.recursive===!0&&r.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`)||r.recursive===!0&&n.resource.startsWith(r.resource.endsWith("/")?r.resource:`${r.resource}/`))))}o(ue,"conflicts");function de(e,t,n){if(t===void 0||!n&&t.some(s=>s.mode!=="read"))return!1;if(e===void 0)return!0;let r=new Map;for(let s of t){let i=s.group??s.resource;r.set(i,[...r.get(i)??[],s])}return[...r.values()].every(s=>s.some(i=>e.some(a=>(i.mode==="read"||a.mode==="write")&&(a.resource==="*"||i.resource===a.resource&&(i.recursive!==!0||a.recursive===!0)||a.recursive===!0&&i.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}o(de,"coveredAccess");async function le(e,t){if(t===void 0)return await e;t.throwIfAborted();let n,r=new Promise((s,i)=>{n=o(()=>i(t.reason),"abort"),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}o(le,"waitForDependencies");var I=class e{constructor(t=X()){this.state=t}static{o(this,"ResourceScheduler")}run(t,n,r,s={}){let i=Promise.resolve(t),a=this.state.active.getStore();if(a?.open){let S=i.then(R=>{if(r?.throwIfAborted(),!de(a.accesses,R,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 R});a.nested??=new e;let f=a.nested.run(S,n,r,{allowNestedWrites:a.allowNestedWrites});return a.children.add(f),f.then(()=>a.children.delete(f),()=>a.children.delete(f)),f}let m=[...this.state.pending],p=i.catch(()=>{}),w,d=new Promise(S=>{w=S}),E={accesses:p,done:d};return this.state.pending.add(E),(async()=>{try{r?.throwIfAborted();let S=await le(i.then(async R=>(await Promise.all(m.map($=>Promise.race([$.done,$.accesses.then(ce=>ue(R,ce)?$.done:void 0)]))),R)),r);r?.throwIfAborted();let f={accesses:S,children:new Set,open:!0,allowNestedWrites:s.allowNestedWrites===!0};try{return await this.state.active.run(f,n)}finally{for(;f.children.size>0;)await Promise.allSettled([...f.children]);f.open=!1}}finally{this.state.pending.delete(E),w()}})()}},pe=Symbol.for("pi-agent-resource.resource-scheduler-state"),fe=globalThis,Ce=fe[pe]??=X(),me=new I(Ce);import{realpath as ye,stat as ve}from"node:fs/promises";import N from"node:path";import{fileURLToPath as ge}from"node:url";async function Q(e,t,n){if(/^[a-z][a-z\d+.-]*:/iu.test(e)&&!/^[a-z]:[\\/]/iu.test(e)&&!e.startsWith("file:"))return[{resource:e,mode:n}];let r=N.resolve(t,e.startsWith("file:")?ge(e):e),[s,i]=await Promise.allSettled([ye(r),ve(r,{bigint:!0})]),a;if(s.status==="fulfilled")a=s.value;else{let d=s.reason;if(!(d instanceof Error)||!("code"in d)||d.code!=="ENOENT")throw d;let E=N.dirname(r);if(E===r)a=r;else{let f=(await Q(E,t,n)).find(R=>R.resource.startsWith("file:"));a=N.join(f?.resource.slice(5)??E,N.basename(r))}}let m=a.split(N.sep).join("/"),p=`file:${process.platform==="win32"?m.toLowerCase():m}`,w=[{resource:p,group:p,mode:n}];if(i.status==="fulfilled"){let d=i.value;d.isDirectory()&&(w[0]={resource:p,group:p,mode:n,recursive:!0}),d.ino!==0n&&w.push({resource:`inode:${d.dev}:${d.ino}`,group:p,mode:n,recursive:d.isDirectory()})}else{let d=i.reason;if(!(d instanceof Error)||!("code"in d)||d.code!=="ENOENT")throw d}return w}o(Q,"resourceAccesses");import{Type as l}from"typebox";import{Value as Re}from"typebox/value";var W=l.Object({code:l.String(),message:l.String(),source:l.Optional(l.String())},{additionalProperties:!1});function Z(e){return l.Union([l.Object({status:l.Literal("success"),data:e,errors:l.Array(W,{maxItems:0})},{additionalProperties:!1}),l.Object({status:l.Union([l.Literal("error"),l.Literal("partial")]),data:l.Optional(e),errors:l.Array(W,{minItems:1})},{additionalProperties:!1})])}o(Z,"structuredResultSchema");var ee=1024*1024;function H(e){let t=new Set,n=o(r=>{if(!(r===null||typeof r=="string"||typeof r=="boolean")&&!(typeof r=="number"&&Number.isFinite(r))){if(typeof r!="object"||t.has(r))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");t.add(r);for(let s of Array.isArray(r)?r:Object.values(r))n(s);t.delete(r)}},"visit");if(n(e),Buffer.byteLength(JSON.stringify(e))>ee)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}o(H,"assertJsonData");function te(e,t="EXECUTION_FAILED",n){return{code:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:t,message:e instanceof Error?e.message:String(e),...n===void 0?{}:{source:n}}}o(te,"resultError");function he(e,t,n){try{if(H(n),!Re.Check(Z(t),n))throw new TypeError("Result adapter returned data outside its public schema");return{...e,structuredContent:n,isError:n.status!=="success"}}catch(r){let s=te(r,"INVALID_STRUCTURED_RESULT"),i={status:"error",errors:[s]};return H(i),{...e,content:[...e.content,{type:"text",text:s.message}],structuredContent:i,isError:!0}}}o(he,"withStructuredResult");function Te(e,t){if(t.length===0)return;let n=e.trim();if(n.length===0||/[\r\n]/u.test(n))throw new TypeError("Content provider summary must be one non-empty line");return[n,...t.map(({description:r})=>r)].join(`
2
- `)}o(Te,"renderContentDescription");import{Type as u}from"typebox";import{Value as Pe}from"typebox/value";import{Type as c}from"typebox";import{Value as we}from"typebox/value";var C={additionalProperties:!0},k=c.Function([],c.Unknown()),y=c.String({minLength:1}),Ee=c.Object({type:c.Literal("text"),text:c.String(),textSignature:c.Optional(c.String())},C),Se=c.Object({type:c.Literal("image"),data:c.String(),mimeType:c.String()},C),be=c.Object({type:c.Literal("custom"),kind:y,data:c.Unknown()},C),Oe=c.Array(c.Union([Ee,Se,be]),{minItems:1}),ne=c.Union([c.Object({source:y,link:c.Optional(y),read:k,write:c.Optional(c.Never())},C),c.Object({source:y,link:c.Optional(y),read:c.Optional(c.Never()),write:k},C),c.Object({source:y,link:c.Optional(y),read:k,write:k},C)]),Ae=c.Object({id:y,tryResolve:k},C),xe=c.Union([c.Object({kind:c.Literal("not-handled")},C),c.Object({kind:c.Literal("resolved"),resource:ne},C),c.Object({kind:c.Literal("failed"),error:c.Unknown()},C)]);function q(e){return _(Oe,e)?D(()=>e.every(t=>t.type!=="text"||!("textSignature"in t)||typeof t.textSignature=="string")):!1}o(q,"isAgentContent");function re(e){return _(ne,e)?D(()=>{let t=e,n=!("read"in t)||typeof t.read=="function",r=!("write"in t)||typeof t.write=="function";return n&&r}):!1}o(re,"isResource");function Ne(e){return _(Ae,e)}o(Ne,"isResourceResolver");function ke(e){return _(xe,e)?D(()=>{let t=e;return t.kind!=="resolved"||re(t.resource)}):!1}o(ke,"isResourceResolutionAttempt");function _(e,t){return D(()=>we.Check(e,t))}o(_,"safeCheck");function D(e){try{return e()}catch{return!1}}o(D,"safeEvaluate");var v={additionalProperties:!0},je=u.Function([],u.Unknown()),L=u.String({minLength:1}),Ie=u.Object({provider:L,capability:u.Union([u.Literal("read"),u.Literal("write")])},v),_e=u.Object({source:L,bytes:u.Unknown(),mediaType:u.Optional(u.String())},v),De=u.Object({signal:u.Optional(u.Unknown())},v),Le=u.Object({id:L,description:L,tryConvert:je},v),Ue=u.Union([u.Object({kind:u.Literal("not-handled")},v),u.Object({kind:u.Literal("converted"),content:u.Unknown()},v),u.Object({kind:u.Literal("failed"),error:u.Unknown()},v)]),Ve=u.Object({target:u.Unknown(),converter:u.Unknown(),priority:u.Optional(u.Number())},v);function b(e){return O(Ie,e)&&T(()=>e.provider.trim().length>0)}o(b,"isContentTarget");function K(e){return O(_e,e)?T(()=>{let t=e;return t.bytes instanceof Uint8Array&&(!("mediaType"in t)||typeof t.mediaType=="string")}):!1}o(K,"isContentInput");function z(e){return O(De,e)?T(()=>{let t=e;return!("signal"in t)||t.signal instanceof AbortSignal}):!1}o(z,"isContentConversionContext");function oe(e){return O(Le,e)?T(()=>{let t=e;return t.id.trim().length>0&&t.description.trim().length>0&&!/[\r\n]/u.test(t.description)}):!1}o(oe,"isContentConverter");function F(e){return O(Ue,e)?T(()=>{let t=e;return t.kind!=="converted"||q(t.content)}):!1}o(F,"isContentConversionAttempt");function h(e){return O(Ve,e)?T(()=>{let t=e;return b(t.target)&&oe(t.converter)&&(!("priority"in t)||typeof t.priority=="number"&&Number.isFinite(t.priority))}):!1}o(h,"isContentConverterRegistration");function O(e,t){return T(()=>Pe.Check(e,t))}o(O,"safeCheck");function T(e){try{return e()}catch{return!1}}o(T,"safeEvaluate");var U=class extends Error{static{o(this,"UnsupportedContentError")}source;target;constructor(t,n){super(`No content converter for ${t} in ${n.provider}/${n.capability}`),this.name="UnsupportedContentError",this.source=t,this.target=n}};function Y(e){if(!b(e))throw new TypeError("Invalid content target");let t={...e},n=[],r=o(()=>[...n].sort((s,i)=>s.priority-i.priority||s.order-i.order),"snapshotConverters");return{target:t,register(s){if(!h(s))throw new TypeError("Invalid content converter registration");if(!A(t,s.target))throw new Error(`Content converter ${s.converter.id} targets ${s.target.provider}/${s.target.capability}, not ${t.provider}/${t.capability}`);if(n.some(({converter:i})=>i.id===s.converter.id))throw new Error(`Content converter ${s.converter.id} is already registered for ${t.provider}/${t.capability}`);n.push({converter:s.converter,priority:s.priority??0,order:n.length})},listDescriptions(){return r().map(({converter:s})=>({id:s.id,description:s.description}))},async convert(s,i){if(!K(s))throw new TypeError("Invalid content input");if(!z(i))throw new TypeError("Invalid content conversion context");B(i.signal);let a=r();for(let{converter:m}of a){B(i.signal);let p=await m.tryConvert(s,i);if(B(i.signal),!F(p))throw new TypeError(`Content converter ${m.id} returned an invalid outcome`);if(p.kind!=="not-handled"){if(p.kind==="failed")throw p.error;return p.content}}throw new U(s.source,t)}}}o(Y,"createContentRunner");function A(e,t){return e.provider===t.provider&&e.capability===t.capability}o(A,"targetsEqual");function B(e){e?.throwIfAborted()}o(B,"throwIfAborted");import{Type as g}from"typebox";import{Value as $e}from"typebox/value";var x="pi-agent-resource/content-conversion",V=2,P=`${x}/host/ready`,j=`${x}/converter/register`,se={additionalProperties:!0},We=g.Function([],g.Unknown()),He=g.Object({protocol:g.Literal(x),apiVersion:g.Literal(V),target:g.Unknown()},se),qe=g.Object({registration:g.Unknown(),accept:We},se);function G(e){return ie(He,e)&&M(()=>b(e.target))}o(G,"isContentHostReady");function J(e){return ie(qe,e)&&M(()=>h(e.registration))}o(J,"isContentConverterRegistrationRequest");function ie(e,t){return M(()=>$e.Check(e,t))}o(ie,"safeCheck");function M(e){try{return e()}catch{return!1}}o(M,"safeEvaluate");function Ke(e,t){let n=Y(t),r=e.events.on(j,s=>{if(!J(s))throw new Error("Invalid content converter registration request");if(!A(n.target,s.registration.target))return;let i;try{n.register(s.registration),i=Promise.resolve()}catch(a){i=Promise.reject(a instanceof Error?a:new Error("Content converter registration failed",{cause:a}))}s.accept(i)});return e.on("session_shutdown",r),e.events.emit(P,{protocol:x,apiVersion:V,target:n.target}),{target:n.target,listDescriptions(){return n.listDescriptions()},convert(s,i){return n.convert(s,i)}}}o(Ke,"createContentHost");function ze(e,t){if(!h(t))throw new TypeError("Invalid content converter registration");let n=o(()=>{let i,a={registration:t,accept(m){if(i!==void 0)throw new Error(`Content converter ${t.converter.id} registration was accepted more than once`);i=m}};return e.events.emit(j,a),i},"announce"),r=o(()=>{},"unsubscribe");r=e.events.on(P,i=>{if(!G(i))throw new Error("Invalid content conversion host readiness event");if(!A(t.target,i.target))return;let a=n();if(a===void 0)throw new Error(`${i.target.provider}/${i.target.capability} announced readiness without accepting content converter ${t.converter.id}`);r(),a.catch(()=>{})}),e.on("session_shutdown",r);let s=n();if(s!==void 0)return r(),s}o(ze,"connectContentConverter");export{I as a,me as b,Q as c,W as d,Z as e,ee as f,H as g,te as h,he as i,Te as j,q as k,re as l,Ne as m,ke as n,b as o,K as p,z as q,oe as r,F as s,h as t,U as u,Y as v,A as w,x,V as y,P as z,j as A,G as B,J as C,Ke as D,ze as E};
File without changes
@@ -1,7 +0,0 @@
1
- import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createTwoFilesPatch as m,diffLines as l}from"diff";function y(i,e,n,r=i){return{diff:m(i,r,e,n,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:p(e,n)}}s(y,"createUnifiedDiff");function p(i,e){let n=0,r=0;for(let t of l(i,e)){let a=g(t.value);t.removed&&(n+=a),t.added&&(r+=a)}return{removed:n,added:r}}s(p,"computeStats");function g(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
2
- `,`
3
- `);return e.endsWith(`
4
- `)?e.slice(0,-1).split(`
5
- `).length:e.split(`
6
- `).length}s(g,"countDiffLines");function x(i,e){let n=l(i,e),r=[],t=0;for(let a of n){let o=g(a.value);o!==0&&(a.removed||(a.added&&r.push({start:t+1,end:t+o}),t+=o))}return E(r)}s(x,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,t)=>r.start-t.start),n=[d(e[0])];for(let r=1;r<e.length;r++){let t=d(n.at(-1)),a=d(e[r]);a.start<=t.end+1?t.end=Math.max(t.end,a.end):n.push(a)}return n}s(E,"mergeAdjacentRanges");var f=class i{static{s(this,"FileRange")}start;end;constructor(e,n=e){n.lineNumber<e.lineNumber&&([e,n]=[n,e]),this.start=e,this.end=n}static fromLines(e,n){let r=n??e;return new i({lineNumber:e},{lineNumber:r})}},c=class i{static{s(this,"FileMutationResult")}data;constructor(e){this.data=e??{}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,n=e?.[0];if(n?.range){let r=n.range.start,a=d(e).at(-1)?.range?.end??r;return new f(r,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let n of this.files)e.add(n.path);for(let n of this.errors)n.path&&e.add(n.path);for(let n of this.warnings)n.file&&e.add(n.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let t=this.errors[0];return t?`Failed: ${t.code??"ERROR"}${t.reason?` \u2014 ${t.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let t=this.appliedPaths;return t&&t.length>0?`${t.length} path${t.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,n=this.overwrittenFiles.length,r=[];if(e>0&&r.push(`Created ${e} ${e===1?"file":"files"}`),n>0&&r.push(`Edited ${n} ${n===1?"file":"files"}`),this.diffs.length>0){let t=0,a=0;for(let o of this.diffs)for(let u of o.split(`
7
- `))u.startsWith("+")&&!u.startsWith("+++")?t++:u.startsWith("-")&&!u.startsWith("---")&&a++;(t>0||a>0)&&r.push(`+${t}/-${a} lines`)}return r.join(", ")}getFileChange(e){return this.files.find(n=>n.path===e)}getDiffFor(e){let n=h(e);for(let r of this.diffs){let t=r.match(/^---\s+(.+)$/m);if(t&&(h(d(t[1]))===n||t[1]===e))return r}}getErrorsFor(e){return this.errors.filter(n=>n.path===e)}getWarningsFor(e){return this.warnings.filter(n=>n.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let n=e;return n.data&&typeof n.data=="object"?(Object.setPrototypeOf(n,i.prototype),n):new i(n)}return new i}};function h(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(h,"normalisePath");export{y as a,x as b,f as c,c as d};
@@ -1 +0,0 @@
1
- import{a as c}from"./chunk-EI7MMDWY.js";import f from"node:path";import{pathToFileURL as p}from"node:url";function g(e,t){let o=new Map;for(let r of e){let n=o.get(r.source)??[];n.push(r),o.set(r.source,n)}let i=new Set,a=e.length,s=[...o].sort(([r,n],[h,u])=>u.length-n.length||r.localeCompare(h));for(let[r,n]of s){if(a<=t)break;i.add(r),a-=n.length}return{files:[...o].sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!i.has(r))return{kind:"detailed",source:r,matches:n};let h=new Map;for(let u of n)h.set(u.lineText,(h.get(u.lineText)??0)+1);return{kind:"compacted",source:r,matchCount:n.length,uniqueLineCount:h.size,groups:o.size===1?[...h].sort(([u,y],[b,C])=>C-y||u.localeCompare(b)).slice(0,t).map(([u,y])=>({text:u,matchCount:y})):[]}})}}c(g,"planSearchPresentation");function F(e,t,o,i,a,s=50){let r=g(t,s).files.map(n=>n.kind==="detailed"?x(n.source,n.matches,i):{path:S(n.source,i),link:p(n.source).href,matchCount:n.matchCount,uniqueLineCount:n.uniqueLineCount,groups:n.groups,lines:[]});return{...a!==void 0&&{sessionId:a},query:e,matchCount:t.length,fileCount:r.length,complete:o,files:r}}c(F,"createSearchToolDetails");function I(e){if(!d(e)||typeof e.query!="string"||!m(e.matchCount)||!m(e.fileCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||!Array.isArray(e.files)||!e.files.every(R))return!1;let t=e.files;return e.fileCount===t.length&&e.matchCount===t.reduce((o,i)=>o+i.matchCount,0)}c(I,"isSearchToolDetails");function x(e,t,o){let i=new Map;for(let s of t){let l=i.get(s.lineNumber);if(l!==void 0&&l.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let r=l??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};r.ranges.push({from:s.startColumn,to:s.endColumn}),i.set(s.lineNumber,r)}let a=[...i.values()].sort((s,l)=>s.lineNumber-l.lineNumber).map(s=>{let l=[...s.ranges].sort((r,n)=>r.from-n.from||r.to-n.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:l.length,ranges:l}});return{path:S(e,o),link:p(e).href,matchCount:t.length,lines:a}}c(x,"createSearchResultFile");function R(e){if(!d(e)||typeof e.path!="string"||typeof e.link!="string"||!m(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(M))return!1;let t=e.lines,o=e.groups,i=new Set(t.flatMap(a=>a.logicalMatchIds??[]));return(o===void 0||Array.isArray(o)&&o.every(a=>d(a)&&typeof a.text=="string"&&m(a.matchCount)))&&(e.uniqueLineCount===void 0||m(e.uniqueLineCount))&&(t.length===0||(i.size>0?i.size===e.matchCount:e.matchCount===t.reduce((a,s)=>a+s.matchCount,0)))}c(R,"isSearchResultFile");function M(e){return d(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&m(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(t=>typeof t=="string"))&&e.ranges.every(t=>k(t,e.text))}c(M,"isSearchResultLine");function k(e,t){return d(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=t.length}c(k,"isSearchResultRange");function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(d,"isRecord");function m(e){return Number.isSafeInteger(e)&&e>=0}c(m,"isCount");function S(e,t){let o=f.relative(t,e);return o.length>0&&!o.startsWith("..")&&!f.isAbsolute(o)?o:e}c(S,"displaySource");export{g as a,F as b,I as c};
@@ -1,16 +0,0 @@
1
- import{a as A,d as R}from"./chunk-7AVXUV4A.js";import{a as v}from"./chunk-FZBCKIJJ.js";import{b as N,d as L}from"./chunk-BSICWXMH.js";import{f as $}from"./chunk-YHUTTZC6.js";import{e as I,h as _,i as O}from"./chunk-2P2OGO3G.js";import{a as u}from"./chunk-EI7MMDWY.js";import B from"node:path";import{truncateHead as q,DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as ae}from"@earendil-works/pi-coding-agent";import{Text as k}from"@earendil-works/pi-tui";import{Type as h}from"typebox";import{Value as le}from"typebox/value";var U=h.Object({source:h.String(),sources:h.Array(h.String())},{additionalProperties:!1}),j=h.Object({kind:h.Literal("diff"),equal:h.Boolean(),before:U,after:U,stats:h.Object({added:h.Integer(),removed:h.Integer()}),diff:h.String(),truncated:h.Boolean(),fullResult:h.Optional(h.String())},{additionalProperties:!1}),ce=I(j),V=h.Union([h.String({minLength:1}),v]),H=h.Object({before:V,after:V},{additionalProperties:!1});async function fe(e,i,c){if(!le.Check(H,i))throw Object.assign(new Error("Use before and after source strings or read request objects"),{code:"INVALID_ARGUMENTS"});let n=i,r=u(async s=>{let t=typeof s=="string"?{path:s}:s,f=await e.read(t,c,"script");if(f.isError||f.details.failure)throw Object.assign(new Error(f.details.failure?.message??"Comparison read failed"),{code:f.details.failure?.code??"READ_FAILED",details:f.details.failure});if(f.script===void 0)throw Object.assign(new Error("Source has no comparable text data"),{code:"UNSUPPORTED_CONTENT"});return J(f.script,t.path??"source")},"resolve"),o=await r(n.before),a=await r(n.after),l=A(o.source,o.content,a.content,a.source);return{kind:"diff",ok:!0,equal:o.content===a.content,before:o,after:a,...l}}u(fe,"executeDiff");function J(e,i){if(e.kind==="text")return{source:e.source,sources:[e.source],content:e.content};if(e.kind==="resources"){let c=e.resources.map(n=>J(n,i));return{source:e.source??i,sources:c.flatMap(n=>n.sources),content:c.map(n=>n.content).join(`
2
- `)}}if(e.kind==="bytes")throw Object.assign(new Error(`Byte sources are not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});if(e.blocks.length===0||e.blocks.some(c=>c.type!=="text"))throw Object.assign(new Error(`Source is not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});return{source:e.source,sources:[e.source],content:e.blocks.flatMap(c=>c.type==="text"?[c.text]:[]).join(`
3
- `)}}u(J,"comparisonText");function S(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="diff"&&"ok"in e&&e.ok===!0}u(S,"isDiffOutcome");function P(e,i=process.cwd()){let c=u(r=>B.isAbsolute(r)?B.relative(i,r)||".":r,"displaySource"),n=`Diff: ${c(e.before.source)} \u2192 ${c(e.after.source)}`;return{results:[new R({ok:!0,path:n,beforeContentMap:{[n]:e.before.content},afterContent:e.after.content,diffs:[e.diff]})]}}u(P,"diffPresentation");function T(e){return e.equal?`No differences: ${e.before.source} \u2192 ${e.after.source}`:e.diff}u(T,"diffText");function Ne(e){return{content:[{type:"text",text:T(e)}],details:{}}}u(Ne,"diffReadResult");function Le(e,i,c){e.registerTool({name:"diff",exposure:"direct",namespace:{name:"ide_read",description:"Read resources and compare sources."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:"Diff",parameters:H,outputSchema:ce,promptSnippet:"Compare two text-readable sources",description:"Use diff to compare two sources. before and after accept a source string or a read request {path, offset?, limit?, views?}. Use any source that read can resolve as text. Omit limit to compare complete resolved text; read presentation limits do not clip comparison inputs. Multiple resolved resources are joined with one newline separator in resolver order. Diff line numbers are relative to each selected text, not the original file when a window is selected. Native non-text content is rejected. Output uses the existing text diff and a shared output budget; oversized output has a full temporary reference. The same diff function is available inside Apply.",renderCall(n,r){return new k(r.fg("toolTitle",r.bold("Diff")),0,0)},renderResult(n,r,o,a){let l=n.details;if(l?.comparison?.equal)return new k(T(l.comparison),0,0);let s=i.getToolRenderer("diff")?.renderResult;return s?s(n,r,o,a):new k(n.content.filter(t=>t.type==="text").map(t=>t.text).join(`
4
- `),0,0)},async execute(n,r,o,a,l){let s=c();if(s===void 0)throw new Error("Diff requires the read extension");try{let t=await fe(s,r,{cwd:l.cwd,signal:o}),f=T(t),m=q(f),y=m.truncated?await s.saveTemporary(f):void 0,p=y===void 0?"":`
5
- Full diff: ${y}`;return O({content:[{type:"text",text:y===void 0?f:q(f,{maxLines:ae-2,maxBytes:se-Buffer.byteLength(p)}).content+p}],details:{...P(t,l.cwd),comparison:t,temporarySource:y}},j,{status:"success",data:{kind:"diff",equal:t.equal,before:{source:t.before.source,sources:t.before.sources},after:{source:t.after.source,sources:t.after.sources},stats:t.stats,diff:m.content,truncated:m.truncated,...y===void 0?{}:{fullResult:y}},errors:[]})}catch(t){if(o?.aborted)throw t;let f=_(t,"DIFF_FAILED");return O({content:[{type:"text",text:f.message}],details:{}},j,{status:"error",errors:[f]})}}})}u(Le,"registerDiff");import{parser as Y}from"@lezer/javascript";import{TreeFragment as W}from"@lezer/common";var pe=new Set(["read","search","diff","open","createFile","deleteFile","copyFile","moveFile","flush","result"]);function z(e,i=Y.parse(e)){let c=[];i.iterate({enter(r){if(r.name==="AssignmentExpression"){let t=r.node.firstChild;t?.name==="VariableName"&&c.push({name:e.slice(t.from,t.to),from:0,to:e.length})}if(r.name!=="VariableDefinition")return;let o=r.node.parent;for(;o?.parent&&!["VariableDeclaration","ParamList","Block","Script"].includes(o.name);)o=o.parent;let a=o?.name==="VariableDeclaration"&&o.firstChild?.name==="var",l=new Set(["Script","FunctionDeclaration","FunctionExpression","ArrowFunction",...a?[]:["Block"]]),s=r.node.parent;for(s?.name==="FunctionDeclaration"&&(s=s.parent);s?.parent&&!l.has(s.name);)s=s.parent;c.push({name:e.slice(r.from,r.to),from:s?.from??0,to:s?.to??e.length})}});let n=[];return i.iterate({enter(r){if(r.name!=="CallExpression")return;let o=r.node.firstChild;if(o?.name!=="VariableName")return;let a=e.slice(o.from,o.to);if(!pe.has(a)||c.some(t=>t.name===a&&t.from<=r.from&&t.to>=r.to))return;let l=r.node.getChild("ArgList")?.getChild("ObjectExpression"),s=Object.create(null);if(!l){let t=r.node.getChild("ArgList"),f=t?e.slice(t.from+1,t.to).replace(/\)$/,""):"";f&&(s.arguments={text:f.length>160?f.slice(0,120)+"\u2026":f,literal:!1})}for(let t of l?.getChildren("Property")??[]){let f=t.firstChild,y=(f?e.slice(f.from,f.to):"").replace(/^["']|["']$/g,"");if(!/^[a-zA-Z_$][\w$]*$/.test(y)){for(let ie of["path","query","target","before","after"])delete s[ie];let x=e.slice(t.from,t.to);s[`argument@${t.from}`]={text:x.length>160?x.slice(0,160)+"\u2026":x,literal:!1};continue}let p=t.lastChild;if(!p||p.type.isError||p.name===":")continue;let g=e.slice(p.from,p.to),d=g.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),w=/^(?:["'])(?:\d+#[0-9A-F]+|CHANGE#[0-9A-F]+|begin|end|scope-(?:begin|end)-[^"']+)["']$/.test(g);s[y]={text:d.length>160&&!w?`${d.slice(0,100)}\u2026${d.slice(-40)} (${g.length} source chars)`:d,literal:["String","Number","BooleanLiteral","Null"].includes(p.name)&&p.lastChild?.type.isError!==!0}}return n.push({name:a,from:r.from,to:r.to,path:s.path,query:s.query,target:s.target,before:s.before,after:s.after,arguments:s}),!1}}),n}u(z,"parseApplyCalls");function ue(e,i=z(e),c,n=r=>r){let r=0,o=[],a=u(l=>n(l.split(`
6
- `).map(s=>s.length>200?s.slice(0,200)+"\u2026":s).join(`
7
- `)),"codePreview");for(let l of i)o.push(a(e.slice(r,l.from))),o.push(c?.(l)??`${l.name}(${l.path?l.path.literal?l.path.text:`\u2039${l.path.text}\u203A`:"\u2026"})`),r=l.to;return o.push(a(e.slice(r))),o.join("")}u(ue,"compactApplySource");function G(e,i){let c="",n="",r=[];return o=>{if(o===c)return n;let a=0;for(;a<c.length&&a<o.length&&c[a]===o[a];)a++;r=W.applyChanges(r,[{fromA:a,toA:c.length,fromB:a,toB:o.length}]);let l=Y.parse(o,r);return r=W.addTree(l),n=ue(o,z(o,l),e,i),c=o,n}}u(G,"createApplySourceProjection");import{lstat as Z,unlink as de}from"node:fs/promises";import K from"node:path";import X from"fs-extra";import{Type as b}from"typebox";import{Value as me}from"typebox/value";var D=b.String({minLength:1,description:"Local regular file path, relative to cwd or absolute."}),ge=b.Object({path:D},{additionalProperties:!1}),ye=b.Object({path:D,target:D,overwrite:b.Optional(b.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))},{additionalProperties:!1});function E(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="file-operation"}u(E,"isFileOperationResult");function C(e){return[`${e.operation}: ${e.effect}`,e.path,e.target===void 0?void 0:`Target: ${e.target}`,e.error===void 0?void 0:`${e.error.code}: ${e.error.message}`].filter(i=>i!==void 0).join(`
8
- `)}u(C,"formatFileOperation");async function ze(e,i,c,n){let r=!1,o,a;try{let l=e==="delete"?ge:ye;if(!me.Check(l,i))throw Object.assign(new Error("Invalid file operation arguments"),{code:"INVALID_ARGUMENTS"});let s=i;o=K.resolve(c,s.path),a=s.target===void 0?void 0:K.resolve(c,s.target),n?.throwIfAborted();let t=await he(o);if(a!==void 0){let f=await we(a);if(f!==void 0){if(!f.isFile()||f.isSymbolicLink())throw Object.assign(new Error("Target must be a regular file"),{code:"INVALID_FILE_TYPE"});if(o===a||t.ino===f.ino&&t.dev===f.dev)throw Object.assign(new Error("Source and target are the same file"),{code:"SAME_FILE"});if(s.overwrite!==!0)throw Object.assign(new Error("Target exists; use overwrite: true to replace it"),{code:"EEXIST"})}}return n?.throwIfAborted(),r=!0,e==="delete"?await de(o):a!==void 0&&(e==="copy"?await X.copy(o,a,{overwrite:s.overwrite===!0,errorOnExist:!0}):await X.move(o,a,{overwrite:s.overwrite===!0})),{kind:"file-operation",operation:e,ok:!0,effect:"applied",path:o,...a===void 0?{}:{target:a}}}catch(l){return{kind:"file-operation",operation:e,ok:!1,effect:r?"unknown":"not-applied",...o===void 0?{}:{path:o},...a===void 0?{}:{target:a},error:{code:l!==null&&typeof l=="object"&&"code"in l?String(l.code):"FILE_OPERATION_FAILED",message:l instanceof Error?l.message:String(l)}}}}u(ze,"executeFileOperation");async function he(e){let i=await Z(e);if(!i.isFile()||i.isSymbolicLink())throw Object.assign(new Error("Source must be a regular file"),{code:"INVALID_FILE_TYPE"});return i}u(he,"regularFile");async function we(e){try{return await Z(e)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&i.code==="ENOENT")return;throw i}}u(we,"optionalStat");import{Text as ne}from"@earendil-works/pi-tui";function Q(e){let i=e.select(),c=e.mutationValues().filter(xe);return i.files.map(n=>{let r=c.flatMap(l=>l.files.filter(s=>s.source===n.source).map(s=>({outcome:l,changed:s}))),o=e.mutationPresentation(n.source)?.data,a=o?.afterContent===n.after?o:void 0;return new R({ok:!0,path:n.source,files:[{path:n.source,action:n.before===null?"created":"edited"}],snapshot:{content:n.before??""},beforeContentMap:{[n.source]:n.before},afterContent:n.after??"",afterDocument:a?.afterDocument,resultPresentation:a?.resultPresentation,scopeMarkers:a?.scopeMarkers,hints:a?.hints,warnings:a?.warnings,diffStatuses:a?.diffStatuses,diffs:[A(n.source,n.before??"",n.after??"").diff],operations:r.map(({outcome:l,changed:s})=>({operation:l.operation==="remove"?"delete":l.operation,changes:s.changes.length})),formatting:a?.formatting??r.at(-1)?.changed.formatting})})}u(Q,"finalApplyMutations");function xe(e){return e!==null&&typeof e=="object"&&"operation"in e&&"files"in e&&Array.isArray(e.files)&&"effect"in e}u(xe,"isMutation");import{highlightCode as oe}from"@earendil-works/pi-coding-agent";import{wrapTextWithAnsi as ee,visibleWidth as te,truncateToWidth as be}from"@earendil-works/pi-tui";function ft(e,i,c,n=process.cwd()){let r=e.select(),o=[...r.automatic,...r.explicit.filter(t=>t.kind==="operation")].filter(t=>S(t.value)&&!t.value.equal),a=o.flatMap(t=>S(t.value)?[P(t.value,n)]:[]),l=new Set(o.flatMap(t=>t.presentation?.content??[]));if(r.files.length===0){let t=[...r.automatic.map(f=>f.presentation),...r.explicit.map(f=>f.kind==="operation"?f.presentation:void 0)].filter(f=>f!==void 0);return{comparisons:a,cwd:n,blocks:[...i.content.filter(f=>!l.has(f)).flatMap(f=>f.type==="text"?[{text:re(f.text),read:t.find(m=>m.content.includes(f))}]:[])]}}let s=i.mutations??Q(e);return{...s.length>0?{mutations:{results:s}}:{},comparisons:a,cwd:n,blocks:[...r.explicit.flatMap(t=>t.kind==="operation"&&S(t.value)&&!t.value.equal?[]:E(t.value)?[{text:C(t.value)}]:t.kind==="operation"?t.presentation?.content.flatMap(f=>f.type==="text"?[{text:f.text,read:t.presentation}]:[])??[]:[{text:re(typeof t.value=="string"?t.value:t.value===void 0?"undefined":JSON.stringify(t.value,null,2))}]),...r.automatic.flatMap(({value:t,presentation:f})=>{if(E(t))return[{text:C(t)}];if(t!==null&&typeof t=="object"&&"kind"in t&&t.kind==="index-operation")return f?.content.flatMap(m=>m.type==="text"?[{text:m.text}]:[])??[];if(t===null||typeof t!="object"||!("errors"in t)||!Array.isArray(t.errors))return[];if("operations"in t&&Array.isArray(t.operations)){let m=t.operations.filter(p=>p!==null&&typeof p=="object"&&"status"in p&&p.status==="applied").length;if(m===t.operations.length)return[];let y=t.operations.filter(p=>p!==null&&typeof p=="object"&&"status"in p&&p.status!=="applied").map(p=>({text:Oe(p)}));return[{text:`Apply partially applied: ${m} of ${t.operations.length} operations completed.`},...y]}return t.errors.flatMap(m=>m!==null&&typeof m=="object"&&"message"in m&&typeof m.message=="string"?[{text:m.message}]:[])}),...c===void 0?[]:[{text:c instanceof Error?c.message:JSON.stringify(c)}]]}}u(ft,"createApplyDisplay");function F(e,i,c,n,r,o,a=!1){let l=Math.max(1,c);if(l<5)return e.split(`
9
- `).flatMap(d=>ee(d,l));let s=l-4,t=u(d=>i.fg("borderMuted",d),"border"),m=be(` ${n==="call"?"Apply \xB7 JavaScript":"Result"} `,l-4,""),y=[t(`${n==="call"?"\u256D":"\u251C"}\u2500`)+i.fg(a?"error":"accent",m)+t(`${"\u2500".repeat(Math.max(0,l-te(m)-3))}${n==="call"?"\u256E":"\u2524"}`)],p=`${t("\u2502")}${" ".repeat(l-2)}${t("\u2502")}`;for(let d of e.split(`
10
- `)){let w=o==="diff"?i.fg(d.startsWith("+")?"toolDiffAdded":d.startsWith("-")?"toolDiffRemoved":"toolDiffContext",d):o?oe(d,o).join(`
11
- `):i.fg("toolOutput",d);for(let x of ee(w,s))y.push(`${t("\u2502")} ${x}${" ".repeat(Math.max(0,s-te(x)))} ${t("\u2502")}`)}n==="call"&&y.push(p),r&&y.push(t(`\u2570${"\u2500".repeat(l-2)}\u256F`));let g=i.getBgAnsi("toolPendingBg");return y.map(d=>g+$(d,g)+"\x1B[0m")}u(F,"applyFrameRows");function Ae(e,i="compact"){return(c,n,r)=>{if(!r.expanded&&i==="disabled")return new ne(n.fg("toolTitle","apply"),0,0);let o=r.state,a=o.projectSource??=G(e?s=>e(s,n):void 0,e?s=>oe(s,"javascript").join(`
12
- `):void 0),l=c!==null&&typeof c=="object"&&"source"in c&&typeof c.source=="string"?c.source:"";return{invalidate(){},render(s){return F(r.expanded||i==="full"?o.displaySource??l:i==="disabled"?"":Re(a(o.displaySource??l)),n,s,"call",!o.applyResultReady,r.expanded||i==="full"||!e?"javascript":void 0)}}}}u(Ae,"createApplyCallRenderer");function Re(e,i=N){let c=e.split(`
13
- `);if(c.length<=i)return e;let n=Math.max(2,i-1),r=Math.ceil(n/2),o=Math.floor(n/2),a=c.length-r-o;return[...c.slice(0,r),`\u2026 ${a} lines omitted \u2026`,...c.slice(-o)].join(`
14
- `)}u(Re,"compactApplyPreview");var pt=Ae();function Se(e){return(i,c,n,r)=>{r.state.applyResultReady=!0;let o=i.details;r.state.displaySource=o?.displaySource;let a=o?.display,l=a?.blocks??[{text:r.isError?"Apply failed":"Apply finished"}],s=L({kind:"source"}),t=l.map(p=>s(p.read??{content:[{type:"text",text:p.text}],details:ke(p.text)},c,n,{...r,isError:!1,lastComponent:void 0})),f=a?.mutations,m=(a?.comparisons??[]).flatMap(p=>[e?.(p,n,c.expanded,a?.cwd??process.cwd())??new ne((p.results??[]).flatMap(d=>d.data.diffs??[]).join(`
15
- `),0,0)]),y=f===void 0?void 0:e?.(f,n,c.expanded,a?.cwd??process.cwd());return{invalidate(){y?.invalidate();for(let p of m)p.invalidate()},render(p){let g=[];for(let d of t){let w=d.render(Math.max(1,p-4));w.length!==0&&(g.length>0&&g.push(""),g.push(...w))}for(let d of m)g.length>0&&g.push(""),g.push(...d.render(Math.max(1,p-4)));if(y!==void 0){let d=y.render(Math.max(1,p-4));g.length>0&&d.length>0&&g.push(""),g.push(...d),d.length===0&&g.push(...(f?.results??[]).map(w=>w.path??"Changed file"))}else f!==void 0&&g.push(...(f.results??[]).map(d=>d.path??"Changed file"));return g.length===0&&l.length>0&&l.every(d=>d.read?.details.diagnosticCheck?.complete&&d.read.details.diagnosticCheck.count===0)?F("",n,p,"result",!0).slice(-1):F(g.length===0?"No output":g.join(`
16
- `),n,p,"result",!0,void 0,r.isError)}}}}u(Se,"createApplyResultRenderer");function Oe(e){if(e===null||typeof e!="object")return String(e);let i="index"in e?Number(e.index)+1:"?",c="kind"in e?String(e.kind):"operation",n="status"in e?String(e.status):"unknown",r="error"in e&&e.error!==null&&typeof e.error=="object"?`: ${"code"in e.error?String(e.error.code):"ERROR"}: ${"message"in e.error?String(e.error.message):"Operation failed"}`:"";return`Operation ${i} (${c}): ${n}${r}`}u(Oe,"formatDisplayOutcome");function re(e){if(/^(?:Undo transaction:|Undo available)/u.test(e.trim()))return"";try{let i=JSON.parse(e);return JSON.stringify(M(i),null,2)}catch{return e.replace(/APPLY#[0-9A-F]{12}/gu,"Apply transaction")}}u(re,"redactApplyReceipts");function M(e){return Array.isArray(e)?e.map(M):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([i])=>i!=="transaction").map(([i,c])=>[i,M(c)]))}u(M,"redactTransactionKeys");function ke(e){try{let i=JSON.parse(e);return i!==null&&typeof i=="object"?{source:"result.json"}:{}}catch{return{}}}u(ke,"jsonDetails");var ut=Se();export{j as a,fe as b,S as c,Ne as d,Le as e,ze as f,Q as g,ft as h,Ae as i,pt as j,Se as k,ut as l};
@@ -1,28 +0,0 @@
1
- import{a as me,b as pe,c as fe}from"./chunk-ESPNEJHK.js";import{a as de}from"./chunk-M5IVSCR2.js";import"./chunk-PXWDDBBC.js";import{a as I}from"./chunk-I5JLCFUX.js";import"./chunk-7AVXUV4A.js";import{e as Q,f as ee}from"./chunk-T7I2VX3J.js";import{a as se}from"./chunk-FBOW7XOV.js";import{a as ie,b as oe}from"./chunk-WJTHY6AG.js";import{b as E}from"./chunk-BSICWXMH.js";import"./chunk-YHUTTZC6.js";import{a as re}from"./chunk-6CZO43OH.js";import{a as te,b as ne}from"./chunk-OBNING2A.js";import"./chunk-F7NVAC4Q.js";import{d as ce}from"./chunk-MIZAFRDR.js";import{a as ue}from"./chunk-ZTYWHL2F.js";import{a as ae,b as le}from"./chunk-7UGNGK7Y.js";import{h as H,i as L}from"./chunk-2P2OGO3G.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import tt from"node:path";import{stripVTControlCharacters as nt}from"node:util";import{truncateLine as rt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as ge,DEFAULT_MAX_LINES as he,formatSize as Qe,truncateTail as et}from"@earendil-works/pi-coding-agent";function $(t){return et(t,{maxBytes:ge-4096,maxLines:he-32})}s($,"terminalOutputTail");function M(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0||t.status!=="running"?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
- `)}
3
- output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${he} line output budget`:`${Qe(ge)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
- `)}
6
- output:
7
- ${a}${r.length===0?"":`
8
- ${r}`}`}s(M,"formatAgentTerminalSnapshot");var it=500;function ye(t,e,n,r,i){let a=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${D(n)} \xB7 ${a}`)}`;return new R(`${o}
9
- ${i.fg("accent",G(r.family))} ${t}`,0,0)}s(ye,"renderRunCall");function we(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new R(r.join(`
10
- `),0,0)}s(we,"renderTerminalActionResult");function O(t,e,n,r,i){let a=[at(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&a.push(...r.map(o=>` ${i.fg("dim",o)}`)),new R(a.join(`
11
- `),0,0)}s(O,"renderTerminalAction");function v(t,e,n,r){let i=be(t,E,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new R(i.join(`
12
- `),0,0)}s(v,"renderTerminalResult");function Se(t,e,n){if(e===!0?e="full":e===!1&&(e="compact"),e==="disabled"){if(!(t.status!==void 0&&!["running","completed"].includes(t.status)||t.exitCode!==void 0&&t.exitCode!==0||t.error!==void 0))return new R(k(t,(l,u)=>n.fg(l,u)),0,0);let o=_(t.output??"",E),c=[...o.omission===void 0?[]:[` ${n.fg("muted",o.omission)}`],...o.lines.map(l=>` ${n.fg("dim",l)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],k(t,(l,u)=>n.fg(l,u))];return new R(c.join(`
13
- `),0,0)}if(e==="full"){let a=be(t,Number.POSITIVE_INFINITY,n).slice(2);return new R(a.join(`
14
- `),0,0)}let r=_(t.output??"",E),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(a=>` ${n.fg("dim",a)}`)];return i.push(k(t,(a,o)=>n.fg(a,o))),new R(i.join(`
15
- `),0,0)}s(Se,"renderRunResult");function Te(t,e){let n=s((o,c)=>e?.fg(o,c)??c,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${D(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",G(t.shellFamily))} ${B(t.command,84)}`],a=ot(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",B(o,90))}`)),i.push(k(t,n)),i.join(`
16
- `)}s(Te,"renderActiveTerminal");function be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":D(t.cwd),o=t.shellFamily??"posix",c=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",G(o))} ${t.command??""}`],l=_(t.output??"",e);return l.omission!==void 0&&c.push(` ${n.fg("muted",l.omission)}`),l.lines.length>0&&c.push(...l.lines.map(u=>` ${n.fg("dim",u)}`)),c.push(k(t,(u,d)=>n.fg(u,d))),c}s(be,"terminalCardLines");function ot(t,e){return _(t,e).lines}s(ot,"outputTail");function _(t,e){let n=$(nt(t).replaceAll("\r","")),r=n.content.split(`
17
- `).map(l=>rt(l.trimEnd(),it).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),c=a+o;return{lines:r.slice(a),...n.truncated||c>0?{omission:c>0?`\u2026 ${c} earlier lines`:"\u2026 earlier output omitted"}:{}}}s(_,"outputWindow");function k(t,e){let n=t.status??"running",r=st(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,lt(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}s(k,"statusLine");function st(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}s(st,"statusIcon");function G(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}s(G,"promptMarker");function at(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":D(t.cwd),i=t.background===!0?"background":"wait",a=B(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}s(at,"terminalIdentity");function D(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${tt.sep}`))?`~${t.slice(e.length)}`:t}s(D,"shortCwd");function B(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}s(B,"oneLine");function lt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(lt,"formatElapsed");function Re(t){return{id:"terminal",onDidChange:s(e=>t.onDidChange(e),"onDidChange"),list:s(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:s(n=>Te(e,n).split(`
18
- `),"renderSummary"),renderDetail:s(n=>v(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as pt}from"node:timers/promises";var ut="#d8dee9",q="#111418",ct=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function V(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=q,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,f=Math.max(0,p.baseY);for(let h=0;h<c;h+=1){let w=p.getLine(f+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||dt(m,P,y,h)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(V,"renderTerminalScreen");function dt(t,e,n,r){let i=ve(e,"foreground"),a=ve(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==q&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(dt,"drawCell");function ve(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?ut:q;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:mt(a)}s(ve,"cellColor");function mt(t){let e=ct[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return xe(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return xe(o(r),o(i),o(a))}s(mt,"ansiColor");function xe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(xe,"rgb");var X="\0pi-terminal-write\0",K="\0pi-terminal-keys\0";function ft(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${u} must be a number`);i.set(u,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(ft,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:te,apiVersion:ne,id:"terminal",setup(o){o.addResolver({resolver:gt(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return v(m===void 0?p:{...p,output:e.screenTail(m).join(`
19
- `)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=ft(c.request.views)}catch(m){return{kind:"return",result:Y(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:Y(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,p=[];for(let f=0;f<m;f+=1){c.resolverContext.signal?.throwIfAborted(),f>0&&await pt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await V(e,l,void 0,u.scale);p.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:p,script:{kind:"native",source:d.source,blocks:p},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:Y(l,m instanceof Error?m.message:String(m))}}}}),o.describe("shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated. image and parameterized sequence views return the virtual terminal screen as ordered PNG frames.")}},a={protocol:ie,apiVersion:oe,id:"terminal",setup(o){o.addResolver({resolver:ht(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),yt(c,X)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),wt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>Rt(l,u),"matches"),renderCall(l,u,d){let m=l,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),O(f.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=bt(l.details);return we(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([re(t,i),se(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I,{status:"error",errors:[H(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I,{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I,{status:"error",errors:[H(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let p=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await V(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:f,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function gt(t){return{id:"terminal",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:St(r)}]}}}}}}s(gt,"createReadResolver");function ht(t){return{id:"terminal-input",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=Tt(r),a=i.indexOf(X),o=i.indexOf(K);if(a>=0){t.write(n.source,i.slice(a+X.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+K.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(ht,"createInputResolver");function yt(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(yt,"transformWriteInput");function wt(t){if(!b(t.input)||!ke(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${K}${typeof t.input.text=="string"?t.input.text:""}`}}}s(wt,"transformInsertInput");function St(t){return M(t)}s(St,"formatSnapshot");function Tt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(Tt,"singleText");function Y(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(Y,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function bt(t){if(!b(t)||!b(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}s(bt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}s(Ae,"terminalInputLabel");function Rt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(Rt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");import{truncateToWidth as vt,visibleWidth as xt}from"@earendil-works/pi-tui";async function Le(t,e){await ue(t,{protocol:ae,apiVersion:le,id:"terminal",setup(r){r.addResolver({resolver:Pt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Le,"registerTerminalSearch");function Pt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=N(e);return ce(n.matches,!1)},async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=Et(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=N(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
20
- `)}
21
-
22
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=J(i)?N(i.payload):N(void 0),o=O(a.snapshot,"search",JSON.stringify(a.query),a.matches.slice(-6).map(c=>`${c.lineNumber}: ${c.lineText}`),r);return new z(o,n.expanded===!0,r)}}}s(Pt,"terminalSearchResolver");var Ce=12,z=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{s(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=Ce)return n;let r=Ce-1,i=String(n.length-r),a=`\u2026 ${i} visual rows omitted \xB7 ctrl+o to expand`,o=xt(a)<=e?a:`\u2026 ${i} visual rows omitted \xB7 ctrl+o`;return[...n.slice(0,r),this.theme.fg("muted",vt(o,e))]}invalidate(){this.content.invalidate()}};function Et(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[a,o]of t.output.replaceAll("\r","").split(`
23
- `).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||At(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(Et,"findTerminalMatches");function At(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(At,"isWordBoundary");function N(t){if(!$t(t))throw new TypeError("Invalid terminal search result");return t}s(N,"parsePayload");function $t(t){return J(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&J(t.snapshot)&&typeof t.snapshot.source=="string"}s($t,"isTerminalSearchPayload");function J(t){return typeof t=="object"&&t!==null}s(J,"isRecord");import{spawn as kt}from"node:child_process";import{closeSync as Ct,mkdirSync as Lt,openSync as It,rmSync as Mt,writeSync as _t}from"node:fs";import Ot from"node:os";import Ie from"node:path";import{createRequire as Dt}from"node:module";import{randomUUID as Nt}from"node:crypto";import{stripVTControlCharacters as Wt}from"node:util";var Oe=Dt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Me=1e6,Ut=100,Ft=30,jt=2e3,W=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=Gt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(qt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Jt(n);this.#i.set(n,It(r,"a",384));let i=e.cols??Ut,a=e.rows??Ft,o=Bt(i,a),c=s(p=>{},"resolveCompletion"),l=new Promise(p=>{c=p}),u={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let p=Oe("node-pty"),f={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Yt(Vt())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...u,status:"failed",endedAt:Date.now(),error:zt(p)};return this.#e.set(n,f),this.#s(n),c(f),queueMicrotask(()=>this.#l(f)),f}let m={...u,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{x(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return x(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(x(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(p=>{o||(p!==void 0&&x(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Ht(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await Z(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let p=d;p<d+a;p+=1){let f=n[p]??"",h=i[p]??"",w=h.length>0&&!n.includes(h),y=f.length>0&&h.length===0;f!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let f=d.padEnd(l.cursorX," ");return`${f.slice(0,l.cursorX)}\u258C${f.slice(l.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Xt(n))}async stop(e,n="stopped"){let r=this.required(e);return x(r.status)||(r.status="stopping",this.#n(r),await _e(r,!1),await Promise.race([r.completion.then(()=>!0),Z(jt).then(()=>!1)])||(await _e(r,!0),await Promise.race([r.completion,Z(1e3)])),x(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),Mt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!x(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Wt(n),i=this.#i.get(e.id);if(i!==void 0&&_t(i,r),e.output+=r,e.output.length>Me){let a=e.output.length-Me;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(Ct(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Ht(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}s(Ht,"looksInteractive");function Bt(t,e){let{Terminal:n}=Oe("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Bt,"createScreen");function Gt(){return Nt().replaceAll("-","").slice(0,12)}s(Gt,"defaultSessionId");function qt(t){return t.startsWith("shell:")?t.slice(6):t}s(qt,"normalizeSessionId");function x(t){return t!=="running"&&t!=="stopping"}s(x,"isTerminalStatus");function Vt(){return process.env}s(Vt,"processEnvironment");function Yt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Yt,"cleanEnvironment");function Xt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Kt).join("")}s(Xt,"encodeTerminalKeys");function Kt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Kt,"encodeTerminalKey");async function _e(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=kt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(_e,"terminateProcessTree");function Z(t){return new Promise(e=>setTimeout(e,t))}s(Z,"delay");function zt(t){return t instanceof Error?t.message:String(t)}s(zt,"errorMessage");function Jt(t){let e=Ie.join(Ot.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Lt(e,{recursive:!0,mode:448}),Ie.join(e,`${t}.log`)}s(Jt,"createOutputLog");import{AgentSession as Zt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Zt.prototype,n=e[U]??Qt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function Qt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(Qt,"installObservers");import en from"node:os";import Ne from"node:path";function We(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Ne.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||en.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Ne.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(We,"resolveShellProfile");function Ue(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as nn}from"node:util";import{defineTool as rn}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as on}from"@earendil-works/pi-tui";import{open as tn}from"node:fs/promises";import{Type as g}from"typebox";var Fe=1024*1024,je=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function He(t){let e=await tn(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>Fe;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=Fe/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let p=u.subarray(m).toString("utf8");i=d+p,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(He,"structuredShellResult");var sn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function Ge(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=sn(n);return t.registerTool(rn({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use Apply or the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,parameters:c,outputSchema:je,async execute(l,u,d,m,p){r.bind(p);let f=u.cwd===void 0?p.cwd:Be.resolve(p.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:f,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await an(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),F(e.snapshot(h));if(h.status==="failed")return F(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",F(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),F(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new on(u.fg("toolTitle",o),0,0);let p=typeof l.command=="string"?l.command:"",f=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return ye(p,l.background===!0,f,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(Ge,"registerTerminalTools");function qe(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(qe,"terminalPreview");async function F(t){return{...qe(t),structuredContent:await He(t)}}s(F,"terminalResult");async function an(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(qe(u)),(nn(u.output).replaceAll("\r","").split(`
24
- `).filter(m=>m.length>0).length>=E||u.status!=="running")&&c()},"publish");o=t.onDidChange(u=>{u.id===e.id&&l()}),a=setTimeout(c,2e3),l()})}s(an,"captureInitialBackgroundPreview");import{Box as Ve,Container as Ye}from"@earendil-works/pi-tui";var ln=120,un=12e4,j=class{constructor(e,n,r=un){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>{let c=Xe(i.details)?i.details:void 0,l=new Ye;c!==void 0&&l.addChild(v(c,a,o,"stale \xB7 inspect session"));let u=new Ve(1,1,d=>o.bg("toolPendingBg",d));return u.addChild(l),u}),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>{let c=new Ye;for(let u of cn(i.details))c.addChild(v(u,a,o));let l=new Ve(1,1,u=>o.bg("toolSuccessBg",u));return l.addChild(c),l}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{s(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||e.staleReminderDelivered||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}e.staleReminderDelivered=!0;let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:mn(n),details:n},{triggerTurn:!0,deliverAs:"followUp"})}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:dn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},ln)))}};function cn(t){return!ze(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Xe)}s(cn,"completionSnapshots");function Xe(t){return ze(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}s(Xe,"isTerminalSessionSnapshot");function dn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
25
- ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,a=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Ke(n.elapsedMs)}
26
- ${a||"(no output)"}`}).join(`
27
- `)}`}s(dn,"formatCompletionMessage");function mn(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Ke(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
28
- ${e||"(no output)"}`}s(mn,"formatStaleMessage");function Ke(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Ke,"formatElapsed");function ze(t){return typeof t=="object"&&t!==null}s(ze,"isRecord");function Je(t){return t==="full"||t==="disabled"?t:"compact"}s(Je,"toolPresentation");async function pn(t,e){ee(t,[await Q({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=pe("terminal")??new W,r=We(),i=new j(t,n),a=de(t).add(Re(n));await Promise.all([$e(t,n),Le(t,n)]);let o=Ge(t,n,r,i,Je(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){me("terminal",n);return}fe("terminal",n),await n.dispose()})}s(pn,"registerTerminal");export{pn as default};
File without changes
@@ -1 +0,0 @@
1
- import{e as m,i as p,m as f}from"./chunk-2P2OGO3G.js";import{a as i}from"./chunk-EI7MMDWY.js";import{Type as r}from"typebox";import{Value as u}from"typebox/value";import{Type as d}from"typebox";var T=d.Object({path:d.Optional(d.String({description:"What to read: a supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# reference, or registered protocol source. Supply a path; an empty call cannot select a source."})),offset:d.Optional(d.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor or a SEARCH selection, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:d.Optional(d.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:d.Optional(d.Array(d.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))});import{Type as t}from"typebox";var O=t.Object({value:t.String(),kind:t.String(),state:t.Optional(t.String())},{additionalProperties:!1}),L=t.Object({lineNumber:t.Integer(),content:t.String(),lineEnding:t.String(),anchors:t.Optional(t.Array(t.String()))},{additionalProperties:!1}),k=t.Object({path:t.String(),offset:t.Integer()},{additionalProperties:!1}),y={source:t.String(),truncated:t.Boolean(),continuation:t.Optional(k),fullResult:t.Optional(t.String())},x=t.Object({...y,kind:t.Literal("text"),lines:t.Array(L),startLine:t.Integer(),endLine:t.Integer(),totalLines:t.Integer(),references:t.Optional(t.Array(O))},{additionalProperties:!1}),b=t.Object({...y,kind:t.Literal("bytes"),bytes:t.Array(t.Integer({minimum:0,maximum:255})),byteOffset:t.Integer(),byteLength:t.Integer(),totalBytes:t.Integer()},{additionalProperties:!1}),C=t.Union([t.Object({type:t.Literal("text"),text:t.String()},{additionalProperties:!1}),t.Object({type:t.Literal("image"),data:t.String(),mimeType:t.String()},{additionalProperties:!1})]),h=t.Object({...y,kind:t.Literal("native"),blocks:t.Array(C)},{additionalProperties:!1}),c=t.Union([t.Object({kind:t.Literal("recovery"),source:t.String(),candidates:t.Array(t.Object({path:t.String()},{additionalProperties:!1}))},{additionalProperties:!1}),x,b,h,t.Object({kind:t.Literal("resources"),source:t.Optional(t.String()),resources:t.Array(t.Union([x,b,h])),truncated:t.Boolean(),fullResult:t.Optional(t.String())},{additionalProperties:!1})]),P=m(c);function v(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}i(v,"publicLine");function S(e){if(e.kind==="resources"){let o=e.resources.map(s=>S(s));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:o,truncated:o.some(s=>typeof s=="object"&&s!==null&&"truncated"in s&&s.truncated===!0)}}if(e.kind==="bytes"){let o=e.bytes.slice(0,32768),s=e.truncated===!0||o.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:o,byteOffset:e.byteOffset,byteLength:o.length,totalBytes:e.totalBytes,truncated:s,...e.byteOffset+o.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+o.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(o=>{if(o.type==="text")return{type:o.type,text:o.text};if(o.type==="image")return{type:o.type,data:o.data,mimeType:o.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let n=[],a=0;for(let o of e.lines){let s=v(o);if(a+=Buffer.byteLength(JSON.stringify(s)),n.length>=2e3||a>512*1024)break;n.push(s)}if(n.length===0&&e.lines.length>0)throw new RangeError("Selected line exceeds the structured window; use a raw byte range or a source-specific view");let R=n.length<e.lines.length,g=n.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,lines:n,startLine:n[0]?.lineNumber??0,endLine:n.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:R,...e.references===void 0?{}:{references:e.references},...R||g<e.totalLines?{continuation:{path:e.source,offset:g+1}}:{}}}i(S,"publicData");function w(e){let n=e.details.failure;if(e.isError||n!==void 0)return p(e,c,{status:"error",...n?.candidates?.length&&n.source!==void 0?{data:{kind:"recovery",source:n.source,candidates:n.candidates}}:{},errors:[{code:n?.code??"READ_FAILED",message:n?.message??"Read failed",...n?.source===void 0?{}:{source:n.source}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let a=S(e.script);return p(e,c,{status:"success",data:e.details.temporarySource!==void 0&&typeof a=="object"&&a!==null?{...a,fullResult:e.details.temporarySource}:a,errors:[]})}catch(a){return p(e,c,{status:"error",errors:[{code:a instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:a instanceof Error?a.message:String(a)}]})}}i(w,"structuredRead");var l=r.Function([],r.Unknown()),E=r.Object({resolver:r.Unknown(),matchesCall:r.Optional(l),renderCall:r.Optional(l),priority:r.Optional(r.Number()),renderResult:r.Optional(l),preserveTruncatedOutput:r.Optional(r.Boolean())}),D=r.Object({resolver:r.Unknown(),priority:r.Optional(r.Number())}),A=r.Object({id:r.String({pattern:"\\S"}),priority:r.Optional(r.Number()),resolve:l}),N=r.Object({view:r.String({pattern:"\\S"}),includes:r.Optional(r.Array(r.String({pattern:"\\S"}))),presenter:r.Object({id:r.String(),present:l}),priority:r.Optional(r.Number())}),F=r.Object({resolvedBy:r.String({pattern:"\\S"}),contentKind:r.Union([r.Literal("text"),r.Literal("any")])}),I=r.Union([r.Object({stage:r.Literal("pre-read"),handler:l}),r.Object({stage:r.Literal("read"),when:F,handler:l}),r.Object({stage:r.Literal("post-read"),handler:l})]);function W(e){if(!u.Check(D,e))return!1;let n=e,a=n.resolver;return typeof a.id=="string"&&a.id.length>0&&typeof a.tryResolve=="function"&&(!("priority"in n)||typeof n.priority=="number")}i(W,"isTextTargetResolverRegistration");function M(e){if(!u.Check(E,e))return!1;let n=e;return f(n.resolver)?n.resolver.id!=="any"&&(!("priority"in n)||typeof n.priority=="number")&&(!("matchesCall"in n)||typeof n.matchesCall=="function")&&(!("renderCall"in n)||typeof n.renderCall=="function")&&"matchesCall"in n=="renderCall"in n&&(!("renderResult"in n)||typeof n.renderResult=="function"):!1}i(M,"isResourceResolverRegistration");function Q(e){return u.Check(I,e)}i(Q,"isReadHandlerRegistration");function J(e){return u.Check(N,e)}i(J,"isReadViewRegistration");function Y(e){return u.Check(A,e)}i(Y,"isFragmentResolverRegistration");function X(e){return U(e)?e.kind==="not-handled"?!0:e.kind==="failed"?typeof e.message=="string"&&e.message.length>0:e.kind==="resolved"&&typeof e.originLine=="number":!1}i(X,"isReadFragmentResolution");function U(e){return typeof e=="object"&&e!==null}i(U,"isRecord");export{T as a,c as b,P as c,w as d,W as e,M as f,Q as g,J as h,Y as i,X as j};
@@ -1 +0,0 @@
1
- import{d as v,e as E,h as f,i as b}from"./chunk-2P2OGO3G.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as L}from"typebox/value";var I=e.Union([e.Literal("pending"),e.Literal("applied"),e.Literal("not-applied"),e.Literal("unknown")]),j=e.Object({source:e.String(),effect:I,action:e.Optional(e.String())},{additionalProperties:!1}),D=e.Object({id:e.String(),operation:e.String(),effect:I,errors:e.Array(v),status:e.Optional(e.Union([e.Literal("success"),e.Literal("error"),e.Literal("warning"),e.Literal("unknown")])),sources:e.Optional(e.Array(e.String())),warnings:e.Optional(e.Array(v))},{additionalProperties:!1}),T=e.Object({operation:e.String(),effect:I,operationId:e.Optional(e.String()),files:e.Array(j),operations:e.Optional(e.Array(D)),parentToolCallId:e.Optional(e.String()),transaction:e.Optional(e.String()),transactions:e.Optional(e.Array(e.String())),recovery:e.Optional(e.Array(e.Object({source:e.String(),field:e.String(),anchor:e.String(),total:e.Integer(),candidates:e.Array(e.Object({rank:e.Integer(),range:e.Object({start:e.Object({lineNumber:e.Integer(),column:e.Integer()}),end:e.Object({lineNumber:e.Integer(),column:e.Integer()})})}))}))),action:e.Optional(e.Object({source:e.String(),kind:e.Optional(e.String()),status:e.Optional(e.String()),command:e.Optional(e.String()),deleted:e.Optional(e.Boolean()),session:e.Optional(e.String()),file:e.Optional(e.String()),line:e.Optional(e.Integer()),verified:e.Optional(e.Boolean()),evaluation:e.Optional(e.Object({expression:e.String(),result:e.String(),type:e.Optional(e.String()),variablesReference:e.Integer()},{additionalProperties:!1})),breakpoints:e.Optional(e.Array(e.Object({source:e.String(),file:e.String(),line:e.Integer(),verified:e.Boolean()},{additionalProperties:!1})))},{additionalProperties:!1}))},{additionalProperties:!1}),_=E(T);function c(s){return typeof s=="object"&&s!==null}y(c,"record");function N(s,u,h=[]){let n=s.details,p=c(n)?n:{},O=c(n)&&c(n.nativeEditBatch)?n.nativeEditBatch:void 0;if(O?.state==="accepted")return{status:"success",errors:[],data:{operation:u,effect:"pending",files:typeof p.source=="string"?[{source:p.source,effect:"pending"}]:[],...typeof O.parentToolCallId=="string"?{parentToolCallId:O.parentToolCallId}:{}}};let S=new Set(h.map(o=>o.resourceSource)),i=[],l=[],R=n.results;for(let o of R??[]){let r=o.data,m=[...new Set([...(r.files??[]).map(a=>a.path),...r.path?[r.path]:[]])];for(let a of m)l.push({source:a,effect:S.has(a)||r.ok===!0&&r.files?.some(M=>M.path===a)?"applied":n.effect??"unknown"});for(let a of r.errors??[])i.push({code:a.code??"MUTATION_FAILED",message:a.reason??"Mutation failed",source:a.path});r.ok===!1&&(r.errors?.length??0)===0&&i.push({code:"MUTATION_FAILED",message:"Mutation failed",...r.path?{source:r.path}:{}})}for(let o of S)l.some(r=>r.source===o)||l.push({source:o,effect:"applied"});let t=c(n.metadata)&&c(n.metadata.semanticAction)?n.metadata.semanticAction:void 0;if(t){let o=t.effect==="not-applied"||t.effect==="unknown"?t.effect:t.ok===!1?"unknown":"applied",r=typeof t.source=="string"?t.source:void 0;if(r&&!Array.isArray(t.restored)&&l.push({source:r,effect:u==="copy"&&typeof t.target=="string"&&t.target!==r?"not-applied":o}),Array.isArray(t.restored))for(let m of t.restored)typeof m=="string"&&l.push({source:m,effect:o});typeof t.target=="string"&&l.push({source:t.target,effect:o}),c(t.error)&&i.push(f(t.error.message,typeof t.error.code=="string"?t.error.code:"MUTATION_FAILED",r)),typeof t.postProcessingError=="string"&&i.push(f(t.postProcessingError,"POST_EDIT_FAILED",r)),t.ok===!1&&i.length===0&&i.push(f("Resource operation failed","MUTATION_FAILED",r))}let d=[...new Map(l.map(o=>[o.source,o])).values()],k=d.some(o=>o.effect==="applied");s.isError&&i.length===0&&i.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(R?.length??0)===0&&!t&&S.size===0&&i.length===0&&i.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=d.some(o=>o.effect==="unknown")||i.some(o=>o.code==="UNKNOWN_RESULT")?"unknown":k?"applied":"not-applied",g=t&&typeof t.source=="string"?{source:t.source,...typeof t.kind=="string"?{kind:t.kind}:{},...typeof t.status=="string"?{status:t.status}:{},...typeof t.command=="string"?{command:t.command}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.session=="string"?{session:t.session}:{},...typeof t.file=="string"?{file:t.file}:{},...typeof t.line=="number"?{line:t.line}:{},...typeof t.verified=="boolean"?{verified:t.verified}:{},...c(t.evaluation)?{evaluation:{expression:t.evaluation.expression,result:t.evaluation.result,variablesReference:t.evaluation.variablesReference,...typeof t.evaluation.type=="string"?{type:t.evaluation.type}:{}}}:{},...Array.isArray(t.breakpoints)?{breakpoints:t.breakpoints.filter(c).map(o=>({source:o.source,file:o.file,line:o.line,verified:o.verified}))}:{}}:void 0,A=g&&L.Check(T.properties.action,g)?g:void 0;return g&&!A&&i.push(f("Action adapter returned invalid fields","INVALID_STRUCTURED_RESULT")),{status:i.length===0?"success":!t&&k&&d.some(o=>o.effect!=="applied")?"partial":"error",data:{operation:u,effect:w,files:d,...n.anchorRecoveries===void 0?{}:{recovery:n.anchorRecoveries.map(o=>({source:o.path,field:o.field,anchor:o.anchor,total:o.total,candidates:[...o.candidates]}))},...typeof t?.transaction=="string"?{transaction:t.transaction}:{},...A?{action:A}:{}},errors:i}}y(N,"mutationOutcome");function C(s,u,h=[],n){let p=N(s,u,h);return p.data&&n!==void 0&&(p.data.operationId=n),b(s,T,p)}y(C,"structuredMutation");export{T as a,_ as b,N as c,C as d};
@@ -1 +0,0 @@
1
- import{e as c}from"./chunk-2P2OGO3G.js";import{a as l}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var g=t.Object({query:t.String({minLength:1,description:"Text to find, a Boolean expression, or a prefixed query described below, such as files:*.ts. Quote text to keep it literal, or use regex:<pattern> for regular-expression matching."}),path:t.Optional(t.String({description:"Optional file, directory, or HTTP(S) URL scope. Use literal or regex: queries for web pages."})),include:t.Optional(t.String({description:"Optional include glob for local search"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local search"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum detailed results returned to the agent (default 50)"}))},{additionalProperties:!1});import{Type as e}from"typebox";var d=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),s=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),u=e.Object({source:e.String(),range:d,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(s)},{additionalProperties:!1}),p=e.Union([e.Object({kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(u),all:e.Optional(s),notices:e.Optional(e.Array(e.String()))},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),b=c(p);function S(i,o,r){return{kind:"matches",truncated:i.length>100,complete:o,matches:i.slice(0,100).map((n,a)=>({source:n.source,range:{startLine:n.lineNumber,startColumn:n.startColumn,endLine:n.endLineNumber??n.lineNumber,endColumn:n.endColumn},...Buffer.byteLength(n.matchedText)<=4096?{matchedText:n.matchedText}:{textTruncated:!0},...r===void 0?{}:{references:{line:`SEARCH#${r}:${a+1}:line`,match:`SEARCH#${r}:${a+1}:match`}}})),...o&&r!==void 0?{all:{line:`SEARCH#${r}:all:line`,match:`SEARCH#${r}:all:match`}}:{}}}l(S,"selectionData");export{g as a,p as b,b as c,S as d};