@e4779/pi-fabric 0.92.17-fork.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1044) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/dist/activity/store.d.ts +33 -0
  5. package/dist/activity/store.d.ts.map +1 -0
  6. package/dist/activity/types.d.ts +104 -0
  7. package/dist/activity/types.d.ts.map +1 -0
  8. package/dist/actors/binding-store.d.ts +17 -0
  9. package/dist/actors/binding-store.d.ts.map +1 -0
  10. package/dist/actors/context.d.ts +13 -0
  11. package/dist/actors/context.d.ts.map +1 -0
  12. package/dist/actors/delivery-policy.d.ts +8 -0
  13. package/dist/actors/delivery-policy.d.ts.map +1 -0
  14. package/dist/actors/directory.d.ts +47 -0
  15. package/dist/actors/directory.d.ts.map +1 -0
  16. package/dist/actors/global-registry.d.ts +47 -0
  17. package/dist/actors/global-registry.d.ts.map +1 -0
  18. package/dist/actors/host-event-observer.d.ts +5 -0
  19. package/dist/actors/host-event-observer.d.ts.map +1 -0
  20. package/dist/actors/host-event-payload.d.ts +14 -0
  21. package/dist/actors/host-event-payload.d.ts.map +1 -0
  22. package/dist/actors/log-store.d.ts +22 -0
  23. package/dist/actors/log-store.d.ts.map +1 -0
  24. package/dist/actors/manager.d.ts +175 -0
  25. package/dist/actors/manager.d.ts.map +1 -0
  26. package/dist/actors/mesh-monitor.d.ts +22 -0
  27. package/dist/actors/mesh-monitor.d.ts.map +1 -0
  28. package/dist/actors/predicate.d.ts +7 -0
  29. package/dist/actors/predicate.d.ts.map +1 -0
  30. package/dist/actors/registry-store.d.ts +15 -0
  31. package/dist/actors/registry-store.d.ts.map +1 -0
  32. package/dist/actors/types.d.ts +218 -0
  33. package/dist/actors/types.d.ts.map +1 -0
  34. package/dist/agents/bash-worktree-add.d.ts +24 -0
  35. package/dist/agents/bash-worktree-add.d.ts.map +1 -0
  36. package/dist/agents/budget-ledger.d.ts +88 -0
  37. package/dist/agents/budget-ledger.d.ts.map +1 -0
  38. package/dist/agents/claude-cli.d.ts +32 -0
  39. package/dist/agents/claude-cli.d.ts.map +1 -0
  40. package/dist/agents/claude-cli.js +17 -0
  41. package/dist/agents/claude-cli.js.map +7 -0
  42. package/dist/agents/clone-first-worktree.d.ts +17 -0
  43. package/dist/agents/clone-first-worktree.d.ts.map +1 -0
  44. package/dist/agents/compact-control.d.ts +32 -0
  45. package/dist/agents/compact-control.d.ts.map +1 -0
  46. package/dist/agents/compact-control.js +129 -0
  47. package/dist/agents/compact-control.js.map +7 -0
  48. package/dist/agents/constants.d.ts +9 -0
  49. package/dist/agents/constants.d.ts.map +1 -0
  50. package/dist/agents/cow-clone.d.ts +8 -0
  51. package/dist/agents/cow-clone.d.ts.map +1 -0
  52. package/dist/agents/handoff-completion.d.ts +4 -0
  53. package/dist/agents/handoff-completion.d.ts.map +1 -0
  54. package/dist/agents/handoff.d.ts +19 -0
  55. package/dist/agents/handoff.d.ts.map +1 -0
  56. package/dist/agents/lifecycle.d.ts +32 -0
  57. package/dist/agents/lifecycle.d.ts.map +1 -0
  58. package/dist/agents/manager.d.ts +75 -0
  59. package/dist/agents/manager.d.ts.map +1 -0
  60. package/dist/agents/pi-binary.d.ts +7 -0
  61. package/dist/agents/pi-binary.d.ts.map +1 -0
  62. package/dist/agents/request.d.ts +13 -0
  63. package/dist/agents/request.d.ts.map +1 -0
  64. package/dist/agents/result.d.ts +8 -0
  65. package/dist/agents/result.d.ts.map +1 -0
  66. package/dist/agents/result.js +9 -0
  67. package/dist/agents/result.js.map +7 -0
  68. package/dist/agents/rm.d.ts +15 -0
  69. package/dist/agents/rm.d.ts.map +1 -0
  70. package/dist/agents/semaphore.d.ts +7 -0
  71. package/dist/agents/semaphore.d.ts.map +1 -0
  72. package/dist/agents/service-provider.d.ts +9 -0
  73. package/dist/agents/service-provider.d.ts.map +1 -0
  74. package/dist/agents/service-schema.d.ts +6 -0
  75. package/dist/agents/service-schema.d.ts.map +1 -0
  76. package/dist/agents/service-types.d.ts +192 -0
  77. package/dist/agents/service-types.d.ts.map +1 -0
  78. package/dist/agents/service.d.ts +36 -0
  79. package/dist/agents/service.d.ts.map +1 -0
  80. package/dist/agents/session-export.d.ts +39 -0
  81. package/dist/agents/session-export.d.ts.map +1 -0
  82. package/dist/agents/session-pins.d.ts +24 -0
  83. package/dist/agents/session-pins.d.ts.map +1 -0
  84. package/dist/agents/thinking-transfer.d.ts +39 -0
  85. package/dist/agents/thinking-transfer.d.ts.map +1 -0
  86. package/dist/agents/transports/herdr-transport.d.ts +10 -0
  87. package/dist/agents/transports/herdr-transport.d.ts.map +1 -0
  88. package/dist/agents/transports/localterm-transport.d.ts +7 -0
  89. package/dist/agents/transports/localterm-transport.d.ts.map +1 -0
  90. package/dist/agents/transports/process-transport.d.ts +7 -0
  91. package/dist/agents/transports/process-transport.d.ts.map +1 -0
  92. package/dist/agents/transports/process-utils.d.ts +33 -0
  93. package/dist/agents/transports/process-utils.d.ts.map +1 -0
  94. package/dist/agents/transports/screen-transport.d.ts +7 -0
  95. package/dist/agents/transports/screen-transport.d.ts.map +1 -0
  96. package/dist/agents/transports/tmux-transport.d.ts +7 -0
  97. package/dist/agents/transports/tmux-transport.d.ts.map +1 -0
  98. package/dist/agents/types.d.ts +280 -0
  99. package/dist/agents/types.d.ts.map +1 -0
  100. package/dist/agents/veda-cli.d.ts +22 -0
  101. package/dist/agents/veda-cli.d.ts.map +1 -0
  102. package/dist/agents/veda-cli.js +13 -0
  103. package/dist/agents/veda-cli.js.map +7 -0
  104. package/dist/agents/worktree-manager.d.ts +14 -0
  105. package/dist/agents/worktree-manager.d.ts.map +1 -0
  106. package/dist/agents/worktree-paths.d.ts +5 -0
  107. package/dist/agents/worktree-paths.d.ts.map +1 -0
  108. package/dist/agents.d.ts +8 -0
  109. package/dist/agents.d.ts.map +1 -0
  110. package/dist/agents.js +761 -0
  111. package/dist/agents.js.map +7 -0
  112. package/dist/async-settlement.d.ts +4 -0
  113. package/dist/async-settlement.d.ts.map +1 -0
  114. package/dist/audit/details.d.ts +86 -0
  115. package/dist/audit/details.d.ts.map +1 -0
  116. package/dist/audit/index.d.ts +4 -0
  117. package/dist/audit/index.d.ts.map +1 -0
  118. package/dist/audit/projection.d.ts +20 -0
  119. package/dist/audit/projection.d.ts.map +1 -0
  120. package/dist/audit/trace.d.ts +99 -0
  121. package/dist/audit/trace.d.ts.map +1 -0
  122. package/dist/capture/catalog.d.ts +30 -0
  123. package/dist/capture/catalog.d.ts.map +1 -0
  124. package/dist/capture/interceptor.d.ts +20 -0
  125. package/dist/capture/interceptor.d.ts.map +1 -0
  126. package/dist/capture/wrapper.d.ts +15 -0
  127. package/dist/capture/wrapper.d.ts.map +1 -0
  128. package/dist/chunks/chunk-2DMJ7MEI.js +1984 -0
  129. package/dist/chunks/chunk-2DMJ7MEI.js.map +7 -0
  130. package/dist/chunks/chunk-2PZWDVJB.js +738 -0
  131. package/dist/chunks/chunk-2PZWDVJB.js.map +7 -0
  132. package/dist/chunks/chunk-2UQV52II.js +440 -0
  133. package/dist/chunks/chunk-2UQV52II.js.map +7 -0
  134. package/dist/chunks/chunk-32BNQ75J.js +1445 -0
  135. package/dist/chunks/chunk-32BNQ75J.js.map +7 -0
  136. package/dist/chunks/chunk-3H7SDWZI.js +467 -0
  137. package/dist/chunks/chunk-3H7SDWZI.js.map +7 -0
  138. package/dist/chunks/chunk-3MEHEH6B.js +41 -0
  139. package/dist/chunks/chunk-3MEHEH6B.js.map +7 -0
  140. package/dist/chunks/chunk-3QECYQGA.js +70 -0
  141. package/dist/chunks/chunk-3QECYQGA.js.map +7 -0
  142. package/dist/chunks/chunk-3WIGAX56.js +644 -0
  143. package/dist/chunks/chunk-3WIGAX56.js.map +7 -0
  144. package/dist/chunks/chunk-3YZUQESG.js +16 -0
  145. package/dist/chunks/chunk-3YZUQESG.js.map +7 -0
  146. package/dist/chunks/chunk-4JETKRFE.js +287 -0
  147. package/dist/chunks/chunk-4JETKRFE.js.map +7 -0
  148. package/dist/chunks/chunk-4SSMGBF4.js +93 -0
  149. package/dist/chunks/chunk-4SSMGBF4.js.map +7 -0
  150. package/dist/chunks/chunk-5SU3YXBS.js +15 -0
  151. package/dist/chunks/chunk-5SU3YXBS.js.map +7 -0
  152. package/dist/chunks/chunk-656HWVFU.js +409 -0
  153. package/dist/chunks/chunk-656HWVFU.js.map +7 -0
  154. package/dist/chunks/chunk-7A6NVHB5.js +1242 -0
  155. package/dist/chunks/chunk-7A6NVHB5.js.map +7 -0
  156. package/dist/chunks/chunk-7TB7NXSL.js +58 -0
  157. package/dist/chunks/chunk-7TB7NXSL.js.map +7 -0
  158. package/dist/chunks/chunk-AAHHYDTO.js +24 -0
  159. package/dist/chunks/chunk-AAHHYDTO.js.map +7 -0
  160. package/dist/chunks/chunk-ARLYAW2A.js +95 -0
  161. package/dist/chunks/chunk-ARLYAW2A.js.map +7 -0
  162. package/dist/chunks/chunk-AYBIR4YV.js +210 -0
  163. package/dist/chunks/chunk-AYBIR4YV.js.map +7 -0
  164. package/dist/chunks/chunk-BOTRGFQQ.js +87 -0
  165. package/dist/chunks/chunk-BOTRGFQQ.js.map +7 -0
  166. package/dist/chunks/chunk-CGPK5WHX.js +96 -0
  167. package/dist/chunks/chunk-CGPK5WHX.js.map +7 -0
  168. package/dist/chunks/chunk-CI56CW53.js +470 -0
  169. package/dist/chunks/chunk-CI56CW53.js.map +7 -0
  170. package/dist/chunks/chunk-CPSW2GW4.js +1466 -0
  171. package/dist/chunks/chunk-CPSW2GW4.js.map +7 -0
  172. package/dist/chunks/chunk-CQFP2RCP.js +64 -0
  173. package/dist/chunks/chunk-CQFP2RCP.js.map +7 -0
  174. package/dist/chunks/chunk-D5WKZONW.js +797 -0
  175. package/dist/chunks/chunk-D5WKZONW.js.map +7 -0
  176. package/dist/chunks/chunk-DLXPTBPL.js +151 -0
  177. package/dist/chunks/chunk-DLXPTBPL.js.map +7 -0
  178. package/dist/chunks/chunk-G4LADAYY.js +287 -0
  179. package/dist/chunks/chunk-G4LADAYY.js.map +7 -0
  180. package/dist/chunks/chunk-GXNR6NRU.js +447 -0
  181. package/dist/chunks/chunk-GXNR6NRU.js.map +7 -0
  182. package/dist/chunks/chunk-IGVDD2HT.js +10 -0
  183. package/dist/chunks/chunk-IGVDD2HT.js.map +7 -0
  184. package/dist/chunks/chunk-J2HV2URQ.js +1125 -0
  185. package/dist/chunks/chunk-J2HV2URQ.js.map +7 -0
  186. package/dist/chunks/chunk-KAD7UWT2.js +99 -0
  187. package/dist/chunks/chunk-KAD7UWT2.js.map +7 -0
  188. package/dist/chunks/chunk-KYXZJNV6.js +227 -0
  189. package/dist/chunks/chunk-KYXZJNV6.js.map +7 -0
  190. package/dist/chunks/chunk-LMAVZN7J.js +8 -0
  191. package/dist/chunks/chunk-LMAVZN7J.js.map +7 -0
  192. package/dist/chunks/chunk-M3S7XITB.js +110 -0
  193. package/dist/chunks/chunk-M3S7XITB.js.map +7 -0
  194. package/dist/chunks/chunk-MGDLRV2R.js +112 -0
  195. package/dist/chunks/chunk-MGDLRV2R.js.map +7 -0
  196. package/dist/chunks/chunk-MGWQOKBV.js +30 -0
  197. package/dist/chunks/chunk-MGWQOKBV.js.map +7 -0
  198. package/dist/chunks/chunk-N5GUXC6F.js +184 -0
  199. package/dist/chunks/chunk-N5GUXC6F.js.map +7 -0
  200. package/dist/chunks/chunk-NQOEHX62.js +215 -0
  201. package/dist/chunks/chunk-NQOEHX62.js.map +7 -0
  202. package/dist/chunks/chunk-OKOHRXGF.js +100 -0
  203. package/dist/chunks/chunk-OKOHRXGF.js.map +7 -0
  204. package/dist/chunks/chunk-OP2KTYQB.js +286 -0
  205. package/dist/chunks/chunk-OP2KTYQB.js.map +7 -0
  206. package/dist/chunks/chunk-OTCASLY2.js +52 -0
  207. package/dist/chunks/chunk-OTCASLY2.js.map +7 -0
  208. package/dist/chunks/chunk-PAN6C3JM.js +42 -0
  209. package/dist/chunks/chunk-PAN6C3JM.js.map +7 -0
  210. package/dist/chunks/chunk-PH7ZJ27F.js +6873 -0
  211. package/dist/chunks/chunk-PH7ZJ27F.js.map +7 -0
  212. package/dist/chunks/chunk-PM5I335G.js +225 -0
  213. package/dist/chunks/chunk-PM5I335G.js.map +7 -0
  214. package/dist/chunks/chunk-PSNXUZMY.js +218 -0
  215. package/dist/chunks/chunk-PSNXUZMY.js.map +7 -0
  216. package/dist/chunks/chunk-PXAICAUT.js +24 -0
  217. package/dist/chunks/chunk-PXAICAUT.js.map +7 -0
  218. package/dist/chunks/chunk-RERA6YWA.js +359 -0
  219. package/dist/chunks/chunk-RERA6YWA.js.map +7 -0
  220. package/dist/chunks/chunk-RNOPHITP.js +1720 -0
  221. package/dist/chunks/chunk-RNOPHITP.js.map +7 -0
  222. package/dist/chunks/chunk-RRGTKHXZ.js +931 -0
  223. package/dist/chunks/chunk-RRGTKHXZ.js.map +7 -0
  224. package/dist/chunks/chunk-SWB2OHYW.js +93 -0
  225. package/dist/chunks/chunk-SWB2OHYW.js.map +7 -0
  226. package/dist/chunks/chunk-T3A5GNCW.js +19 -0
  227. package/dist/chunks/chunk-T3A5GNCW.js.map +7 -0
  228. package/dist/chunks/chunk-TPLMVELH.js +118 -0
  229. package/dist/chunks/chunk-TPLMVELH.js.map +7 -0
  230. package/dist/chunks/chunk-TSRKCXNI.js +17 -0
  231. package/dist/chunks/chunk-TSRKCXNI.js.map +7 -0
  232. package/dist/chunks/chunk-U5FYOMG5.js +119 -0
  233. package/dist/chunks/chunk-U5FYOMG5.js.map +7 -0
  234. package/dist/chunks/chunk-U6CTHPZC.js +1924 -0
  235. package/dist/chunks/chunk-U6CTHPZC.js.map +7 -0
  236. package/dist/chunks/chunk-UDFDF7IY.js +1572 -0
  237. package/dist/chunks/chunk-UDFDF7IY.js.map +7 -0
  238. package/dist/chunks/chunk-UKMQK5VP.js +231 -0
  239. package/dist/chunks/chunk-UKMQK5VP.js.map +7 -0
  240. package/dist/chunks/chunk-UQ4LTUH4.js +2181 -0
  241. package/dist/chunks/chunk-UQ4LTUH4.js.map +7 -0
  242. package/dist/chunks/chunk-UTR3I23Z.js +65 -0
  243. package/dist/chunks/chunk-UTR3I23Z.js.map +7 -0
  244. package/dist/chunks/chunk-VPPIJRNZ.js +50 -0
  245. package/dist/chunks/chunk-VPPIJRNZ.js.map +7 -0
  246. package/dist/chunks/chunk-VRYEGVHR.js +195 -0
  247. package/dist/chunks/chunk-VRYEGVHR.js.map +7 -0
  248. package/dist/chunks/chunk-VRZNFNPB.js +4218 -0
  249. package/dist/chunks/chunk-VRZNFNPB.js.map +7 -0
  250. package/dist/chunks/chunk-VXZZJ44D.js +295 -0
  251. package/dist/chunks/chunk-VXZZJ44D.js.map +7 -0
  252. package/dist/chunks/chunk-W3FRE4VI.js +297 -0
  253. package/dist/chunks/chunk-W3FRE4VI.js.map +7 -0
  254. package/dist/chunks/chunk-WVH324VF.js +60 -0
  255. package/dist/chunks/chunk-WVH324VF.js.map +7 -0
  256. package/dist/chunks/chunk-X7G62ZGH.js +151 -0
  257. package/dist/chunks/chunk-X7G62ZGH.js.map +7 -0
  258. package/dist/chunks/chunk-XB3RJVT4.js +17 -0
  259. package/dist/chunks/chunk-XB3RJVT4.js.map +7 -0
  260. package/dist/chunks/chunk-XT4346N7.js +651 -0
  261. package/dist/chunks/chunk-XT4346N7.js.map +7 -0
  262. package/dist/chunks/chunk-Y7KNRAFL.js +1180 -0
  263. package/dist/chunks/chunk-Y7KNRAFL.js.map +7 -0
  264. package/dist/chunks/chunk-YK5AZ7CZ.js +692 -0
  265. package/dist/chunks/chunk-YK5AZ7CZ.js.map +7 -0
  266. package/dist/chunks/chunk-YU4O6SWQ.js +246 -0
  267. package/dist/chunks/chunk-YU4O6SWQ.js.map +7 -0
  268. package/dist/chunks/chunk-YU62DDKK.js +22 -0
  269. package/dist/chunks/chunk-YU62DDKK.js.map +7 -0
  270. package/dist/chunks/chunk-Z63R5GVN.js +121 -0
  271. package/dist/chunks/chunk-Z63R5GVN.js.map +7 -0
  272. package/dist/chunks/chunk-ZDNGXLEC.js +221 -0
  273. package/dist/chunks/chunk-ZDNGXLEC.js.map +7 -0
  274. package/dist/chunks/chunk-ZZ4LHQYJ.js +777 -0
  275. package/dist/chunks/chunk-ZZ4LHQYJ.js.map +7 -0
  276. package/dist/commands/fabric.d.ts +17 -0
  277. package/dist/commands/fabric.d.ts.map +1 -0
  278. package/dist/compaction/bounds.d.ts +23 -0
  279. package/dist/compaction/bounds.d.ts.map +1 -0
  280. package/dist/compaction/branch-details.d.ts +83 -0
  281. package/dist/compaction/branch-details.d.ts.map +1 -0
  282. package/dist/compaction/branch-summary.d.ts +9 -0
  283. package/dist/compaction/branch-summary.d.ts.map +1 -0
  284. package/dist/compaction/enrichers.d.ts +10 -0
  285. package/dist/compaction/enrichers.d.ts.map +1 -0
  286. package/dist/compaction/hook.d.ts +99 -0
  287. package/dist/compaction/hook.d.ts.map +1 -0
  288. package/dist/compaction/hook.js +22 -0
  289. package/dist/compaction/hook.js.map +7 -0
  290. package/dist/compaction/instructions.d.ts +38 -0
  291. package/dist/compaction/instructions.d.ts.map +1 -0
  292. package/dist/compaction/normalize.d.ts +83 -0
  293. package/dist/compaction/normalize.d.ts.map +1 -0
  294. package/dist/compaction/projections.d.ts +31 -0
  295. package/dist/compaction/projections.d.ts.map +1 -0
  296. package/dist/compaction/qa.d.ts +27 -0
  297. package/dist/compaction/qa.d.ts.map +1 -0
  298. package/dist/compaction/render.d.ts +10 -0
  299. package/dist/compaction/render.d.ts.map +1 -0
  300. package/dist/compaction/threshold.d.ts +5 -0
  301. package/dist/compaction/threshold.d.ts.map +1 -0
  302. package/dist/compaction/trace-events.d.ts +23 -0
  303. package/dist/compaction/trace-events.d.ts.map +1 -0
  304. package/dist/components/catalog.d.ts +25 -0
  305. package/dist/components/catalog.d.ts.map +1 -0
  306. package/dist/components/effect-policy.d.ts +21 -0
  307. package/dist/components/effect-policy.d.ts.map +1 -0
  308. package/dist/components/effect-scope.d.ts +31 -0
  309. package/dist/components/effect-scope.d.ts.map +1 -0
  310. package/dist/components/loader.d.ts +27 -0
  311. package/dist/components/loader.d.ts.map +1 -0
  312. package/dist/components/model-guidance.d.ts +48 -0
  313. package/dist/components/model-guidance.d.ts.map +1 -0
  314. package/dist/components/provider-component.d.ts +31 -0
  315. package/dist/components/provider-component.d.ts.map +1 -0
  316. package/dist/components/supervisor.d.ts +29 -0
  317. package/dist/components/supervisor.d.ts.map +1 -0
  318. package/dist/components/types.d.ts +140 -0
  319. package/dist/components/types.d.ts.map +1 -0
  320. package/dist/config-migrations.d.ts +11 -0
  321. package/dist/config-migrations.d.ts.map +1 -0
  322. package/dist/config.d.ts +282 -0
  323. package/dist/config.d.ts.map +1 -0
  324. package/dist/core/action-arguments.d.ts +12 -0
  325. package/dist/core/action-arguments.d.ts.map +1 -0
  326. package/dist/core/action-registry.d.ts +170 -0
  327. package/dist/core/action-registry.d.ts.map +1 -0
  328. package/dist/core/action-registry.js +20 -0
  329. package/dist/core/action-registry.js.map +7 -0
  330. package/dist/core/action-repair.d.ts +15 -0
  331. package/dist/core/action-repair.d.ts.map +1 -0
  332. package/dist/core/action-result.d.ts +13 -0
  333. package/dist/core/action-result.d.ts.map +1 -0
  334. package/dist/core/agent-dir.d.ts +2 -0
  335. package/dist/core/agent-dir.d.ts.map +1 -0
  336. package/dist/core/approval-controller.d.ts +31 -0
  337. package/dist/core/approval-controller.d.ts.map +1 -0
  338. package/dist/core/atomic-write.d.ts +15 -0
  339. package/dist/core/atomic-write.d.ts.map +1 -0
  340. package/dist/core/auto-approval-classifier.d.ts +17 -0
  341. package/dist/core/auto-approval-classifier.d.ts.map +1 -0
  342. package/dist/core/call-preview.d.ts +8 -0
  343. package/dist/core/call-preview.d.ts.map +1 -0
  344. package/dist/core/child-tool-allowlist.d.ts +3 -0
  345. package/dist/core/child-tool-allowlist.d.ts.map +1 -0
  346. package/dist/core/compact-controller.d.ts +42 -0
  347. package/dist/core/compact-controller.d.ts.map +1 -0
  348. package/dist/core/core-override-guidance.d.ts +7 -0
  349. package/dist/core/core-override-guidance.d.ts.map +1 -0
  350. package/dist/core/damaged-file.d.ts +6 -0
  351. package/dist/core/damaged-file.d.ts.map +1 -0
  352. package/dist/core/direct-tool-approval.d.ts +19 -0
  353. package/dist/core/direct-tool-approval.d.ts.map +1 -0
  354. package/dist/core/effect-conflict.d.ts +3 -0
  355. package/dist/core/effect-conflict.d.ts.map +1 -0
  356. package/dist/core/file-lock.d.ts +12 -0
  357. package/dist/core/file-lock.d.ts.map +1 -0
  358. package/dist/core/kernel-skills.d.ts +3 -0
  359. package/dist/core/kernel-skills.d.ts.map +1 -0
  360. package/dist/core/model-resolution.d.ts +62 -0
  361. package/dist/core/model-resolution.d.ts.map +1 -0
  362. package/dist/core/model-usage.d.ts +8 -0
  363. package/dist/core/model-usage.d.ts.map +1 -0
  364. package/dist/core/pi-arguments.d.ts +3 -0
  365. package/dist/core/pi-arguments.d.ts.map +1 -0
  366. package/dist/core/pi-bash-error.d.ts +9 -0
  367. package/dist/core/pi-bash-error.d.ts.map +1 -0
  368. package/dist/core/pi-tools.d.ts +9 -0
  369. package/dist/core/pi-tools.d.ts.map +1 -0
  370. package/dist/core/provider-bindings.d.ts +47 -0
  371. package/dist/core/provider-bindings.d.ts.map +1 -0
  372. package/dist/core/proxy-contract.d.ts +18 -0
  373. package/dist/core/proxy-contract.d.ts.map +1 -0
  374. package/dist/core/session-context.d.ts +14 -0
  375. package/dist/core/session-context.d.ts.map +1 -0
  376. package/dist/core/shell-jobs.d.ts +99 -0
  377. package/dist/core/shell-jobs.d.ts.map +1 -0
  378. package/dist/core/skill-block.d.ts +10 -0
  379. package/dist/core/skill-block.d.ts.map +1 -0
  380. package/dist/core/skill-dir.d.ts +4 -0
  381. package/dist/core/skill-dir.d.ts.map +1 -0
  382. package/dist/core/skill-prompt.d.ts +3 -0
  383. package/dist/core/skill-prompt.d.ts.map +1 -0
  384. package/dist/core/skill-references.d.ts +7 -0
  385. package/dist/core/skill-references.d.ts.map +1 -0
  386. package/dist/core/stable-hash.d.ts +3 -0
  387. package/dist/core/stable-hash.d.ts.map +1 -0
  388. package/dist/core/system-guidance.d.ts +13 -0
  389. package/dist/core/system-guidance.d.ts.map +1 -0
  390. package/dist/core/token-math.d.ts +16 -0
  391. package/dist/core/token-math.d.ts.map +1 -0
  392. package/dist/core/tool-ownership.d.ts +47 -0
  393. package/dist/core/tool-ownership.d.ts.map +1 -0
  394. package/dist/core/tool-result-proxy.d.ts +18 -0
  395. package/dist/core/tool-result-proxy.d.ts.map +1 -0
  396. package/dist/entropy/active.d.ts +9 -0
  397. package/dist/entropy/active.d.ts.map +1 -0
  398. package/dist/entropy/compiled-store.d.ts +16 -0
  399. package/dist/entropy/compiled-store.d.ts.map +1 -0
  400. package/dist/entropy/compiled-surface.d.ts +57 -0
  401. package/dist/entropy/compiled-surface.d.ts.map +1 -0
  402. package/dist/entropy/compiler.d.ts +27 -0
  403. package/dist/entropy/compiler.d.ts.map +1 -0
  404. package/dist/entropy/corpus.d.ts +22 -0
  405. package/dist/entropy/corpus.d.ts.map +1 -0
  406. package/dist/entropy/fingerprint.d.ts +9 -0
  407. package/dist/entropy/fingerprint.d.ts.map +1 -0
  408. package/dist/entropy/index.d.ts +16 -0
  409. package/dist/entropy/index.d.ts.map +1 -0
  410. package/dist/entropy/index.js +194 -0
  411. package/dist/entropy/index.js.map +7 -0
  412. package/dist/entropy/meter.d.ts +10 -0
  413. package/dist/entropy/meter.d.ts.map +1 -0
  414. package/dist/entropy/normal-form.d.ts +40 -0
  415. package/dist/entropy/normal-form.d.ts.map +1 -0
  416. package/dist/entropy/passes.d.ts +13 -0
  417. package/dist/entropy/passes.d.ts.map +1 -0
  418. package/dist/entropy/pool-store.d.ts +15 -0
  419. package/dist/entropy/pool-store.d.ts.map +1 -0
  420. package/dist/entropy/pool.d.ts +41 -0
  421. package/dist/entropy/pool.d.ts.map +1 -0
  422. package/dist/entropy/presentation.d.ts +12 -0
  423. package/dist/entropy/presentation.d.ts.map +1 -0
  424. package/dist/entropy/sessions.d.ts +47 -0
  425. package/dist/entropy/sessions.d.ts.map +1 -0
  426. package/dist/entropy/surface.d.ts +30 -0
  427. package/dist/entropy/surface.d.ts.map +1 -0
  428. package/dist/entropy/trial.d.ts +38 -0
  429. package/dist/entropy/trial.d.ts.map +1 -0
  430. package/dist/entropy/types.d.ts +181 -0
  431. package/dist/entropy/types.d.ts.map +1 -0
  432. package/dist/execution-service.d.ts +66 -0
  433. package/dist/execution-service.d.ts.map +1 -0
  434. package/dist/fabric-exec-arguments.d.ts +7 -0
  435. package/dist/fabric-exec-arguments.d.ts.map +1 -0
  436. package/dist/fabric-exec-tool.d.ts +8 -0
  437. package/dist/fabric-exec-tool.d.ts.map +1 -0
  438. package/dist/fabric-runtime-state.d.ts +96 -0
  439. package/dist/fabric-runtime-state.d.ts.map +1 -0
  440. package/dist/fabric-runtime-state.js +11928 -0
  441. package/dist/fabric-runtime-state.js.map +7 -0
  442. package/dist/fabric-state.d.ts +95 -0
  443. package/dist/fabric-state.d.ts.map +1 -0
  444. package/dist/failure-progress.d.ts +3 -0
  445. package/dist/failure-progress.d.ts.map +1 -0
  446. package/dist/host-compatibility.d.ts +5 -0
  447. package/dist/host-compatibility.d.ts.map +1 -0
  448. package/dist/index.d.ts +11 -0
  449. package/dist/index.d.ts.map +1 -0
  450. package/dist/index.js +6094 -0
  451. package/dist/index.js.map +7 -0
  452. package/dist/jev/auth.d.ts +5 -0
  453. package/dist/jev/auth.d.ts.map +1 -0
  454. package/dist/jev/browser.d.ts +37 -0
  455. package/dist/jev/browser.d.ts.map +1 -0
  456. package/dist/jev/browser.js +13 -0
  457. package/dist/jev/browser.js.map +7 -0
  458. package/dist/jev/client.d.ts +29 -0
  459. package/dist/jev/client.d.ts.map +1 -0
  460. package/dist/jev/client.js +11 -0
  461. package/dist/jev/client.js.map +7 -0
  462. package/dist/jev/config.d.ts +17 -0
  463. package/dist/jev/config.d.ts.map +1 -0
  464. package/dist/jev/guest-types.d.ts +2 -0
  465. package/dist/jev/guest-types.d.ts.map +1 -0
  466. package/dist/jev/manager.d.ts +36 -0
  467. package/dist/jev/manager.d.ts.map +1 -0
  468. package/dist/jev/observation.d.ts +59 -0
  469. package/dist/jev/observation.d.ts.map +1 -0
  470. package/dist/jev/observation.js +20 -0
  471. package/dist/jev/observation.js.map +7 -0
  472. package/dist/jev/types.d.ts +142 -0
  473. package/dist/jev/types.d.ts.map +1 -0
  474. package/dist/jev/validation.d.ts +8 -0
  475. package/dist/jev/validation.d.ts.map +1 -0
  476. package/dist/jev.d.ts +9 -0
  477. package/dist/jev.d.ts.map +1 -0
  478. package/dist/jev.js +49 -0
  479. package/dist/jev.js.map +7 -0
  480. package/dist/lifecycle/broker.d.ts +30 -0
  481. package/dist/lifecycle/broker.d.ts.map +1 -0
  482. package/dist/lifecycle/delivery-scheduler.d.ts +30 -0
  483. package/dist/lifecycle/delivery-scheduler.d.ts.map +1 -0
  484. package/dist/lifecycle/types.d.ts +91 -0
  485. package/dist/lifecycle/types.d.ts.map +1 -0
  486. package/dist/log-tail.d.ts +11 -0
  487. package/dist/log-tail.d.ts.map +1 -0
  488. package/dist/main-agent.d.ts +70 -0
  489. package/dist/main-agent.d.ts.map +1 -0
  490. package/dist/managed-host.d.ts +22 -0
  491. package/dist/managed-host.d.ts.map +1 -0
  492. package/dist/mcp.d.ts +9 -0
  493. package/dist/mcp.d.ts.map +1 -0
  494. package/dist/mcp.js +21 -0
  495. package/dist/mcp.js.map +7 -0
  496. package/dist/memory/client.d.ts +31 -0
  497. package/dist/memory/client.d.ts.map +1 -0
  498. package/dist/memory/context.d.ts +114 -0
  499. package/dist/memory/context.d.ts.map +1 -0
  500. package/dist/memory/digest.d.ts +48 -0
  501. package/dist/memory/digest.d.ts.map +1 -0
  502. package/dist/memory/digest.js +7 -0
  503. package/dist/memory/digest.js.map +7 -0
  504. package/dist/memory/discovery.d.ts +43 -0
  505. package/dist/memory/discovery.d.ts.map +1 -0
  506. package/dist/memory/discovery.js +25 -0
  507. package/dist/memory/discovery.js.map +7 -0
  508. package/dist/memory/expand-service.d.ts +4 -0
  509. package/dist/memory/expand-service.d.ts.map +1 -0
  510. package/dist/memory/host-source.d.ts +60 -0
  511. package/dist/memory/host-source.d.ts.map +1 -0
  512. package/dist/memory/index.d.ts +113 -0
  513. package/dist/memory/index.d.ts.map +1 -0
  514. package/dist/memory/lineage.d.ts +25 -0
  515. package/dist/memory/lineage.d.ts.map +1 -0
  516. package/dist/memory/normalize.d.ts +188 -0
  517. package/dist/memory/normalize.d.ts.map +1 -0
  518. package/dist/memory/normalize.js +26 -0
  519. package/dist/memory/normalize.js.map +7 -0
  520. package/dist/memory/portable.d.ts +66 -0
  521. package/dist/memory/portable.d.ts.map +1 -0
  522. package/dist/memory/provider.d.ts +15 -0
  523. package/dist/memory/provider.d.ts.map +1 -0
  524. package/dist/memory/recall-service.d.ts +5 -0
  525. package/dist/memory/recall-service.d.ts.map +1 -0
  526. package/dist/memory/regex.d.ts +19 -0
  527. package/dist/memory/regex.d.ts.map +1 -0
  528. package/dist/memory/request-cache.d.ts +49 -0
  529. package/dist/memory/request-cache.d.ts.map +1 -0
  530. package/dist/memory/request-context.d.ts +57 -0
  531. package/dist/memory/request-context.d.ts.map +1 -0
  532. package/dist/memory/request-limits.d.ts +8 -0
  533. package/dist/memory/request-limits.d.ts.map +1 -0
  534. package/dist/memory/search.d.ts +98 -0
  535. package/dist/memory/search.d.ts.map +1 -0
  536. package/dist/memory/search.js +24 -0
  537. package/dist/memory/search.js.map +7 -0
  538. package/dist/memory/sessions-service.d.ts +3 -0
  539. package/dist/memory/sessions-service.d.ts.map +1 -0
  540. package/dist/memory/source-observation.d.ts +28 -0
  541. package/dist/memory/source-observation.d.ts.map +1 -0
  542. package/dist/memory/tokenize.d.ts +24 -0
  543. package/dist/memory/tokenize.d.ts.map +1 -0
  544. package/dist/memory.d.ts +8 -0
  545. package/dist/memory.d.ts.map +1 -0
  546. package/dist/memory.js +119 -0
  547. package/dist/memory.js.map +7 -0
  548. package/dist/mesh/store.d.ts +78 -0
  549. package/dist/mesh/store.d.ts.map +1 -0
  550. package/dist/output-budget.d.ts +12 -0
  551. package/dist/output-budget.d.ts.map +1 -0
  552. package/dist/prewalk/arm.d.ts +8 -0
  553. package/dist/prewalk/arm.d.ts.map +1 -0
  554. package/dist/prewalk/controller.d.ts +66 -0
  555. package/dist/prewalk/controller.d.ts.map +1 -0
  556. package/dist/prewalk/fs-drift.d.ts +19 -0
  557. package/dist/prewalk/fs-drift.d.ts.map +1 -0
  558. package/dist/prewalk/handoff.d.ts +46 -0
  559. package/dist/prewalk/handoff.d.ts.map +1 -0
  560. package/dist/protocol.d.ts +275 -0
  561. package/dist/protocol.d.ts.map +1 -0
  562. package/dist/protocol.js +46 -0
  563. package/dist/protocol.js.map +7 -0
  564. package/dist/providers/agents-actions.d.ts +3 -0
  565. package/dist/providers/agents-actions.d.ts.map +1 -0
  566. package/dist/providers/agents-message-router.d.ts +29 -0
  567. package/dist/providers/agents-message-router.d.ts.map +1 -0
  568. package/dist/providers/agents-progress.d.ts +18 -0
  569. package/dist/providers/agents-progress.d.ts.map +1 -0
  570. package/dist/providers/agents-provider.d.ts +51 -0
  571. package/dist/providers/agents-provider.d.ts.map +1 -0
  572. package/dist/providers/arg-normalization.d.ts +15 -0
  573. package/dist/providers/arg-normalization.d.ts.map +1 -0
  574. package/dist/providers/captured-tools-provider.d.ts +23 -0
  575. package/dist/providers/captured-tools-provider.d.ts.map +1 -0
  576. package/dist/providers/compact-provider.d.ts +14 -0
  577. package/dist/providers/compact-provider.d.ts.map +1 -0
  578. package/dist/providers/components-provider.d.ts +12 -0
  579. package/dist/providers/components-provider.d.ts.map +1 -0
  580. package/dist/providers/jev-provider.d.ts +70 -0
  581. package/dist/providers/jev-provider.d.ts.map +1 -0
  582. package/dist/providers/jev-provider.js +28 -0
  583. package/dist/providers/jev-provider.js.map +7 -0
  584. package/dist/providers/mcp-descriptor-cache.d.ts +47 -0
  585. package/dist/providers/mcp-descriptor-cache.d.ts.map +1 -0
  586. package/dist/providers/mcp-provider.d.ts +47 -0
  587. package/dist/providers/mcp-provider.d.ts.map +1 -0
  588. package/dist/providers/memory-provider.d.ts +32 -0
  589. package/dist/providers/memory-provider.d.ts.map +1 -0
  590. package/dist/providers/memory-provider.js +23 -0
  591. package/dist/providers/memory-provider.js.map +7 -0
  592. package/dist/providers/mesh-provider.d.ts +17 -0
  593. package/dist/providers/mesh-provider.d.ts.map +1 -0
  594. package/dist/providers/pi-bash-cwd.d.ts +49 -0
  595. package/dist/providers/pi-bash-cwd.d.ts.map +1 -0
  596. package/dist/providers/pi-tools-provider.d.ts +25 -0
  597. package/dist/providers/pi-tools-provider.d.ts.map +1 -0
  598. package/dist/providers/schema-provider.d.ts +15 -0
  599. package/dist/providers/schema-provider.d.ts.map +1 -0
  600. package/dist/providers/state-provider.d.ts +16 -0
  601. package/dist/providers/state-provider.d.ts.map +1 -0
  602. package/dist/providers/write-diff-limits.d.ts +5 -0
  603. package/dist/providers/write-diff-limits.d.ts.map +1 -0
  604. package/dist/providers/write-preview.d.ts +3 -0
  605. package/dist/providers/write-preview.d.ts.map +1 -0
  606. package/dist/ref-names.d.ts +2 -0
  607. package/dist/ref-names.d.ts.map +1 -0
  608. package/dist/repairs/active.d.ts +7 -0
  609. package/dist/repairs/active.d.ts.map +1 -0
  610. package/dist/repairs/apply.d.ts +7 -0
  611. package/dist/repairs/apply.d.ts.map +1 -0
  612. package/dist/repairs/catalog-digest.d.ts +5 -0
  613. package/dist/repairs/catalog-digest.d.ts.map +1 -0
  614. package/dist/repairs/classify.d.ts +10 -0
  615. package/dist/repairs/classify.d.ts.map +1 -0
  616. package/dist/repairs/compiler.d.ts +33 -0
  617. package/dist/repairs/compiler.d.ts.map +1 -0
  618. package/dist/repairs/promote.d.ts +4 -0
  619. package/dist/repairs/promote.d.ts.map +1 -0
  620. package/dist/repairs/store.d.ts +10 -0
  621. package/dist/repairs/store.d.ts.map +1 -0
  622. package/dist/repairs/types.d.ts +49 -0
  623. package/dist/repairs/types.d.ts.map +1 -0
  624. package/dist/repeat-guard.d.ts +25 -0
  625. package/dist/repeat-guard.d.ts.map +1 -0
  626. package/dist/residency/actor-client.d.ts +16 -0
  627. package/dist/residency/actor-client.d.ts.map +1 -0
  628. package/dist/residency/actor-client.js +9 -0
  629. package/dist/residency/actor-client.js.map +7 -0
  630. package/dist/residency/client.d.ts +44 -0
  631. package/dist/residency/client.d.ts.map +1 -0
  632. package/dist/residency/host.d.ts +3 -0
  633. package/dist/residency/host.d.ts.map +1 -0
  634. package/dist/residency/host.js +32 -0
  635. package/dist/residency/host.js.map +7 -0
  636. package/dist/residency/launcher-owner.d.ts +7 -0
  637. package/dist/residency/launcher-owner.d.ts.map +1 -0
  638. package/dist/residency/launcher.d.ts +3 -0
  639. package/dist/residency/launcher.d.ts.map +1 -0
  640. package/dist/residency/launcher.js +154 -0
  641. package/dist/residency/launcher.js.map +7 -0
  642. package/dist/residency/pi-entry.d.ts +3 -0
  643. package/dist/residency/pi-entry.d.ts.map +1 -0
  644. package/dist/residency/pi-entry.js +48 -0
  645. package/dist/residency/pi-entry.js.map +7 -0
  646. package/dist/residency/protocol.d.ts +122 -0
  647. package/dist/residency/protocol.d.ts.map +1 -0
  648. package/dist/run-display.d.ts +3 -0
  649. package/dist/run-display.d.ts.map +1 -0
  650. package/dist/runtime/core-override-guest-types.d.ts +15 -0
  651. package/dist/runtime/core-override-guest-types.d.ts.map +1 -0
  652. package/dist/runtime/core-override-guest-types.js +9 -0
  653. package/dist/runtime/core-override-guest-types.js.map +7 -0
  654. package/dist/runtime/core-tool-properties.d.ts +6 -0
  655. package/dist/runtime/core-tool-properties.d.ts.map +1 -0
  656. package/dist/runtime/cpython-child-source.d.ts +2 -0
  657. package/dist/runtime/cpython-child-source.d.ts.map +1 -0
  658. package/dist/runtime/cpython-linux-sandbox.d.ts +2 -0
  659. package/dist/runtime/cpython-linux-sandbox.d.ts.map +1 -0
  660. package/dist/runtime/cpython-runtime.d.ts +9 -0
  661. package/dist/runtime/cpython-runtime.d.ts.map +1 -0
  662. package/dist/runtime/cpython-runtime.js +677 -0
  663. package/dist/runtime/cpython-runtime.js.map +7 -0
  664. package/dist/runtime/dynamic-guest-types.d.ts +3 -0
  665. package/dist/runtime/dynamic-guest-types.d.ts.map +1 -0
  666. package/dist/runtime/dynamic-guest-types.js +8 -0
  667. package/dist/runtime/dynamic-guest-types.js.map +7 -0
  668. package/dist/runtime/guest-code-repair.d.ts +2 -0
  669. package/dist/runtime/guest-code-repair.d.ts.map +1 -0
  670. package/dist/runtime/guest-stack-map.d.ts +11 -0
  671. package/dist/runtime/guest-stack-map.d.ts.map +1 -0
  672. package/dist/runtime/guest-types.d.ts +40 -0
  673. package/dist/runtime/guest-types.d.ts.map +1 -0
  674. package/dist/runtime/guest-types.js +13 -0
  675. package/dist/runtime/guest-types.js.map +7 -0
  676. package/dist/runtime/kernel.d.ts +30 -0
  677. package/dist/runtime/kernel.d.ts.map +1 -0
  678. package/dist/runtime/monty-bridge.d.ts +4 -0
  679. package/dist/runtime/monty-bridge.d.ts.map +1 -0
  680. package/dist/runtime/monty-runtime.d.ts +6 -0
  681. package/dist/runtime/monty-runtime.d.ts.map +1 -0
  682. package/dist/runtime/monty-runtime.js +485 -0
  683. package/dist/runtime/monty-runtime.js.map +7 -0
  684. package/dist/runtime/monty-source.d.ts +10 -0
  685. package/dist/runtime/monty-source.d.ts.map +1 -0
  686. package/dist/runtime/monty-values.d.ts +7 -0
  687. package/dist/runtime/monty-values.d.ts.map +1 -0
  688. package/dist/runtime/node-process-child-source.d.ts +2 -0
  689. package/dist/runtime/node-process-child-source.d.ts.map +1 -0
  690. package/dist/runtime/node-process-runtime.d.ts +10 -0
  691. package/dist/runtime/node-process-runtime.d.ts.map +1 -0
  692. package/dist/runtime/node-process-runtime.js +16 -0
  693. package/dist/runtime/node-process-runtime.js.map +7 -0
  694. package/dist/runtime/orchestration.d.ts +3 -0
  695. package/dist/runtime/orchestration.d.ts.map +1 -0
  696. package/dist/runtime/python-arguments.d.ts +2 -0
  697. package/dist/runtime/python-arguments.d.ts.map +1 -0
  698. package/dist/runtime/python-error-guidance.d.ts +6 -0
  699. package/dist/runtime/python-error-guidance.d.ts.map +1 -0
  700. package/dist/runtime/quickjs-runtime.d.ts +8 -0
  701. package/dist/runtime/quickjs-runtime.d.ts.map +1 -0
  702. package/dist/runtime/quickjs-runtime.js +15 -0
  703. package/dist/runtime/quickjs-runtime.js.map +7 -0
  704. package/dist/runtime/type-checker.d.ts +18 -0
  705. package/dist/runtime/type-checker.d.ts.map +1 -0
  706. package/dist/runtime/type-checker.js +11 -0
  707. package/dist/runtime/type-checker.js.map +7 -0
  708. package/dist/runtime/typescript-kernel.d.ts +14 -0
  709. package/dist/runtime/typescript-kernel.d.ts.map +1 -0
  710. package/dist/runtime/typescript-kernel.js +53 -0
  711. package/dist/runtime/typescript-kernel.js.map +7 -0
  712. package/dist/runtime-paths.d.ts +7 -0
  713. package/dist/runtime-paths.d.ts.map +1 -0
  714. package/dist/runtime-state-builtins.d.ts +26 -0
  715. package/dist/runtime-state-builtins.d.ts.map +1 -0
  716. package/dist/runtime-state-speculation.d.ts +16 -0
  717. package/dist/runtime-state-speculation.d.ts.map +1 -0
  718. package/dist/schema/controller.d.ts +35 -0
  719. package/dist/schema/controller.d.ts.map +1 -0
  720. package/dist/schema/policy.d.ts +2 -0
  721. package/dist/schema/policy.d.ts.map +1 -0
  722. package/dist/schema/types.d.ts +86 -0
  723. package/dist/schema/types.d.ts.map +1 -0
  724. package/dist/schema/workspace.d.ts +19 -0
  725. package/dist/schema/workspace.d.ts.map +1 -0
  726. package/dist/speculation/eligibility.d.ts +22 -0
  727. package/dist/speculation/eligibility.d.ts.map +1 -0
  728. package/dist/speculation/freshness.d.ts +10 -0
  729. package/dist/speculation/freshness.d.ts.map +1 -0
  730. package/dist/speculation/partial-json.d.ts +9 -0
  731. package/dist/speculation/partial-json.d.ts.map +1 -0
  732. package/dist/speculation/python-scanner.d.ts +7 -0
  733. package/dist/speculation/python-scanner.d.ts.map +1 -0
  734. package/dist/speculation/python-scanner.js +166 -0
  735. package/dist/speculation/python-scanner.js.map +7 -0
  736. package/dist/speculation/scanner.d.ts +13 -0
  737. package/dist/speculation/scanner.d.ts.map +1 -0
  738. package/dist/speculation/scanner.js +182 -0
  739. package/dist/speculation/scanner.js.map +7 -0
  740. package/dist/speculation/store.d.ts +41 -0
  741. package/dist/speculation/store.d.ts.map +1 -0
  742. package/dist/speculation/stream-tap.d.ts +30 -0
  743. package/dist/speculation/stream-tap.d.ts.map +1 -0
  744. package/dist/speculation/types.d.ts +44 -0
  745. package/dist/speculation/types.d.ts.map +1 -0
  746. package/dist/state/complexity.d.ts +13 -0
  747. package/dist/state/complexity.d.ts.map +1 -0
  748. package/dist/state/evidence-runner.d.ts +17 -0
  749. package/dist/state/evidence-runner.d.ts.map +1 -0
  750. package/dist/state/store.d.ts +76 -0
  751. package/dist/state/store.d.ts.map +1 -0
  752. package/dist/state/types.d.ts +165 -0
  753. package/dist/state/types.d.ts.map +1 -0
  754. package/dist/storage/retention.d.ts +22 -0
  755. package/dist/storage/retention.d.ts.map +1 -0
  756. package/dist/thinking.d.ts +19 -0
  757. package/dist/thinking.d.ts.map +1 -0
  758. package/dist/topology/control-plane.d.ts +58 -0
  759. package/dist/topology/control-plane.d.ts.map +1 -0
  760. package/dist/topology/participant-directory.d.ts +33 -0
  761. package/dist/topology/participant-directory.d.ts.map +1 -0
  762. package/dist/topology/peer-settle.d.ts +51 -0
  763. package/dist/topology/peer-settle.d.ts.map +1 -0
  764. package/dist/topology/records.d.ts +6 -0
  765. package/dist/topology/records.d.ts.map +1 -0
  766. package/dist/topology/types.d.ts +89 -0
  767. package/dist/topology/types.d.ts.map +1 -0
  768. package/dist/type-error-guidance.d.ts +3 -0
  769. package/dist/type-error-guidance.d.ts.map +1 -0
  770. package/dist/ui/arc-group.d.ts +17 -0
  771. package/dist/ui/arc-group.d.ts.map +1 -0
  772. package/dist/ui/border-status-editor.d.ts +22 -0
  773. package/dist/ui/border-status-editor.d.ts.map +1 -0
  774. package/dist/ui/code-preview-shell.d.ts +11 -0
  775. package/dist/ui/code-preview-shell.d.ts.map +1 -0
  776. package/dist/ui/code-preview.d.ts +53 -0
  777. package/dist/ui/code-preview.d.ts.map +1 -0
  778. package/dist/ui/controller.d.ts +20 -0
  779. package/dist/ui/controller.d.ts.map +1 -0
  780. package/dist/ui/conversation-chrome.d.ts +16 -0
  781. package/dist/ui/conversation-chrome.d.ts.map +1 -0
  782. package/dist/ui/conversation-chrome.js +11 -0
  783. package/dist/ui/conversation-chrome.js.map +7 -0
  784. package/dist/ui/conversation-commands.d.ts +12 -0
  785. package/dist/ui/conversation-commands.d.ts.map +1 -0
  786. package/dist/ui/conversation-history.d.ts +6 -0
  787. package/dist/ui/conversation-history.d.ts.map +1 -0
  788. package/dist/ui/conversation-host.d.ts +7 -0
  789. package/dist/ui/conversation-host.d.ts.map +1 -0
  790. package/dist/ui/conversation-host.js +9 -0
  791. package/dist/ui/conversation-host.js.map +7 -0
  792. package/dist/ui/conversation-native-reader-checkpoint.d.ts +8 -0
  793. package/dist/ui/conversation-native-reader-checkpoint.d.ts.map +1 -0
  794. package/dist/ui/conversation-native-reader-replay.d.ts +10 -0
  795. package/dist/ui/conversation-native-reader-replay.d.ts.map +1 -0
  796. package/dist/ui/conversation-native-reader.d.ts +110 -0
  797. package/dist/ui/conversation-native-reader.d.ts.map +1 -0
  798. package/dist/ui/conversation-native-reader.js +1050 -0
  799. package/dist/ui/conversation-native-reader.js.map +7 -0
  800. package/dist/ui/conversation-queue-store.d.ts +14 -0
  801. package/dist/ui/conversation-queue-store.d.ts.map +1 -0
  802. package/dist/ui/conversation-queue.d.ts +244 -0
  803. package/dist/ui/conversation-queue.d.ts.map +1 -0
  804. package/dist/ui/conversation-render.d.ts +104 -0
  805. package/dist/ui/conversation-render.d.ts.map +1 -0
  806. package/dist/ui/conversation-selection.d.ts +18 -0
  807. package/dist/ui/conversation-selection.d.ts.map +1 -0
  808. package/dist/ui/conversation-shortcut.d.ts +3 -0
  809. package/dist/ui/conversation-shortcut.d.ts.map +1 -0
  810. package/dist/ui/conversation-targets.d.ts +7 -0
  811. package/dist/ui/conversation-targets.d.ts.map +1 -0
  812. package/dist/ui/conversation-targets.js +12 -0
  813. package/dist/ui/conversation-targets.js.map +7 -0
  814. package/dist/ui/conversation-transcript.d.ts +25 -0
  815. package/dist/ui/conversation-transcript.d.ts.map +1 -0
  816. package/dist/ui/conversation.d.ts +219 -0
  817. package/dist/ui/conversation.d.ts.map +1 -0
  818. package/dist/ui/conversation.js +2861 -0
  819. package/dist/ui/conversation.js.map +7 -0
  820. package/dist/ui/core-tool-render.d.ts +20 -0
  821. package/dist/ui/core-tool-render.d.ts.map +1 -0
  822. package/dist/ui/dashboard-detail.d.ts +68 -0
  823. package/dist/ui/dashboard-detail.d.ts.map +1 -0
  824. package/dist/ui/dashboard-fabric-graph.d.ts +50 -0
  825. package/dist/ui/dashboard-fabric-graph.d.ts.map +1 -0
  826. package/dist/ui/dashboard-graph-controller.d.ts +52 -0
  827. package/dist/ui/dashboard-graph-controller.d.ts.map +1 -0
  828. package/dist/ui/dashboard-modal-controller.d.ts +36 -0
  829. package/dist/ui/dashboard-modal-controller.d.ts.map +1 -0
  830. package/dist/ui/dashboard-model.d.ts +111 -0
  831. package/dist/ui/dashboard-model.d.ts.map +1 -0
  832. package/dist/ui/dashboard-presentation.d.ts +6 -0
  833. package/dist/ui/dashboard-presentation.d.ts.map +1 -0
  834. package/dist/ui/dashboard.d.ts +156 -0
  835. package/dist/ui/dashboard.d.ts.map +1 -0
  836. package/dist/ui/dashboard.js +4622 -0
  837. package/dist/ui/dashboard.js.map +7 -0
  838. package/dist/ui/diff-background.d.ts +12 -0
  839. package/dist/ui/diff-background.d.ts.map +1 -0
  840. package/dist/ui/dynamic-border.d.ts +8 -0
  841. package/dist/ui/dynamic-border.d.ts.map +1 -0
  842. package/dist/ui/escape-halt.d.ts +11 -0
  843. package/dist/ui/escape-halt.d.ts.map +1 -0
  844. package/dist/ui/fabric-actor-delivery-selector.d.ts +17 -0
  845. package/dist/ui/fabric-actor-delivery-selector.d.ts.map +1 -0
  846. package/dist/ui/fabric-actor-tool-selector.d.ts +22 -0
  847. package/dist/ui/fabric-actor-tool-selector.d.ts.map +1 -0
  848. package/dist/ui/fabric-code-parser.d.ts +9 -0
  849. package/dist/ui/fabric-code-parser.d.ts.map +1 -0
  850. package/dist/ui/fabric-host-event-selector.d.ts +29 -0
  851. package/dist/ui/fabric-host-event-selector.d.ts.map +1 -0
  852. package/dist/ui/fabric-model-selector.d.ts +64 -0
  853. package/dist/ui/fabric-model-selector.d.ts.map +1 -0
  854. package/dist/ui/fabric-render.d.ts +113 -0
  855. package/dist/ui/fabric-render.d.ts.map +1 -0
  856. package/dist/ui/fabric-thinking-selector.d.ts +26 -0
  857. package/dist/ui/fabric-thinking-selector.d.ts.map +1 -0
  858. package/dist/ui/fabric-title-hint.d.ts +3 -0
  859. package/dist/ui/fabric-title-hint.d.ts.map +1 -0
  860. package/dist/ui/format.d.ts +9 -0
  861. package/dist/ui/format.d.ts.map +1 -0
  862. package/dist/ui/handoff-completion.d.ts +3 -0
  863. package/dist/ui/handoff-completion.d.ts.map +1 -0
  864. package/dist/ui/highlight.d.ts +69 -0
  865. package/dist/ui/highlight.d.ts.map +1 -0
  866. package/dist/ui/model-picker.d.ts +46 -0
  867. package/dist/ui/model-picker.d.ts.map +1 -0
  868. package/dist/ui/model-picker.js +17 -0
  869. package/dist/ui/model-picker.js.map +7 -0
  870. package/dist/ui/preview-lines.d.ts +16 -0
  871. package/dist/ui/preview-lines.d.ts.map +1 -0
  872. package/dist/ui/row-balance.d.ts +29 -0
  873. package/dist/ui/row-balance.d.ts.map +1 -0
  874. package/dist/ui/settings-component.d.ts +26 -0
  875. package/dist/ui/settings-component.d.ts.map +1 -0
  876. package/dist/ui/settings-rpc.d.ts +15 -0
  877. package/dist/ui/settings-rpc.d.ts.map +1 -0
  878. package/dist/ui/settings-section-context.d.ts +18 -0
  879. package/dist/ui/settings-section-context.d.ts.map +1 -0
  880. package/dist/ui/settings-sections-agents.d.ts +5 -0
  881. package/dist/ui/settings-sections-agents.d.ts.map +1 -0
  882. package/dist/ui/settings-sections-execution.d.ts +8 -0
  883. package/dist/ui/settings-sections-execution.d.ts.map +1 -0
  884. package/dist/ui/settings-sections-lifecycle.d.ts +6 -0
  885. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -0
  886. package/dist/ui/settings-sections-presentation.d.ts +6 -0
  887. package/dist/ui/settings-sections-presentation.d.ts.map +1 -0
  888. package/dist/ui/settings-sections.d.ts +12 -0
  889. package/dist/ui/settings-sections.d.ts.map +1 -0
  890. package/dist/ui/settings-submenus.d.ts +74 -0
  891. package/dist/ui/settings-submenus.d.ts.map +1 -0
  892. package/dist/ui/settings-values.d.ts +63 -0
  893. package/dist/ui/settings-values.d.ts.map +1 -0
  894. package/dist/ui/settings.d.ts +21 -0
  895. package/dist/ui/settings.d.ts.map +1 -0
  896. package/dist/ui/settings.js +1985 -0
  897. package/dist/ui/settings.js.map +7 -0
  898. package/dist/ui/shell-hang-keys.d.ts +11 -0
  899. package/dist/ui/shell-hang-keys.d.ts.map +1 -0
  900. package/dist/ui/shiki-language.d.ts +7 -0
  901. package/dist/ui/shiki-language.d.ts.map +1 -0
  902. package/dist/ui/shiki-theme.d.ts +7 -0
  903. package/dist/ui/shiki-theme.d.ts.map +1 -0
  904. package/dist/ui/snapshot.d.ts +17 -0
  905. package/dist/ui/snapshot.d.ts.map +1 -0
  906. package/dist/ui/spinner.d.ts +6 -0
  907. package/dist/ui/spinner.d.ts.map +1 -0
  908. package/dist/ui/state-file-preview.d.ts +13 -0
  909. package/dist/ui/state-file-preview.d.ts.map +1 -0
  910. package/dist/ui/structured.d.ts +9 -0
  911. package/dist/ui/structured.d.ts.map +1 -0
  912. package/dist/ui/tool-call-timing.d.ts +2 -0
  913. package/dist/ui/tool-call-timing.d.ts.map +1 -0
  914. package/dist/ui/tool-display.d.ts +8 -0
  915. package/dist/ui/tool-display.d.ts.map +1 -0
  916. package/dist/ui/topology.d.ts +162 -0
  917. package/dist/ui/topology.d.ts.map +1 -0
  918. package/dist/ui/transcript-parser.d.ts +18 -0
  919. package/dist/ui/transcript-parser.d.ts.map +1 -0
  920. package/dist/ui/transcript-reader.d.ts +10 -0
  921. package/dist/ui/transcript-reader.d.ts.map +1 -0
  922. package/dist/ui/transcript-sanitization.d.ts +14 -0
  923. package/dist/ui/transcript-sanitization.d.ts.map +1 -0
  924. package/dist/ui/transcript.d.ts +52 -0
  925. package/dist/ui/transcript.d.ts.map +1 -0
  926. package/dist/ui/types.d.ts +84 -0
  927. package/dist/ui/types.d.ts.map +1 -0
  928. package/dist/ui/widget.d.ts +16 -0
  929. package/dist/ui/widget.d.ts.map +1 -0
  930. package/dist/ui/word-diff/alignment.d.ts +6 -0
  931. package/dist/ui/word-diff/alignment.d.ts.map +1 -0
  932. package/dist/ui/word-diff/change-block.d.ts +18 -0
  933. package/dist/ui/word-diff/change-block.d.ts.map +1 -0
  934. package/dist/ui/word-diff/changed-line.d.ts +14 -0
  935. package/dist/ui/word-diff/changed-line.d.ts.map +1 -0
  936. package/dist/ui/word-diff/emphasis.d.ts +9 -0
  937. package/dist/ui/word-diff/emphasis.d.ts.map +1 -0
  938. package/dist/ui/word-diff/line-emphasis.d.ts +7 -0
  939. package/dist/ui/word-diff/line-emphasis.d.ts.map +1 -0
  940. package/dist/ui/word-diff/line-matching.d.ts +10 -0
  941. package/dist/ui/word-diff/line-matching.d.ts.map +1 -0
  942. package/dist/ui/word-diff/line-similarity.d.ts +16 -0
  943. package/dist/ui/word-diff/line-similarity.d.ts.map +1 -0
  944. package/dist/ui/word-diff/normalize.d.ts +3 -0
  945. package/dist/ui/word-diff/normalize.d.ts.map +1 -0
  946. package/dist/ui/word-diff/parse.d.ts +17 -0
  947. package/dist/ui/word-diff/parse.d.ts.map +1 -0
  948. package/dist/ui/word-diff/range-refinement.d.ts +5 -0
  949. package/dist/ui/word-diff/range-refinement.d.ts.map +1 -0
  950. package/dist/ui/word-diff/ranges.d.ts +11 -0
  951. package/dist/ui/word-diff/ranges.d.ts.map +1 -0
  952. package/dist/ui/word-diff/smart-filter.d.ts +3 -0
  953. package/dist/ui/word-diff/smart-filter.d.ts.map +1 -0
  954. package/dist/ui/word-diff/sparse-line-matching.d.ts +25 -0
  955. package/dist/ui/word-diff/sparse-line-matching.d.ts.map +1 -0
  956. package/dist/ui/word-diff/text-boundaries.d.ts +11 -0
  957. package/dist/ui/word-diff/text-boundaries.d.ts.map +1 -0
  958. package/dist/ui/word-diff/token-alignment.d.ts +9 -0
  959. package/dist/ui/word-diff/token-alignment.d.ts.map +1 -0
  960. package/dist/ui/word-diff/token-text-refinement.d.ts +4 -0
  961. package/dist/ui/word-diff/token-text-refinement.d.ts.map +1 -0
  962. package/dist/ui/word-diff/tokens.d.ts +16 -0
  963. package/dist/ui/word-diff/tokens.d.ts.map +1 -0
  964. package/dist/ui/word-diff/types.d.ts +10 -0
  965. package/dist/ui/word-diff/types.d.ts.map +1 -0
  966. package/dist/util.d.ts +3 -0
  967. package/dist/util.d.ts.map +1 -0
  968. package/dist/worker/model-control.d.ts +14 -0
  969. package/dist/worker/model-control.d.ts.map +1 -0
  970. package/dist/worker/model-control.js +118 -0
  971. package/dist/worker/model-control.js.map +7 -0
  972. package/dist/worker/options.d.ts +3 -0
  973. package/dist/worker/options.d.ts.map +1 -0
  974. package/dist/worker/options.js +156 -0
  975. package/dist/worker/options.js.map +7 -0
  976. package/dist/worker/run-record.d.ts +22 -0
  977. package/dist/worker/run-record.d.ts.map +1 -0
  978. package/dist/worker/run-record.js +124 -0
  979. package/dist/worker/run-record.js.map +7 -0
  980. package/dist/worker/session-export.d.ts +45 -0
  981. package/dist/worker/session-export.d.ts.map +1 -0
  982. package/dist/worker/session-export.js +91 -0
  983. package/dist/worker/session-export.js.map +7 -0
  984. package/dist/worker.d.ts +3 -0
  985. package/dist/worker.d.ts.map +1 -0
  986. package/dist/worker.js +1074 -0
  987. package/dist/worker.js.map +7 -0
  988. package/docs/agents.md +618 -0
  989. package/docs/architecture.md +141 -0
  990. package/docs/audit-trace.md +116 -0
  991. package/docs/certification.md +166 -0
  992. package/docs/compaction.md +345 -0
  993. package/docs/component-calculus.md +191 -0
  994. package/docs/components.md +330 -0
  995. package/docs/configuration.md +529 -0
  996. package/docs/entropy.md +214 -0
  997. package/docs/interface.md +210 -0
  998. package/docs/jev.md +289 -0
  999. package/docs/kernels.md +186 -0
  1000. package/docs/memory-recall.md +664 -0
  1001. package/docs/programmatic-compaction.md +205 -0
  1002. package/docs/provider-component-calculus.md +378 -0
  1003. package/docs/providers.md +163 -0
  1004. package/docs/repairs.md +90 -0
  1005. package/docs/residency-runtime.md +82 -0
  1006. package/docs/schema-enforcement.md +166 -0
  1007. package/docs/skills.md +50 -0
  1008. package/docs/speculation.md +171 -0
  1009. package/docs/state-layer.md +197 -0
  1010. package/package.json +135 -0
  1011. package/skillsets/python/fabric-advisor/SKILL.md +29 -0
  1012. package/skillsets/python/fabric-ambient/SKILL.md +44 -0
  1013. package/skillsets/python/fabric-ambient/references/setup.md +67 -0
  1014. package/skillsets/python/fabric-council/SKILL.md +54 -0
  1015. package/skillsets/python/fabric-exec/SKILL.md +74 -0
  1016. package/skillsets/python/fabric-exec/references/agents.md +65 -0
  1017. package/skillsets/python/fabric-exec/references/mcp.md +23 -0
  1018. package/skillsets/python/fabric-exec/references/mesh.md +27 -0
  1019. package/skillsets/python/fabric-fusion/SKILL.md +112 -0
  1020. package/skillsets/python/fabric-guide/SKILL.md +29 -0
  1021. package/skillsets/python/fabric-jev/SKILL.md +162 -0
  1022. package/skillsets/python/fabric-rlm/SKILL.md +120 -0
  1023. package/skillsets/python/fabric-schema/SKILL.md +55 -0
  1024. package/skillsets/python/fabric-spec/SKILL.md +42 -0
  1025. package/skillsets/python/fabric-supervisor/SKILL.md +37 -0
  1026. package/skillsets/python/fabric-swarm/SKILL.md +40 -0
  1027. package/skillsets/python/fabric-workflow/SKILL.md +62 -0
  1028. package/skillsets/typescript/fabric-advisor/SKILL.md +29 -0
  1029. package/skillsets/typescript/fabric-ambient/SKILL.md +44 -0
  1030. package/skillsets/typescript/fabric-ambient/references/setup.md +90 -0
  1031. package/skillsets/typescript/fabric-council/SKILL.md +94 -0
  1032. package/skillsets/typescript/fabric-exec/SKILL.md +142 -0
  1033. package/skillsets/typescript/fabric-exec/references/agents.md +218 -0
  1034. package/skillsets/typescript/fabric-exec/references/mcp.md +49 -0
  1035. package/skillsets/typescript/fabric-exec/references/mesh.md +51 -0
  1036. package/skillsets/typescript/fabric-fusion/SKILL.md +332 -0
  1037. package/skillsets/typescript/fabric-guide/SKILL.md +29 -0
  1038. package/skillsets/typescript/fabric-jev/SKILL.md +159 -0
  1039. package/skillsets/typescript/fabric-rlm/SKILL.md +284 -0
  1040. package/skillsets/typescript/fabric-schema/SKILL.md +121 -0
  1041. package/skillsets/typescript/fabric-spec/SKILL.md +42 -0
  1042. package/skillsets/typescript/fabric-supervisor/SKILL.md +37 -0
  1043. package/skillsets/typescript/fabric-swarm/SKILL.md +80 -0
  1044. package/skillsets/typescript/fabric-workflow/SKILL.md +133 -0
@@ -0,0 +1,4218 @@
1
+ import {
2
+ ansi256ToRgb,
3
+ effectiveShikiThemeIsLight,
4
+ highlightCode,
5
+ highlightFileLines,
6
+ highlightSourceLines,
7
+ languageFromPath,
8
+ observePiTheme,
9
+ observedThemeVariant
10
+ } from "./chunk-ZZ4LHQYJ.js";
11
+ import {
12
+ countContentLines,
13
+ countNewlines,
14
+ headlineArg,
15
+ isFabricAgentToolPreview,
16
+ selectPreviewTextLines,
17
+ shouldSkipWriteDiffBytes,
18
+ shouldSkipWriteDiffComplexity
19
+ } from "./chunk-J2HV2URQ.js";
20
+ import {
21
+ fabricStringLiterals
22
+ } from "./chunk-656HWVFU.js";
23
+
24
+ // src/ui/structured.ts
25
+ import { stringify } from "yaml";
26
+ var normalizeJsonValue = (value) => {
27
+ try {
28
+ const serialized = JSON.stringify(value);
29
+ return serialized === void 0 ? void 0 : JSON.parse(serialized);
30
+ } catch {
31
+ return void 0;
32
+ }
33
+ };
34
+ var formatJsonAsYaml = (value) => {
35
+ const normalized = normalizeJsonValue(value);
36
+ if (normalized === void 0) return void 0;
37
+ return stringify(normalized, { indent: 2, lineWidth: 0 }).trimEnd();
38
+ };
39
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
40
+ var hoistMultilineStrings = (value, path, sections, seen) => {
41
+ if (typeof value === "string") {
42
+ if (!value.includes("\n")) return value;
43
+ sections.push({ path, text: value });
44
+ return `<multi-line string, see section: ${path}>`;
45
+ }
46
+ if (Array.isArray(value)) {
47
+ if (seen.has(value)) return "[circular reference]";
48
+ seen.add(value);
49
+ const skeleton = value.map(
50
+ (item, index) => hoistMultilineStrings(item, `${path}[${index}]`, sections, seen)
51
+ );
52
+ seen.delete(value);
53
+ return skeleton;
54
+ }
55
+ if (isPlainObject(value)) {
56
+ if (seen.has(value)) return "[circular reference]";
57
+ seen.add(value);
58
+ const skeleton = {};
59
+ for (const [key, item] of Object.entries(value)) {
60
+ skeleton[key] = hoistMultilineStrings(
61
+ item,
62
+ path ? `${path}.${key}` : key,
63
+ sections,
64
+ seen
65
+ );
66
+ }
67
+ seen.delete(value);
68
+ return skeleton;
69
+ }
70
+ return value;
71
+ };
72
+ var boundedSection = (value, maxChars) => {
73
+ if (value.length <= maxChars) return value;
74
+ if (maxChars <= 0) return "";
75
+ let omitted = value.length - maxChars;
76
+ let marker = `\u2026[${omitted} chars omitted]\u2026`;
77
+ for (let pass = 0; pass < 2; pass++) {
78
+ omitted = value.length - Math.max(0, maxChars - marker.length);
79
+ marker = `\u2026[${omitted} chars omitted]\u2026`;
80
+ }
81
+ if (marker.length >= maxChars) return marker.slice(0, maxChars);
82
+ const available = maxChars - marker.length;
83
+ const head = Math.ceil(available / 2);
84
+ const tail = Math.floor(available / 2);
85
+ return `${value.slice(0, head)}${marker}${value.slice(value.length - tail)}`;
86
+ };
87
+ var fairSectionBudgets = (lengths, budget) => {
88
+ const budgets = Array.from({ length: lengths.length }, () => 0);
89
+ const pending = lengths.map((length, index) => ({ length, index })).sort((left, right) => left.length - right.length);
90
+ let remaining = Math.max(0, budget);
91
+ for (let position = 0; position < pending.length; position++) {
92
+ const item = pending[position];
93
+ const share = Math.floor(remaining / (pending.length - position));
94
+ const allocated = Math.min(item.length, share);
95
+ budgets[item.index] = allocated;
96
+ remaining -= allocated;
97
+ }
98
+ return budgets;
99
+ };
100
+ var renderHoistedSections = (yaml, sections, maxChars) => {
101
+ const headers = sections.map((section) => `--- ${section.path} (${section.text.length} chars) ---
102
+ `);
103
+ const separators = sections.length * 2;
104
+ const fixedChars = yaml.length + separators + headers.reduce((sum, header) => sum + header.length, 0);
105
+ const fullChars = fixedChars + sections.reduce((sum, section) => sum + section.text.length, 0);
106
+ const budgets = maxChars !== void 0 && fullChars > maxChars ? fairSectionBudgets(sections.map((section) => section.text.length), maxChars - fixedChars) : sections.map((section) => section.text.length);
107
+ const raw = sections.map((section, index) => `${headers[index]}${boundedSection(section.text, budgets[index])}`).join("\n\n");
108
+ return `${yaml}
109
+
110
+ ${raw}`;
111
+ };
112
+ var formatFabricValue = (value, format, maxChars) => {
113
+ if (value === void 0) return { text: "" };
114
+ if (format === "text" && typeof value === "object" && value !== null && "text" in value) {
115
+ const text = value.text;
116
+ if (typeof text === "string") return { text };
117
+ }
118
+ if (typeof value === "string") return { text: value };
119
+ if (format === "auto" || format === "yaml") {
120
+ const sections = [];
121
+ const skeleton = hoistMultilineStrings(value, "", sections, /* @__PURE__ */ new Set());
122
+ const yaml = formatJsonAsYaml(skeleton);
123
+ if (yaml !== void 0) {
124
+ if (sections.length === 0) return { text: yaml, language: "yaml" };
125
+ return {
126
+ text: renderHoistedSections(yaml, sections, maxChars),
127
+ language: "yaml",
128
+ highlightedLineCount: countNewlines(yaml) + 1
129
+ };
130
+ }
131
+ }
132
+ try {
133
+ return {
134
+ text: JSON.stringify(value, null, format === "json" ? 2 : 0),
135
+ ...format === "json" ? { language: "json" } : {}
136
+ };
137
+ } catch {
138
+ return { text: String(value) };
139
+ }
140
+ };
141
+
142
+ // src/ui/arc-group.ts
143
+ var ANSI_ESCAPE = /\x1b\[[0-9;]*m/g;
144
+ var ARC_CLOSING = "\u2570\u2500 ";
145
+ var ARC_CONTINUATION = "\u251C\u2500 ";
146
+ var visibleText = (line) => line.replace(ANSI_ESCAPE, "");
147
+ var isArcLine = (line) => {
148
+ const visible = visibleText(line);
149
+ return visible.startsWith(ARC_CLOSING) || visible.startsWith(ARC_CONTINUATION);
150
+ };
151
+ var continueArc = (line) => visibleText(line).startsWith(ARC_CLOSING) ? line.replace(ARC_CLOSING, ARC_CONTINUATION) : line;
152
+ function continueArcGroup(lines) {
153
+ let start = lines.length;
154
+ while (start > 0 && isArcLine(lines[start - 1])) start--;
155
+ if (start === lines.length) return lines;
156
+ const next = [...lines];
157
+ for (let index = start; index < next.length; index++) {
158
+ next[index] = continueArc(next[index]);
159
+ }
160
+ return next;
161
+ }
162
+ function arcItem(theme, label) {
163
+ return theme.fg("muted", `${ARC_CLOSING}${label}`);
164
+ }
165
+ function arcItemStyled(theme, label) {
166
+ return theme.fg("muted", ARC_CLOSING) + label;
167
+ }
168
+ function pushArcItem(lines, item) {
169
+ for (let index = lines.length - 1; index >= 0 && isArcLine(lines[index]); index--) {
170
+ lines[index] = continueArc(lines[index]);
171
+ }
172
+ lines.push(item);
173
+ }
174
+
175
+ // src/ui/core-tool-render.ts
176
+ import { readFileSync, statSync } from "node:fs";
177
+ import { homedir } from "node:os";
178
+ import { basename, extname, isAbsolute, relative, resolve } from "node:path";
179
+
180
+ // src/ui/tool-call-timing.ts
181
+ var formatToolCallDuration = (startedAt, endedAt) => {
182
+ if (startedAt === void 0 || endedAt === void 0) return void 0;
183
+ const durationMs = Math.max(0, endedAt - startedAt);
184
+ return durationMs < 1e3 ? `${durationMs}ms` : `${(durationMs / 1e3).toFixed(1)}s`;
185
+ };
186
+
187
+ // src/ui/core-tool-render.ts
188
+ import { diffLines } from "diff";
189
+ import { bundledLanguages } from "shiki/langs";
190
+
191
+ // src/ui/diff-background.ts
192
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
193
+ var DIFF_ADD_MARKER = "\0PI_DIFF_ADD\0";
194
+ var DIFF_REMOVE_MARKER = "\0PI_DIFF_REMOVE\0";
195
+ var markDiffLine = (kind, line) => (kind === "add" ? DIFF_ADD_MARKER : DIFF_REMOVE_MARKER) + line;
196
+ var parseMarkedDiffLine = (rawLine) => {
197
+ const addIndex = rawLine.indexOf(DIFF_ADD_MARKER);
198
+ if (addIndex >= 0) {
199
+ return {
200
+ kind: "add",
201
+ line: rawLine.slice(0, addIndex) + rawLine.slice(addIndex + DIFF_ADD_MARKER.length)
202
+ };
203
+ }
204
+ const removeIndex = rawLine.indexOf(DIFF_REMOVE_MARKER);
205
+ if (removeIndex >= 0) {
206
+ return {
207
+ kind: "remove",
208
+ line: rawLine.slice(0, removeIndex) + rawLine.slice(removeIndex + DIFF_REMOVE_MARKER.length)
209
+ };
210
+ }
211
+ return { line: rawLine };
212
+ };
213
+ var createDiffBackgroundResolver = (theme, intensity) => {
214
+ if (intensity === "off") return () => void 0;
215
+ const cache = {};
216
+ return (kind) => cache[kind] ??= deriveDiffBg(kind, theme, intensity === "medium" ? 0.24 : 0.14) ?? fallbackDiffBg(kind, intensity);
217
+ };
218
+ var applyDiffBackground = (line, background) => {
219
+ if (!background) return line;
220
+ const colored = line.replace(/\x1b\[0m/g, "\x1B[0m" + background).replace(/\x1b\[39m/g, "\x1B[39m" + background).replace(/\x1b\[49m/g, "\x1B[49m" + background);
221
+ return background + colored;
222
+ };
223
+ var fallbackDiffBg = (kind, intensity) => {
224
+ if (observedThemeVariant() === "light") {
225
+ if (kind === "add") {
226
+ return intensity === "medium" ? "\x1B[48;2;170;222;186m" : "\x1B[48;2;198;230;206m";
227
+ }
228
+ return intensity === "medium" ? "\x1B[48;2;236;178;184m" : "\x1B[48;2;242;206;210m";
229
+ }
230
+ if (kind === "add") {
231
+ return intensity === "medium" ? "\x1B[48;2;22;68;40m" : "\x1B[48;2;10;42;26m";
232
+ }
233
+ return intensity === "medium" ? "\x1B[48;2;78;36;40m" : "\x1B[48;2;50;24;30m";
234
+ };
235
+ var deriveDiffBg = (kind, theme, intensity) => {
236
+ const themed = theme;
237
+ const fg = themed?.getFgAnsi?.(kind === "add" ? "toolDiffAdded" : "toolDiffRemoved");
238
+ const fgRgb = parseAnsiRgb(fg ?? "");
239
+ if (!fgRgb) return void 0;
240
+ const base = parseAnsiRgb(themed?.getBgAnsi?.(kind === "add" ? "toolSuccessBg" : "toolErrorBg") ?? "") ?? parseAnsiRgb(themed?.getBgAnsi?.("toolSuccessBg") ?? "") ?? (observedThemeVariant() === "light" ? { r: 255, g: 255, b: 255 } : { r: 0, g: 0, b: 0 });
241
+ return `\x1B[48;2;${Math.round(base.r + (fgRgb.r - base.r) * intensity)};${Math.round(base.g + (fgRgb.g - base.g) * intensity)};${Math.round(base.b + (fgRgb.b - base.b) * intensity)}m`;
242
+ };
243
+ var PRINTABLE_ASCII_RE = /^[\x20-\x7e]*$/;
244
+ var TRUNCATION_SAFE_RE = /^(?:[\x20-\x7e\t]|\x1b\[[0-9;]*m)*$/;
245
+ var segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
246
+ var wrapDiffAnsiToWidth = (text, width, maxRows = 3, continuationPrefix = "") => {
247
+ if (width <= 0) return [""];
248
+ const rows = [];
249
+ let row = "";
250
+ let rowWidth = 0;
251
+ let index = 0;
252
+ let state = "";
253
+ const continuationWidth = visibleWidth(continuationPrefix);
254
+ const pushRow = () => {
255
+ rows.push(truncateWrappedRow(row, rowWidth, width));
256
+ if (rows.length >= maxRows) {
257
+ truncateLastRow(rows, width);
258
+ return false;
259
+ }
260
+ row = continuationPrefix ? state + continuationPrefix : state;
261
+ rowWidth = continuationWidth;
262
+ return true;
263
+ };
264
+ while (index < text.length) {
265
+ const ansi = extractSgr(text, index);
266
+ if (ansi) {
267
+ row += ansi.sequence;
268
+ state = updateAnsiState(state, ansi.sequence);
269
+ index += ansi.sequence.length;
270
+ continue;
271
+ }
272
+ const nextAnsi = text.indexOf("\x1B", index);
273
+ const plainEnd = nextAnsi >= 0 ? nextAnsi : text.length;
274
+ const plain = text.slice(index, plainEnd);
275
+ const remainingWidth = width - rowWidth;
276
+ if (plain.length <= remainingWidth && PRINTABLE_ASCII_RE.test(plain)) {
277
+ row += plain;
278
+ rowWidth += plain.length;
279
+ } else {
280
+ for (const { segment } of segmenter.segment(plain)) {
281
+ const segmentWidth = visibleWidth(segment);
282
+ if (rowWidth > 0 && rowWidth + segmentWidth > width && !pushRow()) return rows;
283
+ if (rowWidth > 0 && rowWidth + segmentWidth > width) {
284
+ row = state;
285
+ rowWidth = 0;
286
+ }
287
+ if (segmentWidth > width && rowWidth === 0) {
288
+ const clipped = truncateToWidth(segment, width, "");
289
+ if (clipped) {
290
+ row += clipped;
291
+ rowWidth += visibleWidth(clipped);
292
+ }
293
+ if (!pushRow()) return rows;
294
+ continue;
295
+ }
296
+ row += segment;
297
+ rowWidth += segmentWidth;
298
+ }
299
+ }
300
+ index = plainEnd;
301
+ }
302
+ rows.push(truncateWrappedRow(row, rowWidth, width));
303
+ if (rows.length > maxRows) return truncateLastRow(rows.slice(0, maxRows), width);
304
+ return rows;
305
+ };
306
+ var truncateWrappedRow = (row, rowWidth, width) => {
307
+ if (rowWidth <= width && TRUNCATION_SAFE_RE.test(row)) return row;
308
+ return truncateToWidth(row, width, "");
309
+ };
310
+ var truncateLastRow = (rows, width) => {
311
+ const last = rows.at(-1) ?? "";
312
+ if (visibleWidth(last) >= width && width > 1) {
313
+ rows[rows.length - 1] = truncateToWidth(last, width - 1, "") + "\u203A";
314
+ }
315
+ return rows;
316
+ };
317
+ var extractSgr = (text, index) => {
318
+ if (text[index] !== "\x1B" || text[index + 1] !== "[") return void 0;
319
+ let end = index + 2;
320
+ while (end < text.length && text[end] !== "m") end++;
321
+ if (end >= text.length) return void 0;
322
+ return { sequence: text.slice(index, end + 1) };
323
+ };
324
+ var updateAnsiState = (current, sequence) => {
325
+ if (sequence === "\x1B[0m") return "";
326
+ if (/^\x1b\[3(?:8;[^m]+|9)m$/.test(sequence)) {
327
+ return replaceAnsi(current, /\x1b\[3(?:8;[^m]+|9)m/g, sequence === "\x1B[39m" ? "" : sequence);
328
+ }
329
+ if (/^\x1b\[4(?:8;[^m]+|9)m$/.test(sequence)) {
330
+ return replaceAnsi(current, /\x1b\[4(?:8;[^m]+|9)m/g, sequence === "\x1B[49m" ? "" : sequence);
331
+ }
332
+ if (sequence === "\x1B[22m") return current.replace(/\x1b\[(?:1|2)m/g, "");
333
+ if (sequence === "\x1B[1m") return replaceAnsi(current, /\x1b\[1m/g, sequence);
334
+ if (sequence === "\x1B[2m") return replaceAnsi(current, /\x1b\[2m/g, sequence);
335
+ if (sequence === "\x1B[3m" || sequence === "\x1B[23m") {
336
+ return replaceAnsi(current, /\x1b\[(?:3|23)m/g, sequence === "\x1B[23m" ? "" : sequence);
337
+ }
338
+ if (sequence === "\x1B[4m" || sequence === "\x1B[24m") {
339
+ return replaceAnsi(current, /\x1b\[(?:4|24)m/g, sequence === "\x1B[24m" ? "" : sequence);
340
+ }
341
+ return current + sequence;
342
+ };
343
+ var replaceAnsi = (current, pattern, replacement) => current.replace(pattern, "") + replacement;
344
+ var parseAnsiRgb = (ansi) => {
345
+ const match = ansi.match(/\x1b\[(?:38|48);2;(\d+);(\d+);(\d+)m/);
346
+ if (match) return { r: Number(match[1]), g: Number(match[2]), b: Number(match[3]) };
347
+ const indexed = ansi.match(/\x1b\[(?:38|48);5;(\d+)m/);
348
+ if (indexed) return ansi256ToRgb(Number(indexed[1]));
349
+ return void 0;
350
+ };
351
+
352
+ // src/ui/word-diff/normalize.ts
353
+ var expandPreviewTabs = (text) => text.replace(/\t/g, " ");
354
+ var escapeControlChars = (text) => text.replace(/\x1b/g, "\u241B").replace(/\r/g, "\u240D").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, "\uFFFD");
355
+
356
+ // src/ui/word-diff/tokens.ts
357
+ var WORD_TOKEN_PATTERN = new RegExp("[$_\\p{L}][$_\\p{L}\\p{N}\\p{Mark}]*|\\p{N}+(?:\\.\\p{N}+)?|===|!==|=>|==|!=|<=|>=|&&|\\|\\||[^\\s]", "gu");
358
+ var IDENTIFIER_TOKEN_PATTERN = /^[$_\p{L}][$_\p{L}\p{N}\p{Mark}]*$/u;
359
+ var NUMBER_TOKEN_PATTERN = new RegExp("^\\p{N}+(?:\\.\\p{N}+)?$", "u");
360
+ var SYMBOL_TOKEN_PATTERN = new RegExp("^\\p{S}+$", "u");
361
+ var MEANINGFUL_OPERATOR_TOKEN_PATTERN = /^(?:===|!==|=>|==|!=|<=|>=|&&|\|\||[+\-*\/%<>=!?:~&|^]+)$/;
362
+ var DOMAIN_SEPARATOR_TOKEN_PATTERN = /^[-/:@#]$/;
363
+ var STRUCTURAL_PUNCTUATION_TOKEN_PATTERN = /^[{}()[\].,;]$/;
364
+ function wordEmphasisTokens(text) {
365
+ const tokens = [];
366
+ for (const match of text.matchAll(WORD_TOKEN_PATTERN)) {
367
+ const value = match[0];
368
+ const start = match.index;
369
+ tokens.push({ value, start, end: start + value.length });
370
+ }
371
+ return tokens;
372
+ }
373
+ function wordTokenValues(text) {
374
+ return Array.from(text.matchAll(WORD_TOKEN_PATTERN), (match) => match[0]);
375
+ }
376
+ function isIdentifierToken(value) {
377
+ return IDENTIFIER_TOKEN_PATTERN.test(value);
378
+ }
379
+ function isNumberToken(value) {
380
+ return NUMBER_TOKEN_PATTERN.test(value);
381
+ }
382
+ function isSymbolToken(value) {
383
+ return SYMBOL_TOKEN_PATTERN.test(value);
384
+ }
385
+ function isMeaningfulOperatorToken(value) {
386
+ return MEANINGFUL_OPERATOR_TOKEN_PATTERN.test(value);
387
+ }
388
+ function wordEmphasisTokenWeight(value) {
389
+ if (isIdentifierToken(value)) return 2;
390
+ if (isNumberToken(value)) return 1.5;
391
+ if (DOMAIN_SEPARATOR_TOKEN_PATTERN.test(value)) return 0.25;
392
+ if (isMeaningfulOperatorToken(value)) return 1;
393
+ if (STRUCTURAL_PUNCTUATION_TOKEN_PATTERN.test(value)) return 0.05;
394
+ return 1;
395
+ }
396
+ function splitIdentifierToken(value, start) {
397
+ const parts = [];
398
+ const partPattern = new RegExp("[$_]+|(?:\\p{Lu}\\p{Mark}*)+(?=(?:\\p{Lu}\\p{Mark}*)(?:\\p{Ll}\\p{Mark}*)|\\p{N}|$)|(?:\\p{Lu}\\p{Mark}*)?(?:\\p{Ll}\\p{Mark}*)+|\\p{N}+|(?:\\p{Lu}\\p{Mark}*)+|(?:\\p{L}\\p{Mark}*)+", "gu");
399
+ for (const match of value.matchAll(partPattern)) {
400
+ const part = match[0];
401
+ const offset = match.index;
402
+ parts.push({ value: part, start: start + offset, end: start + offset + part.length });
403
+ }
404
+ return parts.length > 0 ? parts : [{ value, start, end: start + value.length }];
405
+ }
406
+ function wordEmphasisSimilarityTokenValues(tokens) {
407
+ const values = [];
408
+ for (const token of tokens) {
409
+ if (!isIdentifierToken(token.value)) {
410
+ values.push(token.value);
411
+ continue;
412
+ }
413
+ const parts = splitIdentifierToken(token.value, 0).map((part) => part.value).filter(isIdentifierSimilarityPart);
414
+ if (parts.length === 0) values.push(token.value.toLowerCase());
415
+ else values.push(...parts.map((part) => part.toLowerCase()));
416
+ }
417
+ return values;
418
+ }
419
+ function isIdentifierSimilarityPart(value) {
420
+ return !/^[$_]+$/.test(value);
421
+ }
422
+
423
+ // src/ui/word-diff/changed-line.ts
424
+ function indexedChangedLine(index, line) {
425
+ return { index, line };
426
+ }
427
+ function normalizedChangedContent(line) {
428
+ return line.normalizedContent ??= normalizeDiffContent(line.line.content);
429
+ }
430
+ function changedLineTokens(line) {
431
+ return line.tokens ??= wordEmphasisTokens(normalizedChangedContent(line));
432
+ }
433
+ function normalizeDiffContent(content) {
434
+ return escapeControlChars(expandPreviewTabs(content));
435
+ }
436
+
437
+ // src/ui/word-diff/alignment.ts
438
+ var ALIGNMENT_SCORE_EPSILON = 1e-9;
439
+ function sameAlignmentScore(a, b) {
440
+ return Math.abs(a - b) < ALIGNMENT_SCORE_EPSILON;
441
+ }
442
+ function suffixAlignedPairs(beforeLength, afterLength, scoreAt) {
443
+ const columns = afterLength + 1;
444
+ const dp = new Float64Array((beforeLength + 1) * columns);
445
+ for (let i2 = beforeLength - 1; i2 >= 0; i2--) {
446
+ const rowOffset = i2 * columns;
447
+ const nextRowOffset = rowOffset + columns;
448
+ for (let j2 = afterLength - 1; j2 >= 0; j2--) {
449
+ const pairScore = scoreAt(i2, j2);
450
+ const align = Number.isFinite(pairScore) ? dp[nextRowOffset + j2 + 1] + pairScore : pairScore;
451
+ dp[rowOffset + j2] = Math.max(align, dp[nextRowOffset + j2], dp[rowOffset + j2 + 1]);
452
+ }
453
+ }
454
+ const pairs = [];
455
+ let i = 0;
456
+ let j = 0;
457
+ while (i < beforeLength && j < afterLength) {
458
+ const rowOffset = i * columns;
459
+ const nextRowOffset = rowOffset + columns;
460
+ const pairScore = scoreAt(i, j);
461
+ const align = Number.isFinite(pairScore) ? dp[nextRowOffset + j + 1] + pairScore : pairScore;
462
+ if (Number.isFinite(pairScore) && sameAlignmentScore(dp[rowOffset + j], align)) {
463
+ pairs.push([i, j]);
464
+ i++;
465
+ j++;
466
+ } else if (dp[nextRowOffset + j] >= dp[rowOffset + j + 1]) {
467
+ i++;
468
+ } else {
469
+ j++;
470
+ }
471
+ }
472
+ return pairs;
473
+ }
474
+ function prefixAlignedPairs(beforeLength, afterLength, scoreAt) {
475
+ const columns = afterLength + 1;
476
+ const dp = new Float64Array((beforeLength + 1) * columns);
477
+ for (let i2 = 1; i2 <= beforeLength; i2++) {
478
+ const rowOffset = i2 * columns;
479
+ const previousRowOffset = rowOffset - columns;
480
+ for (let j2 = 1; j2 <= afterLength; j2++) {
481
+ const pairScore = scoreAt(i2 - 1, j2 - 1);
482
+ const pair = Number.isFinite(pairScore) ? dp[previousRowOffset + j2 - 1] + pairScore : pairScore;
483
+ dp[rowOffset + j2] = Math.max(dp[previousRowOffset + j2], dp[rowOffset + j2 - 1], pair);
484
+ }
485
+ }
486
+ const pairs = [];
487
+ let i = beforeLength;
488
+ let j = afterLength;
489
+ while (i > 0 && j > 0) {
490
+ const rowOffset = i * columns;
491
+ const previousRowOffset = rowOffset - columns;
492
+ const pairScore = scoreAt(i - 1, j - 1);
493
+ const pair = Number.isFinite(pairScore) ? dp[previousRowOffset + j - 1] + pairScore : pairScore;
494
+ if (Number.isFinite(pairScore) && sameAlignmentScore(dp[rowOffset + j], pair)) {
495
+ pairs.push([i - 1, j - 1]);
496
+ i--;
497
+ j--;
498
+ } else if (dp[previousRowOffset + j] >= dp[rowOffset + j - 1]) {
499
+ i--;
500
+ } else {
501
+ j--;
502
+ }
503
+ }
504
+ return pairs.reverse();
505
+ }
506
+ function suffixAlignmentScore(beforeLength, afterLength, scoreAt) {
507
+ let next = new Float64Array(afterLength + 1);
508
+ let current = new Float64Array(afterLength + 1);
509
+ for (let i = beforeLength - 1; i >= 0; i--) {
510
+ current[afterLength] = 0;
511
+ for (let j = afterLength - 1; j >= 0; j--) {
512
+ const pairScore = scoreAt(i, j);
513
+ const match = Number.isFinite(pairScore) ? numericAt(next, j + 1) + pairScore : pairScore;
514
+ current[j] = Math.max(match, numericAt(next, j), numericAt(current, j + 1));
515
+ }
516
+ [next, current] = [current, next];
517
+ }
518
+ return numericAt(next, 0);
519
+ }
520
+ function numericAt(values, index) {
521
+ const value = values[index];
522
+ if (value === void 0) throw new RangeError(`Missing alignment cell ${index}`);
523
+ return value;
524
+ }
525
+
526
+ // src/ui/word-diff/line-similarity.ts
527
+ var SIMILARITY_BIGRAM_PREFIX = "\0PI_SIM_BIGRAM\0";
528
+ var MAX_LINE_TOKEN_SIMILARITY_CELLS = 16384;
529
+ function changedLineSimilarityTokenValues(line) {
530
+ return line.similarityTokenValues ??= wordEmphasisSimilarityTokenValues(
531
+ changedLineTokens(line)
532
+ );
533
+ }
534
+ function changedLineSimilarityFeatureValues(line) {
535
+ return line.similarityFeatureValues ??= similarityFeatures(
536
+ changedLineSimilarityTokenValues(line)
537
+ );
538
+ }
539
+ function changedLineSimilarityDocuments(removed, added) {
540
+ const removedFeatures = removed.map(changedLineSimilarityFeatureValues);
541
+ const addedFeatures = added.map(changedLineSimilarityFeatureValues);
542
+ const documentCounts = /* @__PURE__ */ new Map();
543
+ countSimilarityDocuments(removedFeatures, documentCounts);
544
+ countSimilarityDocuments(addedFeatures, documentCounts);
545
+ return { removedFeatures, addedFeatures, documentCounts };
546
+ }
547
+ function countSimilarityDocuments(featureLists, documentCounts) {
548
+ for (const features of featureLists) {
549
+ for (const feature of new Set(features))
550
+ documentCounts.set(feature, (documentCounts.get(feature) ?? 0) + 1);
551
+ }
552
+ }
553
+ function hasUniqueSharedSimilarityFeature(removed, added, documents) {
554
+ const addedFeatures = new Set(changedLineSimilarityFeatureValues(added));
555
+ for (const feature of new Set(changedLineSimilarityFeatureValues(removed))) {
556
+ if (!addedFeatures.has(feature)) continue;
557
+ if (documents.documentCounts.get(feature) === 2 && tokenWeight(feature) >= 1) return true;
558
+ }
559
+ return false;
560
+ }
561
+ function similarityFeatures(tokens) {
562
+ const features = [...tokens];
563
+ appendSimilarityShingles(
564
+ features,
565
+ tokens.filter(isSimilarityShingleToken),
566
+ 2,
567
+ SIMILARITY_BIGRAM_PREFIX
568
+ );
569
+ return features;
570
+ }
571
+ function appendSimilarityShingles(features, tokens, size, prefix) {
572
+ for (let index = 0; index + size <= tokens.length; index++)
573
+ features.push(`${prefix}${tokens.slice(index, index + size).join("\0")}`);
574
+ }
575
+ function isSimilarityShingleToken(token) {
576
+ return wordEmphasisTokenWeight(token) >= 1;
577
+ }
578
+ function similarityTokenWeight(documents) {
579
+ const weights = /* @__PURE__ */ new Map();
580
+ const lineCount = documents.removedFeatures.length + documents.addedFeatures.length;
581
+ return (token) => {
582
+ const cached = weights.get(token);
583
+ if (cached !== void 0) return cached;
584
+ const documentCount = documents.documentCounts.get(token) ?? lineCount;
585
+ const rarity = Math.min(3, 1 + Math.log((lineCount + 1) / (documentCount + 1)));
586
+ const weight = tokenWeight(token) * rarity;
587
+ weights.set(token, weight);
588
+ return weight;
589
+ };
590
+ }
591
+ function fallbackLineSimilarity(removed, added, weight, removedWeight, addedWeight) {
592
+ return unorderedTokenSimilarity(
593
+ changedLineSimilarityFeatureValues(removed),
594
+ changedLineSimilarityFeatureValues(added),
595
+ weight,
596
+ removedWeight,
597
+ addedWeight
598
+ );
599
+ }
600
+ function tokenSimilarity(beforeTokens, afterTokens, weight = tokenWeight, minimumRelevantSimilarity = 0, beforeWeight, afterWeight) {
601
+ if (beforeTokens.length === 0 || afterTokens.length === 0)
602
+ return beforeTokens.length === afterTokens.length ? 1 : 0;
603
+ const bagSimilarity = unorderedTokenSimilarity(
604
+ beforeTokens,
605
+ afterTokens,
606
+ weight,
607
+ beforeWeight,
608
+ afterWeight
609
+ );
610
+ if (bagSimilarity < minimumRelevantSimilarity) return bagSimilarity;
611
+ const orderedSimilarity = orderedTokenSimilarity(
612
+ beforeTokens,
613
+ afterTokens,
614
+ weight,
615
+ beforeWeight ?? similarityTokenListWeight(beforeTokens, weight),
616
+ afterWeight ?? similarityTokenListWeight(afterTokens, weight)
617
+ );
618
+ if (orderedSimilarity === void 0) return bagSimilarity;
619
+ return Math.max(
620
+ orderedSimilarity,
621
+ bagSimilarity * 0.8,
622
+ orderedSimilarity * 0.75 + bagSimilarity * 0.25
623
+ );
624
+ }
625
+ function unorderedTokenSimilarity(beforeTokens, afterTokens, weight, beforeWeight = similarityTokenListWeight(beforeTokens, weight), afterWeight = similarityTokenListWeight(afterTokens, weight)) {
626
+ const remaining = /* @__PURE__ */ new Map();
627
+ for (const token of beforeTokens) remaining.set(token, (remaining.get(token) ?? 0) + 1);
628
+ let sharedWeight = 0;
629
+ for (const token of afterTokens) {
630
+ const count = remaining.get(token) ?? 0;
631
+ if (count === 0) continue;
632
+ sharedWeight += weight(token);
633
+ if (count === 1) remaining.delete(token);
634
+ else remaining.set(token, count - 1);
635
+ }
636
+ return 2 * sharedWeight / (beforeWeight + afterWeight);
637
+ }
638
+ function orderedTokenSimilarity(beforeTokens, afterTokens, weight, beforeWeight, afterWeight) {
639
+ if (beforeTokens.length * afterTokens.length > MAX_LINE_TOKEN_SIMILARITY_CELLS) return void 0;
640
+ const score = suffixAlignmentScore(
641
+ beforeTokens.length,
642
+ afterTokens.length,
643
+ (beforeIndex, afterIndex) => {
644
+ const beforeToken = stringAt(beforeTokens, beforeIndex);
645
+ return beforeToken === stringAt(afterTokens, afterIndex) ? weight(beforeToken) : Number.NEGATIVE_INFINITY;
646
+ }
647
+ );
648
+ return 2 * score / (beforeWeight + afterWeight);
649
+ }
650
+ function similarityTokenListWeight(tokens, weight) {
651
+ return tokens.reduce((total, token) => total + weight(token), 0);
652
+ }
653
+ function tokenWeight(token) {
654
+ if (token.startsWith(SIMILARITY_BIGRAM_PREFIX)) return 1.15;
655
+ return wordEmphasisTokenWeight(token);
656
+ }
657
+ function stringAt(values, index) {
658
+ const value = values[index];
659
+ if (value === void 0) throw new RangeError(`Missing similarity token ${index}`);
660
+ return value;
661
+ }
662
+
663
+ // src/ui/word-diff/sparse-line-matching.ts
664
+ var MAX_POSITIONAL_FALLBACK_AMBIGUITY_CELLS = 1e4;
665
+ var MAX_SPARSE_FEATURE_DOCUMENTS = 6;
666
+ var MAX_SPARSE_FEATURE_DOCUMENTS_PER_SIDE = 3;
667
+ var MAX_SPARSE_CANDIDATES_PER_LINE = 8;
668
+ var MIN_SPARSE_RARE_FEATURE_COUNT = 2;
669
+ var MIN_SPARSE_EVIDENCE_MARGIN = 1;
670
+ var MIN_SPARSE_EVIDENCE_RATIO = 0.9;
671
+ function matchChangedLinesSparse(removed, added, policy) {
672
+ const similarityDocuments = changedLineSimilarityDocuments(removed, added);
673
+ const tokenWeight2 = similarityTokenWeight(similarityDocuments);
674
+ const removedWeights = [];
675
+ const addedWeights = [];
676
+ const canCheckAmbiguity = removed.length * added.length <= MAX_POSITIONAL_FALLBACK_AMBIGUITY_CELLS;
677
+ const scoreCache = canCheckAmbiguity ? /* @__PURE__ */ new Map() : void 0;
678
+ const scoreAt = (removedPosition, addedPosition) => {
679
+ const key = removedPosition * added.length + addedPosition;
680
+ const cached = scoreCache?.get(key);
681
+ if (cached !== void 0) return cached;
682
+ const removedFeatures = similarityDocuments.removedFeatures[removedPosition];
683
+ const addedFeatures = similarityDocuments.addedFeatures[addedPosition];
684
+ if (removedFeatures === void 0 || addedFeatures === void 0)
685
+ throw new RangeError(`Missing similarity features ${removedPosition}:${addedPosition}`);
686
+ const removedWeight = removedWeights[removedPosition] ??= similarityTokenListWeight(
687
+ removedFeatures,
688
+ tokenWeight2
689
+ );
690
+ const addedWeight = addedWeights[addedPosition] ??= similarityTokenListWeight(
691
+ addedFeatures,
692
+ tokenWeight2
693
+ );
694
+ const score = fallbackLineSimilarity(
695
+ changedLineAt(removed, removedPosition),
696
+ changedLineAt(added, addedPosition),
697
+ tokenWeight2,
698
+ removedWeight,
699
+ addedWeight
700
+ );
701
+ scoreCache?.set(key, score);
702
+ return score;
703
+ };
704
+ const sparseCandidates = sparseChangedLinePairCandidates(similarityDocuments, tokenWeight2);
705
+ const pairs = sparseChangedLineAnchors(removed, added, sparseCandidates, scoreAt, policy);
706
+ const positions = changedLinePositions(removed, added);
707
+ const usedRemoved = /* @__PURE__ */ new Set();
708
+ const usedAdded = /* @__PURE__ */ new Set();
709
+ for (const pair of pairs) {
710
+ const removedPosition = positions.removed.get(pair.removedIndex);
711
+ const addedPosition = positions.added.get(pair.addedIndex);
712
+ if (removedPosition !== void 0) usedRemoved.add(removedPosition);
713
+ if (addedPosition !== void 0) usedAdded.add(addedPosition);
714
+ }
715
+ for (let index = 0; index < Math.min(removed.length, added.length); index++) {
716
+ if (usedRemoved.has(index) || usedAdded.has(index)) continue;
717
+ const score = scoreAt(index, index);
718
+ if (score < policy.minPositionalFallbackPairScore) continue;
719
+ const removedLine = changedLineAt(removed, index);
720
+ const addedLine = changedLineAt(added, index);
721
+ if (hasUniqueSharedSimilarityFeature(removedLine, addedLine, similarityDocuments)) {
722
+ pairs.push({
723
+ removedIndex: removedLine.index,
724
+ addedIndex: addedLine.index,
725
+ confidence: policy.linePairConfidence(score, 0)
726
+ });
727
+ usedRemoved.add(index);
728
+ usedAdded.add(index);
729
+ continue;
730
+ }
731
+ if (!canCheckAmbiguity) continue;
732
+ const competingScore = policy.competingChangedLineScoreAt(
733
+ removed.length,
734
+ added.length,
735
+ index,
736
+ index,
737
+ scoreAt
738
+ );
739
+ if (policy.isAmbiguousChangedLinePairScore(score, competingScore)) continue;
740
+ pairs.push({
741
+ removedIndex: removedLine.index,
742
+ addedIndex: addedLine.index,
743
+ confidence: policy.linePairConfidence(score, competingScore)
744
+ });
745
+ usedRemoved.add(index);
746
+ usedAdded.add(index);
747
+ }
748
+ return pairs.sort(
749
+ (a, b) => (positions.removed.get(a.removedIndex) ?? 0) - (positions.removed.get(b.removedIndex) ?? 0)
750
+ );
751
+ }
752
+ function sparseChangedLinePairCandidates(documents, tokenWeight2) {
753
+ const removedPositions = similarityFeaturePositions(documents.removedFeatures);
754
+ const addedPositions = similarityFeaturePositions(documents.addedFeatures);
755
+ const candidates = /* @__PURE__ */ new Map();
756
+ const addedLength = documents.addedFeatures.length;
757
+ for (const [feature, featureRemovedPositions] of removedPositions) {
758
+ const featureAddedPositions = addedPositions.get(feature);
759
+ if (!featureAddedPositions) continue;
760
+ const documentCount = documents.documentCounts.get(feature) ?? Number.POSITIVE_INFINITY;
761
+ if (documentCount > MAX_SPARSE_FEATURE_DOCUMENTS || featureRemovedPositions.length > MAX_SPARSE_FEATURE_DOCUMENTS_PER_SIDE || featureAddedPositions.length > MAX_SPARSE_FEATURE_DOCUMENTS_PER_SIDE)
762
+ continue;
763
+ const weight = tokenWeight2(feature);
764
+ if (weight < 1) continue;
765
+ const uniqueFeature = documentCount === 2 && featureRemovedPositions.length === 1 && featureAddedPositions.length === 1;
766
+ for (const removedPosition of featureRemovedPositions) {
767
+ for (const addedPosition of featureAddedPositions) {
768
+ const key = removedPosition * addedLength + addedPosition;
769
+ const candidate = candidates.get(key);
770
+ if (candidate) {
771
+ candidate.evidence += weight;
772
+ candidate.sharedFeatureCount++;
773
+ candidate.hasUniqueFeature ||= uniqueFeature;
774
+ } else {
775
+ candidates.set(key, {
776
+ removedPosition,
777
+ addedPosition,
778
+ evidence: weight,
779
+ sharedFeatureCount: 1,
780
+ hasUniqueFeature: uniqueFeature,
781
+ competingEvidence: 0
782
+ });
783
+ }
784
+ }
785
+ }
786
+ }
787
+ const candidateList = [...candidates.values()];
788
+ addCompetingSparseEvidence(candidateList);
789
+ return boundedSparseChangedLinePairCandidates(candidateList);
790
+ }
791
+ function similarityFeaturePositions(featureLists) {
792
+ const positions = /* @__PURE__ */ new Map();
793
+ for (let position = 0; position < featureLists.length; position++) {
794
+ const features = featureLists[position];
795
+ if (!features) continue;
796
+ for (const feature of new Set(features)) {
797
+ const featurePositions = positions.get(feature);
798
+ if (featurePositions) featurePositions.push(position);
799
+ else positions.set(feature, [position]);
800
+ }
801
+ }
802
+ return positions;
803
+ }
804
+ function addCompetingSparseEvidence(candidates) {
805
+ const removedEvidence = topTwoCandidateValues(
806
+ candidates,
807
+ (candidate) => candidate.removedPosition,
808
+ (candidate) => candidate.evidence
809
+ );
810
+ const addedEvidence = topTwoCandidateValues(
811
+ candidates,
812
+ (candidate) => candidate.addedPosition,
813
+ (candidate) => candidate.evidence
814
+ );
815
+ for (const candidate of candidates) {
816
+ candidate.competingEvidence = Math.max(
817
+ competingCandidateValue(removedEvidence.get(candidate.removedPosition), candidate.evidence),
818
+ competingCandidateValue(addedEvidence.get(candidate.addedPosition), candidate.evidence)
819
+ );
820
+ }
821
+ }
822
+ function topTwoCandidateValues(candidates, position, value) {
823
+ const values = /* @__PURE__ */ new Map();
824
+ for (const candidate of candidates) {
825
+ const current = values.get(position(candidate)) ?? { best: 0, second: 0 };
826
+ const candidateValue = value(candidate);
827
+ if (candidateValue >= current.best) {
828
+ current.second = current.best;
829
+ current.best = candidateValue;
830
+ } else if (candidateValue > current.second) current.second = candidateValue;
831
+ values.set(position(candidate), current);
832
+ }
833
+ return values;
834
+ }
835
+ function competingCandidateValue(values, candidateValue) {
836
+ if (!values) return 0;
837
+ return candidateValue === values.best ? values.second : values.best;
838
+ }
839
+ function boundedSparseChangedLinePairCandidates(candidates) {
840
+ const byRemoved = /* @__PURE__ */ new Map();
841
+ const byAdded = /* @__PURE__ */ new Map();
842
+ for (const candidate of candidates) {
843
+ appendSparseCandidate(byRemoved, candidate.removedPosition, candidate);
844
+ appendSparseCandidate(byAdded, candidate.addedPosition, candidate);
845
+ }
846
+ const selectedByRemoved = topSparseCandidates(byRemoved);
847
+ const selectedByAdded = topSparseCandidates(byAdded);
848
+ return candidates.filter(
849
+ (candidate) => selectedByRemoved.has(candidate) && selectedByAdded.has(candidate)
850
+ );
851
+ }
852
+ function appendSparseCandidate(candidates, position, candidate) {
853
+ const atPosition = candidates.get(position);
854
+ if (atPosition) atPosition.push(candidate);
855
+ else candidates.set(position, [candidate]);
856
+ }
857
+ function topSparseCandidates(candidates) {
858
+ const selected = /* @__PURE__ */ new Set();
859
+ for (const atPosition of candidates.values()) {
860
+ atPosition.sort(compareSparseCandidates);
861
+ for (const candidate of atPosition.slice(0, MAX_SPARSE_CANDIDATES_PER_LINE))
862
+ selected.add(candidate);
863
+ }
864
+ return selected;
865
+ }
866
+ function compareSparseCandidates(a, b) {
867
+ return Number(b.hasUniqueFeature) - Number(a.hasUniqueFeature) || b.evidence - a.evidence || b.sharedFeatureCount - a.sharedFeatureCount || Math.abs(a.removedPosition - a.addedPosition) - Math.abs(b.removedPosition - b.addedPosition) || a.removedPosition - b.removedPosition || a.addedPosition - b.addedPosition;
868
+ }
869
+ function sparseChangedLineAnchors(removed, added, sparseCandidates, scoreAt, policy) {
870
+ const scoredCandidates = sparseCandidates.map((candidate) => ({
871
+ ...candidate,
872
+ score: scoreAt(candidate.removedPosition, candidate.addedPosition)
873
+ })).sort((a, b) => b.score - a.score || compareSparseCandidates(a, b));
874
+ const removedScores = topTwoCandidateValues(
875
+ scoredCandidates,
876
+ (candidate) => candidate.removedPosition,
877
+ (candidate) => candidate.score
878
+ );
879
+ const addedScores = topTwoCandidateValues(
880
+ scoredCandidates,
881
+ (candidate) => candidate.addedPosition,
882
+ (candidate) => candidate.score
883
+ );
884
+ const usedRemoved = /* @__PURE__ */ new Set();
885
+ const usedAdded = /* @__PURE__ */ new Set();
886
+ const pairs = [];
887
+ for (const candidate of scoredCandidates) {
888
+ if (candidate.score < policy.minChangedLinePairScore) continue;
889
+ if (usedRemoved.has(candidate.removedPosition) || usedAdded.has(candidate.addedPosition))
890
+ continue;
891
+ if (!hasStrongSparseEvidence(candidate)) continue;
892
+ const competingScore = Math.max(
893
+ competingCandidateValue(removedScores.get(candidate.removedPosition), candidate.score),
894
+ competingCandidateValue(addedScores.get(candidate.addedPosition), candidate.score),
895
+ sparsePositionalCompetingScore(candidate, removed.length, added.length, scoreAt)
896
+ );
897
+ if (!policy.isReciprocalBestChangedLinePair(candidate.score, competingScore)) continue;
898
+ usedRemoved.add(candidate.removedPosition);
899
+ usedAdded.add(candidate.addedPosition);
900
+ pairs.push({
901
+ removedIndex: changedLineAt(removed, candidate.removedPosition).index,
902
+ addedIndex: changedLineAt(added, candidate.addedPosition).index,
903
+ confidence: policy.linePairConfidence(candidate.score, competingScore)
904
+ });
905
+ }
906
+ return pairs;
907
+ }
908
+ function sparsePositionalCompetingScore(candidate, removedLength, addedLength, scoreAt) {
909
+ let competingScore = 0;
910
+ if (candidate.removedPosition < addedLength && candidate.addedPosition !== candidate.removedPosition)
911
+ competingScore = scoreAt(candidate.removedPosition, candidate.removedPosition);
912
+ if (candidate.addedPosition < removedLength && candidate.removedPosition !== candidate.addedPosition)
913
+ competingScore = Math.max(
914
+ competingScore,
915
+ scoreAt(candidate.addedPosition, candidate.addedPosition)
916
+ );
917
+ return competingScore;
918
+ }
919
+ function hasStrongSparseEvidence(candidate) {
920
+ if (!candidate.hasUniqueFeature && candidate.sharedFeatureCount < MIN_SPARSE_RARE_FEATURE_COUNT)
921
+ return false;
922
+ return candidate.evidence - candidate.competingEvidence > MIN_SPARSE_EVIDENCE_MARGIN && candidate.competingEvidence < candidate.evidence * MIN_SPARSE_EVIDENCE_RATIO;
923
+ }
924
+ function changedLinePositions(removed, added) {
925
+ return {
926
+ removed: new Map(removed.map((line, index) => [line.index, index])),
927
+ added: new Map(added.map((line, index) => [line.index, index]))
928
+ };
929
+ }
930
+ function changedLineAt(lines, index) {
931
+ const line = lines[index];
932
+ if (line === void 0) throw new RangeError(`Missing changed line ${index}`);
933
+ return line;
934
+ }
935
+
936
+ // src/ui/word-diff/line-matching.ts
937
+ function matchChangedLines(removed, added) {
938
+ if (removed.length === 0 || added.length === 0) return [];
939
+ if (removed.length * added.length > MAX_CHANGED_LINE_PAIR_CELLS)
940
+ return matchChangedLinesSparse(removed, added, SPARSE_LINE_MATCHING_POLICY);
941
+ const similarityDocuments = changedLineSimilarityDocuments(removed, added);
942
+ const tokenWeight2 = similarityTokenWeight(similarityDocuments);
943
+ const { removedFeatures, addedFeatures } = similarityDocuments;
944
+ const removedWeights = removedFeatures.map(
945
+ (tokens) => similarityTokenListWeight(tokens, tokenWeight2)
946
+ );
947
+ const addedWeights = addedFeatures.map(
948
+ (tokens) => similarityTokenListWeight(tokens, tokenWeight2)
949
+ );
950
+ const scores = removedFeatures.map(
951
+ (beforeTokens, removedPosition) => addedFeatures.map(
952
+ (afterTokens, addedPosition) => tokenSimilarity(
953
+ beforeTokens,
954
+ afterTokens,
955
+ tokenWeight2,
956
+ MIN_POSITIONAL_FALLBACK_PAIR_SCORE,
957
+ removedWeights[removedPosition],
958
+ addedWeights[addedPosition]
959
+ )
960
+ )
961
+ );
962
+ const similarPairs = prefixAlignedPairs(
963
+ removed.length,
964
+ added.length,
965
+ (removedPosition, addedPosition) => {
966
+ const score = scores[removedPosition]?.[addedPosition] ?? 0;
967
+ return score >= MIN_CHANGED_LINE_PAIR_SCORE ? score + 0.01 : Number.NEGATIVE_INFINITY;
968
+ }
969
+ );
970
+ if (similarPairs.length === 0 && removed.length === 1 && added.length === 1)
971
+ return [
972
+ {
973
+ removedIndex: changedLineAt2(removed, 0).index,
974
+ addedIndex: changedLineAt2(added, 0).index,
975
+ confidence: "medium"
976
+ }
977
+ ];
978
+ const positions = changedLinePositions2(removed, added);
979
+ const confidentPairs = confidentChangedLinePairs(
980
+ positions,
981
+ scores,
982
+ addPositionalFallbackPairs(removed, added, scores, similarPairs)
983
+ );
984
+ return addCrossingPairs(removed, added, scores, positions, confidentPairs);
985
+ }
986
+ var MIN_CHANGED_LINE_PAIR_SCORE = 0.45;
987
+ var MIN_POSITIONAL_FALLBACK_PAIR_SCORE = 0.28;
988
+ var CHANGED_LINE_PAIR_AMBIGUITY_MARGIN = 0.06;
989
+ var CHANGED_LINE_PAIR_AMBIGUITY_RATIO = 0.92;
990
+ var MIN_HIGH_CONFIDENCE_CROSSING_PAIR_SCORE = 0.72;
991
+ var HIGH_CONFIDENCE_CROSSING_PAIR_MARGIN = 0.12;
992
+ var HIGH_CONFIDENCE_CROSSING_PAIR_RATIO = 0.85;
993
+ var MAX_CHANGED_LINE_PAIR_CELLS = 1024;
994
+ var SPARSE_LINE_MATCHING_POLICY = {
995
+ minPositionalFallbackPairScore: MIN_POSITIONAL_FALLBACK_PAIR_SCORE,
996
+ minChangedLinePairScore: MIN_CHANGED_LINE_PAIR_SCORE,
997
+ competingChangedLineScoreAt,
998
+ isAmbiguousChangedLinePairScore,
999
+ isReciprocalBestChangedLinePair,
1000
+ linePairConfidence
1001
+ };
1002
+ function changedLinePositions2(removed, added) {
1003
+ return {
1004
+ removed: new Map(removed.map((line, index) => [line.index, index])),
1005
+ added: new Map(added.map((line, index) => [line.index, index]))
1006
+ };
1007
+ }
1008
+ function confidentChangedLinePairs(positions, scores, pairs) {
1009
+ const confidentPairs = [];
1010
+ for (const [removedIndex, addedIndex] of pairs) {
1011
+ const removedPosition = positions.removed.get(removedIndex);
1012
+ const addedPosition = positions.added.get(addedIndex);
1013
+ if (removedPosition === void 0 || addedPosition === void 0) continue;
1014
+ const score = scores[removedPosition]?.[addedPosition] ?? 0;
1015
+ const competingScore = competingChangedLineScore(scores, removedPosition, addedPosition);
1016
+ if (isAmbiguousChangedLinePairScore(score, competingScore)) continue;
1017
+ confidentPairs.push({
1018
+ removedIndex,
1019
+ addedIndex,
1020
+ confidence: linePairConfidence(score, competingScore)
1021
+ });
1022
+ }
1023
+ return confidentPairs;
1024
+ }
1025
+ function competingChangedLineScore(scores, removedPosition, addedPosition, usedRemoved, usedAdded) {
1026
+ return competingChangedLineScoreAt(
1027
+ scores.length,
1028
+ scores[removedPosition]?.length ?? 0,
1029
+ removedPosition,
1030
+ addedPosition,
1031
+ (candidateRemovedPosition, candidateAddedPosition) => scores[candidateRemovedPosition]?.[candidateAddedPosition] ?? 0,
1032
+ usedRemoved,
1033
+ usedAdded
1034
+ );
1035
+ }
1036
+ function competingChangedLineScoreAt(removedLength, addedLength, removedPosition, addedPosition, scoreAt, usedRemoved, usedAdded) {
1037
+ let competingScore = 0;
1038
+ for (let candidateAddedPosition = 0; candidateAddedPosition < addedLength; candidateAddedPosition++) {
1039
+ if (candidateAddedPosition === addedPosition || usedAdded?.has(candidateAddedPosition))
1040
+ continue;
1041
+ competingScore = Math.max(competingScore, scoreAt(removedPosition, candidateAddedPosition));
1042
+ }
1043
+ for (let candidateRemovedPosition = 0; candidateRemovedPosition < removedLength; candidateRemovedPosition++) {
1044
+ if (candidateRemovedPosition === removedPosition || usedRemoved?.has(candidateRemovedPosition))
1045
+ continue;
1046
+ competingScore = Math.max(competingScore, scoreAt(candidateRemovedPosition, addedPosition));
1047
+ }
1048
+ return competingScore;
1049
+ }
1050
+ function isAmbiguousChangedLinePairScore(score, competingScore) {
1051
+ return competingScore >= MIN_POSITIONAL_FALLBACK_PAIR_SCORE && (score - competingScore <= CHANGED_LINE_PAIR_AMBIGUITY_MARGIN || competingScore >= score * CHANGED_LINE_PAIR_AMBIGUITY_RATIO);
1052
+ }
1053
+ function isReciprocalBestChangedLinePair(score, competingScore) {
1054
+ return score > competingScore && !isAmbiguousChangedLinePairScore(score, competingScore);
1055
+ }
1056
+ function linePairConfidence(score, competingScore) {
1057
+ if (score >= MIN_HIGH_CONFIDENCE_CROSSING_PAIR_SCORE && score - competingScore >= HIGH_CONFIDENCE_CROSSING_PAIR_MARGIN && competingScore <= score * HIGH_CONFIDENCE_CROSSING_PAIR_RATIO)
1058
+ return "high";
1059
+ return "medium";
1060
+ }
1061
+ function addCrossingPairs(removed, added, scores, positions, pairs) {
1062
+ const usedRemoved = /* @__PURE__ */ new Set();
1063
+ const usedAdded = /* @__PURE__ */ new Set();
1064
+ for (const pair of pairs) {
1065
+ const removedPosition = positions.removed.get(pair.removedIndex);
1066
+ const addedPosition = positions.added.get(pair.addedIndex);
1067
+ if (removedPosition !== void 0) usedRemoved.add(removedPosition);
1068
+ if (addedPosition !== void 0) usedAdded.add(addedPosition);
1069
+ }
1070
+ const candidates = [];
1071
+ for (let removedPosition = 0; removedPosition < removed.length; removedPosition++) {
1072
+ if (usedRemoved.has(removedPosition)) continue;
1073
+ for (let addedPosition = 0; addedPosition < added.length; addedPosition++) {
1074
+ if (usedAdded.has(addedPosition)) continue;
1075
+ const score = scores[removedPosition]?.[addedPosition] ?? 0;
1076
+ if (score >= MIN_CHANGED_LINE_PAIR_SCORE)
1077
+ candidates.push({ removedPosition, addedPosition, score });
1078
+ }
1079
+ }
1080
+ candidates.sort((a, b) => b.score - a.score);
1081
+ const competingScores = changedLineCompetingScores(scores);
1082
+ const out = [...pairs];
1083
+ for (const candidate of candidates) {
1084
+ if (usedRemoved.has(candidate.removedPosition) || usedAdded.has(candidate.addedPosition))
1085
+ continue;
1086
+ let confidence;
1087
+ if (candidate.score >= MIN_HIGH_CONFIDENCE_CROSSING_PAIR_SCORE) {
1088
+ const availableCompetingScore = competingChangedLineScore(
1089
+ scores,
1090
+ candidate.removedPosition,
1091
+ candidate.addedPosition,
1092
+ usedRemoved,
1093
+ usedAdded
1094
+ );
1095
+ if (linePairConfidence(candidate.score, availableCompetingScore) === "high")
1096
+ confidence = "high";
1097
+ }
1098
+ confidence ??= reciprocalCrossingPairConfidence(competingScores, candidate);
1099
+ if (!confidence) continue;
1100
+ usedRemoved.add(candidate.removedPosition);
1101
+ usedAdded.add(candidate.addedPosition);
1102
+ out.push({
1103
+ removedIndex: changedLineAt2(removed, candidate.removedPosition).index,
1104
+ addedIndex: changedLineAt2(added, candidate.addedPosition).index,
1105
+ confidence
1106
+ });
1107
+ }
1108
+ return out.sort(
1109
+ (a, b) => (positions.removed.get(a.removedIndex) ?? 0) - (positions.removed.get(b.removedIndex) ?? 0)
1110
+ );
1111
+ }
1112
+ function changedLineCompetingScores(scores) {
1113
+ const removed = [];
1114
+ const added = [];
1115
+ for (let removedPosition = 0; removedPosition < scores.length; removedPosition++) {
1116
+ const removedScores = scores[removedPosition] ?? [];
1117
+ for (let addedPosition = 0; addedPosition < removedScores.length; addedPosition++) {
1118
+ const score = removedScores[addedPosition] ?? 0;
1119
+ addCandidateValue(removed, removedPosition, score);
1120
+ addCandidateValue(added, addedPosition, score);
1121
+ }
1122
+ }
1123
+ return { removed, added };
1124
+ }
1125
+ function addCandidateValue(values, position, value) {
1126
+ const current = values[position] ?? { best: 0, second: 0 };
1127
+ if (value >= current.best) {
1128
+ current.second = current.best;
1129
+ current.best = value;
1130
+ } else if (value > current.second) current.second = value;
1131
+ values[position] = current;
1132
+ }
1133
+ function reciprocalCrossingPairConfidence(competingScores, candidate) {
1134
+ const competingScore = Math.max(
1135
+ competingCandidateValue(competingScores.removed[candidate.removedPosition], candidate.score),
1136
+ competingCandidateValue(competingScores.added[candidate.addedPosition], candidate.score)
1137
+ );
1138
+ if (!isReciprocalBestChangedLinePair(candidate.score, competingScore)) return void 0;
1139
+ return linePairConfidence(candidate.score, competingScore);
1140
+ }
1141
+ function addPositionalFallbackPairs(removed, added, scores, similarPairs) {
1142
+ const pairs = [];
1143
+ let removedCursor = 0;
1144
+ let addedCursor = 0;
1145
+ for (const [removedPosition, addedPosition] of similarPairs) {
1146
+ pairs.push(
1147
+ ...positionPairs(
1148
+ removed,
1149
+ added,
1150
+ scores,
1151
+ removedCursor,
1152
+ removedPosition,
1153
+ addedCursor,
1154
+ addedPosition
1155
+ )
1156
+ );
1157
+ pairs.push([
1158
+ changedLineAt2(removed, removedPosition).index,
1159
+ changedLineAt2(added, addedPosition).index
1160
+ ]);
1161
+ removedCursor = removedPosition + 1;
1162
+ addedCursor = addedPosition + 1;
1163
+ }
1164
+ pairs.push(
1165
+ ...positionPairs(
1166
+ removed,
1167
+ added,
1168
+ scores,
1169
+ removedCursor,
1170
+ removed.length,
1171
+ addedCursor,
1172
+ added.length
1173
+ )
1174
+ );
1175
+ return pairs;
1176
+ }
1177
+ function positionPairs(removed, added, scores, removedStart, removedEnd, addedStart, addedEnd) {
1178
+ const pairs = [];
1179
+ const count = Math.min(removedEnd - removedStart, addedEnd - addedStart);
1180
+ for (let offset = 0; offset < count; offset++) {
1181
+ const removedPosition = removedStart + offset;
1182
+ const addedPosition = addedStart + offset;
1183
+ const score = scores[removedPosition]?.[addedPosition] ?? 0;
1184
+ if (score < MIN_POSITIONAL_FALLBACK_PAIR_SCORE) continue;
1185
+ pairs.push([
1186
+ changedLineAt2(removed, removedPosition).index,
1187
+ changedLineAt2(added, addedPosition).index
1188
+ ]);
1189
+ }
1190
+ return pairs;
1191
+ }
1192
+ function changedLineAt2(lines, index) {
1193
+ const line = lines[index];
1194
+ if (line === void 0) throw new RangeError(`Missing changed line ${index}`);
1195
+ return line;
1196
+ }
1197
+
1198
+ // src/ui/word-diff/parse.ts
1199
+ function diffLineNumberWidth(lines) {
1200
+ return lines.reduce((width, line) => Math.max(width, normalizedDiffLineNumber(line).length), 0);
1201
+ }
1202
+ function formatDiffLineNumber(lineNumber, width) {
1203
+ return lineNumber.trim().padStart(width, " ");
1204
+ }
1205
+ function normalizedDiffLineNumber(line) {
1206
+ return line?.lineNumber.trim() ?? "";
1207
+ }
1208
+ function parseDiffLine(line) {
1209
+ const numbered = line.match(/^([+\- ])(\s*\d+)\s(.*)$/);
1210
+ if (numbered) {
1211
+ const [, kind, lineNumber, content] = numbered;
1212
+ if (kind !== "+" && kind !== "-" && kind !== " " || lineNumber === void 0 || content === void 0)
1213
+ return null;
1214
+ return { kind, lineNumber, content };
1215
+ }
1216
+ if (line.startsWith("+++") || line.startsWith("---")) return null;
1217
+ const prefix = line[0];
1218
+ if (prefix !== "+" && prefix !== "-" && prefix !== " ") return null;
1219
+ return { kind: prefix, lineNumber: "", content: line.slice(1) };
1220
+ }
1221
+ function isAddedDiffLine(line) {
1222
+ return line?.kind === "+";
1223
+ }
1224
+ function isRemovedDiffLine(line) {
1225
+ return line?.kind === "-";
1226
+ }
1227
+
1228
+ // src/ui/word-diff/ranges.ts
1229
+ function rangesForTokenGroup(tokens, group) {
1230
+ const ranges = [];
1231
+ for (let index = group.start; index < group.end; index++) {
1232
+ const token = tokens[index];
1233
+ if (token) appendTokenRange(ranges, token);
1234
+ }
1235
+ return ranges;
1236
+ }
1237
+ function pushTokenRange(ranges, token) {
1238
+ ranges.push([token.start, token.end]);
1239
+ }
1240
+ function mergeRangesByStart(ranges) {
1241
+ return mergeRanges([...ranges].sort((a, b) => a[0] - b[0]));
1242
+ }
1243
+ function mergeRanges(ranges) {
1244
+ const merged = [];
1245
+ for (const range of ranges) {
1246
+ const previous = merged.at(-1);
1247
+ if (previous && range[0] - previous[1] <= 1) previous[1] = range[1];
1248
+ else merged.push([...range]);
1249
+ }
1250
+ return merged;
1251
+ }
1252
+ function appendTokenRange(ranges, token) {
1253
+ const previous = ranges.at(-1);
1254
+ if (previous && token.start - previous[1] <= 1) previous[1] = token.end;
1255
+ else ranges.push([token.start, token.end]);
1256
+ }
1257
+
1258
+ // src/ui/word-diff/text-boundaries.ts
1259
+ var NON_ASCII_TEXT_PATTERN = /[^\x00-\x7F]/;
1260
+ var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1261
+ function commonPrefixLength(before, after) {
1262
+ const prefix = commonPrefixCodeUnitLength(before, after);
1263
+ if (!needsBoundarySafeOffsets(before) && !needsBoundarySafeOffsets(after)) return prefix;
1264
+ return commonGraphemePrefixLength(before, after, prefix);
1265
+ }
1266
+ function commonSuffixLength(before, after, prefixLength) {
1267
+ const suffix = commonSuffixCodeUnitLength(before, after, prefixLength);
1268
+ if (!needsBoundarySafeOffsets(before) && !needsBoundarySafeOffsets(after)) return suffix;
1269
+ return commonGraphemeSuffixLength(before, after, suffix);
1270
+ }
1271
+ function needsBoundarySafeOffsets(text) {
1272
+ return NON_ASCII_TEXT_PATTERN.test(text) || text.includes("\r\n");
1273
+ }
1274
+ function textBoundarySegments(text) {
1275
+ if (!needsBoundarySafeOffsets(text)) {
1276
+ return Array.from({ length: text.length }, (_, index) => ({
1277
+ value: text[index] ?? "",
1278
+ start: index,
1279
+ end: index + 1
1280
+ }));
1281
+ }
1282
+ return Array.from(graphemeSegmenter.segment(text), (segment) => ({
1283
+ value: segment.segment,
1284
+ start: segment.index,
1285
+ end: segment.index + segment.segment.length
1286
+ }));
1287
+ }
1288
+ function rangesAtGraphemeBoundaries(text, ranges) {
1289
+ if (ranges.length === 0 || !needsBoundarySafeOffsets(text)) return ranges;
1290
+ const segmentedText = graphemeSegmenter.segment(text);
1291
+ return ranges.map(([start, end]) => [
1292
+ graphemeStartAtOrBefore(segmentedText, start, text.length),
1293
+ graphemeEndAtOrAfter(segmentedText, end, text.length)
1294
+ ]);
1295
+ }
1296
+ function commonPrefixCodeUnitLength(before, after) {
1297
+ const end = Math.min(before.length, after.length);
1298
+ let index = 0;
1299
+ while (index < end && before[index] === after[index]) index++;
1300
+ return index;
1301
+ }
1302
+ function commonSuffixCodeUnitLength(before, after, prefixLength) {
1303
+ const maxLength = Math.min(before.length, after.length) - prefixLength;
1304
+ let length = 0;
1305
+ while (length < maxLength && before[before.length - 1 - length] === after[after.length - 1 - length])
1306
+ length++;
1307
+ return length;
1308
+ }
1309
+ function commonGraphemePrefixLength(before, after, prefix) {
1310
+ const beforeSegments = graphemeSegmenter.segment(before);
1311
+ const afterSegments = graphemeSegmenter.segment(after);
1312
+ let safePrefix = prefix;
1313
+ while (safePrefix > 0) {
1314
+ const beforeBoundary = graphemeBoundaryAtOrBefore(beforeSegments, safePrefix);
1315
+ const afterBoundary = graphemeBoundaryAtOrBefore(afterSegments, safePrefix);
1316
+ const nextPrefix = Math.min(beforeBoundary, afterBoundary);
1317
+ if (nextPrefix === safePrefix) break;
1318
+ safePrefix = nextPrefix;
1319
+ }
1320
+ return safePrefix;
1321
+ }
1322
+ function commonGraphemeSuffixLength(before, after, suffix) {
1323
+ const beforeSegments = graphemeSegmenter.segment(before);
1324
+ const afterSegments = graphemeSegmenter.segment(after);
1325
+ let safeSuffix = suffix;
1326
+ while (safeSuffix > 0) {
1327
+ const beforeStart = before.length - safeSuffix;
1328
+ const afterStart = after.length - safeSuffix;
1329
+ const beforeTrim = graphemeBoundaryAtOrAfter(beforeSegments, beforeStart, before.length) - beforeStart;
1330
+ const afterTrim = graphemeBoundaryAtOrAfter(afterSegments, afterStart, after.length) - afterStart;
1331
+ const trim = Math.max(beforeTrim, afterTrim);
1332
+ if (trim === 0) break;
1333
+ safeSuffix = Math.max(0, safeSuffix - trim);
1334
+ }
1335
+ return safeSuffix;
1336
+ }
1337
+ function graphemeBoundaryAtOrBefore(segments, offset) {
1338
+ if (offset <= 0) return 0;
1339
+ const segment = segments.containing(offset - 1);
1340
+ if (!segment) return offset;
1341
+ const segmentEnd = segment.index + segment.segment.length;
1342
+ return segmentEnd === offset ? offset : segment.index;
1343
+ }
1344
+ function graphemeBoundaryAtOrAfter(segments, offset, textLength) {
1345
+ if (offset <= 0) return 0;
1346
+ if (offset >= textLength) return textLength;
1347
+ const segment = segments.containing(offset);
1348
+ if (!segment || segment.index === offset) return offset;
1349
+ return segment.index + segment.segment.length;
1350
+ }
1351
+ function graphemeStartAtOrBefore(segments, offset, textLength) {
1352
+ if (offset <= 0) return 0;
1353
+ if (offset >= textLength) return textLength;
1354
+ return segments.containing(offset)?.index ?? offset;
1355
+ }
1356
+ function graphemeEndAtOrAfter(segments, offset, textLength) {
1357
+ if (offset <= 0) return 0;
1358
+ if (offset >= textLength) return textLength;
1359
+ const segment = segments.containing(offset - 1);
1360
+ return segment ? segment.index + segment.segment.length : offset;
1361
+ }
1362
+
1363
+ // src/ui/word-diff/token-alignment.ts
1364
+ var WORD_EMPHASIS_EXACT_LCS_MAX_CELLS = 262144;
1365
+ function collectChangedTokenGaps(before, beforeStart, beforeEnd, after, afterStart, afterEnd, gaps) {
1366
+ while (beforeStart < beforeEnd && afterStart < afterEnd && tokenAt(before, beforeStart).value === tokenAt(after, afterStart).value) {
1367
+ beforeStart++;
1368
+ afterStart++;
1369
+ }
1370
+ while (beforeStart < beforeEnd && afterStart < afterEnd && tokenAt(before, beforeEnd - 1).value === tokenAt(after, afterEnd - 1).value) {
1371
+ beforeEnd--;
1372
+ afterEnd--;
1373
+ }
1374
+ if (beforeStart === beforeEnd || afterStart === afterEnd) {
1375
+ appendChangedTokenGap(gaps, beforeStart, beforeEnd, afterStart, afterEnd);
1376
+ return "high";
1377
+ }
1378
+ const beforeLength = beforeEnd - beforeStart;
1379
+ const afterLength = afterEnd - afterStart;
1380
+ if (beforeLength * afterLength <= WORD_EMPHASIS_EXACT_LCS_MAX_CELLS) {
1381
+ collectChangedTokenGapsByLcs(before, beforeStart, beforeEnd, after, afterStart, afterEnd, gaps);
1382
+ return "high";
1383
+ }
1384
+ const anchors = uniqueOrderedAnchors(before, beforeStart, beforeEnd, after, afterStart, afterEnd);
1385
+ if (anchors.length === 0) {
1386
+ appendChangedTokenGap(gaps, beforeStart, beforeEnd, afterStart, afterEnd);
1387
+ return "low";
1388
+ }
1389
+ let confidence = "high";
1390
+ let previousBefore = beforeStart;
1391
+ let previousAfter = afterStart;
1392
+ for (const anchor of anchors) {
1393
+ confidence = lowerWordChangeConfidence(
1394
+ confidence,
1395
+ collectChangedTokenGaps(
1396
+ before,
1397
+ previousBefore,
1398
+ anchor.beforeIndex,
1399
+ after,
1400
+ previousAfter,
1401
+ anchor.afterIndex,
1402
+ gaps
1403
+ )
1404
+ );
1405
+ previousBefore = anchor.beforeIndex + 1;
1406
+ previousAfter = anchor.afterIndex + 1;
1407
+ }
1408
+ confidence = lowerWordChangeConfidence(
1409
+ confidence,
1410
+ collectChangedTokenGaps(
1411
+ before,
1412
+ previousBefore,
1413
+ beforeEnd,
1414
+ after,
1415
+ previousAfter,
1416
+ afterEnd,
1417
+ gaps
1418
+ )
1419
+ );
1420
+ return lowerWordChangeConfidence(confidence, "medium");
1421
+ }
1422
+ function lowerWordChangeConfidence(a, b) {
1423
+ return WORD_CHANGE_CONFIDENCE_RANK[a] <= WORD_CHANGE_CONFIDENCE_RANK[b] ? a : b;
1424
+ }
1425
+ var WORD_CHANGE_CONFIDENCE_RANK = {
1426
+ low: 0,
1427
+ medium: 1,
1428
+ high: 2
1429
+ };
1430
+ function collectChangedTokenGapsByLcs(before, beforeStart, beforeEnd, after, afterStart, afterEnd, gaps) {
1431
+ const beforeLength = beforeEnd - beforeStart;
1432
+ const afterLength = afterEnd - afterStart;
1433
+ const pairs = suffixAlignedPairs(beforeLength, afterLength, (beforeIndex2, afterIndex2) => {
1434
+ const beforeToken = tokenAt(before, beforeStart + beforeIndex2);
1435
+ const afterToken = tokenAt(after, afterStart + afterIndex2);
1436
+ return beforeToken.value === afterToken.value ? wordEmphasisTokenWeight(beforeToken.value) : Number.NEGATIVE_INFINITY;
1437
+ });
1438
+ let beforeIndex = 0;
1439
+ let afterIndex = 0;
1440
+ for (const [nextBeforeIndex, nextAfterIndex] of pairs) {
1441
+ appendChangedTokenGap(
1442
+ gaps,
1443
+ beforeStart + beforeIndex,
1444
+ beforeStart + nextBeforeIndex,
1445
+ afterStart + afterIndex,
1446
+ afterStart + nextAfterIndex
1447
+ );
1448
+ beforeIndex = nextBeforeIndex + 1;
1449
+ afterIndex = nextAfterIndex + 1;
1450
+ }
1451
+ appendChangedTokenGap(
1452
+ gaps,
1453
+ beforeStart + beforeIndex,
1454
+ beforeEnd,
1455
+ afterStart + afterIndex,
1456
+ afterEnd
1457
+ );
1458
+ }
1459
+ function uniqueOrderedAnchors(before, beforeStart, beforeEnd, after, afterStart, afterEnd) {
1460
+ const beforeCounts = tokenCounts(before, beforeStart, beforeEnd);
1461
+ const afterCounts = tokenCounts(after, afterStart, afterEnd);
1462
+ const afterUniqueIndexes = /* @__PURE__ */ new Map();
1463
+ for (let index = afterStart; index < afterEnd; index++) {
1464
+ const value = tokenAt(after, index).value;
1465
+ if (beforeCounts.get(value) === 1 && afterCounts.get(value) === 1)
1466
+ afterUniqueIndexes.set(value, index);
1467
+ }
1468
+ const candidates = [];
1469
+ for (let index = beforeStart; index < beforeEnd; index++) {
1470
+ const value = tokenAt(before, index).value;
1471
+ if (beforeCounts.get(value) !== 1 || afterCounts.get(value) !== 1) continue;
1472
+ const afterIndex = afterUniqueIndexes.get(value);
1473
+ if (afterIndex !== void 0) candidates.push({ beforeIndex: index, afterIndex });
1474
+ }
1475
+ return longestIncreasingAfterIndexes(candidates);
1476
+ }
1477
+ function longestIncreasingAfterIndexes(candidates) {
1478
+ if (candidates.length <= 1) return candidates;
1479
+ const tails = [];
1480
+ const previous = Array.from({ length: candidates.length }, () => -1);
1481
+ const tailCandidateIndexes = [];
1482
+ for (let index2 = 0; index2 < candidates.length; index2++) {
1483
+ const afterIndex = candidateAt(candidates, index2).afterIndex;
1484
+ let low = 0;
1485
+ let high = tails.length;
1486
+ while (low < high) {
1487
+ const middle = low + high >> 1;
1488
+ if (numberAt(tails, middle) < afterIndex) low = middle + 1;
1489
+ else high = middle;
1490
+ }
1491
+ if (low > 0) previous[index2] = numberAt(tailCandidateIndexes, low - 1);
1492
+ tails[low] = afterIndex;
1493
+ tailCandidateIndexes[low] = index2;
1494
+ }
1495
+ const ordered = [];
1496
+ let index = tailCandidateIndexes[tails.length - 1] ?? -1;
1497
+ while (index >= 0) {
1498
+ ordered.push(candidateAt(candidates, index));
1499
+ index = previous[index] ?? -1;
1500
+ }
1501
+ return ordered.reverse();
1502
+ }
1503
+ function tokenCounts(tokens, start, end) {
1504
+ const counts = /* @__PURE__ */ new Map();
1505
+ for (let index = start; index < end; index++) {
1506
+ const value = tokenAt(tokens, index).value;
1507
+ counts.set(value, (counts.get(value) ?? 0) + 1);
1508
+ }
1509
+ return counts;
1510
+ }
1511
+ function appendChangedTokenGap(gaps, beforeStart, beforeEnd, afterStart, afterEnd) {
1512
+ if (beforeStart === beforeEnd && afterStart === afterEnd) return;
1513
+ gaps.push({
1514
+ removed: { start: beforeStart, end: beforeEnd },
1515
+ added: { start: afterStart, end: afterEnd }
1516
+ });
1517
+ }
1518
+ function tokenAt(tokens, index) {
1519
+ const token = tokens[index];
1520
+ if (token === void 0) throw new RangeError(`Missing word-emphasis token ${index}`);
1521
+ return token;
1522
+ }
1523
+ function candidateAt(candidates, index) {
1524
+ const candidate = candidates[index];
1525
+ if (candidate === void 0) throw new RangeError(`Missing anchor candidate ${index}`);
1526
+ return candidate;
1527
+ }
1528
+ function numberAt(values, index) {
1529
+ const value = values[index];
1530
+ if (value === void 0) throw new RangeError(`Missing numeric value ${index}`);
1531
+ return value;
1532
+ }
1533
+
1534
+ // src/ui/word-diff/token-text-refinement.ts
1535
+ var MAX_REFINED_TEXT_ALIGNMENT_CELLS = 1024;
1536
+ var MAX_REFINED_TEXT_GRAPHEMES = 48;
1537
+ var MAX_REFINED_TEXT_INTERNAL_RUNS = 4;
1538
+ var MIN_REFINED_TEXT_INTERNAL_RUN_GRAPHEMES = 3;
1539
+ function refinedTokenTextRanges(beforeToken, afterToken) {
1540
+ if (beforeToken.value === afterToken.value) return void 0;
1541
+ const prefix = commonPrefixLength(beforeToken.value, afterToken.value);
1542
+ const suffix = commonSuffixLength(beforeToken.value, afterToken.value, prefix);
1543
+ if (!shouldRefineTokenText(beforeToken.value, afterToken.value, prefix, suffix)) return void 0;
1544
+ const aligned = refinedTokenTextRangesByAlignment(beforeToken, afterToken, prefix, suffix);
1545
+ if (aligned) return aligned;
1546
+ return tokenTextGapRanges(
1547
+ beforeToken,
1548
+ afterToken,
1549
+ prefix,
1550
+ beforeToken.value.length - suffix,
1551
+ prefix,
1552
+ afterToken.value.length - suffix
1553
+ );
1554
+ }
1555
+ function refinedTokenTextRangesByAlignment(beforeToken, afterToken, prefix, suffix) {
1556
+ const beforeValue = beforeToken.value;
1557
+ const afterValue = afterToken.value;
1558
+ if (!isIdentifierToken(beforeValue) || !isIdentifierToken(afterValue)) return void 0;
1559
+ if (beforeValue.length * afterValue.length > MAX_REFINED_TEXT_ALIGNMENT_CELLS) return void 0;
1560
+ if (!hasPotentialInternalCommonText(beforeValue, afterValue, prefix, suffix)) return void 0;
1561
+ const beforeSegments = textBoundarySegments(beforeValue);
1562
+ const afterSegments = textBoundarySegments(afterValue);
1563
+ if (beforeSegments.length > MAX_REFINED_TEXT_GRAPHEMES || afterSegments.length > MAX_REFINED_TEXT_GRAPHEMES || beforeSegments.length * afterSegments.length > MAX_REFINED_TEXT_ALIGNMENT_CELLS)
1564
+ return void 0;
1565
+ const pairs = suffixAlignedPairs(
1566
+ beforeSegments.length,
1567
+ afterSegments.length,
1568
+ (before, after) => segmentAt(beforeSegments, before).value === segmentAt(afterSegments, after).value ? 1 : Number.NEGATIVE_INFINITY
1569
+ );
1570
+ const runs = commonTextRuns(pairs);
1571
+ const keptRuns = runs.filter(
1572
+ (run) => isEdgeTextRun(run, beforeSegments.length, afterSegments.length) || run.beforeEnd - run.beforeStart >= MIN_REFINED_TEXT_INTERNAL_RUN_GRAPHEMES
1573
+ );
1574
+ const internalRunCount = keptRuns.filter(
1575
+ (run) => !isEdgeTextRun(run, beforeSegments.length, afterSegments.length)
1576
+ ).length;
1577
+ if (internalRunCount === 0 || internalRunCount > MAX_REFINED_TEXT_INTERNAL_RUNS) return void 0;
1578
+ const removed = [];
1579
+ const added = [];
1580
+ let beforeIndex = 0;
1581
+ let afterIndex = 0;
1582
+ for (const run of keptRuns) {
1583
+ pushTextSegmentRange(removed, beforeToken, beforeSegments, beforeIndex, run.beforeStart);
1584
+ pushTextSegmentRange(added, afterToken, afterSegments, afterIndex, run.afterStart);
1585
+ beforeIndex = run.beforeEnd;
1586
+ afterIndex = run.afterEnd;
1587
+ }
1588
+ pushTextSegmentRange(removed, beforeToken, beforeSegments, beforeIndex, beforeSegments.length);
1589
+ pushTextSegmentRange(added, afterToken, afterSegments, afterIndex, afterSegments.length);
1590
+ return removed.length > 0 || added.length > 0 ? { removed, added } : void 0;
1591
+ }
1592
+ function tokenTextGapRanges(beforeToken, afterToken, beforeStart, beforeEnd, afterStart, afterEnd) {
1593
+ const removed = beforeStart < beforeEnd ? [[beforeToken.start + beforeStart, beforeToken.start + beforeEnd]] : [];
1594
+ const added = afterStart < afterEnd ? [[afterToken.start + afterStart, afterToken.start + afterEnd]] : [];
1595
+ return removed.length > 0 || added.length > 0 ? { removed, added } : void 0;
1596
+ }
1597
+ function hasPotentialInternalCommonText(before, after, prefix, suffix) {
1598
+ const beforeMiddle = before.slice(prefix, before.length - suffix);
1599
+ const afterMiddle = after.slice(prefix, after.length - suffix);
1600
+ const [shorter, longer] = beforeMiddle.length <= afterMiddle.length ? [beforeMiddle, afterMiddle] : [afterMiddle, beforeMiddle];
1601
+ if (shorter.length < MIN_REFINED_TEXT_INTERNAL_RUN_GRAPHEMES) return false;
1602
+ for (let index = 0; index <= shorter.length - MIN_REFINED_TEXT_INTERNAL_RUN_GRAPHEMES; index++) {
1603
+ const candidate = shorter.slice(index, index + MIN_REFINED_TEXT_INTERNAL_RUN_GRAPHEMES);
1604
+ if (longer.includes(candidate)) return true;
1605
+ }
1606
+ return false;
1607
+ }
1608
+ function commonTextRuns(pairs) {
1609
+ const runs = [];
1610
+ for (const [beforeIndex, afterIndex] of pairs) {
1611
+ const previous = runs.at(-1);
1612
+ if (previous?.beforeEnd === beforeIndex && previous.afterEnd === afterIndex) {
1613
+ previous.beforeEnd++;
1614
+ previous.afterEnd++;
1615
+ } else {
1616
+ runs.push({
1617
+ beforeStart: beforeIndex,
1618
+ beforeEnd: beforeIndex + 1,
1619
+ afterStart: afterIndex,
1620
+ afterEnd: afterIndex + 1
1621
+ });
1622
+ }
1623
+ }
1624
+ return runs;
1625
+ }
1626
+ function isEdgeTextRun(run, beforeLength, afterLength) {
1627
+ return run.beforeStart === 0 && run.afterStart === 0 || run.beforeEnd === beforeLength && run.afterEnd === afterLength;
1628
+ }
1629
+ function pushTextSegmentRange(ranges, token, segments, start, end) {
1630
+ if (start >= end) return;
1631
+ ranges.push([
1632
+ token.start + textSegmentOffset(segments, start, token.value.length),
1633
+ token.start + textSegmentOffset(segments, end, token.value.length)
1634
+ ]);
1635
+ }
1636
+ function textSegmentOffset(segments, index, textLength) {
1637
+ return index === segments.length ? textLength : segmentAt(segments, index).start;
1638
+ }
1639
+ function segmentAt(segments, index) {
1640
+ const segment = segments[index];
1641
+ if (segment === void 0) throw new RangeError(`Missing text segment ${index}`);
1642
+ return segment;
1643
+ }
1644
+ function shouldRefineTokenText(before, after, prefix, suffix) {
1645
+ const sharedEdgeLength = prefix + suffix;
1646
+ if (sharedEdgeLength === 0) return false;
1647
+ if (isIdentifierToken(before) && isIdentifierToken(after)) {
1648
+ if (sharedEdgeLength < 2 && !needsBoundarySafeOffsets(before) && !needsBoundarySafeOffsets(after))
1649
+ return false;
1650
+ if (prefix === 0 && suffix > 0) {
1651
+ const beforeChangedLength = before.length - suffix;
1652
+ const afterChangedLength = after.length - suffix;
1653
+ if (beforeChangedLength !== afterChangedLength && Math.min(beforeChangedLength, afterChangedLength) < 2)
1654
+ return false;
1655
+ }
1656
+ return true;
1657
+ }
1658
+ if (isNumberToken(before) && isNumberToken(after)) return true;
1659
+ if (isMeaningfulOperatorToken(before) && isMeaningfulOperatorToken(after)) return true;
1660
+ return false;
1661
+ }
1662
+
1663
+ // src/ui/word-diff/range-refinement.ts
1664
+ var MAX_SOFT_TOKEN_ALIGNMENT_CELLS = 4096;
1665
+ var MIN_SOFT_TOKEN_SUBSTITUTION_SIMILARITY = 0.45;
1666
+ function refinedRangesForChangedTokens(beforeText, beforeTokens, afterText, afterTokens, gaps) {
1667
+ const ranges = refinedRangesForTokenGaps(beforeTokens, afterTokens, gaps);
1668
+ return {
1669
+ removed: mergeRanges(rangesAtGraphemeBoundaries(beforeText, ranges.removed)),
1670
+ added: mergeRanges(rangesAtGraphemeBoundaries(afterText, ranges.added))
1671
+ };
1672
+ }
1673
+ function refinedRangesForTokenGaps(beforeTokens, afterTokens, gaps) {
1674
+ const removed = [];
1675
+ const added = [];
1676
+ for (const gap of gaps) {
1677
+ const removedGroup = nonEmptyTokenGroup(gap.removed);
1678
+ const addedGroup = nonEmptyTokenGroup(gap.added);
1679
+ const refined = removedGroup && addedGroup ? refinedChangedTokenGroupRanges(beforeTokens, removedGroup, afterTokens, addedGroup) : void 0;
1680
+ if (refined) {
1681
+ removed.push(...refined.removed);
1682
+ added.push(...refined.added);
1683
+ continue;
1684
+ }
1685
+ if (removedGroup) removed.push(...rangesForTokenGroup(beforeTokens, removedGroup));
1686
+ if (addedGroup) added.push(...rangesForTokenGroup(afterTokens, addedGroup));
1687
+ }
1688
+ return { removed: mergeRanges(removed), added: mergeRanges(added) };
1689
+ }
1690
+ function nonEmptyTokenGroup(group) {
1691
+ return group.start < group.end ? group : void 0;
1692
+ }
1693
+ function refinedChangedTokenGroupRanges(beforeTokens, beforeGroup, afterTokens, afterGroup) {
1694
+ return refinedSingleTokenRanges(beforeTokens, beforeGroup, afterTokens, afterGroup) ?? refinedSoftTokenGroupRanges(beforeTokens, beforeGroup, afterTokens, afterGroup);
1695
+ }
1696
+ function refinedSingleTokenRanges(beforeTokens, beforeGroup, afterTokens, afterGroup) {
1697
+ if (beforeGroup.end - beforeGroup.start !== 1 || afterGroup.end - afterGroup.start !== 1)
1698
+ return void 0;
1699
+ return refinedTokenPairRanges(
1700
+ tokenAt2(beforeTokens, beforeGroup.start),
1701
+ tokenAt2(afterTokens, afterGroup.start)
1702
+ );
1703
+ }
1704
+ function refinedTokenPairRanges(beforeToken, afterToken) {
1705
+ const identifierRanges = refinedIdentifierTokenRanges(beforeToken, afterToken);
1706
+ const textRanges = refinedTokenTextRanges(beforeToken, afterToken);
1707
+ if (identifierRanges && isNarrowerThanWholeTokens(identifierRanges, beforeToken, afterToken)) {
1708
+ if (shouldSuppressUnbalancedIdentifierPartRefinement(beforeToken, afterToken, textRanges))
1709
+ return textRanges;
1710
+ if (textRanges && (textRanges.removed.length === 0 || textRanges.added.length === 0) && highlightedRangeWidth(textRanges) < highlightedRangeWidth(identifierRanges))
1711
+ return textRanges;
1712
+ return identifierRanges;
1713
+ }
1714
+ return textRanges ?? identifierRanges;
1715
+ }
1716
+ function highlightedRangeWidth(ranges) {
1717
+ let width = 0;
1718
+ for (const [start, end] of ranges.removed) width += end - start;
1719
+ for (const [start, end] of ranges.added) width += end - start;
1720
+ return width;
1721
+ }
1722
+ function shouldSuppressUnbalancedIdentifierPartRefinement(beforeToken, afterToken, textRanges) {
1723
+ if (textRanges) return false;
1724
+ if (!isIdentifierToken(beforeToken.value) || !isIdentifierToken(afterToken.value)) return false;
1725
+ const beforePartCount = splitIdentifierToken(beforeToken.value, 0).filter(
1726
+ (part) => isIdentifierSimilarityPart(part.value)
1727
+ ).length;
1728
+ const afterPartCount = splitIdentifierToken(afterToken.value, 0).filter(
1729
+ (part) => isIdentifierSimilarityPart(part.value)
1730
+ ).length;
1731
+ return Math.min(beforePartCount, afterPartCount) === 1 && beforePartCount !== afterPartCount;
1732
+ }
1733
+ function refinedSoftTokenGroupRanges(beforeTokens, beforeGroup, afterTokens, afterGroup) {
1734
+ const before = beforeTokens.slice(beforeGroup.start, beforeGroup.end);
1735
+ const after = afterTokens.slice(afterGroup.start, afterGroup.end);
1736
+ if (before.length * after.length > MAX_SOFT_TOKEN_ALIGNMENT_CELLS) return void 0;
1737
+ const pairs = softAlignedTokenPairs(before, after);
1738
+ if (pairs.length === 0) return void 0;
1739
+ const pairedBefore = /* @__PURE__ */ new Set();
1740
+ const pairedAfter = /* @__PURE__ */ new Set();
1741
+ const removed = [];
1742
+ const added = [];
1743
+ for (const [beforeIndex, afterIndex] of pairs) {
1744
+ pairedBefore.add(beforeIndex);
1745
+ pairedAfter.add(afterIndex);
1746
+ const beforeToken = tokenAt2(before, beforeIndex);
1747
+ const afterToken = tokenAt2(after, afterIndex);
1748
+ if (beforeToken.value === afterToken.value) continue;
1749
+ const refined = refinedTokenPairRanges(beforeToken, afterToken);
1750
+ if (refined) {
1751
+ removed.push(...refined.removed);
1752
+ added.push(...refined.added);
1753
+ } else {
1754
+ pushTokenRange(removed, beforeToken);
1755
+ pushTokenRange(added, afterToken);
1756
+ }
1757
+ }
1758
+ for (let index = 0; index < before.length; index++) {
1759
+ if (!pairedBefore.has(index)) pushTokenRange(removed, tokenAt2(before, index));
1760
+ }
1761
+ for (let index = 0; index < after.length; index++) {
1762
+ if (!pairedAfter.has(index)) pushTokenRange(added, tokenAt2(after, index));
1763
+ }
1764
+ const result = { removed: mergeRangesByStart(removed), added: mergeRangesByStart(added) };
1765
+ return result.removed.length > 0 || result.added.length > 0 ? result : void 0;
1766
+ }
1767
+ function softAlignedTokenPairs(before, after) {
1768
+ return suffixAlignedPairs(before.length, after.length, (beforeIndex, afterIndex) => {
1769
+ const substitution = softTokenSubstitutionWeight(
1770
+ tokenAt2(before, beforeIndex),
1771
+ tokenAt2(after, afterIndex)
1772
+ );
1773
+ return substitution > 0 ? substitution : Number.NEGATIVE_INFINITY;
1774
+ });
1775
+ }
1776
+ function softTokenSubstitutionWeight(beforeToken, afterToken) {
1777
+ if (beforeToken.value === afterToken.value) return wordEmphasisTokenWeight(beforeToken.value);
1778
+ const similarity = softTokenSimilarity(beforeToken.value, afterToken.value);
1779
+ return similarity >= MIN_SOFT_TOKEN_SUBSTITUTION_SIMILARITY ? Math.min(
1780
+ wordEmphasisTokenWeight(beforeToken.value),
1781
+ wordEmphasisTokenWeight(afterToken.value)
1782
+ ) * similarity : 0;
1783
+ }
1784
+ function softTokenSimilarity(before, after) {
1785
+ if (isIdentifierToken(before) && isIdentifierToken(after))
1786
+ return identifierTokenSimilarity(before, after);
1787
+ if (isNumberToken(before) && isNumberToken(after)) return edgeTextSimilarity(before, after);
1788
+ if (isMeaningfulOperatorToken(before) && isMeaningfulOperatorToken(after))
1789
+ return edgeTextSimilarity(before, after);
1790
+ return 0;
1791
+ }
1792
+ function identifierTokenSimilarity(before, after) {
1793
+ const beforeParts = splitIdentifierToken(before, 0).map((part) => part.value.toLowerCase()).filter(isIdentifierSimilarityPart);
1794
+ const afterParts = splitIdentifierToken(after, 0).map((part) => part.value.toLowerCase()).filter(isIdentifierSimilarityPart);
1795
+ const partSimilarity = tokenDiceSimilarity(beforeParts, afterParts);
1796
+ return Math.max(partSimilarity, edgeTextSimilarity(before, after));
1797
+ }
1798
+ function tokenDiceSimilarity(before, after) {
1799
+ if (before.length === 0 || after.length === 0) return 0;
1800
+ const remaining = /* @__PURE__ */ new Map();
1801
+ for (const token of before) remaining.set(token, (remaining.get(token) ?? 0) + 1);
1802
+ let shared = 0;
1803
+ for (const token of after) {
1804
+ const count = remaining.get(token) ?? 0;
1805
+ if (count === 0) continue;
1806
+ shared++;
1807
+ if (count === 1) remaining.delete(token);
1808
+ else remaining.set(token, count - 1);
1809
+ }
1810
+ return 2 * shared / (before.length + after.length);
1811
+ }
1812
+ function edgeTextSimilarity(before, after) {
1813
+ const prefix = commonPrefixLength(before, after);
1814
+ const suffix = commonSuffixLength(before, after, prefix);
1815
+ return 2 * (prefix + suffix) / (before.length + after.length);
1816
+ }
1817
+ function refinedIdentifierTokenRanges(beforeToken, afterToken) {
1818
+ if (!isIdentifierToken(beforeToken.value) || !isIdentifierToken(afterToken.value))
1819
+ return void 0;
1820
+ const beforeParts = splitIdentifierToken(beforeToken.value, beforeToken.start);
1821
+ const afterParts = splitIdentifierToken(afterToken.value, afterToken.start);
1822
+ if (beforeParts.length <= 1 && afterParts.length <= 1) return void 0;
1823
+ const gaps = [];
1824
+ collectChangedTokenGaps(
1825
+ beforeParts,
1826
+ 0,
1827
+ beforeParts.length,
1828
+ afterParts,
1829
+ 0,
1830
+ afterParts.length,
1831
+ gaps
1832
+ );
1833
+ const ranges = refinedRangesForTokenGaps(beforeParts, afterParts, gaps);
1834
+ return hasWordChangeRanges(ranges) ? ranges : void 0;
1835
+ }
1836
+ function isNarrowerThanWholeTokens(ranges, beforeToken, afterToken) {
1837
+ return ranges.removed.some((range) => range[0] > beforeToken.start || range[1] < beforeToken.end) || ranges.added.some((range) => range[0] > afterToken.start || range[1] < afterToken.end) || ranges.removed.length === 0 || ranges.added.length === 0;
1838
+ }
1839
+ function hasWordChangeRanges(ranges) {
1840
+ return ranges.removed.length > 0 || ranges.added.length > 0;
1841
+ }
1842
+ function tokenAt2(tokens, index) {
1843
+ const token = tokens[index];
1844
+ if (token === void 0) throw new RangeError(`Missing word-emphasis token ${index}`);
1845
+ return token;
1846
+ }
1847
+
1848
+ // src/ui/word-diff/smart-filter.ts
1849
+ function filterLowSignalWordEmphasis(before, after, ranges) {
1850
+ const hasRemovedSignal = ranges.removed.some((range) => hasSmartRangeSignal(before, range));
1851
+ const hasAddedSignal = ranges.added.some((range) => hasSmartRangeSignal(after, range));
1852
+ return {
1853
+ removed: ranges.removed.filter(
1854
+ (range) => shouldKeepSmartRange(before.slice(range[0], range[1]), hasAddedSignal)
1855
+ ),
1856
+ added: ranges.added.filter(
1857
+ (range) => shouldKeepSmartRange(after.slice(range[0], range[1]), hasRemovedSignal)
1858
+ )
1859
+ };
1860
+ }
1861
+ function hasSmartRangeSignal(content, range) {
1862
+ const tokens = wordTokenValues(content.slice(range[0], range[1]));
1863
+ return tokens.some(isSmartSignalToken);
1864
+ }
1865
+ function shouldKeepSmartRange(text, oppositeSideHasSignal) {
1866
+ const tokens = wordTokenValues(text);
1867
+ const signalTokens = tokens.filter(isSmartSignalToken);
1868
+ if (signalTokens.length === 0) return false;
1869
+ const wordTokens = signalTokens.filter(
1870
+ (token) => isIdentifierToken(token) || isNumberToken(token)
1871
+ );
1872
+ const hasIntrinsicSignal = signalTokens.some(
1873
+ (token) => isMeaningfulOperatorToken(token) || isSymbolToken(token)
1874
+ );
1875
+ if (!oppositeSideHasSignal && !hasIntrinsicSignal && wordTokens.every((token) => LOW_SIGNAL_SYNTAX_TOKENS.has(token)))
1876
+ return false;
1877
+ if (!oppositeSideHasSignal && !hasIntrinsicSignal && isWrapperCallNoise(text, wordTokens))
1878
+ return false;
1879
+ return true;
1880
+ }
1881
+ function isSmartSignalToken(token) {
1882
+ return isIdentifierToken(token) || isNumberToken(token) || isMeaningfulOperatorToken(token) || isSymbolToken(token);
1883
+ }
1884
+ var LOW_SIGNAL_SYNTAX_TOKENS = /* @__PURE__ */ new Set([
1885
+ "as",
1886
+ "const",
1887
+ "else",
1888
+ "export",
1889
+ "from",
1890
+ "function",
1891
+ "if",
1892
+ "import",
1893
+ "let",
1894
+ "var"
1895
+ ]);
1896
+ var WRAPPER_CALL_TOKENS = /* @__PURE__ */ new Set(["filter", "flatMap", "forEach", "map", "reduce"]);
1897
+ function isWrapperCallNoise(text, tokens) {
1898
+ return tokens.length === 1 && tokens[0] !== void 0 && WRAPPER_CALL_TOKENS.has(tokens[0]) && /^[\s.()[\]{};,]*[$_\p{L}][$_\p{L}\p{N}\p{Mark}]*[\s.()[\]{};,]*$/u.test(text);
1899
+ }
1900
+
1901
+ // src/ui/word-diff/emphasis.ts
1902
+ function shouldEmphasizeChangedPair(ranges, lineConfidence) {
1903
+ if (ranges.removed.length === 0 && ranges.added.length === 0) return false;
1904
+ if (lineConfidence === "low") return false;
1905
+ if (ranges.confidence === "low" && lineConfidence !== "high") return false;
1906
+ return true;
1907
+ }
1908
+ function changedRangesForTokensWithConfidence(before, after, beforeTokens, afterTokens, wordEmphasis) {
1909
+ if (wordEmphasis === "off") return emptyWordChangeRanges();
1910
+ const gaps = [];
1911
+ const alignmentConfidence = collectChangedTokenGaps(
1912
+ beforeTokens,
1913
+ 0,
1914
+ beforeTokens.length,
1915
+ afterTokens,
1916
+ 0,
1917
+ afterTokens.length,
1918
+ gaps
1919
+ );
1920
+ const ranges = refinedRangesForChangedTokens(before, beforeTokens, after, afterTokens, gaps);
1921
+ const confidence = hasWordChangeRanges2(ranges) ? alignmentConfidence : "low";
1922
+ if (wordEmphasis !== "smart") return { ...ranges, confidence };
1923
+ const filtered = filterLowSignalWordEmphasis(before, after, ranges);
1924
+ return { ...filtered, confidence: hasWordChangeRanges2(filtered) ? confidence : "low" };
1925
+ }
1926
+ function hasWordChangeRanges2(ranges) {
1927
+ return ranges.removed.length > 0 || ranges.added.length > 0;
1928
+ }
1929
+ function emptyWordChangeRanges() {
1930
+ return { removed: [], added: [], confidence: "low" };
1931
+ }
1932
+
1933
+ // src/ui/word-diff/change-block.ts
1934
+ function analyzeChangedLineBlock(block, wordEmphasis) {
1935
+ const removed = [];
1936
+ const added = [];
1937
+ for (let index = 0; index < block.length; index++) {
1938
+ const line = block[index];
1939
+ if (line === void 0) continue;
1940
+ if (isRemovedDiffLine(line)) removed.push(indexedChangedLine(index, line));
1941
+ else if (isAddedDiffLine(line)) added.push(indexedChangedLine(index, line));
1942
+ }
1943
+ const removedByIndex = new Map(removed.map((line) => [line.index, line]));
1944
+ const addedByIndex = new Map(added.map((line) => [line.index, line]));
1945
+ const pairs = matchChangedLines(removed, added);
1946
+ const ranges = [];
1947
+ for (const pair of pairs) {
1948
+ const removedLine = removedByIndex.get(pair.removedIndex);
1949
+ const addedLine = addedByIndex.get(pair.addedIndex);
1950
+ if (!removedLine || !addedLine) continue;
1951
+ ranges.push({
1952
+ pair,
1953
+ ranges: changedRangesForTokensWithConfidence(
1954
+ normalizedChangedContent(removedLine),
1955
+ normalizedChangedContent(addedLine),
1956
+ changedLineTokens(removedLine),
1957
+ changedLineTokens(addedLine),
1958
+ wordEmphasis
1959
+ )
1960
+ });
1961
+ }
1962
+ return { removed, added, pairs, ranges };
1963
+ }
1964
+
1965
+ // src/ui/word-diff/line-emphasis.ts
1966
+ var changedLineEmphasis = (block, wordEmphasis) => {
1967
+ const emphasis = /* @__PURE__ */ new Map();
1968
+ if (wordEmphasis === "off") return emphasis;
1969
+ for (const { pair, ranges } of analyzeChangedLineBlock(block, wordEmphasis).ranges) {
1970
+ if (!shouldEmphasizeChangedPair(ranges, pair.confidence)) continue;
1971
+ emphasis.set(pair.removedIndex, { ranges: ranges.removed, kind: "remove" });
1972
+ emphasis.set(pair.addedIndex, { ranges: ranges.added, kind: "add" });
1973
+ }
1974
+ return emphasis;
1975
+ };
1976
+
1977
+ // src/ui/core-tool-render.ts
1978
+ var CORE_TOOLS = /* @__PURE__ */ new Set(["bash", "powershell", "read", "write", "edit", "grep", "find", "ls"]);
1979
+ var isCoreToolAudit = (audit) => audit.tool !== void 0 && CORE_TOOLS.has(audit.tool) && (audit.provider === "pi" || audit.ref === `pi.${audit.tool}`);
1980
+ var positiveEnvInteger = (name, fallback) => {
1981
+ const parsed = Number.parseInt(process.env[name] ?? "", 10);
1982
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
1983
+ };
1984
+ var SECRET_SCAN_CHARS = positiveEnvInteger("CODE_PREVIEW_SECRET_SCAN_CHARS", 2e5);
1985
+ var MAX_HIGHLIGHT_CHARS = positiveEnvInteger("CODE_PREVIEW_MAX_HIGHLIGHT_CHARS", 8e4);
1986
+ var CONTENT_LANGUAGE_DETECTION_CHARS = positiveEnvInteger(
1987
+ "CODE_PREVIEW_CONTENT_LANGUAGE_DETECTION_CHARS",
1988
+ 5e4
1989
+ );
1990
+ var recordOf = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1991
+ var stringOf = (value) => typeof value === "string" ? value : void 0;
1992
+ var numberOf = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1993
+ var argString = (audit, key) => stringOf(audit.args?.[key]);
1994
+ var escapeControlChars2 = (text) => text.replace(/\x1b/g, "\u241B").replace(/\r/g, "\u240D").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, "\uFFFD");
1995
+ var expandTabs = (text) => text.replace(/\t/g, " ");
1996
+ var formatBytes = (bytes) => {
1997
+ if (bytes < 1024) return `${bytes} B`;
1998
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
1999
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2000
+ };
2001
+ var countLabel = (count, singular) => `${count} ${count === 1 ? singular : `${singular}s`}`;
2002
+ var metadata = (theme, values) => {
2003
+ const present = values.filter((value) => Boolean(value));
2004
+ return present.length > 0 ? theme.fg("dim", ` \xB7 ${present.join(" \xB7 ")}`) : "";
2005
+ };
2006
+ var formatDisplayPath = (filePath, cwd) => {
2007
+ if (!filePath) return "";
2008
+ if (isAbsolute(filePath)) {
2009
+ const fromCwd = relative(cwd, filePath);
2010
+ if (fromCwd && fromCwd !== ".." && !fromCwd.startsWith("../") && !isAbsolute(fromCwd)) {
2011
+ return fromCwd;
2012
+ }
2013
+ if (!fromCwd) return ".";
2014
+ const fromHome = relative(homedir(), filePath);
2015
+ if (fromHome && fromHome !== ".." && !fromHome.startsWith("../") && !isAbsolute(fromHome)) {
2016
+ return `~/${fromHome}`;
2017
+ }
2018
+ if (!fromHome) return "~";
2019
+ }
2020
+ return filePath;
2021
+ };
2022
+ var renderPath = (filePath, cwd, theme, fallback = "...") => theme.fg("accent", escapeControlChars2(formatDisplayPath(filePath, cwd) || fallback));
2023
+ var normalizedResult = (audit) => {
2024
+ const preview = recordOf(audit.preview);
2025
+ return preview && "result" in preview ? preview.result : audit.result;
2026
+ };
2027
+ var contentOutput = (value) => {
2028
+ if (typeof value === "string") return value;
2029
+ if (!Array.isArray(value)) return void 0;
2030
+ const text = value.flatMap((part) => {
2031
+ const record = recordOf(part);
2032
+ return record?.type === "text" && typeof record.text === "string" ? [record.text] : [];
2033
+ }).join("\n");
2034
+ return text || void 0;
2035
+ };
2036
+ var resultOutput = (audit) => {
2037
+ const result = normalizedResult(audit);
2038
+ if (typeof result === "string") return result;
2039
+ const record = recordOf(result);
2040
+ return stringOf(record?.output) ?? stringOf(record?.text) ?? contentOutput(record?.content);
2041
+ };
2042
+ var resultDetails = (audit) => {
2043
+ const preview = recordOf(audit.preview);
2044
+ const previewDetails = recordOf(preview?.details);
2045
+ if (previewDetails) return previewDetails;
2046
+ return recordOf(recordOf(normalizedResult(audit))?.details);
2047
+ };
2048
+ var nativeTruncated = (audit) => {
2049
+ const truncation = recordOf(resultDetails(audit)?.truncation);
2050
+ return truncation?.truncated === true || audit.resultTruncated === true;
2051
+ };
2052
+ var READ_CONTINUATION_NOTICE = /^\[(?:Showing lines \d+-\d+ of \d+(?: \([^)]+\))?|\d+ more lines in file)\. Use offset=\d+ to continue\.\]$/;
2053
+ var splitReadContinuationNotice = (text) => {
2054
+ const match = /^(.*?)(?:\r?\n){2}(\[[^\r\n]+\])$/s.exec(text);
2055
+ const notice = match?.[2];
2056
+ if (!match || !notice || !READ_CONTINUATION_NOTICE.test(notice)) return { content: text };
2057
+ return { content: match[1] ?? "", notice: notice.slice(1, -1) };
2058
+ };
2059
+ var toolLimit = (audit, options) => {
2060
+ if (options.expanded) return options.maxLines;
2061
+ const configured = (() => {
2062
+ switch (audit.tool) {
2063
+ case "read":
2064
+ return options.settings.readCollapsedLines;
2065
+ case "write":
2066
+ return options.settings.writeCollapsedLines;
2067
+ case "edit":
2068
+ return options.settings.editCollapsedLines === "all" ? options.maxLines : options.settings.editCollapsedLines;
2069
+ case "grep":
2070
+ return options.settings.grepCollapsedLines;
2071
+ case "find":
2072
+ case "ls":
2073
+ return options.settings.pathListCollapsedLines;
2074
+ case "bash":
2075
+ case "powershell":
2076
+ return 8;
2077
+ default:
2078
+ return options.maxLines;
2079
+ }
2080
+ })();
2081
+ return Math.max(1, Math.min(configured, options.maxLines));
2082
+ };
2083
+ var previewEntries = (lines, limit) => {
2084
+ if (limit <= 0 || lines.length <= limit) {
2085
+ return { entries: lines.map((line, index) => ({ kind: "line", line, index })), hidden: 0 };
2086
+ }
2087
+ if (limit < 8) {
2088
+ return {
2089
+ entries: lines.slice(0, limit).map((line, index) => ({ kind: "line", line, index })),
2090
+ hidden: lines.length - limit
2091
+ };
2092
+ }
2093
+ const head = Math.ceil(limit * 0.65);
2094
+ const tail = Math.max(1, limit - head - 1);
2095
+ const hidden = lines.length - head - tail;
2096
+ return {
2097
+ entries: [
2098
+ ...lines.slice(0, head).map((line, index) => ({ kind: "line", line, index })),
2099
+ { kind: "hidden", hidden },
2100
+ ...lines.slice(-tail).map((line, offset) => ({
2101
+ kind: "line",
2102
+ line,
2103
+ index: lines.length - tail + offset
2104
+ }))
2105
+ ],
2106
+ hidden
2107
+ };
2108
+ };
2109
+ var secretWarnings = (source) => {
2110
+ if (!source) return [];
2111
+ const sample = source.length <= SECRET_SCAN_CHARS ? source : `${source.slice(0, SECRET_SCAN_CHARS / 2)}
2112
+ ${source.slice(-SECRET_SCAN_CHARS / 2)}`;
2113
+ const warnings = [
2114
+ ["private key", /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
2115
+ ["AWS secret key", /\bAWS_SECRET_ACCESS_KEY\s*=\s*["']?[^\s'"]{12,}/i],
2116
+ [
2117
+ "API key",
2118
+ /\b(?:OPENAI|ANTHROPIC|GOOGLE|GEMINI|MISTRAL|GROQ|TOGETHER|PERPLEXITY|XAI)_API_KEY\s*=\s*["']?[^\s'"]{12,}/i
2119
+ ],
2120
+ ["GitHub token", /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{20,}\b/],
2121
+ ["JWT", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/]
2122
+ ];
2123
+ return warnings.filter(([, pattern]) => pattern.test(sample)).map(([label]) => label);
2124
+ };
2125
+ var warningLine = (source, options, theme) => {
2126
+ if (!options.settings.secretWarnings) return void 0;
2127
+ const warnings = secretWarnings(source);
2128
+ return warnings.length > 0 ? theme.fg("warning", `\u26A0 Preview ${countLabel(warnings.length, "warning")}: possible ${warnings.join(", ")}`) : void 0;
2129
+ };
2130
+ var resolveLanguage = (filePath, content) => {
2131
+ const fromPath = languageFromPath(filePath);
2132
+ if (fromPath) return fromPath;
2133
+ const firstLine = content?.split("\n", 1)[0]?.trim();
2134
+ if (firstLine?.startsWith("#!")) {
2135
+ const parts = firstLine.replace(/^#!\s*/, "").split(/\s+/).filter(Boolean);
2136
+ const envIndex = parts.findIndex((part) => part.split("/").at(-1) === "env");
2137
+ const command = envIndex >= 0 ? parts.slice(envIndex + 1).find((part) => !part.startsWith("-")) : parts[0];
2138
+ const executable = command?.split("/").at(-1)?.toLowerCase().replace(/\d+(?:\.\d+)?$/, "");
2139
+ const shebang = {
2140
+ bash: "bash",
2141
+ sh: "bash",
2142
+ zsh: "bash",
2143
+ python: "python",
2144
+ node: "javascript",
2145
+ deno: "typescript",
2146
+ ruby: "ruby",
2147
+ php: "php"
2148
+ };
2149
+ const language = executable ? shebang[executable] : void 0;
2150
+ if (language && language in bundledLanguages) return language;
2151
+ }
2152
+ if (!content || content.length > CONTENT_LANGUAGE_DETECTION_CHARS) return void 0;
2153
+ const trimmed = content.trim();
2154
+ if (!trimmed) return void 0;
2155
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2156
+ try {
2157
+ JSON.parse(trimmed);
2158
+ return "json";
2159
+ } catch {
2160
+ }
2161
+ }
2162
+ if (/^<(!doctype\s+html|html)(\s|>)/i.test(trimmed)) return "html";
2163
+ if (/^<\?xml\s/i.test(trimmed)) return "xml";
2164
+ return void 0;
2165
+ };
2166
+ var BASH_TRUNCATION_NOTICE = /^\[Showing (?:last [^\r\n]+ of line \d+ \(line is [^)]+\)|lines \d+-\d+ of \d+(?: \([^)]+ limit\))?)\. Full output: [^\r\n]+\]$/;
2167
+ var isBashTruncationNotice = (line) => BASH_TRUNCATION_NOTICE.test(line);
2168
+ var renderContent = (content, filePath, theme, options, config) => {
2169
+ const limit = toolLimit({ ref: "", tool: config.lineNumbers ? "read" : "write" }, options);
2170
+ const selected = selectPreviewTextLines(content, limit);
2171
+ if (selected.total === 0) {
2172
+ return { lines: [theme.fg("muted", config.emptyLabel)], hidden: 0 };
2173
+ }
2174
+ const skipHighlight = options.settings.syntaxHighlighting && content.length > MAX_HIGHLIGHT_CHARS;
2175
+ const language = options.settings.syntaxHighlighting && !skipHighlight ? resolveLanguage(filePath, content) : void 0;
2176
+ const rendered = [];
2177
+ const warning = warningLine(content, options, theme);
2178
+ if (warning) rendered.push(warning);
2179
+ const absoluteFilePath = language && filePath ? resolve(options.cwd, filePath) : void 0;
2180
+ let chunk = [];
2181
+ const flush = () => {
2182
+ if (chunk.length === 0) return;
2183
+ const normalized = chunk.map((entry) => expandTabs(escapeControlChars2(entry.line)));
2184
+ const first = chunk[0];
2185
+ const from = (config.firstLine ?? 1) - 1 + first.index;
2186
+ const fileLines = absoluteFilePath && language && first.index + chunk.length <= selected.total ? highlightFileLines(
2187
+ absoluteFilePath,
2188
+ language,
2189
+ from,
2190
+ from + chunk.length,
2191
+ options.invalidate
2192
+ ) : null;
2193
+ const fileVerified = fileLines !== null && fileLines.every((line, index) => line.raw === normalized[index]);
2194
+ const highlighted = fileVerified ? fileLines.map((line) => line.ansi) : language ? highlightCode(normalized.join("\n"), language, options.invalidate) : null;
2195
+ const width = String((config.firstLine ?? 1) + selected.total - 1).length;
2196
+ for (let index = 0; index < chunk.length; index++) {
2197
+ const entry = chunk[index];
2198
+ const text = highlighted?.[index] ?? theme.fg("toolOutput", normalized[index] || " ");
2199
+ if (config.lineNumbers) {
2200
+ const lineNumber = String((config.firstLine ?? 1) + entry.index).padStart(width, " ");
2201
+ rendered.push(`${theme.fg("dim", `${lineNumber} \u2502 `)}${text}`);
2202
+ } else {
2203
+ rendered.push(text);
2204
+ }
2205
+ }
2206
+ chunk = [];
2207
+ };
2208
+ for (const entry of selected.entries) {
2209
+ if (entry.kind === "hidden") {
2210
+ flush();
2211
+ rendered.push(theme.fg("muted", ` --- ${entry.hidden} lines hidden ---`));
2212
+ } else if (isBashTruncationNotice(entry.line)) {
2213
+ flush();
2214
+ const notice = theme.fg("muted", escapeControlChars2(entry.line));
2215
+ if (config.lineNumbers) {
2216
+ const width = String((config.firstLine ?? 1) + selected.total - 1).length;
2217
+ const lineNumber = String((config.firstLine ?? 1) + entry.index).padStart(width, " ");
2218
+ rendered.push(`${theme.fg("dim", `${lineNumber} \u2502 `)}${notice}`);
2219
+ } else {
2220
+ rendered.push(notice);
2221
+ }
2222
+ } else {
2223
+ chunk.push({ line: entry.line, index: entry.index });
2224
+ }
2225
+ }
2226
+ flush();
2227
+ if (skipHighlight) pushArcItem(rendered, arcItem(theme, config.skipLabel));
2228
+ return { lines: rendered, hidden: selected.hidden };
2229
+ };
2230
+ var firstShellCommandName = (command) => {
2231
+ const words = [];
2232
+ let index = 0;
2233
+ while (index < command.length && words.length < 8) {
2234
+ while (index < command.length && /\s/.test(command[index] ?? "")) index++;
2235
+ if (index >= command.length || "|&;()<>{}".includes(command[index] ?? "")) break;
2236
+ let word = "";
2237
+ while (index < command.length) {
2238
+ const character = command[index] ?? "";
2239
+ if (/\s/.test(character) || "|&;()<>{}".includes(character)) break;
2240
+ if (character === "'" || character === '"') {
2241
+ const quote = character;
2242
+ index++;
2243
+ while (index < command.length && command[index] !== quote) {
2244
+ if (quote === '"' && command[index] === "\\") index++;
2245
+ word += command[index] ?? "";
2246
+ index++;
2247
+ }
2248
+ if (index < command.length) index++;
2249
+ continue;
2250
+ }
2251
+ if (character === "\\") {
2252
+ index++;
2253
+ word += command[index] ?? "";
2254
+ index++;
2255
+ continue;
2256
+ }
2257
+ word += character;
2258
+ index++;
2259
+ }
2260
+ if (word) words.push(word);
2261
+ }
2262
+ const commandWord = words.find((word) => !/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(word));
2263
+ return commandWord?.split("/").at(-1);
2264
+ };
2265
+ var bashWarnings = (command) => {
2266
+ const compact = command.replace(/\\\n/g, " ").replace(/\s+/g, " ").trim();
2267
+ const warnings = [
2268
+ [
2269
+ "recursive delete",
2270
+ /\brm\b(?=[^;&|]*(?:-[\w-]*r[\w-]*|--recursive)\b)(?=[^;&|]*(?:-[\w-]*f[\w-]*|--force)\b)/i
2271
+ ],
2272
+ ["elevated privileges", /(^|[;&|]\s*)sudo\b/],
2273
+ ["recursive permission change", /\bchmod\s+(?:-[\w-]*R|--recursive)\b/],
2274
+ ["recursive ownership change", /\bchown\s+(?:-[\w-]*R|--recursive)\b/],
2275
+ ["searches entire filesystem", /\bfind\b(?:\s+-[\w-]+)*\s+\/+(?=\s|$)/],
2276
+ ["searches entire home directory", /\bfind\b(?:\s+-[\w-]+)*\s+~\/?(?=\s|$)/],
2277
+ ["discards git changes", /\bgit\s+reset\s+--hard\b/],
2278
+ ["removes untracked files", /\bgit\s+clean\s+-[\w-]*[fd][\w-]*\b/],
2279
+ ["removes Docker data", /\bdocker\s+system\s+prune\b/],
2280
+ ["writes to a system path", />{1,2}\s*\/?(?:etc|bin|sbin|usr|var|System|Library)\b/]
2281
+ ];
2282
+ return warnings.filter(([, pattern]) => pattern.test(compact)).map(([label]) => label);
2283
+ };
2284
+ var injectVisibleRanges = (ansi, ranges, open, close) => {
2285
+ const sorted = ranges.filter(([start, end]) => end > start).sort((a, b) => a[0] - b[0]);
2286
+ let out = "";
2287
+ let visible = 0;
2288
+ let active = false;
2289
+ let rangeIndex = 0;
2290
+ for (let index = 0; index < ansi.length; index++) {
2291
+ if (ansi[index] === "\x1B" && ansi[index + 1] === "[") {
2292
+ const end = ansi.indexOf("m", index + 2);
2293
+ if (end >= 0) {
2294
+ const sequence = ansi.slice(index, end + 1);
2295
+ out += sequence;
2296
+ if (active && (sequence === "\x1B[39m" || sequence === "\x1B[22m")) out += open;
2297
+ index = end;
2298
+ continue;
2299
+ }
2300
+ }
2301
+ while (rangeIndex < sorted.length && visible >= sorted[rangeIndex][1]) {
2302
+ if (active) out += close;
2303
+ active = false;
2304
+ rangeIndex++;
2305
+ }
2306
+ const range = sorted[rangeIndex];
2307
+ if (!active && range && visible >= range[0] && visible < range[1]) {
2308
+ out += open;
2309
+ active = true;
2310
+ }
2311
+ out += ansi[index];
2312
+ visible++;
2313
+ }
2314
+ if (active) out += close;
2315
+ return out;
2316
+ };
2317
+ var wordEmphasisFor = (parsed, mode) => {
2318
+ const emphasis = /* @__PURE__ */ new Map();
2319
+ let start = 0;
2320
+ while (start < parsed.length) {
2321
+ if (!parsed[start] || parsed[start].kind === " ") {
2322
+ start++;
2323
+ continue;
2324
+ }
2325
+ let end = start;
2326
+ while (end < parsed.length && parsed[end] && parsed[end].kind !== " ") end++;
2327
+ const block = parsed.slice(start, end);
2328
+ for (const [index, value] of changedLineEmphasis(block, mode)) {
2329
+ emphasis.set(start + index, value);
2330
+ }
2331
+ start = end;
2332
+ }
2333
+ return emphasis;
2334
+ };
2335
+ var summarizeDiff = (diff) => {
2336
+ let additions = 0;
2337
+ let removals = 0;
2338
+ let replacements = 0;
2339
+ let insertions = 0;
2340
+ let deletions = 0;
2341
+ let hunks = 0;
2342
+ let groupAdditions = 0;
2343
+ let groupRemovals = 0;
2344
+ const flush = () => {
2345
+ if (groupAdditions === 0 && groupRemovals === 0) return;
2346
+ hunks++;
2347
+ if (groupAdditions > 0 && groupRemovals > 0) {
2348
+ replacements++;
2349
+ insertions += Math.max(0, groupAdditions - groupRemovals);
2350
+ deletions += Math.max(0, groupRemovals - groupAdditions);
2351
+ } else if (groupAdditions > 0) insertions += groupAdditions;
2352
+ else deletions += groupRemovals;
2353
+ groupAdditions = 0;
2354
+ groupRemovals = 0;
2355
+ };
2356
+ const lines = diff.split("\n");
2357
+ for (const line of lines) {
2358
+ if (line.startsWith("+") && !line.startsWith("+++")) {
2359
+ additions++;
2360
+ groupAdditions++;
2361
+ } else if (line.startsWith("-") && !line.startsWith("---")) {
2362
+ removals++;
2363
+ groupRemovals++;
2364
+ } else {
2365
+ flush();
2366
+ }
2367
+ }
2368
+ flush();
2369
+ return { additions, removals, replacements, insertions, deletions, totalLines: lines.length, hunks };
2370
+ };
2371
+ var describeDiffShape = (summary) => {
2372
+ const parts = [];
2373
+ if (summary.replacements > 0) parts.push(countLabel(summary.replacements, "replacement"));
2374
+ if (summary.insertions > 0) parts.push(countLabel(summary.insertions, "insertion"));
2375
+ if (summary.deletions > 0) parts.push(countLabel(summary.deletions, "deletion"));
2376
+ return parts.length > 0 ? parts.join(", ") : "changes";
2377
+ };
2378
+ var createSimpleDiff = (before, after) => {
2379
+ const changes = diffLines(before, after);
2380
+ const hasChangeAfter = changes.map(() => false);
2381
+ let futureChange = false;
2382
+ for (let index = changes.length - 1; index >= 0; index--) {
2383
+ hasChangeAfter[index] = futureChange;
2384
+ const change = changes[index];
2385
+ if (change.added || change.removed) futureChange = true;
2386
+ }
2387
+ const out = [];
2388
+ let oldLine = 1;
2389
+ let newLine = 1;
2390
+ let changed = false;
2391
+ let firstChangedLine = 1;
2392
+ const context = 3;
2393
+ const contextLines = (lines, oldStart) => lines.map((line, offset) => ` ${oldStart + offset} ${line}`);
2394
+ for (let index = 0; index < changes.length; index++) {
2395
+ const change = changes[index];
2396
+ const lines = change.value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
2397
+ if (lines.at(-1) === "") lines.pop();
2398
+ if (!change.added && !change.removed) {
2399
+ const later = hasChangeAfter[index] ?? false;
2400
+ if (!changed && later) {
2401
+ const start = Math.max(0, lines.length - context);
2402
+ out.push(...contextLines(lines.slice(start), oldLine + start));
2403
+ } else if (changed) {
2404
+ if (later && lines.length > context * 2) {
2405
+ out.push(...contextLines(lines.slice(0, context), oldLine));
2406
+ out.push("...");
2407
+ out.push(...contextLines(lines.slice(-context), oldLine + lines.length - context));
2408
+ } else {
2409
+ out.push(...contextLines(lines.slice(0, later ? lines.length : context), oldLine));
2410
+ }
2411
+ }
2412
+ oldLine += lines.length;
2413
+ newLine += lines.length;
2414
+ continue;
2415
+ }
2416
+ if (!changed) firstChangedLine = newLine;
2417
+ changed = true;
2418
+ for (const line of lines) {
2419
+ if (change.removed) out.push(`-${oldLine++} ${line}`);
2420
+ else out.push(`+${newLine++} ${line}`);
2421
+ }
2422
+ }
2423
+ return out.length > 0 ? [`@@ ${firstChangedLine} @@`, ...out].join("\n") : "";
2424
+ };
2425
+ var hashSourceText = (value) => {
2426
+ let hash = 5381;
2427
+ for (let index = 0; index < value.length; index++) {
2428
+ hash = (hash << 5) + hash + value.charCodeAt(index) | 0;
2429
+ }
2430
+ return hash;
2431
+ };
2432
+ var DIFF_REMOVED_CONTEXT_LINES = 512;
2433
+ var postEditFileRows = (parsed) => {
2434
+ const rows = [];
2435
+ let lineDelta = 0;
2436
+ for (let index = 0; index < parsed.length; index++) {
2437
+ const line = parsed[index];
2438
+ if (!line) continue;
2439
+ const lineNumber = Number.parseInt(line.lineNumber.trim(), 10);
2440
+ if (line.kind === "+") {
2441
+ if (Number.isFinite(lineNumber) && lineNumber > 0) rows.push({ index, lineNumber });
2442
+ lineDelta++;
2443
+ } else if (line.kind === "-") {
2444
+ lineDelta--;
2445
+ } else if (Number.isFinite(lineNumber)) {
2446
+ const translated = lineNumber + lineDelta;
2447
+ if (translated > 0) rows.push({ index, lineNumber: translated });
2448
+ }
2449
+ }
2450
+ return rows;
2451
+ };
2452
+ var highlightRemovedDiffLines = (parsed, filePath, language, cwd, invalidate) => {
2453
+ let start = 0;
2454
+ while (start < parsed.length && !parsed[start]) start++;
2455
+ let end = start;
2456
+ while (end < parsed.length && parsed[end]) end++;
2457
+ const block = parsed.slice(start, end);
2458
+ const removed = [];
2459
+ const contextBefore = [];
2460
+ for (let offset = 0; offset < block.length; offset++) {
2461
+ const line = block[offset];
2462
+ const n = Number.parseInt(line.lineNumber.trim(), 10);
2463
+ if (!Number.isFinite(n) || n <= 0) continue;
2464
+ if (line.kind === "-") removed.push({ row: start + offset, n, content: expandTabs(line.content) });
2465
+ else if (line.kind === " " && removed.length === 0) contextBefore.push({ n, content: expandTabs(line.content) });
2466
+ }
2467
+ if (removed.length === 0) return null;
2468
+ for (let index = 1; index < removed.length; index++) {
2469
+ if (removed[index].n !== removed[index - 1].n + 1) return null;
2470
+ }
2471
+ const firstRemoved = removed[0].n;
2472
+ for (let index = 1; index < contextBefore.length; index++) {
2473
+ if (contextBefore[index].n !== contextBefore[index - 1].n + 1) return null;
2474
+ }
2475
+ if (contextBefore.length > 0 && contextBefore[contextBefore.length - 1].n !== firstRemoved - 1) {
2476
+ return null;
2477
+ }
2478
+ const anchor = contextBefore.length > 0 ? contextBefore[0].n : firstRemoved;
2479
+ const absolute = resolve(cwd, filePath);
2480
+ let stat;
2481
+ try {
2482
+ stat = statSync(absolute);
2483
+ } catch {
2484
+ return null;
2485
+ }
2486
+ if (!stat.isFile() || stat.size > MAX_HIGHLIGHT_CHARS) return null;
2487
+ let text;
2488
+ try {
2489
+ text = readFileSync(absolute, "utf8");
2490
+ } catch {
2491
+ return null;
2492
+ }
2493
+ if (text.includes("\0")) return null;
2494
+ const fileLines = text.replace(/\r\n?/g, "\n").split("\n").map(expandTabs);
2495
+ for (const line of block) {
2496
+ if (line.kind !== " ") continue;
2497
+ const n = Number.parseInt(line.lineNumber.trim(), 10);
2498
+ if (!Number.isFinite(n)) continue;
2499
+ if (fileLines[n - 1] !== expandTabs(line.content)) return null;
2500
+ }
2501
+ const prefixCount = Math.max(0, Math.min(anchor - 1, DIFF_REMOVED_CONTEXT_LINES));
2502
+ const prefix = fileLines.slice(anchor - 1 - prefixCount, anchor - 1);
2503
+ const removedContents = removed.map((row) => row.content);
2504
+ const contextContents = contextBefore.map((context) => context.content);
2505
+ const virtual = [...prefix, ...contextContents, ...removedContents];
2506
+ const cacheKey = `removed\0${language}\0${absolute}\0${hashSourceText(virtual.join("\n"))}`;
2507
+ const covered = highlightSourceLines(
2508
+ cacheKey,
2509
+ virtual,
2510
+ language,
2511
+ prefixCount,
2512
+ virtual.length,
2513
+ invalidate
2514
+ );
2515
+ if (!covered) return null;
2516
+ const out = /* @__PURE__ */ new Map();
2517
+ for (let index = 0; index < removed.length; index++) {
2518
+ const entry = covered[contextContents.length + index];
2519
+ if (entry && entry.raw === removed[index].content) out.set(removed[index].row, entry.ansi);
2520
+ }
2521
+ return out;
2522
+ };
2523
+ var renderDiff = (diff, filePath, theme, options, limitOverride) => {
2524
+ if (!diff) return { lines: [], hidden: 0 };
2525
+ const sourceLines = diff.split("\n");
2526
+ const limit = Math.max(1, Math.min(limitOverride ?? toolLimit({ ref: "", tool: "edit" }, options), options.maxLines));
2527
+ const shown = sourceLines.slice(0, limit);
2528
+ const hidden = sourceLines.length - shown.length;
2529
+ const parsed = shown.map(parseDiffLine);
2530
+ const width = diffLineNumberWidth(parsed);
2531
+ const skipHighlight = options.settings.syntaxHighlighting && diff.length > MAX_HIGHLIGHT_CHARS;
2532
+ const language = options.settings.syntaxHighlighting && !skipHighlight ? resolveLanguage(filePath) : void 0;
2533
+ const highlighted = Array.from({ length: shown.length }, () => void 0);
2534
+ if (language) {
2535
+ if (filePath) {
2536
+ const numbered = postEditFileRows(parsed);
2537
+ if (numbered.length > 0) {
2538
+ let from = numbered[0].lineNumber;
2539
+ let to = from;
2540
+ for (let index = 1; index < numbered.length; index++) {
2541
+ const lineNumber = numbered[index].lineNumber;
2542
+ from = Math.min(from, lineNumber);
2543
+ to = Math.max(to, lineNumber);
2544
+ }
2545
+ from--;
2546
+ to++;
2547
+ const slice = highlightFileLines(
2548
+ resolve(options.cwd, filePath),
2549
+ language,
2550
+ from,
2551
+ to,
2552
+ options.invalidate
2553
+ );
2554
+ if (slice) {
2555
+ for (const row of numbered) {
2556
+ const entry = slice[row.lineNumber - 1 - from];
2557
+ if (entry && entry.raw === expandTabs(parsed[row.index].content)) {
2558
+ highlighted[row.index] = entry.ansi;
2559
+ }
2560
+ }
2561
+ }
2562
+ }
2563
+ const removedHighlighted = highlightRemovedDiffLines(
2564
+ parsed,
2565
+ filePath,
2566
+ language,
2567
+ options.cwd,
2568
+ options.invalidate
2569
+ );
2570
+ if (removedHighlighted) {
2571
+ for (const [row, ansi] of removedHighlighted) {
2572
+ if (highlighted[row] === void 0) highlighted[row] = ansi;
2573
+ }
2574
+ }
2575
+ }
2576
+ let start = 0;
2577
+ while (start < parsed.length) {
2578
+ if (!parsed[start] || highlighted[start] !== void 0) {
2579
+ start++;
2580
+ continue;
2581
+ }
2582
+ let end = start;
2583
+ while (end < parsed.length && parsed[end] && highlighted[end] === void 0) end++;
2584
+ const oldOffsets = [];
2585
+ const newOffsets = [];
2586
+ const oldContent = [];
2587
+ const newContent = [];
2588
+ for (let offset = start; offset < end; offset++) {
2589
+ const line = parsed[offset];
2590
+ const content = expandTabs(line.content);
2591
+ if (line.kind !== "+") {
2592
+ oldOffsets.push(offset);
2593
+ oldContent.push(content);
2594
+ }
2595
+ if (line.kind !== "-") {
2596
+ newOffsets.push(offset);
2597
+ newContent.push(content);
2598
+ }
2599
+ }
2600
+ const oldRendered = oldContent.length ? highlightCode(oldContent.join("\n"), language, options.invalidate) : null;
2601
+ if (oldRendered) {
2602
+ for (let index = 0; index < oldOffsets.length; index++) {
2603
+ highlighted[oldOffsets[index]] = oldRendered[index];
2604
+ }
2605
+ }
2606
+ const newRendered = newContent.length ? highlightCode(newContent.join("\n"), language, options.invalidate) : null;
2607
+ if (newRendered) {
2608
+ for (let index = 0; index < newOffsets.length; index++) {
2609
+ highlighted[newOffsets[index]] = newRendered[index];
2610
+ }
2611
+ }
2612
+ start = end;
2613
+ }
2614
+ }
2615
+ const emphasis = wordEmphasisFor(parsed, options.settings.wordEmphasis);
2616
+ const emphasisColors = effectiveShikiThemeIsLight() ? { add: "\x1B[48;2;194;209;194m", remove: "\x1B[48;2;216;182;182m" } : { add: "\x1B[48;2;64;132;82m", remove: "\x1B[48;2;148;62;70m" };
2617
+ const lines = shown.map((raw, index) => {
2618
+ const line = parsed[index];
2619
+ if (!line) {
2620
+ const safe = escapeControlChars2(raw);
2621
+ const trimmed = safe.trim();
2622
+ if (trimmed === "...") return theme.fg("muted", " --- unchanged lines hidden ---");
2623
+ if (trimmed.startsWith("@@")) return theme.fg("accent", theme.bold(safe));
2624
+ if (trimmed.startsWith("---") || trimmed.startsWith("+++") || trimmed.startsWith("diff ") || trimmed.startsWith("index ")) {
2625
+ return theme.fg("muted", safe);
2626
+ }
2627
+ return theme.fg("toolDiffContext", safe);
2628
+ }
2629
+ const truncationNotice = isBashTruncationNotice(line.content);
2630
+ let content = truncationNotice ? theme.fg("muted", escapeControlChars2(line.content)) : highlighted[index] ?? theme.fg("toolOutput", escapeControlChars2(expandTabs(line.content)) || " ");
2631
+ const match = truncationNotice ? void 0 : emphasis.get(index);
2632
+ if (match && match.ranges.length > 0) {
2633
+ content = injectVisibleRanges(
2634
+ content,
2635
+ match.ranges,
2636
+ match.kind === "add" ? emphasisColors.add : emphasisColors.remove,
2637
+ "\x1B[49m"
2638
+ );
2639
+ }
2640
+ const lineNumber = formatDiffLineNumber(line.lineNumber, width);
2641
+ if (line.kind === "+") {
2642
+ return markDiffLine("add", `${theme.fg("toolDiffAdded", `+${lineNumber} \u2502 `)}${content}`);
2643
+ }
2644
+ if (line.kind === "-") {
2645
+ return markDiffLine("remove", `${theme.fg("toolDiffRemoved", `-${lineNumber} \u2502 `)}${content}`);
2646
+ }
2647
+ return `\x1B[2m${theme.fg("toolDiffContext", ` ${lineNumber} \u2502 `)}${content}\x1B[22m`;
2648
+ });
2649
+ if (skipHighlight) {
2650
+ pushArcItem(lines, arcItem(theme, "Syntax highlighting skipped for large diff"));
2651
+ }
2652
+ return { lines, hidden };
2653
+ };
2654
+ var renderRead = (audit, theme, options) => {
2655
+ if (!options.expanded && !options.settings.readContentPreview) return null;
2656
+ const output = resultOutput(audit);
2657
+ if (output === void 0) return null;
2658
+ const filePath = argString(audit, "path") ?? "";
2659
+ if (/^Read image file/i.test(output)) {
2660
+ return { lines: [theme.fg("dim", escapeControlChars2(output))], hidden: 0 };
2661
+ }
2662
+ const truncated = nativeTruncated(audit);
2663
+ const { content, notice } = truncated || typeof audit.args?.limit === "number" ? splitReadContinuationNotice(output) : { content: output };
2664
+ const rendered = renderContent(content, filePath, theme, options, {
2665
+ lineNumbers: options.settings.readLineNumbers,
2666
+ firstLine: Math.max(1, Math.floor(numberOf(audit.args?.offset) ?? 1)),
2667
+ emptyLabel: "Empty file",
2668
+ skipLabel: "Syntax highlighting skipped for large file"
2669
+ });
2670
+ if (notice) pushArcItem(rendered.lines, arcItem(theme, notice));
2671
+ else if (truncated) pushArcItem(rendered.lines, arcItem(theme, "Output truncated by read"));
2672
+ return rendered;
2673
+ };
2674
+ var getWriteBefore = (audit) => {
2675
+ const details = resultDetails(audit);
2676
+ return details?.codePreviewBeforeWrite ?? recordOf(audit.preview)?.codePreviewBeforeWrite;
2677
+ };
2678
+ var bashCommand = (audit) => stringOf(recordOf(audit.preview)?.bashCommand) ?? argString(audit, "command") ?? "";
2679
+ var writeContent = (audit) => stringOf(recordOf(audit.preview)?.writeContent) ?? argString(audit, "content");
2680
+ var renderWrite = (audit, theme, options) => {
2681
+ if (!options.expanded && !options.settings.writeContentPreview) return null;
2682
+ const content = writeContent(audit);
2683
+ if (content === void 0) return null;
2684
+ const filePath = argString(audit, "path") ?? "";
2685
+ const before = getWriteBefore(audit);
2686
+ const beforeRecord = recordOf(before);
2687
+ if (audit.success === true && beforeRecord?.kind === "content") {
2688
+ const beforeContent = stringOf(beforeRecord.content);
2689
+ if (beforeContent === void 0) {
2690
+ return {
2691
+ lines: [
2692
+ theme.fg("success", "\u2713 Write applied") + theme.fg("muted", " \xB7 previous content unavailable")
2693
+ ],
2694
+ hidden: 0
2695
+ };
2696
+ }
2697
+ if (beforeContent === content) {
2698
+ return { lines: [theme.fg("muted", "\u2713 Write applied \xB7 no changes")], hidden: 0 };
2699
+ }
2700
+ if (shouldSkipWriteDiffBytes(beforeContent, content)) {
2701
+ return {
2702
+ lines: [
2703
+ theme.fg("success", "\u2713 Write applied") + theme.fg("muted", " \xB7 diff skipped for large content")
2704
+ ],
2705
+ hidden: 0
2706
+ };
2707
+ }
2708
+ if (shouldSkipWriteDiffComplexity(beforeContent, content)) {
2709
+ return {
2710
+ lines: [
2711
+ theme.fg("success", "\u2713 Write applied") + theme.fg("muted", " \xB7 diff skipped for complex rewrite")
2712
+ ],
2713
+ hidden: 0
2714
+ };
2715
+ }
2716
+ const diff = createSimpleDiff(beforeContent, content);
2717
+ const summary = summarizeDiff(diff);
2718
+ const header = `${theme.fg("success", "\u2713 Write applied")} ${theme.fg("muted", describeDiffShape(summary))}` + theme.fg("muted", " \xB7 ") + theme.fg("success", `+${summary.additions}`) + " " + theme.fg("error", `-${summary.removals}`);
2719
+ const rendered = renderDiff(diff, filePath, theme, options);
2720
+ return { lines: [header, ...rendered.lines], hidden: rendered.hidden };
2721
+ }
2722
+ if (audit.success === true && beforeRecord?.kind === "skipped") {
2723
+ let reason = stringOf(beforeRecord.reason) ?? "preview unavailable";
2724
+ const byteLength = numberOf(beforeRecord.byteLength);
2725
+ const maxBytes = numberOf(beforeRecord.maxBytes);
2726
+ if (byteLength !== void 0) {
2727
+ reason += beforeRecord.sizeExceeded === true && maxBytes !== void 0 ? ` (${formatBytes(byteLength)} > ${formatBytes(maxBytes)})` : ` (${formatBytes(byteLength)})`;
2728
+ }
2729
+ return {
2730
+ lines: [
2731
+ theme.fg("success", "\u2713 Write applied") + theme.fg("muted", ` \xB7 diff skipped: ${reason}`)
2732
+ ],
2733
+ hidden: 0
2734
+ };
2735
+ }
2736
+ if (audit.success === true && recordOf(audit.preview)?.writeBeforeCaptured === true && before === void 0) {
2737
+ const rendered = renderContent(content, filePath, theme, options, {
2738
+ emptyLabel: "Empty content",
2739
+ skipLabel: "Syntax highlighting skipped for large content"
2740
+ });
2741
+ return {
2742
+ lines: [
2743
+ theme.fg("success", `\u2713 New file (${countLabel(countContentLines(content), "line")})`),
2744
+ ...rendered.lines
2745
+ ],
2746
+ hidden: rendered.hidden
2747
+ };
2748
+ }
2749
+ return renderContent(content, filePath, theme, options, {
2750
+ emptyLabel: "Empty content",
2751
+ skipLabel: "Syntax highlighting skipped for large content"
2752
+ });
2753
+ };
2754
+ var editOperations = (audit) => {
2755
+ const edits = Array.isArray(audit.args?.edits) ? audit.args.edits : [];
2756
+ return edits.flatMap((edit) => {
2757
+ const record = recordOf(edit);
2758
+ const oldText = stringOf(record?.oldText) ?? stringOf(record?.old_text);
2759
+ const newText = stringOf(record?.newText) ?? stringOf(record?.new_text);
2760
+ return oldText !== void 0 && newText !== void 0 && oldText !== newText ? [{ oldText, newText }] : [];
2761
+ });
2762
+ };
2763
+ var renderEdit = (audit, theme, options) => {
2764
+ if (!options.expanded && !options.settings.editDiffPreview) return null;
2765
+ const filePath = argString(audit, "path") ?? "";
2766
+ const actual = stringOf(resultDetails(audit)?.diff);
2767
+ if (actual) {
2768
+ const summary = summarizeDiff(actual);
2769
+ const header2 = theme.fg("muted", countLabel(summary.hunks, "hunk")) + theme.fg("muted", " \xB7 ") + theme.fg("success", `+${summary.additions}`) + " " + theme.fg("error", `-${summary.removals}`);
2770
+ const rendered = renderDiff(actual, filePath, theme, options);
2771
+ return { lines: [header2, ...rendered.lines], hidden: rendered.hidden };
2772
+ }
2773
+ const operations = editOperations(audit);
2774
+ if (operations.length === 0) {
2775
+ if (audit.fromTrace) {
2776
+ return { lines: [theme.fg("dim", "diff not retained across reload")], hidden: 0 };
2777
+ }
2778
+ return null;
2779
+ }
2780
+ const maxOperations = Math.min(operations.length, 3);
2781
+ const sections = [];
2782
+ let additions = 0;
2783
+ let removals = 0;
2784
+ let hidden = 0;
2785
+ const perOperation = Math.max(8, Math.floor(toolLimit(audit, options) / maxOperations));
2786
+ for (let index = 0; index < maxOperations; index++) {
2787
+ const operation = operations[index];
2788
+ const diff = createSimpleDiff(operation.oldText, operation.newText);
2789
+ const summary = summarizeDiff(diff);
2790
+ additions += summary.additions;
2791
+ removals += summary.removals;
2792
+ if (operations.length > 1) sections.push(theme.fg("muted", `Proposed edit ${index + 1}/${operations.length}`));
2793
+ const rendered = renderDiff(diff, filePath, theme, options, perOperation);
2794
+ sections.push(...rendered.lines);
2795
+ hidden += rendered.hidden;
2796
+ }
2797
+ const header = `${theme.fg("muted", "proposed edit")} ${theme.fg("success", `+${additions}`)} ${theme.fg("error", `-${removals}`)}${operations.length > 1 ? theme.fg("muted", ` \xB7 ${operations.length} edit blocks`) : ""}`;
2798
+ if (operations.length > maxOperations) {
2799
+ pushArcItem(sections, arcItem(theme, `Showing ${maxOperations} of ${operations.length} edit blocks`));
2800
+ }
2801
+ return { lines: [header, ...sections], hidden };
2802
+ };
2803
+ var grepMatchRanges = (code, pattern, literal, ignoreCase) => {
2804
+ if (!literal || !pattern) return [];
2805
+ const haystack = ignoreCase ? code.toLowerCase() : code;
2806
+ const needle = ignoreCase ? pattern.toLowerCase() : pattern;
2807
+ const ranges = [];
2808
+ let index = haystack.indexOf(needle);
2809
+ while (index >= 0) {
2810
+ ranges.push([index, index + needle.length]);
2811
+ index = haystack.indexOf(needle, index + needle.length);
2812
+ }
2813
+ return ranges;
2814
+ };
2815
+ var parseGrepRow = (raw) => {
2816
+ const match = raw.match(/^(.+):(\d+):\s(.*)$/);
2817
+ const context = raw.match(/^(.+)-(\d+)-\s(.*)$/);
2818
+ const parsed = match ?? context;
2819
+ if (!parsed) return null;
2820
+ const lineNumberLabel = parsed[2] ?? "";
2821
+ const lineNumber = Number.parseInt(lineNumberLabel, 10);
2822
+ return {
2823
+ filePath: parsed[1] ?? "",
2824
+ lineNumber: Number.isFinite(lineNumber) ? lineNumber : 0,
2825
+ lineNumberLabel,
2826
+ code: expandTabs(parsed[3] ?? ""),
2827
+ isMatch: Boolean(match)
2828
+ };
2829
+ };
2830
+ var highlightGrepRun = (run, language, options) => {
2831
+ if (!language) return run.map(() => void 0);
2832
+ const first = run[0];
2833
+ const last = run[run.length - 1];
2834
+ const slice = highlightFileLines(
2835
+ resolve(options.cwd, first.filePath),
2836
+ language,
2837
+ first.lineNumber - 1,
2838
+ last.lineNumber,
2839
+ options.invalidate
2840
+ );
2841
+ if (slice && slice.every((line, index) => line.raw === run[index].code)) {
2842
+ return slice.map((line) => line.ansi);
2843
+ }
2844
+ const rendered = highlightCode(
2845
+ run.map((row) => row.code).join("\n"),
2846
+ language,
2847
+ options.invalidate
2848
+ );
2849
+ return run.map((_, index) => rendered?.[index]);
2850
+ };
2851
+ var renderGrepRowLine = (row, highlighted, audit, theme) => {
2852
+ let content = highlighted;
2853
+ if (row.isMatch) {
2854
+ const ranges = grepMatchRanges(
2855
+ row.code,
2856
+ argString(audit, "pattern") ?? "",
2857
+ audit.args?.literal === true,
2858
+ audit.args?.ignoreCase === true
2859
+ );
2860
+ if (ranges.length > 0) {
2861
+ content = injectVisibleRanges(
2862
+ content,
2863
+ ranges,
2864
+ effectiveShikiThemeIsLight() ? "\x1B[48;2;234;225;171m" : "\x1B[48;2;90;74;28m",
2865
+ "\x1B[49m"
2866
+ );
2867
+ }
2868
+ }
2869
+ const number = row.isMatch ? theme.fg("accent", row.lineNumberLabel.padStart(4, " ")) : theme.fg("dim", row.lineNumberLabel.padStart(4, " "));
2870
+ const marker = row.isMatch ? theme.fg("warning", "\u2502") : theme.fg("dim", "\u2506");
2871
+ return `${theme.fg("dim", " ")}${number} ${marker} ${content}`;
2872
+ };
2873
+ var renderGrep = (audit, theme, options) => {
2874
+ if (!options.expanded && !options.settings.grepResultPreview) return null;
2875
+ const output = resultOutput(audit)?.replace(/\r?\n$/, "");
2876
+ if (!output || output === "No matches found") {
2877
+ return { lines: [theme.fg("muted", output || "No matches found")], hidden: 0 };
2878
+ }
2879
+ const raw = output.split("\n");
2880
+ const skipHighlight = options.settings.syntaxHighlighting && output.length > MAX_HIGHLIGHT_CHARS;
2881
+ const syntaxOn = options.settings.syntaxHighlighting && !skipHighlight;
2882
+ const selected = previewEntries(raw, toolLimit(audit, options));
2883
+ const lines = [];
2884
+ let currentPath = "";
2885
+ let currentLanguage;
2886
+ let run = [];
2887
+ const flushRun = () => {
2888
+ if (run.length === 0) return;
2889
+ const highlighted = syntaxOn ? highlightGrepRun(run, currentLanguage, options) : [];
2890
+ for (let index = 0; index < run.length; index++) {
2891
+ const row = run[index];
2892
+ const content = highlighted[index] ?? theme.fg("toolOutput", escapeControlChars2(row.code));
2893
+ lines.push(renderGrepRowLine(row, content, audit, theme));
2894
+ }
2895
+ run = [];
2896
+ };
2897
+ for (const entry of selected.entries) {
2898
+ if (entry.kind === "hidden") {
2899
+ flushRun();
2900
+ lines.push(theme.fg("muted", ` --- ${entry.hidden} lines hidden ---`));
2901
+ currentPath = "";
2902
+ currentLanguage = void 0;
2903
+ continue;
2904
+ }
2905
+ const row = parseGrepRow(entry.line);
2906
+ if (!row) {
2907
+ flushRun();
2908
+ lines.push(
2909
+ entry.line.startsWith("[") && entry.line.endsWith("]") ? theme.fg("warning", escapeControlChars2(entry.line)) : theme.fg("toolOutput", escapeControlChars2(entry.line) || " ")
2910
+ );
2911
+ continue;
2912
+ }
2913
+ if (row.filePath !== currentPath) {
2914
+ flushRun();
2915
+ currentPath = row.filePath;
2916
+ currentLanguage = syntaxOn ? languageFromPath(row.filePath) : void 0;
2917
+ lines.push(theme.fg("accent", escapeControlChars2(row.filePath)));
2918
+ run.push(row);
2919
+ continue;
2920
+ }
2921
+ const previous = run[run.length - 1];
2922
+ if (!previous || row.lineNumber !== previous.lineNumber + 1) {
2923
+ flushRun();
2924
+ }
2925
+ run.push(row);
2926
+ }
2927
+ flushRun();
2928
+ if (skipHighlight) {
2929
+ pushArcItem(lines, arcItem(theme, "Syntax highlighting skipped for large grep output"));
2930
+ }
2931
+ return { lines, hidden: selected.hidden };
2932
+ };
2933
+ var NERD_BY_NAME = {
2934
+ "package.json": "\uE718",
2935
+ "package-lock.json": "\uE718",
2936
+ "tsconfig.json": "\uE628",
2937
+ "readme.md": "\uE73E",
2938
+ license: "\uE60A",
2939
+ dockerfile: "\uE7B0",
2940
+ makefile: "\uE615",
2941
+ ".gitignore": "\uE702",
2942
+ ".env": "\uE615",
2943
+ ".envrc": "\uE795"
2944
+ };
2945
+ var NERD_BY_EXTENSION = {
2946
+ ts: "\uE628",
2947
+ tsx: "\uE7BA",
2948
+ js: "\uE74E",
2949
+ jsx: "\uE7BA",
2950
+ json: "\uE60B",
2951
+ md: "\uE73E",
2952
+ py: "\uE73C",
2953
+ rs: "\uE7A8",
2954
+ go: "\uE627",
2955
+ java: "\uE738",
2956
+ rb: "\uE739",
2957
+ php: "\uE73D",
2958
+ html: "\uE736",
2959
+ css: "\uE749",
2960
+ scss: "\uE749",
2961
+ yaml: "\uE615",
2962
+ yml: "\uE615",
2963
+ toml: "\uE6B2",
2964
+ sh: "\uE795",
2965
+ bash: "\uE795",
2966
+ zsh: "\uE795",
2967
+ sql: "\uE706",
2968
+ xml: "\uE619",
2969
+ png: "\uF1C5",
2970
+ jpg: "\uF1C5",
2971
+ jpeg: "\uF1C5",
2972
+ gif: "\uF1C5",
2973
+ svg: "\uF1C5"
2974
+ };
2975
+ var pathIcon = (filePath, directory, mode) => {
2976
+ if (mode === "off") return "";
2977
+ if (mode === "unicode") return directory ? "\u25B8" : "\u2022";
2978
+ if (directory) return "\uE5FF";
2979
+ const name = basename(filePath).toLowerCase();
2980
+ return NERD_BY_NAME[name] ?? NERD_BY_EXTENSION[extname(name).slice(1)] ?? "\uF15B";
2981
+ };
2982
+ var renderPathList = (audit, theme, options) => {
2983
+ const enabled = audit.tool === "find" ? options.settings.findResultPreview : options.settings.lsResultPreview;
2984
+ if (!options.expanded && !enabled) return null;
2985
+ const output = resultOutput(audit)?.replace(/\r?\n$/, "") ?? "";
2986
+ const emptyMarker = audit.tool === "find" ? "No files found matching pattern" : "(empty directory)";
2987
+ if (!output || output === emptyMarker) {
2988
+ return {
2989
+ lines: [theme.fg("muted", audit.tool === "find" ? output || "No files found" : "Empty directory")],
2990
+ hidden: 0
2991
+ };
2992
+ }
2993
+ const raw = output.split("\n");
2994
+ if (options.expanded && !enabled) {
2995
+ return {
2996
+ lines: raw.map((line) => theme.fg("toolOutput", escapeControlChars2(line) || " ")),
2997
+ hidden: 0
2998
+ };
2999
+ }
3000
+ const selected = previewEntries(raw, toolLimit(audit, options));
3001
+ const lines = [];
3002
+ let chunk = [];
3003
+ const flush = () => {
3004
+ if (chunk.length === 0) return;
3005
+ const shouldTree = chunk.filter((line) => line && !(line.startsWith("[") && line.endsWith("]"))).some((line) => line.includes("/"));
3006
+ const seenDirectories = /* @__PURE__ */ new Set();
3007
+ for (const rawPath of chunk) {
3008
+ if (rawPath.startsWith("[") && rawPath.endsWith("]")) {
3009
+ lines.push(theme.fg("warning", escapeControlChars2(rawPath)));
3010
+ continue;
3011
+ }
3012
+ if (!rawPath) {
3013
+ lines.push("");
3014
+ continue;
3015
+ }
3016
+ if (!shouldTree) {
3017
+ const leading = rawPath.match(/^\s*/)?.[0] ?? "";
3018
+ const body = rawPath.slice(leading.length);
3019
+ const directory2 = body.endsWith("/");
3020
+ const icon = pathIcon(body, directory2, options.settings.pathIcons);
3021
+ const iconText = icon ? leading + icon : leading;
3022
+ lines.push(
3023
+ `${theme.fg("dim", iconText)}${icon ? " " : ""}${renderPath(body, options.cwd, theme, body)}`
3024
+ );
3025
+ continue;
3026
+ }
3027
+ const clean = rawPath.replace(/^\.\//, "");
3028
+ const directory = clean.endsWith("/");
3029
+ const parts = clean.replace(/\/$/, "").split("/").filter(Boolean);
3030
+ let prefix = "";
3031
+ for (let index = 0; index < parts.length; index++) {
3032
+ const part = parts[index];
3033
+ const leaf = index === parts.length - 1;
3034
+ const key = prefix ? `${prefix}/${part}` : part;
3035
+ const isDirectory = !leaf || directory;
3036
+ if (!isDirectory || !seenDirectories.has(key)) {
3037
+ if (isDirectory) seenDirectories.add(key);
3038
+ const icon = pathIcon(part, isDirectory, options.settings.pathIcons);
3039
+ const indent = " ".repeat(index);
3040
+ const label = isDirectory ? theme.fg("accent", `${escapeControlChars2(part)}/`) : theme.fg("toolOutput", escapeControlChars2(part));
3041
+ lines.push(`${theme.fg("dim", indent + icon)}${icon ? " " : ""}${label}`);
3042
+ }
3043
+ prefix = key;
3044
+ }
3045
+ }
3046
+ chunk = [];
3047
+ };
3048
+ for (const entry of selected.entries) {
3049
+ if (entry.kind === "hidden") {
3050
+ flush();
3051
+ lines.push(theme.fg("muted", ` --- ${entry.hidden} lines hidden ---`));
3052
+ } else {
3053
+ chunk.push(entry.line);
3054
+ }
3055
+ }
3056
+ flush();
3057
+ return { lines, hidden: selected.hidden };
3058
+ };
3059
+ var renderBash = (audit, theme, options) => {
3060
+ const commandName = audit.tool === "bash" ? firstShellCommandName(bashCommand(audit)) : "";
3061
+ const resultEnabled = options.settings.bashResultPreview && (commandName === "grep" || commandName === "egrep" || commandName === "fgrep" ? options.settings.grepResultPreview : commandName === "find" ? options.settings.findResultPreview : commandName === "ls" ? options.settings.lsResultPreview : true);
3062
+ if (!options.expanded && !resultEnabled) return null;
3063
+ const command = bashCommand(audit);
3064
+ const displayCommand = escapeControlChars2(command.replace(/\r\n/g, "\n"));
3065
+ const commandLines = displayCommand.split("\n");
3066
+ const highlightedCommand = command ? highlightCode(
3067
+ displayCommand,
3068
+ audit.tool === "powershell" ? "powershell" : "bash",
3069
+ options.invalidate
3070
+ ) : null;
3071
+ const lines = commandLines.slice(1).map(
3072
+ (line, index) => `${theme.fg("dim", " ")}${highlightedCommand?.[index + 1] ?? theme.fg("accent", line)}`
3073
+ );
3074
+ const output = resultOutput(audit)?.replace(/\r?\n$/, "") ?? "";
3075
+ if (!output || output === "(no output)") {
3076
+ if (!output && audit.fromTrace) {
3077
+ return { lines: [...lines, theme.fg("dim", "output not retained across reload")], hidden: 0 };
3078
+ }
3079
+ return {
3080
+ lines: [...lines, theme.fg("muted", output || "No output")],
3081
+ hidden: 0
3082
+ };
3083
+ }
3084
+ const raw = output.split("\n");
3085
+ const selected = previewEntries(raw, toolLimit(audit, options));
3086
+ const warning = warningLine(output, options, theme);
3087
+ if (warning) lines.push(warning);
3088
+ for (const entry of selected.entries) {
3089
+ if (entry.kind === "hidden") {
3090
+ lines.push(theme.fg("muted", ` --- ${entry.hidden} lines hidden ---`));
3091
+ continue;
3092
+ }
3093
+ const text = theme.fg(audit.success === false ? "error" : "muted", escapeControlChars2(entry.line) || " ");
3094
+ lines.push(text);
3095
+ }
3096
+ if (nativeTruncated(audit)) {
3097
+ pushArcItem(lines, arcItem(theme, `Output truncated by ${audit.tool ?? "shell"}`));
3098
+ }
3099
+ const fullOutputPath = stringOf(resultDetails(audit)?.fullOutputPath);
3100
+ if (fullOutputPath) pushArcItem(lines, arcItem(theme, `Full output: ${escapeControlChars2(fullOutputPath)}`));
3101
+ return { lines, hidden: selected.hidden };
3102
+ };
3103
+ var coreToolRendererEnabled = (audit, settings) => isCoreToolAudit(audit) && audit.tool !== void 0 && settings.tools.includes(audit.tool);
3104
+ var coreToolPreviewEnabled = (audit, settings) => {
3105
+ if (!coreToolRendererEnabled(audit, settings)) return true;
3106
+ switch (audit.tool) {
3107
+ case "read":
3108
+ return settings.readContentPreview;
3109
+ case "write":
3110
+ return settings.writeContentPreview;
3111
+ case "edit":
3112
+ return settings.editDiffPreview;
3113
+ case "grep":
3114
+ return settings.grepResultPreview;
3115
+ case "find":
3116
+ return settings.findResultPreview;
3117
+ case "ls":
3118
+ return settings.lsResultPreview;
3119
+ case "bash":
3120
+ case "powershell": {
3121
+ if (!settings.bashResultPreview) return false;
3122
+ const command = audit.tool === "bash" ? firstShellCommandName(bashCommand(audit)) : "";
3123
+ if (command === "grep" || command === "egrep" || command === "fgrep") {
3124
+ return settings.grepResultPreview;
3125
+ }
3126
+ if (command === "find") return settings.findResultPreview;
3127
+ if (command === "ls") return settings.lsResultPreview;
3128
+ return true;
3129
+ }
3130
+ default:
3131
+ return true;
3132
+ }
3133
+ };
3134
+ var renderCoreToolBody = (audit, theme, options) => {
3135
+ observePiTheme(theme);
3136
+ if (!coreToolRendererEnabled(audit, options.settings) || !audit.tool) return null;
3137
+ switch (audit.tool) {
3138
+ case "read":
3139
+ return renderRead(audit, theme, options);
3140
+ case "write":
3141
+ return renderWrite(audit, theme, options);
3142
+ case "edit":
3143
+ return renderEdit(audit, theme, options);
3144
+ case "grep":
3145
+ return renderGrep(audit, theme, options);
3146
+ case "find":
3147
+ case "ls":
3148
+ return renderPathList(audit, theme, options);
3149
+ case "bash":
3150
+ case "powershell":
3151
+ return renderBash(audit, theme, options);
3152
+ default:
3153
+ return null;
3154
+ }
3155
+ };
3156
+ var coreToolTitle = (audit, theme, options) => {
3157
+ observePiTheme(theme);
3158
+ if (!coreToolRendererEnabled(audit, options.settings) || !audit.tool) return null;
3159
+ const title = theme.fg("toolTitle", theme.bold(audit.tool));
3160
+ const timing = options.settings.toolCallTiming ? formatToolCallDuration(audit.startedAt, audit.endedAt) : void 0;
3161
+ const filePath = argString(audit, "path") ?? "";
3162
+ if (audit.tool === "bash" || audit.tool === "powershell") {
3163
+ const command = bashCommand(audit);
3164
+ const firstLine = command.split("\n")[0] ?? "";
3165
+ const language = audit.tool === "powershell" ? "powershell" : "bash";
3166
+ const highlighted = firstLine ? highlightCode(firstLine, language, options.invalidate)?.[0] : void 0;
3167
+ const timeout = numberOf(audit.args?.timeout);
3168
+ const warnings = audit.tool === "bash" && options.settings.bashWarnings ? bashWarnings(command) : [];
3169
+ const prompt = audit.tool === "powershell" ? "PS>" : "$";
3170
+ return `${title} ${theme.fg("dim", prompt)} ${highlighted ?? theme.fg("accent", escapeControlChars2(firstLine))}${metadata(theme, [
3171
+ timeout !== void 0 ? `timeout ${timeout}s` : void 0,
3172
+ warnings.length > 0 ? `\u26A0 ${warnings.join(", ")}` : void 0,
3173
+ timing
3174
+ ])}`;
3175
+ }
3176
+ if (audit.tool === "grep") {
3177
+ const pattern = argString(audit, "pattern") ?? "";
3178
+ const glob = argString(audit, "glob");
3179
+ const limit = numberOf(audit.args?.limit);
3180
+ return `${title} ${theme.fg("accent", `/${escapeControlChars2(pattern)}/`)} ${theme.fg("muted", "in")} ${renderPath(filePath || ".", options.cwd, theme)}${metadata(theme, [
3181
+ glob ? escapeControlChars2(glob) : void 0,
3182
+ limit !== void 0 ? `limit ${limit}` : void 0,
3183
+ timing
3184
+ ])}`;
3185
+ }
3186
+ if (audit.tool === "find") {
3187
+ const pattern = argString(audit, "pattern") || "*";
3188
+ return `${title} ${theme.fg("accent", escapeControlChars2(pattern))} ${theme.fg("muted", "in")} ${renderPath(filePath || ".", options.cwd, theme)}${metadata(theme, [timing])}`;
3189
+ }
3190
+ if (audit.tool === "ls") {
3191
+ return `${title} ${renderPath(filePath || ".", options.cwd, theme)}${metadata(theme, [timing])}`;
3192
+ }
3193
+ if (audit.tool === "read") {
3194
+ const offset = numberOf(audit.args?.offset);
3195
+ const limit = numberOf(audit.args?.limit);
3196
+ const range = offset !== void 0 || limit !== void 0 ? theme.fg("warning", `:${offset ?? 1}${limit !== void 0 ? `-${(offset ?? 1) + limit - 1}` : ""}`) : "";
3197
+ return `${title} ${renderPath(filePath, options.cwd, theme)}${range}${metadata(theme, [
3198
+ languageFromPath(filePath),
3199
+ timing
3200
+ ])}`;
3201
+ }
3202
+ if (audit.tool === "write") {
3203
+ const content = writeContent(audit);
3204
+ const rendererPreview = recordOf(audit.preview);
3205
+ const byteLength = numberOf(rendererPreview?.writeByteLength) ?? (content !== void 0 ? Buffer.byteLength(content, "utf8") : void 0);
3206
+ const lineCount = numberOf(rendererPreview?.writeLineCount) ?? (content !== void 0 ? countContentLines(content) : void 0);
3207
+ return `${title} ${renderPath(filePath, options.cwd, theme)}${metadata(theme, [
3208
+ byteLength !== void 0 ? formatBytes(byteLength) : void 0,
3209
+ lineCount !== void 0 ? countLabel(lineCount, "line") : void 0,
3210
+ languageFromPath(filePath),
3211
+ timing
3212
+ ])}`;
3213
+ }
3214
+ return `${title} ${renderPath(filePath, options.cwd, theme)}${metadata(theme, [timing])}`;
3215
+ };
3216
+
3217
+ // src/ui/fabric-render.ts
3218
+ import { createHash } from "node:crypto";
3219
+ import {
3220
+ getKeybindings,
3221
+ truncateToWidth as truncateToWidth2,
3222
+ visibleWidth as visibleWidth2,
3223
+ wrapTextWithAnsi
3224
+ } from "@earendil-works/pi-tui";
3225
+ var configuredDiffWrapRows = Number.parseInt(
3226
+ process.env.CODE_PREVIEW_DIFF_WRAP_ROWS ?? "",
3227
+ 10
3228
+ );
3229
+ var DIFF_WRAP_ROWS = Number.isFinite(configuredDiffWrapRows) && configuredDiffWrapRows > 0 ? configuredDiffWrapRows : 3;
3230
+ var EXPAND_KEYBINDING = "app.tools.expand";
3231
+ var COLLAPSED_MULTICALL_LIMIT = 8;
3232
+ var EXPANDED_MULTICALL_LIMIT = 30;
3233
+ var AGENT_RESPONSE_LINE_CODE_POINTS = 240;
3234
+ var EXPANDED_AGENT_TOOL_BODY_COUNT = 2;
3235
+ var EXPANDED_AGENT_TOOL_BODY_LINES = 12;
3236
+ var FULL_SGR_RESET = "\x1B[0m";
3237
+ var TEXT_SGR_RESET = "\x1B[22;23;24;27;29;39m";
3238
+ var INHERITED_TEXT_RESET_PARAMETERS = [
3239
+ "22",
3240
+ "23",
3241
+ "24",
3242
+ "25",
3243
+ "27",
3244
+ "28",
3245
+ "29",
3246
+ "39",
3247
+ "54",
3248
+ "55"
3249
+ ];
3250
+ var SGR_SEQUENCE = /\x1b\[([0-9:;]*)m/g;
3251
+ var inheritEnclosingBackground = (text) => text.replace(SGR_SEQUENCE, (_sequence, rawParameters) => {
3252
+ const parameters = rawParameters === "" ? ["0"] : rawParameters.split(";");
3253
+ const kept = [];
3254
+ for (let index = 0; index < parameters.length; index++) {
3255
+ const parameter = parameters[index];
3256
+ const code = Number.parseInt(parameter, 10);
3257
+ if (parameter === "0") {
3258
+ kept.push(...INHERITED_TEXT_RESET_PARAMETERS);
3259
+ } else if (parameter.startsWith("48:")) {
3260
+ continue;
3261
+ } else if (code === 38 || code === 58) {
3262
+ const mode = parameters[index + 1];
3263
+ const end = index + (mode === "2" ? 4 : mode === "5" ? 2 : 0);
3264
+ kept.push(...parameters.slice(index, end + 1));
3265
+ index = end;
3266
+ } else if (code === 48) {
3267
+ const mode = parameters[index + 1];
3268
+ index += mode === "2" ? 4 : mode === "5" ? 2 : 0;
3269
+ } else if (code === 49 || code === 7 || code >= 40 && code <= 47 || code >= 100 && code <= 107) {
3270
+ continue;
3271
+ } else {
3272
+ kept.push(parameter);
3273
+ }
3274
+ }
3275
+ return kept.length > 0 ? `\x1B[${kept.join(";")}m` : "";
3276
+ });
3277
+ var safeTerminalText = (value) => value.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (character) => {
3278
+ const code = character.codePointAt(0)?.toString(16).padStart(2, "0") ?? "00";
3279
+ return `\\x${code}`;
3280
+ });
3281
+ var truncateBoundedLine = (line, width) => {
3282
+ const truncated = truncateToWidth2(line, width, "");
3283
+ if (!truncated.endsWith(FULL_SGR_RESET)) return truncated;
3284
+ return truncated.slice(0, -FULL_SGR_RESET.length) + TEXT_SGR_RESET;
3285
+ };
3286
+ var BoundedLineList = class _BoundedLineList {
3287
+ constructor(lines, theme, diffIntensity = "off", wrapLineIndexes, inheritBackground = false) {
3288
+ this.lines = lines;
3289
+ this.theme = theme;
3290
+ this.diffIntensity = diffIntensity;
3291
+ this.wrapLineIndexes = wrapLineIndexes;
3292
+ this.inheritBackground = inheritBackground;
3293
+ }
3294
+ #cachedWidth;
3295
+ #cachedRows;
3296
+ render(width) {
3297
+ if (this.#cachedWidth === width && this.#cachedRows) return this.#cachedRows;
3298
+ if (width <= 0) return this.#cache(width, []);
3299
+ const diffBackground = createDiffBackgroundResolver(this.theme, this.diffIntensity);
3300
+ const rows = [];
3301
+ for (let lineIndex = 0; lineIndex < this.lines.length; lineIndex++) {
3302
+ const rawLine = this.lines[lineIndex];
3303
+ const { kind, line } = parseMarkedDiffLine(rawLine);
3304
+ if (!kind) {
3305
+ let renderedRows;
3306
+ if (this.wrapLineIndexes?.has(lineIndex)) {
3307
+ const continuationIndent = width > 2 ? " " : "";
3308
+ const wrapped = wrapTextWithAnsi(
3309
+ line,
3310
+ Math.max(1, width - visibleWidth2(continuationIndent))
3311
+ );
3312
+ renderedRows = wrapped.map(
3313
+ (row, index) => truncateBoundedLine(
3314
+ index === 0 ? row : continuationIndent + row,
3315
+ width
3316
+ )
3317
+ );
3318
+ } else renderedRows = [truncateBoundedLine(line, width)];
3319
+ rows.push(...this.inheritBackground ? renderedRows.map(inheritEnclosingBackground) : renderedRows);
3320
+ continue;
3321
+ }
3322
+ const pipe = line.indexOf("\u2502 ");
3323
+ const continuationPrefix = pipe < 0 ? "" : " ".repeat(visibleWidth2(line.slice(0, pipe + 2)));
3324
+ const wrappedRows = wrapDiffAnsiToWidth(
3325
+ line,
3326
+ width,
3327
+ DIFF_WRAP_ROWS,
3328
+ visibleWidth2(continuationPrefix) < width ? continuationPrefix : ""
3329
+ );
3330
+ for (const row of wrappedRows) {
3331
+ const padding = " ".repeat(Math.max(0, width - visibleWidth2(row)));
3332
+ rows.push(applyDiffBackground(row + padding, diffBackground(kind)));
3333
+ }
3334
+ }
3335
+ return this.#cache(width, rows);
3336
+ }
3337
+ invalidate() {
3338
+ this.#cachedWidth = void 0;
3339
+ this.#cachedRows = void 0;
3340
+ }
3341
+ withInheritedBackground() {
3342
+ if (this.inheritBackground) return this;
3343
+ return new _BoundedLineList(
3344
+ this.lines,
3345
+ this.theme,
3346
+ this.diffIntensity,
3347
+ this.wrapLineIndexes,
3348
+ true
3349
+ );
3350
+ }
3351
+ #cache(width, rows) {
3352
+ this.#cachedWidth = width;
3353
+ this.#cachedRows = rows;
3354
+ return rows;
3355
+ }
3356
+ };
3357
+ var InheritedBackgroundComponent = class {
3358
+ constructor(child) {
3359
+ this.child = child;
3360
+ }
3361
+ render(width) {
3362
+ return this.child.render(width).map(inheritEnclosingBackground);
3363
+ }
3364
+ invalidate() {
3365
+ this.child.invalidate?.();
3366
+ }
3367
+ };
3368
+ var inheritComponentBackground = (component) => component instanceof BoundedLineList ? component.withInheritedBackground() : new InheritedBackgroundComponent(component);
3369
+ var renderBoundedLines = (lines, theme, diffIntensity = "off", wrapLineIndexes) => new BoundedLineList(lines, theme, diffIntensity, wrapLineIndexes);
3370
+ var fabricMulticallCallLimit = (expanded) => expanded ? EXPANDED_MULTICALL_LIMIT : COLLAPSED_MULTICALL_LIMIT;
3371
+ var visibleMulticallAudits = (audits, expanded) => {
3372
+ const limit = fabricMulticallCallLimit(expanded);
3373
+ if (expanded || audits.length <= limit) {
3374
+ return audits.slice(0, limit).map((audit, auditIndex) => ({ audit, auditIndex }));
3375
+ }
3376
+ const active = audits.map((audit, auditIndex) => ({ audit, auditIndex })).filter(({ audit }) => audit.success === void 0);
3377
+ const selected = new Set(
3378
+ active.slice(-limit).map(({ auditIndex }) => auditIndex)
3379
+ );
3380
+ for (let auditIndex = 0; auditIndex < audits.length && selected.size < limit; auditIndex++) {
3381
+ if (!selected.has(auditIndex)) selected.add(auditIndex);
3382
+ }
3383
+ return [...selected].sort((left, right) => left - right).map((auditIndex) => ({ audit: audits[auditIndex], auditIndex }));
3384
+ };
3385
+ function expandHint(theme) {
3386
+ let keys = [];
3387
+ try {
3388
+ keys = getKeybindings().getKeys(EXPAND_KEYBINDING);
3389
+ } catch {
3390
+ keys = [];
3391
+ }
3392
+ const keyText = keys.length > 0 ? keys.join("/") : "ctrl-o";
3393
+ return theme.fg("dim", `${keyText} to expand`);
3394
+ }
3395
+ var truncateOneLine = (value, max) => {
3396
+ const single = value.replace(/\s+/g, " ").trim();
3397
+ return single.length <= max ? single : `${single.slice(0, max - 1)}\u2026`;
3398
+ };
3399
+ var argString2 = (args, key) => typeof args[key] === "string" ? args[key] : void 0;
3400
+ var LEGACY_COMMAND_DIGEST = /^sha256:[a-f0-9]{64}$/;
3401
+ var legacyCommandCache = /* @__PURE__ */ new WeakMap();
3402
+ var digestCommand = (command) => `sha256:${createHash("sha256").update(command).digest("hex")}`;
3403
+ var recordOf2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3404
+ var legacyCommandsFrom = (fabricArgs) => {
3405
+ const args = recordOf2(fabricArgs);
3406
+ if (!args) return /* @__PURE__ */ new Map();
3407
+ const cached = legacyCommandCache.get(args);
3408
+ if (cached) return cached;
3409
+ const commands = /* @__PURE__ */ new Map();
3410
+ const remember = (candidate) => {
3411
+ if (typeof candidate === "string") commands.set(digestCommand(candidate), candidate);
3412
+ };
3413
+ const namedStrings = recordOf2(args.strings);
3414
+ if (namedStrings) {
3415
+ for (const value of Object.values(namedStrings)) remember(value);
3416
+ }
3417
+ const rawCode = args.code;
3418
+ const code = typeof rawCode === "string" ? rawCode : Array.isArray(rawCode) && rawCode.every((value) => typeof value === "string") ? rawCode.join("\n") : void 0;
3419
+ if (code) {
3420
+ for (const literal of fabricStringLiterals(code)) remember(literal);
3421
+ }
3422
+ legacyCommandCache.set(args, commands);
3423
+ return commands;
3424
+ };
3425
+ var restoreLegacyBashCommands = (audits, fabricArgs) => {
3426
+ const hasLegacyCommand = audits.some((audit) => {
3427
+ const digest = audit.ref === "pi.bash" ? argString2(audit.args ?? {}, "commandDigest") : void 0;
3428
+ return Boolean(digest && LEGACY_COMMAND_DIGEST.test(digest));
3429
+ });
3430
+ if (!hasLegacyCommand) return audits;
3431
+ const commands = legacyCommandsFrom(fabricArgs);
3432
+ return audits.map((audit) => {
3433
+ if (audit.ref !== "pi.bash" || !audit.args) return audit;
3434
+ const digest = argString2(audit.args, "commandDigest");
3435
+ if (!digest || !LEGACY_COMMAND_DIGEST.test(digest)) return audit;
3436
+ const { commandDigest: _commandDigest, ...argsWithoutDigest } = audit.args;
3437
+ const command = commands.get(digest);
3438
+ return {
3439
+ ...audit,
3440
+ args: command ? { ...argsWithoutDigest, command } : argsWithoutDigest
3441
+ };
3442
+ });
3443
+ };
3444
+ var renderWriteArgumentBody = (path, content, expanded, theme, invalidate, parity) => {
3445
+ if (parity) {
3446
+ const rendered = renderCoreToolBody(
3447
+ { ref: "pi.write", provider: "pi", tool: "write", args: { path, content } },
3448
+ theme,
3449
+ {
3450
+ cwd: parity.cwd,
3451
+ settings: parity.settings,
3452
+ expanded,
3453
+ maxLines: 200,
3454
+ ...invalidate ? { invalidate } : {}
3455
+ }
3456
+ );
3457
+ if (rendered) return rendered;
3458
+ }
3459
+ const allLines = safeTerminalText(content).split("\n");
3460
+ while (allLines.length > 0 && allLines[allLines.length - 1] === "") allLines.pop();
3461
+ const limit = expanded ? Math.min(allLines.length, 200) : 10;
3462
+ const shown = allLines.slice(0, limit);
3463
+ const lang = languageFromPath(path);
3464
+ const highlighted = lang && shown.length > 0 ? highlightCode(shown.join("\n"), lang, invalidate) : null;
3465
+ return {
3466
+ lines: shown.map(
3467
+ (line, index) => highlighted?.[index] ?? theme.fg("toolOutput", line || " ")
3468
+ ),
3469
+ hidden: allLines.length - shown.length
3470
+ };
3471
+ };
3472
+ var renderFabricWriteArgumentPreview = (input, theme, invalidate) => {
3473
+ const available = input.bindings.map(
3474
+ (binding) => input.strings?.[binding.stringKey]
3475
+ );
3476
+ let activeIndex = -1;
3477
+ for (let index = 0; index < available.length; index++) {
3478
+ if (typeof available[index] === "string") activeIndex = index;
3479
+ }
3480
+ if (activeIndex < 0) return null;
3481
+ if (input.bindings.length === 1) {
3482
+ const binding = input.bindings[0];
3483
+ const rows2 = [
3484
+ nestedCallTitle(
3485
+ {
3486
+ ref: "pi.write",
3487
+ provider: "pi",
3488
+ tool: "write",
3489
+ args: { path: binding.path, content: available[0] ?? "" }
3490
+ },
3491
+ theme,
3492
+ invalidate,
3493
+ input.cwd && input.settings ? { cwd: input.cwd, settings: input.settings } : void 0
3494
+ )
3495
+ ];
3496
+ const body = renderWriteArgumentBody(
3497
+ binding.path,
3498
+ available[0] ?? "",
3499
+ input.expanded,
3500
+ theme,
3501
+ invalidate,
3502
+ input.cwd && input.settings ? { cwd: input.cwd, settings: input.settings } : void 0
3503
+ );
3504
+ rows2.push(...body.lines);
3505
+ if (body.hidden > 0) {
3506
+ rows2.push(
3507
+ theme.fg("dim", `\u2026 ${body.hidden} more ${body.hidden === 1 ? "line" : "lines"}`) + (input.expanded ? "" : theme.fg("dim", " \xB7 ") + expandHint(theme))
3508
+ );
3509
+ }
3510
+ return renderBoundedLines(rows2);
3511
+ }
3512
+ const completed = Math.max(
3513
+ 0,
3514
+ available.filter((value) => typeof value === "string").length - 1
3515
+ );
3516
+ const rows = [
3517
+ theme.fg(
3518
+ "warning",
3519
+ `\u25C6 Fabric composing \xB7 ${completed}/${input.bindings.length} writes`
3520
+ )
3521
+ ];
3522
+ const callLimit = fabricMulticallCallLimit(input.expanded);
3523
+ const shownBindings = input.bindings.slice(0, callLimit);
3524
+ for (let index = 0; index < shownBindings.length; index++) {
3525
+ const binding = shownBindings[index];
3526
+ const glyph = index !== activeIndex && typeof available[index] === "string" ? theme.fg("dim", "\u203A") : index === activeIndex ? theme.fg("warning", input.spinner ?? "\u25D0") : theme.fg("dim", "\u25CB");
3527
+ rows.push(
3528
+ `${glyph} ${nestedCallTitle(
3529
+ {
3530
+ ref: "pi.write",
3531
+ provider: "pi",
3532
+ tool: "write",
3533
+ args: {
3534
+ path: binding.path,
3535
+ ...typeof available[index] === "string" ? { content: available[index] } : {}
3536
+ }
3537
+ },
3538
+ theme,
3539
+ invalidate,
3540
+ input.cwd && input.settings ? { cwd: input.cwd, settings: input.settings } : void 0
3541
+ )}`
3542
+ );
3543
+ if (index === activeIndex) {
3544
+ const body = renderWriteArgumentBody(
3545
+ binding.path,
3546
+ available[index] ?? "",
3547
+ input.expanded,
3548
+ theme,
3549
+ invalidate,
3550
+ input.cwd && input.settings ? { cwd: input.cwd, settings: input.settings } : void 0
3551
+ );
3552
+ for (const line of body.lines) rows.push(` ${line}`);
3553
+ if (body.hidden > 0) {
3554
+ rows.push(
3555
+ theme.fg("dim", ` \u2026 ${body.hidden} more ${body.hidden === 1 ? "line" : "lines"}`)
3556
+ );
3557
+ }
3558
+ }
3559
+ }
3560
+ const hidden = input.bindings.length - shownBindings.length;
3561
+ if (hidden > 0) {
3562
+ rows.push(
3563
+ theme.fg("dim", `\u2026 ${hidden} more ${hidden === 1 ? "write" : "writes"}`) + (input.expanded ? "" : theme.fg("dim", " \xB7 ") + expandHint(theme))
3564
+ );
3565
+ }
3566
+ return renderBoundedLines(rows);
3567
+ };
3568
+ var shortIdOf = (value) => typeof value === "string" ? value.slice(0, 8) : void 0;
3569
+ var countOf = (result) => Array.isArray(result) ? String(result.length) : "";
3570
+ var providerCallDetail = (provider, tool, args, result, preview, previewHeadline) => {
3571
+ if (provider === "agents") {
3572
+ if (previewHeadline) return previewHeadline;
3573
+ const name = argString2(args, "name");
3574
+ const previewName = isFabricAgentToolPreview(preview) ? preview.name : void 0;
3575
+ const id = shortIdOf(args.id);
3576
+ const message = argString2(args, "message");
3577
+ const task = argString2(args, "task");
3578
+ switch (tool) {
3579
+ case "create":
3580
+ return name ?? "";
3581
+ case "remove":
3582
+ case "stop":
3583
+ case "cleanup":
3584
+ case "wait":
3585
+ case "join":
3586
+ case "status":
3587
+ case "actorStatus":
3588
+ case "messages":
3589
+ return previewName ?? name ?? id ?? "";
3590
+ case "ask":
3591
+ case "tell":
3592
+ return [previewName ?? name ?? id, message ? truncateOneLine(message, 48) : ""].filter(Boolean).join(" ");
3593
+ case "run":
3594
+ case "spawn":
3595
+ return name ?? (task ? truncateOneLine(task, 64) : previewName ?? "");
3596
+ case "actors":
3597
+ case "list":
3598
+ case "models":
3599
+ case "peers":
3600
+ return countOf(result);
3601
+ default:
3602
+ return previewName ?? id ?? "";
3603
+ }
3604
+ }
3605
+ if (provider === "mesh") {
3606
+ if (previewHeadline) return previewHeadline;
3607
+ switch (tool) {
3608
+ case "publish":
3609
+ return argString2(args, "topic") ?? "";
3610
+ case "read":
3611
+ return [argString2(args, "topic"), countOf(result)].filter(Boolean).join(" \xB7 ");
3612
+ case "get":
3613
+ case "put":
3614
+ case "delete":
3615
+ return argString2(args, "key") ?? "";
3616
+ case "list":
3617
+ return [argString2(args, "prefix"), countOf(result)].filter(Boolean).join(" \xB7 ");
3618
+ case "members":
3619
+ return countOf(result);
3620
+ default:
3621
+ return "";
3622
+ }
3623
+ }
3624
+ if (provider === "mcp") {
3625
+ if (previewHeadline) return previewHeadline;
3626
+ switch (tool) {
3627
+ case "$call":
3628
+ return [argString2(args, "server"), argString2(args, "tool")].filter(Boolean).join(".");
3629
+ case "$register":
3630
+ return argString2(args, "name") ?? "";
3631
+ case "$servers":
3632
+ return countOf(result);
3633
+ default:
3634
+ return "";
3635
+ }
3636
+ }
3637
+ return "";
3638
+ };
3639
+ var structuralCallDetail = (provider, tool, args, result) => {
3640
+ if (provider !== "fabric") return "";
3641
+ const count = countOf(result);
3642
+ switch (tool) {
3643
+ case "discovery.providers":
3644
+ case "discovery.models":
3645
+ case "discovery.search":
3646
+ return count;
3647
+ case "discovery.list":
3648
+ return [argString2(args, "provider"), argString2(args, "namespace"), count].filter(Boolean).join(" \xB7 ");
3649
+ case "discovery.describe":
3650
+ return argString2(args, "ref") ?? "";
3651
+ case "workflow.parallel":
3652
+ case "workflow.pipeline": {
3653
+ const itemCount = typeof args.itemCount === "number" ? args.itemCount : void 0;
3654
+ const stageCount = typeof args.stageCount === "number" ? args.stageCount : void 0;
3655
+ return [
3656
+ itemCount !== void 0 ? `${itemCount} ${itemCount === 1 ? "item" : "items"}` : "",
3657
+ stageCount !== void 0 ? `${stageCount} ${stageCount === 1 ? "stage" : "stages"}` : ""
3658
+ ].filter(Boolean).join(" \xB7 ");
3659
+ }
3660
+ default:
3661
+ return "";
3662
+ }
3663
+ };
3664
+ var callHeadlinePreview = (audit) => {
3665
+ const ref = audit.ref;
3666
+ const provider = audit.provider ?? ref.split(".")[0] ?? ref;
3667
+ const tool = audit.tool ?? ref.split(".")[1] ?? ref;
3668
+ const args = audit.args ?? {};
3669
+ return providerCallDetail(provider, tool, args, audit.result, audit.preview) || headlineArg(args) || structuralCallDetail(provider, tool, args, audit.result);
3670
+ };
3671
+ var nestedResultTruncated = (audit) => {
3672
+ if (audit.resultTruncated === true) return true;
3673
+ const result = audit.result;
3674
+ if (typeof result !== "object" || result === null) return false;
3675
+ const details = result.details;
3676
+ if (typeof details !== "object" || details === null) return false;
3677
+ const truncation = details.truncation;
3678
+ if (typeof truncation !== "object" || truncation === null) return false;
3679
+ return truncation.truncated === true;
3680
+ };
3681
+ function nestedCallTitle(audit, theme, invalidate, core) {
3682
+ const title = nestedCallTitleText(audit, theme, invalidate, core);
3683
+ return nestedResultTruncated(audit) ? `${title} ${theme.fg("warning", "\xB7 truncated")}` : title;
3684
+ }
3685
+ var nestedCallTitleText = (audit, theme, invalidate, core) => {
3686
+ const coreTitle = core ? coreToolTitle(audit, theme, { ...core, ...invalidate ? { invalidate } : {} }) : null;
3687
+ if (coreTitle) return coreTitle;
3688
+ const timing = core?.settings.toolCallTiming ? formatToolCallDuration(audit.startedAt, audit.endedAt) : void 0;
3689
+ const withTiming = (value) => timing ? `${value}${theme.fg("dim", ` \xB7 ${timing}`)}` : value;
3690
+ const ref = audit.ref;
3691
+ const provider = audit.provider ?? ref.split(".")[0] ?? ref;
3692
+ const tool = audit.tool ?? ref.split(".")[1] ?? ref;
3693
+ const title = theme.fg("toolTitle", theme.bold(tool));
3694
+ const args = audit.args ?? {};
3695
+ const providerDetail = providerCallDetail(
3696
+ provider,
3697
+ tool,
3698
+ args,
3699
+ audit.result,
3700
+ audit.preview,
3701
+ audit.previewHeadline
3702
+ );
3703
+ if (providerDetail) return withTiming(`${title} ${theme.fg("accent", providerDetail)}`);
3704
+ const command = argString2(args, "command");
3705
+ if (command) {
3706
+ const firstLine = command.split("\n")[0] ?? "";
3707
+ const highlighted = firstLine.length > 0 ? highlightCode(firstLine, "bash", invalidate) : null;
3708
+ const cmd = highlighted && highlighted[0] ? highlighted[0] : theme.fg("accent", firstLine);
3709
+ return withTiming(`${title} ${theme.fg("dim", "$")} ${cmd}`);
3710
+ }
3711
+ const path = argString2(args, "path");
3712
+ const pattern = argString2(args, "pattern");
3713
+ const task = argString2(args, "task");
3714
+ let detail = "";
3715
+ if (path) detail = path;
3716
+ else if (pattern) detail = `/${pattern}/${path ? ` ${path}` : ""}`;
3717
+ else if (task) detail = truncateOneLine(task, 64);
3718
+ else {
3719
+ detail = headlineArg(args) || structuralCallDetail(provider, tool, args, audit.result) || audit.previewHeadline || "";
3720
+ }
3721
+ return withTiming(detail ? `${title} ${theme.fg("accent", detail)}` : title);
3722
+ };
3723
+ var transcriptToolAudit = (entry) => {
3724
+ const rawName = entry.toolName ?? entry.label;
3725
+ const normalized = rawName.toLowerCase();
3726
+ const tool = normalized === "glob" ? "find" : ["read", "write", "edit", "bash", "powershell", "grep", "find", "ls"].includes(normalized) ? normalized : rawName;
3727
+ const rawArgs = entry.args ?? {};
3728
+ const args = { ...rawArgs };
3729
+ if (typeof rawArgs.file_path === "string" && typeof args.path !== "string") {
3730
+ args.path = rawArgs.file_path;
3731
+ }
3732
+ if (tool === "edit" && !Array.isArray(args.edits)) {
3733
+ const oldText = typeof rawArgs.old_string === "string" ? rawArgs.old_string : void 0;
3734
+ const newText = typeof rawArgs.new_string === "string" ? rawArgs.new_string : void 0;
3735
+ if (oldText !== void 0 && newText !== void 0) args.edits = [{ oldText, newText }];
3736
+ }
3737
+ return {
3738
+ ref: `pi.${tool}`,
3739
+ provider: "pi",
3740
+ tool,
3741
+ ...Object.keys(args).length > 0 ? { args } : {},
3742
+ ...entry.result !== void 0 ? { result: entry.result } : {},
3743
+ ...entry.status !== "running" ? { success: entry.status !== "failed" } : {}
3744
+ };
3745
+ };
3746
+ var AGENT_PREVIEW_RENDER_MAX_DEPTH = 6;
3747
+ var previewStatusGlyph = (status, theme) => status === "running" ? theme.fg("warning", "\u25D0") : status === "failed" ? theme.fg("error", "\u2717") : theme.fg("dim", "\u203A");
3748
+ var descendantBreadcrumb = (node, theme) => {
3749
+ let tail = node.agents?.find((child) => child.status === "running") ?? node.agents?.[0];
3750
+ if (!tail) return void 0;
3751
+ const names = [tail.name];
3752
+ for (let depth = 0; depth < AGENT_PREVIEW_RENDER_MAX_DEPTH; depth += 1) {
3753
+ const next = tail.agents?.find((child) => child.status === "running") ?? tail.agents?.[0];
3754
+ if (!next) break;
3755
+ tail = next;
3756
+ names.push(tail.name);
3757
+ }
3758
+ const runningTool = tail.tools.slice().reverse().find((entry) => entry.status === "running");
3759
+ const shownTool = runningTool ?? tail.tools.at(-1);
3760
+ const trail = names.map((name) => theme.fg("accent", safeTerminalText(name))).join(theme.fg("dim", " \u203A "));
3761
+ const tool = shownTool ? theme.fg("dim", " \u203A ") + nestedCallTitle(transcriptToolAudit(shownTool), theme) : "";
3762
+ const glyph = tail.status === "running" || tail.status === "failed" ? `${previewStatusGlyph(tail.status, theme)} ` : "";
3763
+ return `${glyph}${trail}${tool}`;
3764
+ };
3765
+ var renderAgentToolPreviewLines = (audit, theme, options) => {
3766
+ if (!isFabricAgentToolPreview(audit.preview)) return [];
3767
+ return renderAgentToolPreviewNodeLines(audit.preview, theme, options, 0);
3768
+ };
3769
+ var renderAgentToolPreviewNodeLines = (preview, theme, options, depth) => {
3770
+ const rawPreviewText = safeTerminalText(preview.text ?? "").trim();
3771
+ const responseLines = rawPreviewText ? options.compact ? [rawPreviewText.replace(/\s+/g, " ").trim()] : rawPreviewText.split("\n").flatMap((line) => {
3772
+ const normalized = line.replace(/\s+/g, " ").trim();
3773
+ if (!normalized) return [""];
3774
+ const codePoints = Array.from(normalized);
3775
+ const chunks = [];
3776
+ for (let offset = 0; offset < codePoints.length; offset += AGENT_RESPONSE_LINE_CODE_POINTS) {
3777
+ chunks.push(codePoints.slice(offset, offset + AGENT_RESPONSE_LINE_CODE_POINTS).join(""));
3778
+ }
3779
+ return chunks;
3780
+ }) : [];
3781
+ const tools = options.showTools === false ? [] : preview.tools;
3782
+ const descendantCrumb = !options.expanded && options.showTools !== false && preview.agents !== void 0 && preview.agents.length > 0 ? descendantBreadcrumb(preview, theme) : void 0;
3783
+ const runningTool = tools.slice().reverse().find((entry) => entry.status === "running");
3784
+ const latestTool = tools.at(-1);
3785
+ const collapsedRunningTool = !options.expanded && descendantCrumb === void 0 ? runningTool : void 0;
3786
+ const visibleResponseLines = collapsedRunningTool !== void 0 || descendantCrumb !== void 0 ? [] : responseLines;
3787
+ const visibleTools = options.expanded || descendantCrumb !== void 0 ? options.expanded ? tools : [] : collapsedRunningTool ? [collapsedRunningTool] : responseLines.length === 0 && latestTool ? [latestTool] : [];
3788
+ const chevron = theme.fg("dim", "\u203A");
3789
+ const lines = [];
3790
+ for (const responseLine of visibleResponseLines) {
3791
+ const text = theme.fg("toolOutput", responseLine || " ");
3792
+ lines.push(lines.length === 0 ? `${chevron} ${text}` : ` ${text}`);
3793
+ }
3794
+ for (let toolIndex = 0; toolIndex < visibleTools.length; toolIndex++) {
3795
+ const entry = visibleTools[toolIndex];
3796
+ const nestedAudit = transcriptToolAudit(entry);
3797
+ const title = nestedCallTitle(
3798
+ nestedAudit,
3799
+ theme,
3800
+ options.invalidate,
3801
+ options.core
3802
+ );
3803
+ if (lines.length === 0) {
3804
+ lines.push(`${chevron} ${title}`);
3805
+ } else {
3806
+ const glyph = entry.status === "running" ? theme.fg("warning", "\u25D0") : entry.status === "failed" ? theme.fg("error", "\u2717") : theme.fg("dim", "\u203A");
3807
+ lines.push(` ${glyph} ${title}`);
3808
+ }
3809
+ if (!options.expanded || !options.core || toolIndex < visibleTools.length - EXPANDED_AGENT_TOOL_BODY_COUNT) continue;
3810
+ const body = renderCoreToolBody(nestedAudit, theme, {
3811
+ cwd: options.core.cwd,
3812
+ settings: options.core.settings,
3813
+ expanded: true,
3814
+ maxLines: EXPANDED_AGENT_TOOL_BODY_LINES,
3815
+ ...options.invalidate ? { invalidate: options.invalidate } : {}
3816
+ });
3817
+ if (!body) continue;
3818
+ for (const row of body.lines) lines.push(` ${row}`);
3819
+ if (body.hidden > 0) {
3820
+ lines.push(theme.fg("dim", ` \u2026 ${body.hidden} more lines`));
3821
+ }
3822
+ }
3823
+ if (descendantCrumb !== void 0 && lines.length === 0) {
3824
+ lines.push(`${chevron} ${descendantCrumb}`);
3825
+ }
3826
+ if (options.expanded && options.showTools !== false && preview.agents && preview.agents.length > 0) {
3827
+ if (depth < AGENT_PREVIEW_RENDER_MAX_DEPTH) {
3828
+ for (const child of preview.agents) {
3829
+ const status = child.status && child.status !== "completed" ? theme.fg("dim", ` \xB7 ${safeTerminalText(child.status)}`) : "";
3830
+ const currentTool = child.currentTool && child.status === "running" ? theme.fg("dim", ` \xB7 ${safeTerminalText(child.currentTool)}`) : "";
3831
+ lines.push(
3832
+ ` ${previewStatusGlyph(child.status, theme)} ${theme.fg("accent", safeTerminalText(child.name))}${status}${currentTool}`
3833
+ );
3834
+ const childLines = renderAgentToolPreviewNodeLines(
3835
+ child,
3836
+ theme,
3837
+ { ...options, core: void 0 },
3838
+ depth + 1
3839
+ );
3840
+ for (const row of childLines) lines.push(` ${row}`);
3841
+ }
3842
+ if (preview.agentsTruncated) {
3843
+ lines.push(theme.fg("dim", " \u2026 deeper agent previews hidden"));
3844
+ }
3845
+ } else {
3846
+ lines.push(theme.fg("dim", " \u2026 deeper agent previews hidden"));
3847
+ }
3848
+ }
3849
+ return lines;
3850
+ };
3851
+ var singleCallProgressLine = (progress, previewLines) => progress && previewLines.length === 0 ? safeTerminalText(progress) : "";
3852
+ var compactProgressPreview = (progress) => {
3853
+ const lines = safeTerminalText(progress).split("\n").map((line) => line.replace(/\s+/g, " ").trim()).filter(Boolean);
3854
+ const latest = lines[lines.length - 1] ?? "";
3855
+ if (lines.length <= 1) return latest;
3856
+ return `\u2026 ${lines.length - 1} ${lines.length === 2 ? "line" : "lines"} \xB7 ${latest}`;
3857
+ };
3858
+ var renderFabricMulticallPartial = (input, theme, invalidate) => {
3859
+ const done = input.audits.filter((audit) => audit.success !== void 0).length;
3860
+ let header = theme.fg(
3861
+ "warning",
3862
+ `\u25C6 ${input.activityLabel ?? "Fabric"} running \xB7 ${done}/${input.audits.length} calls`
3863
+ );
3864
+ const progress = input.progress ? compactProgressPreview(input.progress) : "";
3865
+ if (progress) header += theme.fg("dim", ` \xB7 ${progress}`);
3866
+ const rows = [header];
3867
+ const wrapLineIndexes = input.expanded ? /* @__PURE__ */ new Set() : void 0;
3868
+ if (input.phases.length > 0) {
3869
+ rows.push(theme.fg("dim", input.phases.map((phase) => `\u25C6 ${phase}`).join(" ")));
3870
+ }
3871
+ const callsShown = visibleMulticallAudits(input.audits, input.expanded);
3872
+ for (let visibleIndex = 0; visibleIndex < callsShown.length; visibleIndex++) {
3873
+ const { audit, auditIndex } = callsShown[visibleIndex];
3874
+ if (input.expanded && visibleIndex > 0) rows.push("");
3875
+ const glyph = audit.success === void 0 ? theme.fg("warning", input.spinner ?? "\u25D0") : audit.success === false ? theme.fg("error", "\u2717") : theme.fg("dim", "\u203A");
3876
+ const previewLines = renderAgentToolPreviewLines(audit, theme, {
3877
+ expanded: input.expanded,
3878
+ compact: !input.expanded,
3879
+ showTools: input.showAgentToolPreview,
3880
+ core: input.core,
3881
+ ...invalidate ? { invalidate } : {}
3882
+ });
3883
+ let callRow = `${glyph} ${nestedCallTitle(audit, theme, invalidate, input.core)}`;
3884
+ if (audit.success === false && audit.error) {
3885
+ callRow += ` ${theme.fg("dim", "\u203A")} ${theme.fg("error", truncateOneLine(safeTerminalText(audit.error), 240))}`;
3886
+ } else if (previewLines[0]) {
3887
+ callRow += ` ${previewLines[0]}`;
3888
+ }
3889
+ if (previewLines.length > 0) wrapLineIndexes?.add(rows.length);
3890
+ rows.push(callRow);
3891
+ if (audit.success !== false && input.preview?.auditIndex === auditIndex) {
3892
+ for (const line of input.preview.body.split("\n")) rows.push(` ${line}`);
3893
+ if (input.preview.hidden > 0) {
3894
+ rows.push(
3895
+ theme.fg(
3896
+ "dim",
3897
+ ` \u2026 ${input.preview.hidden} more ${input.preview.hidden === 1 ? "line" : "lines"}`
3898
+ )
3899
+ );
3900
+ }
3901
+ }
3902
+ if (audit.success !== false && previewLines.length > 1) {
3903
+ for (const line of previewLines.slice(1)) {
3904
+ wrapLineIndexes?.add(rows.length);
3905
+ rows.push(line);
3906
+ }
3907
+ }
3908
+ }
3909
+ const callsHidden = input.audits.length - callsShown.length;
3910
+ if (callsHidden > 0) {
3911
+ const label = `\u2026 ${callsHidden} nested ${callsHidden === 1 ? "call" : "calls"} hidden`;
3912
+ rows.push(
3913
+ theme.fg("dim", label) + (input.expanded ? "" : theme.fg("dim", " \xB7 ") + expandHint(theme))
3914
+ );
3915
+ }
3916
+ return renderBoundedLines(
3917
+ rows,
3918
+ theme,
3919
+ input.core?.settings.diffIntensity ?? "off",
3920
+ wrapLineIndexes
3921
+ );
3922
+ };
3923
+ var CORE_TOOL_NAMES = /* @__PURE__ */ new Set(["bash", "powershell", "read", "write", "edit", "grep", "find", "ls"]);
3924
+ var captureFabricCoreToolPreviews = (audits, previous = []) => {
3925
+ const prior = previous.slice();
3926
+ return audits.flatMap((audit) => {
3927
+ if (!audit.tool || !CORE_TOOL_NAMES.has(audit.tool) || audit.provider !== "pi" && audit.ref !== `pi.${audit.tool}`) return [];
3928
+ const path = argString2(audit.args ?? {}, "path");
3929
+ const index = prior.findIndex(
3930
+ (candidate) => candidate.ref === audit.ref && argString2(candidate.args ?? {}, "path") === path
3931
+ );
3932
+ const old = index >= 0 ? prior.splice(index, 1)[0] : void 0;
3933
+ return [{
3934
+ ...old ?? {},
3935
+ ...audit,
3936
+ args: { ...old?.args ?? {}, ...audit.args ?? {} },
3937
+ ...audit.result !== void 0 ? { result: audit.result } : old?.result !== void 0 ? { result: old.result } : {},
3938
+ ...audit.preview !== void 0 ? { preview: audit.preview } : old?.preview !== void 0 ? { preview: old.preview } : {}
3939
+ }];
3940
+ });
3941
+ };
3942
+ var restoreFabricCoreToolPreviews = (audits, previews) => {
3943
+ const remaining = previews.slice();
3944
+ return audits.map((audit) => {
3945
+ if (!audit.tool || !CORE_TOOL_NAMES.has(audit.tool) || audit.provider !== "pi" && audit.ref !== `pi.${audit.tool}`) return audit;
3946
+ const path = argString2(audit.args ?? {}, "path");
3947
+ let index = remaining.findIndex(
3948
+ (preview2) => preview2.ref === audit.ref && argString2(preview2.args ?? {}, "path") === path
3949
+ );
3950
+ if (index < 0) index = remaining.findIndex((preview2) => preview2.ref === audit.ref);
3951
+ if (index < 0) return audit;
3952
+ const preview = remaining.splice(index, 1)[0];
3953
+ if (!preview) return audit;
3954
+ return {
3955
+ ...preview,
3956
+ ...audit,
3957
+ args: { ...preview.args ?? {}, ...audit.args ?? {} },
3958
+ ...audit.result !== void 0 ? { result: audit.result } : preview.result !== void 0 ? { result: preview.result } : {},
3959
+ ...audit.preview !== void 0 ? { preview: audit.preview } : preview.preview !== void 0 ? { preview: preview.preview } : {},
3960
+ ...audit.resultTruncated !== void 0 ? { resultTruncated: audit.resultTruncated } : preview.resultTruncated !== void 0 ? { resultTruncated: preview.resultTruncated } : {}
3961
+ };
3962
+ });
3963
+ };
3964
+ var captureFabricAgentPreviews = (audits, previous = []) => {
3965
+ const captured = previous.slice();
3966
+ const indexes = new Map(
3967
+ captured.map((preview, index) => [`${preview.ref}\0${preview.id}`, index])
3968
+ );
3969
+ for (const audit of audits) {
3970
+ if (!isFabricAgentToolPreview(audit.preview)) continue;
3971
+ const entry = { ref: audit.ref, id: audit.preview.id, preview: audit.preview };
3972
+ const key = `${entry.ref}\0${entry.id}`;
3973
+ const index = indexes.get(key);
3974
+ if (index === void 0) {
3975
+ indexes.set(key, captured.length);
3976
+ captured.push(entry);
3977
+ } else captured[index] = entry;
3978
+ }
3979
+ return captured;
3980
+ };
3981
+ var restoreFabricAgentPreviews = (audits, previews) => {
3982
+ const remaining = previews.slice();
3983
+ return audits.map((audit) => {
3984
+ if (isFabricAgentToolPreview(audit.preview)) return audit;
3985
+ const requestedId = argString2(audit.args ?? {}, "id");
3986
+ let index = requestedId ? remaining.findIndex((preview2) => preview2.ref === audit.ref && preview2.id === requestedId) : -1;
3987
+ if (index < 0) index = remaining.findIndex((preview2) => preview2.ref === audit.ref);
3988
+ if (index < 0) return audit;
3989
+ const preview = remaining.splice(index, 1)[0];
3990
+ return preview ? { ...audit, preview: preview.preview } : audit;
3991
+ });
3992
+ };
3993
+ var captureFabricWritePreviews = (audits) => audits.flatMap((audit) => {
3994
+ const rendererPreview = typeof audit.preview === "object" && audit.preview !== null && !Array.isArray(audit.preview) ? audit.preview : void 0;
3995
+ const content = audit.tool === "write" ? typeof rendererPreview?.writeContent === "string" ? rendererPreview.writeContent : argString2(audit.args ?? {}, "content") : void 0;
3996
+ if (content === void 0) return [];
3997
+ return [{ ref: audit.ref, path: argString2(audit.args ?? {}, "path"), content }];
3998
+ });
3999
+ var captureFabricCallHeadlinePreviews = (audits) => audits.flatMap((audit) => {
4000
+ const headline = callHeadlinePreview(audit);
4001
+ return headline ? [{ ref: audit.ref, headline }] : [];
4002
+ });
4003
+ var restoreFabricCallHeadlinePreviews = (audits, previews) => {
4004
+ const remaining = previews.slice();
4005
+ return audits.map((audit) => {
4006
+ const index = remaining.findIndex((preview2) => preview2.ref === audit.ref);
4007
+ if (index < 0) return audit;
4008
+ const [preview] = remaining.splice(index, 1);
4009
+ if (headlineArg(audit.args) || !preview) return audit;
4010
+ return { ...audit, previewHeadline: preview.headline };
4011
+ });
4012
+ };
4013
+ var restoreFabricWritePreviews = (audits, previews) => {
4014
+ const remaining = previews.slice();
4015
+ return audits.map((audit) => {
4016
+ if (audit.tool !== "write" || typeof audit.args?.content === "string") return audit;
4017
+ const path = argString2(audit.args ?? {}, "path");
4018
+ const index = remaining.findIndex(
4019
+ (preview2) => preview2.ref === audit.ref && preview2.path === path
4020
+ );
4021
+ if (index < 0) return audit;
4022
+ const [preview] = remaining.splice(index, 1);
4023
+ return preview ? { ...audit, args: { ...audit.args ?? {}, content: preview.content } } : audit;
4024
+ });
4025
+ };
4026
+ function nestedCallBody(audit) {
4027
+ if (audit.tool === "write" && typeof audit.args?.content === "string") {
4028
+ return audit.args.content;
4029
+ }
4030
+ const result = audit.result;
4031
+ if (typeof result === "string") return result;
4032
+ if (result !== null && typeof result === "object" && !Array.isArray(result)) {
4033
+ const obj = result;
4034
+ if (typeof obj.output === "string") return obj.output;
4035
+ if (typeof obj.text === "string") return obj.text;
4036
+ }
4037
+ return void 0;
4038
+ }
4039
+ var escapeControlChars3 = (text) => text.replace(/\x1b/g, "\u241B").replace(/\r/g, "\u240D").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "\uFFFD");
4040
+ var lineDiff = (oldLines, newLines) => {
4041
+ const m = oldLines.length;
4042
+ const n = newLines.length;
4043
+ if (m * n > 1e6) {
4044
+ return [
4045
+ ...oldLines.map((line) => ({ kind: "-", content: line })),
4046
+ ...newLines.map((line) => ({ kind: "+", content: line }))
4047
+ ];
4048
+ }
4049
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
4050
+ for (let i2 = m - 1; i2 >= 0; i2--) {
4051
+ const oldLine = oldLines[i2] ?? "";
4052
+ const cur = dp[i2];
4053
+ const next = dp[i2 + 1];
4054
+ for (let j2 = n - 1; j2 >= 0; j2--) {
4055
+ const newLine = newLines[j2] ?? "";
4056
+ cur[j2] = oldLine === newLine ? (next[j2 + 1] ?? 0) + 1 : Math.max(next[j2] ?? 0, cur[j2 + 1] ?? 0);
4057
+ }
4058
+ }
4059
+ const out = [];
4060
+ let i = 0;
4061
+ let j = 0;
4062
+ while (i < m && j < n) {
4063
+ const oldLine = oldLines[i] ?? "";
4064
+ const newLine = newLines[j] ?? "";
4065
+ if (oldLine === newLine) {
4066
+ out.push({ kind: " ", content: oldLine });
4067
+ i++;
4068
+ j++;
4069
+ } else if ((dp[i + 1][j] ?? 0) >= (dp[i][j + 1] ?? 0)) {
4070
+ out.push({ kind: "-", content: oldLine });
4071
+ i++;
4072
+ } else {
4073
+ out.push({ kind: "+", content: newLine });
4074
+ j++;
4075
+ }
4076
+ }
4077
+ while (i < m) {
4078
+ out.push({ kind: "-", content: oldLines[i] ?? "" });
4079
+ i++;
4080
+ }
4081
+ while (j < n) {
4082
+ out.push({ kind: "+", content: newLines[j] ?? "" });
4083
+ j++;
4084
+ }
4085
+ return out;
4086
+ };
4087
+ function nestedEditDiff(audit, theme, invalidate) {
4088
+ if (audit.tool !== "edit") return null;
4089
+ const args = audit.args ?? {};
4090
+ const edits = Array.isArray(args.edits) ? args.edits : [];
4091
+ if (edits.length === 0) return null;
4092
+ const lang = languageFromPath(typeof args.path === "string" ? args.path : void 0);
4093
+ const lines = [];
4094
+ for (const edit of edits.slice(0, 5)) {
4095
+ if (!edit || typeof edit !== "object") continue;
4096
+ const record = edit;
4097
+ const oldText = typeof record.oldText === "string" ? record.oldText : "";
4098
+ const newText = typeof record.newText === "string" ? record.newText : "";
4099
+ const diff = lineDiff(oldText.split("\n"), newText.split("\n"));
4100
+ if (diff.length === 0) continue;
4101
+ const oldHighlighted = lang ? highlightCode(
4102
+ diff.filter((entry) => entry.kind !== "+").map((entry) => entry.content).join("\n"),
4103
+ lang,
4104
+ invalidate
4105
+ ) : null;
4106
+ const newHighlighted = lang ? highlightCode(
4107
+ diff.filter((entry) => entry.kind !== "-").map((entry) => entry.content).join("\n"),
4108
+ lang,
4109
+ invalidate
4110
+ ) : null;
4111
+ let oldCursor = 0;
4112
+ let newCursor = 0;
4113
+ for (let index = 0; index < diff.length; index++) {
4114
+ const entry = diff[index];
4115
+ let text;
4116
+ if (entry.kind === "-") {
4117
+ text = oldHighlighted?.[oldCursor++];
4118
+ } else if (entry.kind === "+") {
4119
+ text = newHighlighted?.[newCursor++];
4120
+ } else {
4121
+ oldCursor++;
4122
+ text = newHighlighted?.[newCursor++];
4123
+ }
4124
+ const content = text != null ? text || " " : theme.fg("toolOutput", escapeControlChars3(entry.content) || " ");
4125
+ if (entry.kind === "+") {
4126
+ lines.push(`${theme.fg("toolDiffAdded", "+")} ${content}`);
4127
+ } else if (entry.kind === "-") {
4128
+ lines.push(`${theme.fg("toolDiffRemoved", "-")} ${content}`);
4129
+ } else {
4130
+ lines.push(`${theme.fg("toolDiffContext", " ")} ${content}`);
4131
+ }
4132
+ }
4133
+ }
4134
+ return lines.length > 0 ? lines : null;
4135
+ }
4136
+ var lineCountTrimmed = (value) => {
4137
+ const lines = value.split("\n");
4138
+ let end = lines.length;
4139
+ while (end > 0) {
4140
+ const last = lines[end - 1];
4141
+ if (last === void 0 || last.trim() === "") end--;
4142
+ else break;
4143
+ }
4144
+ return end;
4145
+ };
4146
+ function modelReadHint(audits, output, theme) {
4147
+ if (!output) return "";
4148
+ const modelLines = lineCountTrimmed(output);
4149
+ let readLines = 0;
4150
+ let sawRead = false;
4151
+ for (const audit of audits) {
4152
+ if (audit.tool !== "read") continue;
4153
+ const body = nestedCallBody(audit);
4154
+ if (typeof body !== "string") continue;
4155
+ sawRead = true;
4156
+ readLines += lineCountTrimmed(body);
4157
+ }
4158
+ if (!sawRead || modelLines >= readLines) return "";
4159
+ return theme.fg("warning", "\u2192 " + modelLines + " of " + readLines + " lines to model");
4160
+ }
4161
+
4162
+ // src/ui/spinner.ts
4163
+ var SPINNER_INTERVAL_MS = 250;
4164
+ var SPINNER_FRAMES = ["\u25D0", "\u25D3", "\u25D1", "\u25D2"];
4165
+ var spinnerFrame = (now = Date.now()) => SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length];
4166
+ var updateSpinner = (state, active, invalidate, now = Date.now()) => {
4167
+ if (!active) {
4168
+ if (state.timer) clearTimeout(state.timer);
4169
+ delete state.timer;
4170
+ return spinnerFrame(now);
4171
+ }
4172
+ if (!state.timer) {
4173
+ const delay = SPINNER_INTERVAL_MS - now % SPINNER_INTERVAL_MS;
4174
+ state.timer = setTimeout(() => {
4175
+ delete state.timer;
4176
+ invalidate();
4177
+ }, delay);
4178
+ state.timer.unref?.();
4179
+ }
4180
+ return spinnerFrame(now);
4181
+ };
4182
+
4183
+ export {
4184
+ continueArcGroup,
4185
+ arcItemStyled,
4186
+ isCoreToolAudit,
4187
+ coreToolRendererEnabled,
4188
+ coreToolPreviewEnabled,
4189
+ renderCoreToolBody,
4190
+ coreToolTitle,
4191
+ safeTerminalText,
4192
+ inheritComponentBackground,
4193
+ renderBoundedLines,
4194
+ fabricMulticallCallLimit,
4195
+ expandHint,
4196
+ restoreLegacyBashCommands,
4197
+ renderFabricWriteArgumentPreview,
4198
+ nestedCallTitle,
4199
+ renderAgentToolPreviewLines,
4200
+ singleCallProgressLine,
4201
+ renderFabricMulticallPartial,
4202
+ captureFabricCoreToolPreviews,
4203
+ restoreFabricCoreToolPreviews,
4204
+ captureFabricAgentPreviews,
4205
+ restoreFabricAgentPreviews,
4206
+ captureFabricWritePreviews,
4207
+ captureFabricCallHeadlinePreviews,
4208
+ restoreFabricCallHeadlinePreviews,
4209
+ restoreFabricWritePreviews,
4210
+ nestedCallBody,
4211
+ nestedEditDiff,
4212
+ modelReadHint,
4213
+ spinnerFrame,
4214
+ updateSpinner,
4215
+ formatJsonAsYaml,
4216
+ formatFabricValue
4217
+ };
4218
+ //# sourceMappingURL=chunk-VRZNFNPB.js.map