@hostclubeos/miraos 0.0.8-beta → 0.0.9-beta

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 (238) hide show
  1. package/chunks/{MaxSizedBox-YR2SA5XW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-VEXSGLU4.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
  3. package/chunks/{acp-subagent-executor-ATOLWCVC.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
  4. package/chunks/{acpAgent-DN46FTZ2.js → acpAgent-PCXQRPNU.js} +3 -3
  5. package/chunks/{advisor-6MI5JQGC.js → advisor-WDZ5N5ZP.js} +1 -1
  6. package/chunks/{agent-6HPQ4XCT.js → agent-I7Q3IPSS.js} +1 -1
  7. package/chunks/{agent-headless-KXAJBOPG.js → agent-headless-6LOYWI5T.js} +1 -1
  8. package/chunks/{agent-host-client-NOZRE2ZR.js → agent-host-client-PZZKCNQF.js} +1 -1
  9. package/chunks/{agent-host-connections-6FOSHEWD.js → agent-host-connections-TWWSRTKJ.js} +1 -1
  10. package/chunks/{autofix-pr-IMJA2KZF.js → autofix-pr-RQPGPQ4D.js} +1 -1
  11. package/chunks/{batch-L5VJ4XGP.js → batch-UJD5TSBN.js} +1 -1
  12. package/chunks/{bridge-CCRTJSIM.js → bridge-4TYLRPXZ.js} +1 -1
  13. package/chunks/{channel-settings-store-SB7BP6XT.js → channel-settings-store-RENJMOQ5.js} +1 -1
  14. package/chunks/{chunk-UC455ZS7.js → chunk-24PHAWM3.js} +1 -1
  15. package/chunks/{chunk-CNGBG3X5.js → chunk-26JPBN6V.js} +1 -1
  16. package/chunks/{chunk-W4M6JXZB.js → chunk-2MQH3J4U.js} +1 -1
  17. package/chunks/{chunk-GS4FZF6I.js → chunk-2RXOWQSQ.js} +1 -1
  18. package/chunks/{chunk-LRXYXGMT.js → chunk-323HUW2T.js} +1 -1
  19. package/chunks/{chunk-7DJYSBNJ.js → chunk-3BHXE7CB.js} +1 -1
  20. package/chunks/{chunk-7Q6RNE77.js → chunk-3GYAEXAA.js} +1 -1
  21. package/chunks/{chunk-VOIC5ZW2.js → chunk-3YBZW4HP.js} +1 -1
  22. package/chunks/{chunk-JRIVHFCG.js → chunk-4RJ2RRGZ.js} +1 -1
  23. package/chunks/{chunk-3NA5O4QO.js → chunk-5DIW4X4P.js} +1 -1
  24. package/chunks/{chunk-YELFN6AG.js → chunk-5GB6JNJX.js} +1 -1
  25. package/chunks/{chunk-6TNX3S5H.js → chunk-5HSNCG73.js} +2 -2
  26. package/chunks/{chunk-FC5IAX56.js → chunk-6HDMM7TJ.js} +1 -1
  27. package/chunks/{chunk-CJLKKIUW.js → chunk-6STNGEYC.js} +1 -1
  28. package/chunks/{chunk-ZJOVJLIH.js → chunk-7EFWNFJJ.js} +1 -1
  29. package/chunks/{chunk-SMO4PEHK.js → chunk-7EWIKIJI.js} +1 -1
  30. package/chunks/{chunk-S5NTCBEI.js → chunk-7TB6VG72.js} +1 -1
  31. package/chunks/{chunk-6AAVML2M.js → chunk-7TLL4JLR.js} +1 -1
  32. package/chunks/{chunk-IWIGJDPL.js → chunk-AOMXZNMX.js} +1 -1
  33. package/chunks/{chunk-5YULNQF3.js → chunk-AUM57JI2.js} +1 -1
  34. package/chunks/{chunk-ZQZK267X.js → chunk-AW5UCOZO.js} +1 -1
  35. package/chunks/{chunk-D4WMUCSK.js → chunk-C6HVNDQT.js} +2 -2
  36. package/chunks/{chunk-2DPE27WB.js → chunk-CC6E5CQV.js} +1 -1
  37. package/chunks/{chunk-SK5C26Y6.js → chunk-CLKUQP27.js} +1 -1
  38. package/chunks/{chunk-ARILWFTZ.js → chunk-DFMQQM4M.js} +1 -1
  39. package/chunks/{chunk-IJIQDCNJ.js → chunk-DP7LJTG2.js} +5 -5
  40. package/chunks/{chunk-7EEWU6XO.js → chunk-DQT5VL7G.js} +1 -1
  41. package/chunks/{chunk-AHV4IMUX.js → chunk-E4QOAV5O.js} +1 -1
  42. package/chunks/{chunk-G3COGFSZ.js → chunk-E4REGDEZ.js} +1 -1
  43. package/chunks/{chunk-MOXZO5PM.js → chunk-EAG7VZJJ.js} +1 -1
  44. package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
  45. package/chunks/{chunk-IJH5HZTB.js → chunk-EMR4QK2F.js} +1 -1
  46. package/chunks/{chunk-YFXKRGHT.js → chunk-EYECE2PH.js} +1 -1
  47. package/chunks/{chunk-7HO5DQ6V.js → chunk-EZDXHUHB.js} +1 -1
  48. package/chunks/{chunk-66N3SLXJ.js → chunk-FJFTKA4H.js} +1 -1
  49. package/chunks/{chunk-DNCXESHL.js → chunk-FSLDNLNU.js} +1 -1
  50. package/chunks/{chunk-K3RWL2YH.js → chunk-FSRXTX3N.js} +1 -1
  51. package/chunks/{chunk-4RRQ7CPF.js → chunk-FWSXFRIQ.js} +1 -1
  52. package/chunks/{chunk-M3IQE5G4.js → chunk-G4ATLMDH.js} +1 -1
  53. package/chunks/{chunk-WUZ53TKN.js → chunk-GAS3HKRX.js} +1 -1
  54. package/chunks/{chunk-LTXZHHNK.js → chunk-GFFL2LR2.js} +1 -1
  55. package/chunks/{chunk-IK5TB2CB.js → chunk-GYFIY7TD.js} +1 -1
  56. package/chunks/{chunk-XJKDC7OE.js → chunk-GYXRI4P5.js} +1 -1
  57. package/chunks/{chunk-4C5BOFDC.js → chunk-H3U7DXIU.js} +1 -1
  58. package/chunks/{chunk-5AJKMBPM.js → chunk-HEDVPRMD.js} +1 -1
  59. package/chunks/{chunk-32DLSPV5.js → chunk-HI3644FQ.js} +1 -1
  60. package/chunks/{chunk-CLLQQMTU.js → chunk-HTHYLMBO.js} +1 -1
  61. package/chunks/{chunk-VAFRD2H4.js → chunk-IW7RPDV2.js} +1 -1
  62. package/chunks/{chunk-5BWVS5D3.js → chunk-IXQI4K6O.js} +1 -1
  63. package/chunks/{chunk-BWLMXGA2.js → chunk-IYH3IZL4.js} +1 -1
  64. package/chunks/{chunk-XGPGIMZK.js → chunk-J52J35K4.js} +1 -1
  65. package/chunks/{chunk-BWFZEDYG.js → chunk-J7L5IHLG.js} +1 -1
  66. package/chunks/{chunk-6STDVRH5.js → chunk-JHS5B4N7.js} +2 -2
  67. package/chunks/{chunk-EHM4KL2U.js → chunk-JRSO5ZGU.js} +1 -1
  68. package/chunks/{chunk-NYGJ53Y7.js → chunk-JS6VAGRQ.js} +1 -1
  69. package/chunks/{chunk-QCSGHQ2P.js → chunk-KAFPULGU.js} +1 -1
  70. package/chunks/{chunk-CNZS2RPX.js → chunk-LDP47G5M.js} +1 -1
  71. package/chunks/{chunk-GM6YF6IS.js → chunk-LMZZWPKA.js} +1 -1
  72. package/chunks/{chunk-5SX4UPMN.js → chunk-LNCELICB.js} +1 -1
  73. package/chunks/{chunk-K2PGOAJP.js → chunk-LY2DRNTZ.js} +1 -1
  74. package/chunks/{chunk-KZZ5ZQHX.js → chunk-MMGGGYSJ.js} +1 -1
  75. package/chunks/{chunk-SVNSF5ZH.js → chunk-MTBU2ZIM.js} +1 -1
  76. package/chunks/{chunk-MV7LX23I.js → chunk-N27KICJQ.js} +1 -1
  77. package/chunks/{chunk-OPFBBIAQ.js → chunk-NHYFTK4O.js} +1 -1
  78. package/chunks/{chunk-NUDHRTIM.js → chunk-NRDHXSEE.js} +1 -1
  79. package/chunks/{chunk-QZNCYZ7H.js → chunk-NV5VVTYQ.js} +1 -1
  80. package/chunks/{chunk-7GU7HKIT.js → chunk-OEDMFKZL.js} +1 -1
  81. package/chunks/{chunk-V3ASW57P.js → chunk-OQAVMR6K.js} +1 -1
  82. package/chunks/{chunk-GBEQD55S.js → chunk-OY3Y6EMV.js} +1 -1
  83. package/chunks/{chunk-G7D42XGP.js → chunk-OZL4ZMGQ.js} +2 -2
  84. package/chunks/{chunk-PGKVSOWW.js → chunk-PKSPKVFH.js} +1 -1
  85. package/chunks/{chunk-OXG4BLFF.js → chunk-PNFKCYZT.js} +1 -1
  86. package/chunks/{chunk-JT5EN5MI.js → chunk-PTWHFVGG.js} +2 -2
  87. package/chunks/{chunk-3VKLOQ2P.js → chunk-QJ6ZTZFC.js} +1 -1
  88. package/chunks/{chunk-WZAUO3LV.js → chunk-QRGWB7IX.js} +1 -1
  89. package/chunks/{chunk-JCWNB45W.js → chunk-QRP2GXQD.js} +1 -1
  90. package/chunks/{chunk-CEVKKM22.js → chunk-RES5ET63.js} +1 -1
  91. package/chunks/{chunk-HCKF74X7.js → chunk-ROSJCTWB.js} +1 -1
  92. package/chunks/{chunk-WJXADORN.js → chunk-RR3NFNWL.js} +1 -1
  93. package/chunks/{chunk-HCCONFJY.js → chunk-RYQDRFLW.js} +1 -1
  94. package/chunks/{chunk-WSXRO2YB.js → chunk-S7CWSAUQ.js} +1 -1
  95. package/chunks/{chunk-MXFS555I.js → chunk-SAJKF4WS.js} +1 -1
  96. package/chunks/chunk-SINRWOVD.js +36 -0
  97. package/chunks/{chunk-DNXQKR5E.js → chunk-SJNQ6I23.js} +1 -1
  98. package/chunks/{chunk-DTRSC73M.js → chunk-T2GM4S4G.js} +3 -3
  99. package/chunks/{chunk-C3ZJUOTJ.js → chunk-TCQJO42E.js} +1 -1
  100. package/chunks/{chunk-G4OSEVOV.js → chunk-TIIDF23U.js} +2 -2
  101. package/chunks/{chunk-NNYAXFFN.js → chunk-TKH5R7RZ.js} +1 -1
  102. package/chunks/{chunk-JHGMLUAL.js → chunk-TSRTZD3X.js} +1 -1
  103. package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
  104. package/chunks/{chunk-MCY3IS2E.js → chunk-UYI5AMPI.js} +1 -1
  105. package/chunks/{chunk-7L4MR4QM.js → chunk-VO6SPDH4.js} +1 -1
  106. package/chunks/{chunk-SPCIIUIG.js → chunk-VRIHYTDI.js} +1 -1
  107. package/chunks/{chunk-Q4NEZZ6L.js → chunk-VT47A26Q.js} +1 -1
  108. package/chunks/{chunk-E743PFSX.js → chunk-VZOZUCZX.js} +1 -1
  109. package/chunks/{chunk-WW43VZ6O.js → chunk-WLEGTKGA.js} +1 -1
  110. package/chunks/{chunk-77GGGTWS.js → chunk-XHCJN4A2.js} +1 -1
  111. package/chunks/{chunk-UZAFPEVN.js → chunk-XTRZ5PHG.js} +1 -1
  112. package/chunks/{chunk-DTNW2CM3.js → chunk-Y4GZOZWD.js} +1 -1
  113. package/chunks/{chunk-YOBM4ZFW.js → chunk-YUCAGV52.js} +2 -2
  114. package/chunks/{chunk-WOMJLK3E.js → chunk-YWQM4TSO.js} +1 -1
  115. package/chunks/{chunk-WN6Z3J27.js → chunk-YYTOHY4V.js} +1 -1
  116. package/chunks/{chunk-VOCM2M4K.js → chunk-Z25W2S5N.js} +1 -1
  117. package/chunks/{chunk-QWNTORRT.js → chunk-Z6GECBAJ.js} +1 -1
  118. package/chunks/{chunk-XNP5JXCS.js → chunk-ZJU4B4WX.js} +1 -1
  119. package/chunks/{chunk-MCHMWRNO.js → chunk-ZSHDQPAO.js} +1 -1
  120. package/chunks/{chunk-POMEWCFJ.js → chunk-ZUWLTGSR.js} +6 -6
  121. package/chunks/{codex-subagent-executor-TPO62HU5.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
  122. package/chunks/{config-utils-6GWIYBUK.js → config-utils-5B2LYCON.js} +1 -1
  123. package/chunks/{contextCommand-WWVGDTOL.js → contextCommand-UPQGRXWK.js} +1 -1
  124. package/chunks/{core-runtime-ASQR33TV.js → core-runtime-DPMH2BXK.js} +1 -1
  125. package/chunks/{create-sub-session-XY2FXSPE.js → create-sub-session-EJVB3FE5.js} +1 -1
  126. package/chunks/{cron-create-HY3TLNV2.js → cron-create-V2A7PMQC.js} +1 -1
  127. package/chunks/{daemon-git-worktree-guard-ILW3NJJC.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
  128. package/chunks/{daemon-status-provider-JVOGEKWY.js → daemon-status-provider-6BRB5TG3.js} +1 -1
  129. package/chunks/{daemon-trust-policy-XXRBG4JE.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
  130. package/chunks/{daemon-trust-policy-monitor-UL73ADOZ.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
  131. package/chunks/{deferred-core-runtime-PT747R7S.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
  132. package/chunks/{edit-4PJ3NPFA.js → edit-LRG3TMHP.js} +1 -1
  133. package/chunks/{enterPlanMode-KQ62QN7S.js → enterPlanMode-KOUSHJHR.js} +1 -1
  134. package/chunks/{environment-H4HADXGA.js → environment-54CM3OXE.js} +1 -1
  135. package/chunks/{errors-OSD4ZZGR.js → errors-D6XR3NH4.js} +1 -1
  136. package/chunks/{execution-tool-PHHGLKWC.js → execution-tool-7RZ2JLEK.js} +1 -1
  137. package/chunks/{execution-worker-MH3CV66T.js → execution-worker-LXQ7WAFG.js} +1 -1
  138. package/chunks/{exitPlanMode-OU5YP4XN.js → exitPlanMode-4FGFA2QC.js} +1 -1
  139. package/chunks/{fast-path-WKOMHBWN.js → fast-path-4B7OKPYK.js} +1 -1
  140. package/chunks/{glob-FYCOEQPM.js → glob-N2D7SY23.js} +1 -1
  141. package/chunks/{goal-tools-T27GSDNM.js → goal-tools-7RNSDRFO.js} +1 -1
  142. package/chunks/{handleAutoUpdate-XXCPJLKO.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
  143. package/chunks/{i18n-3B2PRJM2.js → i18n-F3OAHCLJ.js} +1 -1
  144. package/chunks/{initializer-HSFVDRTR.js → initializer-OL3DDWR7.js} +1 -1
  145. package/chunks/{installationInfo-SJJ2DYZ6.js → installationInfo-D2L743RV.js} +1 -1
  146. package/chunks/{interactive-mod-session-BWY2JRSQ.js → interactive-mod-session-2GXRCQKR.js} +1 -1
  147. package/chunks/{list-TGCI3MBM.js → list-PU7ZXBY5.js} +1 -1
  148. package/chunks/{llm-FYR73GKD.js → llm-V42HGUVH.js} +4 -4
  149. package/chunks/{loadedSettingsAdapter-DUDCINQL.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
  150. package/chunks/{local-7PEOBJKE.js → local-KM5F5RAB.js} +1 -1
  151. package/chunks/{local-execution-environment-Q4OOA7BL.js → local-execution-environment-OEO2KW3M.js} +1 -1
  152. package/chunks/{loggingContentGenerator-VVESQOIQ.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
  153. package/chunks/{loop-wakeup-M2XLAAKZ.js → loop-wakeup-CJICM24Y.js} +1 -1
  154. package/chunks/{manage-memory-FRVWHM2C.js → manage-memory-7CV6LF4C.js} +1 -1
  155. package/chunks/{managed-execution-engine-AVIM6AQU.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
  156. package/chunks/{managed-local-serve-GIXHGFIU.js → managed-local-serve-KA37YWRW.js} +1 -1
  157. package/chunks/{managed-npm-update-3QSXGSHW.js → managed-npm-update-TSUUH3NN.js} +1 -1
  158. package/chunks/{managed-runtime-attestation-worker-ML4TCRAW.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
  159. package/chunks/{managed-runtime-bootstrap-JWJFGLBM.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
  160. package/chunks/{managed-runtime-session-worker-4ISKROGZ.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
  161. package/chunks/{managed-runtime-ssh-worker-C44V2CPM.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
  162. package/chunks/{managed-session-authority-UJ3FSKMD.js → managed-session-authority-5FYS3G3M.js} +1 -1
  163. package/chunks/{mcp-BWCLHHZ6.js → mcp-TRPV3K74.js} +1 -1
  164. package/chunks/{memory-5XQ2JVNS.js → memory-5CMNRPM2.js} +1 -1
  165. package/chunks/{model-call-collection-DXK2SIDR.js → model-call-collection-S4JKVFUO.js} +1 -1
  166. package/chunks/{model-configuration-6OLZS4C3.js → model-configuration-NEIDLKWQ.js} +1 -1
  167. package/chunks/{modelConfigUtils-5S5PC2RR.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
  168. package/chunks/{monitor-6GKCWWUI.js → monitor-5MNKK5AO.js} +1 -1
  169. package/chunks/{nonInteractiveCli-ROHAB2H7.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
  170. package/chunks/{nonInteractiveToolExecutor-OWCCSC5Y.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
  171. package/chunks/{notebook-edit-WNRQ3QJZ.js → notebook-edit-7HIBTFFW.js} +1 -1
  172. package/chunks/{omni-DJ5RGNKA.js → omni-MX7BMOL5.js} +1 -1
  173. package/chunks/{openaiContentGenerator-237NVB63.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
  174. package/chunks/{openaiResponsesContentGenerator-J33TCZKQ.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
  175. package/chunks/{pidfile-F7IYTFLX.js → pidfile-OHAGZOTV.js} +1 -1
  176. package/chunks/{processUtils-C6CSXITS.js → processUtils-TCDNCYVB.js} +1 -1
  177. package/chunks/{prompt-terminal-ledger-ZGYWPFJF.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
  178. package/chunks/{reactive-degrade-QKXPZQ3W.js → reactive-degrade-C7CGUJNP.js} +1 -1
  179. package/chunks/{read-file-GSNUMHRE.js → read-file-L4ZF6VDG.js} +1 -1
  180. package/chunks/{resumeHistoryUtils-4GUCHQGU.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
  181. package/chunks/{review-M2QGZFIO.js → review-F6JGI2LP.js} +1 -1
  182. package/chunks/{ripGrep-X4JTJZC6.js → ripGrep-L6M2GPCM.js} +1 -1
  183. package/chunks/{run-qwen-serve-4WW37RL2.js → run-qwen-serve-D5HB55SC.js} +1 -1
  184. package/chunks/{runtime-EFHJ6REE.js → runtime-CH3RAOQL.js} +1 -1
  185. package/chunks/{sandboxConfig-5XMIRDS4.js → sandboxConfig-EADWCO37.js} +1 -1
  186. package/chunks/{scheduled-tasks-ZCYM5YQJ.js → scheduled-tasks-PBKD4BHY.js} +1 -1
  187. package/chunks/{scheduler-5UAKCD5Z.js → scheduler-U5K3523K.js} +1 -1
  188. package/chunks/{search-memory-KKPYK33Q.js → search-memory-Y2IPKBDP.js} +1 -1
  189. package/chunks/{send-message-KOZRSWXO.js → send-message-JJQG2S6D.js} +1 -1
  190. package/chunks/{serve-5HSHEBMT.js → serve-2ZYS47MO.js} +1 -1
  191. package/chunks/{server-MC6KHP3G.js → server-5GMO4IHU.js} +3 -3
  192. package/chunks/{session-Z5HFG4IQ.js → session-LLOOVSHK.js} +1 -1
  193. package/chunks/{session-attachments-root-K2E5ETD4.js → session-attachments-root-XCLXH2XO.js} +1 -1
  194. package/chunks/{session-execution-engine-selector-NZA6CAJB.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
  195. package/chunks/{session-pr-refresh-OYJ56U3L.js → session-pr-refresh-MDBOAN3R.js} +1 -1
  196. package/chunks/{sessionService-BC56MX3G.js → sessionService-VKAHCTCC.js} +1 -1
  197. package/chunks/{settings-OHB77GXH.js → settings-ULEB2IYZ.js} +1 -1
  198. package/chunks/{shell-VKSH7JVL.js → shell-RBEKIYKU.js} +1 -1
  199. package/chunks/{skill-HQ4C2C3X.js → skill-GEVOEFMZ.js} +1 -1
  200. package/chunks/{skill-settings-6WPQFE3V.js → skill-settings-4IMGLYJW.js} +1 -1
  201. package/chunks/{spawnChannel-MXKVLS24.js → spawnChannel-B7L5PWQ6.js} +1 -1
  202. package/chunks/{standalone-update-NZP3OAZZ.js → standalone-update-SYQM6NOC.js} +1 -1
  203. package/chunks/{start-opentui-ui-25YQQD3O.js → start-opentui-ui-N427PLF4.js} +2 -2
  204. package/chunks/{startInteractiveUI-DWQJNIIV.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
  205. package/chunks/{team-create-RSD7IADX.js → team-create-MN6FHUHU.js} +1 -1
  206. package/chunks/{team-plan-approval-XAOKZ6BR.js → team-plan-approval-OUYBIT7H.js} +1 -1
  207. package/chunks/{terminal-image-renderer-P5AGEOYS.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
  208. package/chunks/{theme-manager-YBKJYPVQ.js → theme-manager-QOYSKWFK.js} +1 -1
  209. package/chunks/{tool-call-HJCSPR6N.js → tool-call-Q5NLEQFD.js} +1 -1
  210. package/chunks/{tool-result-media-SPWVV3OS.js → tool-result-media-NZJZTOBQ.js} +1 -1
  211. package/chunks/{tool-search-YWCOODLL.js → tool-search-D6Y45RNQ.js} +1 -1
  212. package/chunks/{total-session-admission-HKACVEI2.js → total-session-admission-36W7MDHP.js} +1 -1
  213. package/chunks/{trustedFolders-BXLZULWO.js → trustedFolders-XW5VH6HK.js} +1 -1
  214. package/chunks/{update-relaunch-CBJVLG6S.js → update-relaunch-KQPR2HAP.js} +1 -1
  215. package/chunks/{updateCheck-2J6RY3L3.js → updateCheck-SRW67WAX.js} +1 -1
  216. package/chunks/{upload-config-EN5XYA3V.js → upload-config-BTJNYMRX.js} +1 -1
  217. package/chunks/{useAutoAcceptIndicator-LF7VIUER.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
  218. package/chunks/{validateNonInterActiveAuth-63TR5JOG.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
  219. package/chunks/{version-F22SKNME.js → version-6R6LSGXO.js} +1 -1
  220. package/chunks/{web-fetch-ULH7TOLR.js → web-fetch-Y7LBAU3R.js} +1 -1
  221. package/chunks/{web-search-C3ORWAWR.js → web-search-IB4NYYUH.js} +1 -1
  222. package/chunks/{workflow-4ATPGZ5N.js → workflow-TR4YIPJO.js} +1 -1
  223. package/chunks/{workflow-ancestor-trust-AJ27EBZD.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
  224. package/chunks/{workspace-agents-VLAJGYJF.js → workspace-agents-MY2NFL6A.js} +1 -1
  225. package/chunks/{workspace-providers-status-TFAXNJ6L.js → workspace-providers-status-DNCCKFVE.js} +1 -1
  226. package/chunks/{workspace-recovery-worker-GKYYJPXV.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
  227. package/chunks/{workspace-registration-store-ANR3STGQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
  228. package/chunks/{workspace-registry-OVHNLVBM.js → workspace-registry-E6LFL5GL.js} +1 -1
  229. package/chunks/{workspace-runtime-coordinator-IEN2G7JP.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
  230. package/chunks/{workspace-service-NISFZTBE.js → workspace-service-OVEYIQOC.js} +1 -1
  231. package/chunks/{workspace-skills-status-QRF5ZXMT.js → workspace-skills-status-3NKXA5SK.js} +1 -1
  232. package/chunks/{workspace-trust-reconciler-X3XMX2GJ.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
  233. package/chunks/{write-file-SF42KZAH.js → write-file-FSTHYKKZ.js} +1 -1
  234. package/chunks/{zoom-image-4UMB6G3P.js → zoom-image-JP3EUDXE.js} +1 -1
  235. package/cli.js +2 -2
  236. package/execution-worker.js +1 -1
  237. package/package.json +2 -2
  238. package/chunks/chunk-OHOG4HSN.js +0 -31
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{wrapForMultiplexer}from"./chunk-G3COGFSZ.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var KITTY_CTRL_C="[99;5u";var KITTY_KEYCODE_ENTER=13;var KITTY_KEYCODE_NUMPAD_ENTER=57414;var KITTY_KEYCODE_TAB=9;var KITTY_KEYCODE_BACKSPACE=127;var KITTY_MODIFIER_BASE=1;var KITTY_MODIFIER_EVENT_TYPES_OFFSET=128;var MODIFIER_SHIFT_BIT=1;var MODIFIER_ALT_BIT=2;var MODIFIER_CTRL_BIT=4;var MODIFIER_SUPER_BIT=8;var CTRL_EXIT_PROMPT_DURATION_MS=1e3;var VSCODE_SHIFT_ENTER_SEQUENCE="\\\r\n";var BACKSLASH_ENTER_DETECTION_WINDOW_MS=5;var MAX_KITTY_SEQUENCE_LENGTH=32;var CHAR_CODE_ESC=27;init_esbuild_shims();import*as fs from"node:fs/promises";import{constants as fsConstants}from"node:fs";import{execSync,spawn}from"node:child_process";import*as path from"node:path";import{randomUUID}from"node:crypto";init_esbuild_shims();var ESC="\x1B";var BEL="\x07";var ST=ESC+"\\";var OSC_PREFIX=ESC+"]";var SEP=";";var OSC={ITERM2:9,KITTY:99,GHOSTTY:777,PROGRAM_STATUS:7501};function detectTerminal(){const termProgram=process.env["TERM_PROGRAM"];switch(termProgram){case"iTerm.app":return"iTerm.app";case"kitty":return"kitty";case"ghostty":return"ghostty";case"Apple_Terminal":return"Apple_Terminal";default:break}if(process.env["TERM"]==="xterm-ghostty"){return"ghostty"}if(process.env["TERM"]?.includes("kitty")){return"kitty"}if(process.env["KITTY_WINDOW_ID"])return"kitty";return"unknown"}__name(detectTerminal,"detectTerminal");function sanitizeOscPayload(text){return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g,"")}__name(sanitizeOscPayload,"sanitizeOscPayload");function osc(...parts){const isKitty=detectTerminal()==="kitty";const inScreen=!!process.env["STY"];const terminator=isKitty&&!inScreen?ST:BEL;const sanitized=parts.map(p=>typeof p==="string"?sanitizeOscPayload(p):p);return`${OSC_PREFIX}${sanitized.join(SEP)}${terminator}`}__name(osc,"osc");function encodeKittyPayload(text){return Buffer.from(text,"utf8").toString("base64")}__name(encodeKittyPayload,"encodeKittyPayload");function oscITerm2Notify(title,message){const displayString=title?`${title}:
3
+ import{wrapForMultiplexer}from"./chunk-E4REGDEZ.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var KITTY_CTRL_C="[99;5u";var KITTY_KEYCODE_ENTER=13;var KITTY_KEYCODE_NUMPAD_ENTER=57414;var KITTY_KEYCODE_TAB=9;var KITTY_KEYCODE_BACKSPACE=127;var KITTY_MODIFIER_BASE=1;var KITTY_MODIFIER_EVENT_TYPES_OFFSET=128;var MODIFIER_SHIFT_BIT=1;var MODIFIER_ALT_BIT=2;var MODIFIER_CTRL_BIT=4;var MODIFIER_SUPER_BIT=8;var CTRL_EXIT_PROMPT_DURATION_MS=1e3;var VSCODE_SHIFT_ENTER_SEQUENCE="\\\r\n";var BACKSLASH_ENTER_DETECTION_WINDOW_MS=5;var MAX_KITTY_SEQUENCE_LENGTH=32;var CHAR_CODE_ESC=27;init_esbuild_shims();import*as fs from"node:fs/promises";import{constants as fsConstants}from"node:fs";import{execSync,spawn}from"node:child_process";import*as path from"node:path";import{randomUUID}from"node:crypto";init_esbuild_shims();var ESC="\x1B";var BEL="\x07";var ST=ESC+"\\";var OSC_PREFIX=ESC+"]";var SEP=";";var OSC={ITERM2:9,KITTY:99,GHOSTTY:777,PROGRAM_STATUS:7501};function detectTerminal(){const termProgram=process.env["TERM_PROGRAM"];switch(termProgram){case"iTerm.app":return"iTerm.app";case"kitty":return"kitty";case"ghostty":return"ghostty";case"Apple_Terminal":return"Apple_Terminal";default:break}if(process.env["TERM"]==="xterm-ghostty"){return"ghostty"}if(process.env["TERM"]?.includes("kitty")){return"kitty"}if(process.env["KITTY_WINDOW_ID"])return"kitty";return"unknown"}__name(detectTerminal,"detectTerminal");function sanitizeOscPayload(text){return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g,"")}__name(sanitizeOscPayload,"sanitizeOscPayload");function osc(...parts){const isKitty=detectTerminal()==="kitty";const inScreen=!!process.env["STY"];const terminator=isKitty&&!inScreen?ST:BEL;const sanitized=parts.map(p=>typeof p==="string"?sanitizeOscPayload(p):p);return`${OSC_PREFIX}${sanitized.join(SEP)}${terminator}`}__name(osc,"osc");function encodeKittyPayload(text){return Buffer.from(text,"utf8").toString("base64")}__name(encodeKittyPayload,"encodeKittyPayload");function oscITerm2Notify(title,message){const displayString=title?`${title}:
4
4
  ${message}`:message;return osc(OSC.ITERM2,`
5
5
 
6
6
  ${displayString}`)}__name(oscITerm2Notify,"oscITerm2Notify");function oscKittyNotify(title,message,id){return[osc(OSC.KITTY,`i=${id}:d=0:p=title:e=1`,encodeKittyPayload(title)),osc(OSC.KITTY,`i=${id}:p=body:e=1`,encodeKittyPayload(message)),osc(OSC.KITTY,`i=${id}:d=1:a=focus`,"")]}__name(oscKittyNotify,"oscKittyNotify");function oscGhosttyNotify(title,message){return osc(OSC.GHOSTTY,"notify",title,message)}__name(oscGhosttyNotify,"oscGhosttyNotify");var PROGRAM_STATUS_APP="qwen-code";var PROGRAM_STATUS_MAX_MSG_BYTES=2048;function encodeProgramStatusMsg(msg){let text=msg.replace(/[\x00-\x1f\x7f\x80-\x9f\u2028\u2029]/g," ").trim();while(Buffer.byteLength(text,"utf8")>PROGRAM_STATUS_MAX_MSG_BYTES){text=Array.from(text).slice(0,-16).join("")}return Buffer.from(text,"utf8").toString("base64")}__name(encodeProgramStatusMsg,"encodeProgramStatusMsg");function oscProgramStatus(status){const pairs=[`state=${status.state}`];if(status.state==="blocked"&&status.kind){pairs.push(`kind=${status.kind}`)}pairs.push(`app=${PROGRAM_STATUS_APP}`);if(status.msg){const encoded=encodeProgramStatusMsg(status.msg);if(encoded)pairs.push(`msg=${encoded}`)}return`${OSC_PREFIX}${OSC.PROGRAM_STATUS}${SEP}${pairs.join(":")}${ST}`}__name(oscProgramStatus,"oscProgramStatus");function oscProgramStatusClear(){return`${OSC_PREFIX}${OSC.PROGRAM_STATUS}${SEP}state=clear${ST}`}__name(oscProgramStatusClear,"oscProgramStatusClear");function generateKittyId(){return Math.floor(Math.random()*2**31)}__name(generateKittyId,"generateKittyId");init_esbuild_shims();import{fileURLToPath}from"node:url";function isUncPath(candidate){return/^[\\/]{2}[^\\/]/.test(candidate)}__name(isUncPath,"isUncPath");function isFileUri(text){return/^file:/i.test(text)}__name(isFileUri,"isFileUri");function fileUriToLocalPath(uri){let url;try{url=new URL(uri)}catch{return null}if(url.protocol!=="file:"||url.host!==""){return null}try{const localPath=fileURLToPath(url);return isUncPath(localPath)?null:localPath}catch{return null}}__name(fileUriToLocalPath,"fileUriToLocalPath");var debugLogger=createDebugLogger("CLIPBOARD_UTILS");var PROCESS_TIMEOUT_MS=5e3;var MAX_CLIPBOARD_TEXT_BYTES=16*1024*1024;function writeOsc52(text){try{const MAX_OSC52_BYTES=75e3;if(Buffer.byteLength(text,"utf-8")>MAX_OSC52_BYTES){debugLogger.warn(`writeOsc52: text too large (${Buffer.byteLength(text,"utf-8")} bytes), skipping`);return false}const base64=Buffer.from(text,"utf-8").toString("base64");const sequence=wrapForMultiplexer(`\x1B]52;c;${base64}\x07`);const stream=process.stderr.isTTY?process.stderr:process.stdout.isTTY?process.stdout:null;if(!stream){debugLogger.warn("OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal");return false}stream.write(sequence,err=>{if(err)debugLogger.warn("writeOsc52: async write failed:",err)});return true}catch(e){debugLogger.warn("writeOsc52 failed:",e);return false}}__name(writeOsc52,"writeOsc52");var linuxClipboardTool;var cachedWlPasteTypes=null;var clipboardModulePromise=null;async function getClipboardModule(){if(!clipboardModulePromise){const modName="@teddyzhu/clipboard";clipboardModulePromise=import(modName).catch(()=>{debugLogger.error("Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable.");return null})}return clipboardModulePromise}__name(getClipboardModule,"getClipboardModule");function isWaylandSession(){return process.env["XDG_SESSION_TYPE"]?.toLowerCase()==="wayland"||Boolean(process.env["WAYLAND_DISPLAY"])}__name(isWaylandSession,"isWaylandSession");function getLinuxClipboardTool(){if(linuxClipboardTool!==void 0)return linuxClipboardTool;const sessionType=process.env["XDG_SESSION_TYPE"];const display=process.env["DISPLAY"];let toolName=null;if(isWaylandSession()){toolName="wl-paste"}else if(sessionType==="x11"||display){toolName="xclip"}else{linuxClipboardTool=null;return null}try{execSync("command -v "+toolName,{stdio:"ignore"});linuxClipboardTool=toolName;return toolName}catch{debugLogger.warn(`${toolName} not found`);linuxClipboardTool=null;return null}}__name(getLinuxClipboardTool,"getLinuxClipboardTool");async function saveFromCommand(command,args,destination){let fd;try{fd=await fs.open(destination,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL)}catch{return false}return new Promise(resolve=>{const child=spawn(command,args,{stdio:["ignore","pipe","pipe"]});const fileStream=fd.createWriteStream();let stderr="";let resolved=false;const safeResolve=__name(value=>{if(!resolved){resolved=true;try{if(!child.killed)child.kill()}catch{}try{fileStream.destroy()}catch{}resolve(value)}},"safeResolve");const timer=setTimeout(()=>{debugLogger.debug(`${command} timed out after ${PROCESS_TIMEOUT_MS}ms`);safeResolve(false)},PROCESS_TIMEOUT_MS);child.stderr.on("data",data=>{stderr+=data.toString()});child.stdout.pipe(fileStream);child.stdout.on("error",err=>{debugLogger.debug(`stdout error for ${command}:`,err);clearTimeout(timer);safeResolve(false)});child.on("error",err=>{debugLogger.debug(`Failed to spawn ${command}:`,err);clearTimeout(timer);safeResolve(false)});fileStream.on("error",err=>{debugLogger.debug(`File stream error for ${destination}:`,err);clearTimeout(timer);safeResolve(false)});child.on("close",code=>{clearTimeout(timer);if(resolved)return;if(code!==0){debugLogger.debug(`${command} exited with code ${code}. Args: ${args.join(" ")}`);if(stderr)debugLogger.debug(`${command} stderr: ${stderr.trim()}`);safeResolve(false);return}const checkFile=__name(()=>{fs.stat(destination).then(stats=>{safeResolve(stats.size>0)}).catch(()=>{safeResolve(false)})},"checkFile");if(fileStream.writableFinished){checkFile()}else{fileStream.on("finish",checkFile);fileStream.on("close",()=>{if(!resolved)checkFile()})}})})}__name(saveFromCommand,"saveFromCommand");var EMPTY_CLIPBOARD_STDERR_MARKERS=["target TARGETS not available","no owner for the","Nothing is copied","No selection"];function isEmptyClipboardError(stderr){return EMPTY_CLIPBOARD_STDERR_MARKERS.some(marker=>stderr.includes(marker))}__name(isEmptyClipboardError,"isEmptyClipboardError");var CLIPBOARD_IMAGE_TYPES=new Set(["image/png","image/bmp"]);async function checkClipboardForImage(command,args,onUnavailable){if(command==="wl-paste"&&args.length===1&&args[0]==="--list-types"){const types=await getWlPasteImageTypes(onUnavailable);return types.length>0}return new Promise(resolve=>{try{const child=spawn(command,args,{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`${command} timed out after ${PROCESS_TIMEOUT_MS}ms`);onUnavailable?.();resolve(false)},PROCESS_TIMEOUT_MS);child.stdout.on("data",data=>{stdout+=data.toString()});child.stderr.on("data",data=>{stderr+=data.toString()});child.on("close",code=>{clearTimeout(timer);if(settled)return;settled=true;if(code!==0){debugLogger.debug(`${command} exited with code ${code}. Args: ${args.join(" ")}`);if(stderr){debugLogger.debug(`${command} stderr: ${stderr.trim()}`)}if(isEmptyClipboardError(stderr)){resolve(false);return}onUnavailable?.();resolve(false);return}resolve(stdout.split("\n").map(line=>line.trim()).some(line=>CLIPBOARD_IMAGE_TYPES.has(line)))});child.on("error",err=>{clearTimeout(timer);if(settled)return;settled=true;debugLogger.debug(`Failed to spawn ${command}:`,err);onUnavailable?.();resolve(false)})}catch{onUnavailable?.();resolve(false)}})}__name(checkClipboardForImage,"checkClipboardForImage");async function clipboardHasImage(onUnavailable){cachedWlPasteTypes=null;if(process.platform==="linux"){try{const tool=getLinuxClipboardTool();if(tool==="wl-paste"){return checkClipboardForImage("wl-paste",["--list-types"],onUnavailable)}if(tool==="xclip"){return checkClipboardForImage("xclip",["-selection","clipboard","-t","TARGETS","-o"],onUnavailable)}onUnavailable?.()}catch(error){debugLogger.error("Error checking clipboard for image:",error)}return false}try{const mod=await getClipboardModule();if(!mod){onUnavailable?.();return false}const clipboard=new mod.ClipboardManager;return clipboard.hasFormat("image")}catch(error){debugLogger.error("Error checking clipboard for image:",error);onUnavailable?.();return false}}__name(clipboardHasImage,"clipboardHasImage");var PLAIN_TEXT_TYPES=new Set(["text/plain","utf8_string","string","text"]);var PLAIN_TIER_ORDER=["text/plain","utf8_string","string","text"];var BOOKKEEPING_TYPES=new Set(["targets","multiple","save_targets","delete","incr","timestamp","version"]);function baseTypeName(name){return name.trim().toLowerCase().split(";")[0].trim()}__name(baseTypeName,"baseTypeName");function classifyClipboardType(name){const base=baseTypeName(name);if(BOOKKEEPING_TYPES.has(base)){return null}if(PLAIN_TEXT_TYPES.has(base)){return"plain"}return base.startsWith("text/")?"other":null}__name(classifyClipboardType,"classifyClipboardType");function clipboardReadArgs(tool,type){return tool==="wl-paste"?["--no-newline","--type",type]:["-selection","clipboard","-t",type,"-o"]}__name(clipboardReadArgs,"clipboardReadArgs");var READ_DISCARDED_FOR_SIZE=Symbol("readDiscardedForSize");async function readStdout(command,args,latin1Fallback=false){return new Promise(resolve=>{let child;try{child=spawn(command,args,{stdio:["ignore","pipe","pipe"]})}catch(error){debugLogger.debug(`Failed to spawn ${command} ${args.join(" ")}:`,error);resolve("");return}const chunks=[];let received=0;let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`${command} ${args.join(" ")} timed out after ${PROCESS_TIMEOUT_MS}ms`);resolve("")},PROCESS_TIMEOUT_MS);const done=__name(value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)},"done");child.stdout.on("data",data=>{if(settled)return;received+=data.length;if(received>MAX_CLIPBOARD_TEXT_BYTES){try{child.kill()}catch{}debugLogger.debug(`${command} ${args.join(" ")} exceeded ${MAX_CLIPBOARD_TEXT_BYTES} bytes; discarding the read`);done(READ_DISCARDED_FOR_SIZE);return}chunks.push(data)});child.on("error",err=>{debugLogger.debug(`Failed to spawn ${command} ${args.join(" ")}:`,err);done("")});child.on("close",code=>{if(code===0){const bytes=Buffer.concat(chunks);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{text=latin1Fallback?bytes.toString("latin1"):bytes.toString("utf8")}done(text)}else{debugLogger.debug(`${command} ${args.join(" ")} exited with code ${code}`);done("")}})})}__name(readStdout,"readStdout");async function listWlPasteTypes(onUnavailable){if(cachedWlPasteTypes!==null){return cachedWlPasteTypes}return new Promise(resolve=>{let child;try{child=spawn("wl-paste",["--list-types"],{stdio:["ignore","pipe","pipe"]})}catch(error){debugLogger.error("Failed to spawn wl-paste --list-types:",error);onUnavailable?.();resolve([]);return}let stdout="";let stderr="";let settled=false;const timer=setTimeout(()=>{if(settled)return;settled=true;try{child.kill()}catch{}debugLogger.debug(`wl-paste --list-types timed out after ${PROCESS_TIMEOUT_MS}ms`);onUnavailable?.();resolve([])},PROCESS_TIMEOUT_MS);child.stdout.on("data",data=>{stdout+=data.toString()});child.stderr.on("data",data=>{stderr+=data.toString()});child.on("close",code=>{clearTimeout(timer);if(settled)return;settled=true;if(code!==0){debugLogger.debug(`wl-paste --list-types exited with code ${code}`);if(stderr){debugLogger.debug(`wl-paste stderr: ${stderr.trim()}`)}if(!isEmptyClipboardError(stderr)){onUnavailable?.()}resolve([]);return}const types=stdout.trim().split("\n").map(type=>type.trim()).filter(Boolean);cachedWlPasteTypes=types;resolve(types)});child.on("error",err=>{clearTimeout(timer);if(settled)return;settled=true;debugLogger.debug("Failed to spawn wl-paste --list-types:",err);onUnavailable?.();resolve([])})})}__name(listWlPasteTypes,"listWlPasteTypes");async function getWlPasteImageTypes(onUnavailable){const types=await listWlPasteTypes(onUnavailable);return types.filter(type=>CLIPBOARD_IMAGE_TYPES.has(type))}__name(getWlPasteImageTypes,"getWlPasteImageTypes");async function listClipboardTypes(tool){const names=tool==="wl-paste"?await listWlPasteTypes():await readStdout(tool,["-selection","clipboard","-t","TARGETS","-o"]).then(targets=>typeof targets==="string"?targets.split(/\s+/):[]);const types=[];for(const name of names){const tier=classifyClipboardType(name);if(tier){types.push({raw:name,tier})}}return types}__name(listClipboardTypes,"listClipboardTypes");async function readClipboardText(){if(process.platform!=="linux"){return null}const tool=getLinuxClipboardTool();if(!tool){return null}const offers=await listClipboardTypes(tool);for(const tier of["plain","other"]){const tierOffers=offers.filter(offer=>offer.tier===tier);if(tier==="plain"){tierOffers.sort((a,b)=>PLAIN_TIER_ORDER.indexOf(baseTypeName(a.raw))-PLAIN_TIER_ORDER.indexOf(baseTypeName(b.raw)))}for(const type of tierOffers){const base=baseTypeName(type.raw);const result=await readStdout(tool,clipboardReadArgs(tool,type.raw),base==="string"||base==="text");if(result===READ_DISCARDED_FOR_SIZE){return null}if(result===""){continue}const text=result.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\n+$/,"");const isUriList=base==="text/uri-list";const converted=isUriList?uriListToPaths(text):text;if(converted===""){if(isUriList){continue}return null}return converted.trim()?converted:null}}return null}__name(readClipboardText,"readClipboardText");function uriListToPaths(text){return text.split("\n").filter(line=>!line.startsWith("#")).map(line=>isFileUri(line)?fileUriToLocalPath(line)??line:line).join("\n")}__name(uriListToPaths,"uriListToPaths");async function saveFileWithWlPaste(tempFilePath){const imageTypes=await getWlPasteImageTypes();if(imageTypes.includes("image/png")){const success=await saveFromCommand("wl-paste",["--no-newline","--type","image/png"],tempFilePath);if(success)return tempFilePath;try{await fs.unlink(tempFilePath)}catch{}}if(imageTypes.includes("image/bmp")){const bmpPath=tempFilePath.replace(/\.png$/,".bmp");const bmpSuccess=await saveFromCommand("wl-paste",["--no-newline","--type","image/bmp"],bmpPath);if(bmpSuccess){try{await new Promise((resolve,reject)=>{const child=spawn("python3",["-c","import sys; from PIL import Image; Image.open(sys.argv[1]).save(sys.argv[2])",bmpPath,tempFilePath],{stdio:["ignore","ignore","pipe"]});let stderr="";child.stderr.on("data",d=>{stderr+=d.toString()});const timer=setTimeout(()=>{try{child.kill()}catch{}reject(new Error("python3 timed out"))},PROCESS_TIMEOUT_MS);child.on("close",code=>{clearTimeout(timer);if(code===0)resolve();else reject(new Error(`python3 exited with code ${code}${stderr?": "+stderr.trim():""}`))});child.on("error",err=>{clearTimeout(timer);reject(err)})});try{await fs.unlink(bmpPath)}catch{}return tempFilePath}catch(err){debugLogger.warn("BMP-to-PNG conversion failed (install python3-pil for BMP support):",err);try{await fs.unlink(bmpPath)}catch{}try{await fs.unlink(tempFilePath)}catch{}return false}}try{await fs.unlink(bmpPath)}catch{}}return false}__name(saveFileWithWlPaste,"saveFileWithWlPaste");async function saveFileWithXclip(tempFilePath){const success=await saveFromCommand("xclip",["-selection","clipboard","-t","image/png","-o"],tempFilePath);if(success)return true;try{await fs.unlink(tempFilePath)}catch{}return false}__name(saveFileWithXclip,"saveFileWithXclip");async function saveClipboardImage(targetDir){try{const baseDir=targetDir||process.cwd();const tempDir=path.join(baseDir,"clipboard");await fs.mkdir(tempDir,{recursive:true});const timestamp=new Date().getTime();if(process.platform==="linux"){const pngPath=path.join(tempDir,`clipboard-${timestamp}-${randomUUID()}.png`);const tool=getLinuxClipboardTool();if(tool==="wl-paste"){const savedPath=await saveFileWithWlPaste(pngPath);if(savedPath){try{const stats=await fs.stat(savedPath);if(stats.size>0)return savedPath;await fs.unlink(savedPath)}catch{}}return null}if(tool==="xclip"){if(await saveFileWithXclip(pngPath))return pngPath;return null}return null}const mod=await getClipboardModule();if(!mod)return null;const clipboard=new mod.ClipboardManager;if(!clipboard.hasFormat("image")){return null}const tempFilePath=path.join(tempDir,`clipboard-${timestamp}-${randomUUID()}.png`);const imageData=clipboard.getImageData();const buffer=imageData.data;if(!buffer){return null}await fs.writeFile(tempFilePath,buffer);return tempFilePath}catch(error){debugLogger.error("Error saving clipboard image:",error);return null}}__name(saveClipboardImage,"saveClipboardImage");async function cleanupOldClipboardImages(targetDir){try{const baseDir=targetDir||process.cwd();const tempDir=path.join(baseDir,"clipboard");const files=await fs.readdir(tempDir);const MAX_IMAGES=100;const CLEANUP_COUNT=50;const imageFiles=[];for(const file of files){if(file.startsWith("clipboard-")&&(file.endsWith(".png")||file.endsWith(".jpg")||file.endsWith(".webp")||file.endsWith(".heic")||file.endsWith(".heif")||file.endsWith(".tiff")||file.endsWith(".gif")||file.endsWith(".bmp"))){const filePath=path.join(tempDir,file);const stats=await fs.stat(filePath);imageFiles.push({name:file,path:filePath,atime:stats.atimeMs})}}if(imageFiles.length>MAX_IMAGES){imageFiles.sort((a,b)=>a.atime-b.atime);const removeCount=Math.min(CLEANUP_COUNT,imageFiles.length-MAX_IMAGES+CLEANUP_COUNT);const filesToRemove=imageFiles.slice(0,removeCount);for(const file of filesToRemove){await fs.unlink(file.path)}}}catch{}}__name(cleanupOldClipboardImages,"cleanupOldClipboardImages");export{KITTY_CTRL_C,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_KEYCODE_BACKSPACE,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MODIFIER_SHIFT_BIT,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SUPER_BIT,CTRL_EXIT_PROMPT_DURATION_MS,VSCODE_SHIFT_ENTER_SEQUENCE,BACKSLASH_ENTER_DETECTION_WINDOW_MS,MAX_KITTY_SEQUENCE_LENGTH,CHAR_CODE_ESC,BEL,OSC_PREFIX,detectTerminal,oscITerm2Notify,oscKittyNotify,oscGhosttyNotify,oscProgramStatus,oscProgramStatusClear,generateKittyId,isUncPath,isFileUri,fileUriToLocalPath,writeOsc52,isWaylandSession,clipboardHasImage,readClipboardText,saveClipboardImage,cleanupOldClipboardImages};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getWritableScopes}from"./chunk-JRIVHFCG.js";import{publicProviderBaseUrl}from"./chunk-YQXX44YA.js";import{isImageGenerationCapable,tryResolveModelProtocol}from"./chunk-OHOG4HSN.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function modelKey(scope,provider,model,authType){return createHash("sha256").update(JSON.stringify([scope,provider,model.id,model.baseUrl??"",authType])).digest("hex")}__name(modelKey,"modelKey");function modelEntries(loaded){const seenProviders=new Set;return["System",...getWritableScopes(loaded),"SystemDefaults"].flatMap(scope=>{const providers=loaded.forScope(scope).settings.modelProviders??{};return Object.entries(providers).flatMap(([provider,models])=>{if(seenProviders.has(provider))return[];seenProviders.add(provider);if(!Array.isArray(models))return[];return models.flatMap((model,index)=>{if(!model||typeof model!=="object"||typeof model.id!=="string"||!model.id||model.baseUrl!==void 0&&typeof model.baseUrl!=="string")return[];const authType=tryResolveModelProtocol(provider,model,loaded.merged.providerProtocol);if(!authType||authType==="qwen-oauth")return[];return[{scope,provider,authType,model,index,key:modelKey(scope,provider,model,authType)}]})})})}__name(modelEntries,"modelEntries");function findModelConfiguration(loaded,key){const matches=modelEntries(loaded).filter(entry=>entry.key===key);return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:void 0}__name(findModelConfiguration,"findModelConfiguration");function findModelConfigurationForDeletion(loaded,target){const candidates=modelEntries(loaded).filter(entry=>entry.authType===target.authType&&entry.model.id===target.modelId);const exact=candidates.filter(entry=>(entry.model.baseUrl??void 0)===target.baseUrl);const matches=target.baseUrl!==void 0&&exact.length?exact:candidates;if(matches.length===0)return void 0;return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:"ambiguous"}__name(findModelConfigurationForDeletion,"findModelConfigurationForDeletion");function getModelConfigurationKey(loaded,authType,modelId,baseUrl){const matches=modelEntries(loaded).filter(entry=>entry.authType===authType&&entry.model.id===modelId&&(entry.model.baseUrl??"")===(baseUrl??""));return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0].key:void 0}__name(getModelConfigurationKey,"getModelConfigurationKey");function isConversationModelConfiguration(model){return!model.imageOnly&&!model.voiceOnly&&!model.fastOnly&&!model.visionOnly&&!model.realtimeOnly}__name(isConversationModelConfiguration,"isConversationModelConfiguration");function isImageModelConfiguration(model){if(!isImageGenerationCapable(model)||model.fastOnly||model.voiceOnly||model.realtimeOnly||!model.baseUrl||typeof model.envKey!=="string"||!model.envKey.trim())return false;try{const url=new URL(model.baseUrl);return url.protocol==="https:"&&!url.username&&!url.password&&!url.search&&!url.hash}catch{return false}}__name(isImageModelConfiguration,"isImageModelConfiguration");function listModelConfigurations(loaded){const entries=modelEntries(loaded);const routeKey=__name(entry=>JSON.stringify([entry.authType,entry.model.id,entry.model.baseUrl??""]),"routeKey");const counts=new Map;for(const entry of entries){const route=routeKey(entry);counts.set(route,(counts.get(route)??0)+1)}const writableScopes=getWritableScopes(loaded);return entries.filter(entry=>writableScopes.includes(entry.scope)).map(entry=>{const{model,authType,key}=entry;const uniqueRoute=counts.get(routeKey(entry))===1;let imageModel;let advisorModel;if(uniqueRoute&&isConversationModelConfiguration(model)){if(!model.baseUrl)advisorModel=`${authType}:${model.id}\0`;else{try{const url=new URL(model.baseUrl);if(["https:","http:"].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash)advisorModel=`${authType}:${model.id}\0${model.baseUrl}`}catch{}}}if(uniqueRoute&&isImageModelConfiguration(model)){imageModel=`${authType}:${model.id}\0${model.baseUrl}`}return{key,authType,modelId:model.id,name:model.name,baseUrl:model.baseUrl?publicProviderBaseUrl(model.baseUrl):void 0,envKey:typeof model.envKey==="string"?model.envKey:void 0,contextWindowSize:typeof model.generationConfig?.contextWindowSize==="number"&&Number.isInteger(model.generationConfig.contextWindowSize)&&model.generationConfig.contextWindowSize>0?model.generationConfig.contextWindowSize:void 0,canEditContextWindow:uniqueRoute,purpose:model.imageOnly===true?"image":model.voiceOnly===true?"voice":model.realtimeOnly===true?"realtime":"chat",...imageModel?{imageModel}:{},...advisorModel?{advisorModel}:{}}})}__name(listModelConfigurations,"listModelConfigurations");function updateModelContextWindow(loaded,key,contextWindowSize,assertGenerationOpen){const match=findModelConfiguration(loaded,key);if(!match)return void 0;if(getModelConfigurationKey(loaded,match.authType,match.model.id,match.model.baseUrl)!==key)return void 0;const{scope,provider,index}=match;const providers=loaded.forScope(scope).originalSettings.modelProviders??{};const model=providers[provider][index];const generationConfig={...model.generationConfig};if(contextWindowSize===null)delete generationConfig.contextWindowSize;else generationConfig.contextWindowSize=contextWindowSize;const updated={...model,generationConfig};if(Object.keys(generationConfig).length===0)delete updated.generationConfig;loaded.setValue(scope,"modelProviders",{...providers,[provider]:providers[provider].map((entry,i)=>i===index?updated:entry)},assertGenerationOpen,{throwOnWriteFailure:true});return scope==="Workspace"?"workspace":"user"}__name(updateModelContextWindow,"updateModelContextWindow");export{findModelConfiguration,findModelConfigurationForDeletion,getModelConfigurationKey,isConversationModelConfiguration,isImageModelConfiguration,listModelConfigurations,updateModelContextWindow};
3
+ import{getWritableScopes}from"./chunk-4RJ2RRGZ.js";import{publicProviderBaseUrl}from"./chunk-YQXX44YA.js";import{isImageGenerationCapable,tryResolveModelProtocol}from"./chunk-SINRWOVD.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function modelKey(scope,provider,model,authType){return createHash("sha256").update(JSON.stringify([scope,provider,model.id,model.baseUrl??"",authType])).digest("hex")}__name(modelKey,"modelKey");function modelEntries(loaded){const seenProviders=new Set;return["System",...getWritableScopes(loaded),"SystemDefaults"].flatMap(scope=>{const providers=loaded.forScope(scope).settings.modelProviders??{};return Object.entries(providers).flatMap(([provider,models])=>{if(seenProviders.has(provider))return[];seenProviders.add(provider);if(!Array.isArray(models))return[];return models.flatMap((model,index)=>{if(!model||typeof model!=="object"||typeof model.id!=="string"||!model.id||model.baseUrl!==void 0&&typeof model.baseUrl!=="string")return[];const authType=tryResolveModelProtocol(provider,model,loaded.merged.providerProtocol);if(!authType||authType==="qwen-oauth")return[];return[{scope,provider,authType,model,index,key:modelKey(scope,provider,model,authType)}]})})})}__name(modelEntries,"modelEntries");function findModelConfiguration(loaded,key){const matches=modelEntries(loaded).filter(entry=>entry.key===key);return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:void 0}__name(findModelConfiguration,"findModelConfiguration");function findModelConfigurationForDeletion(loaded,target){const candidates=modelEntries(loaded).filter(entry=>entry.authType===target.authType&&entry.model.id===target.modelId);const exact=candidates.filter(entry=>(entry.model.baseUrl??void 0)===target.baseUrl);const matches=target.baseUrl!==void 0&&exact.length?exact:candidates;if(matches.length===0)return void 0;return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:"ambiguous"}__name(findModelConfigurationForDeletion,"findModelConfigurationForDeletion");function getModelConfigurationKey(loaded,authType,modelId,baseUrl){const matches=modelEntries(loaded).filter(entry=>entry.authType===authType&&entry.model.id===modelId&&(entry.model.baseUrl??"")===(baseUrl??""));return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0].key:void 0}__name(getModelConfigurationKey,"getModelConfigurationKey");function isConversationModelConfiguration(model){return!model.imageOnly&&!model.voiceOnly&&!model.fastOnly&&!model.visionOnly&&!model.realtimeOnly}__name(isConversationModelConfiguration,"isConversationModelConfiguration");function isImageModelConfiguration(model){if(!isImageGenerationCapable(model)||model.fastOnly||model.voiceOnly||model.realtimeOnly||!model.baseUrl||typeof model.envKey!=="string"||!model.envKey.trim())return false;try{const url=new URL(model.baseUrl);return url.protocol==="https:"&&!url.username&&!url.password&&!url.search&&!url.hash}catch{return false}}__name(isImageModelConfiguration,"isImageModelConfiguration");function listModelConfigurations(loaded){const entries=modelEntries(loaded);const routeKey=__name(entry=>JSON.stringify([entry.authType,entry.model.id,entry.model.baseUrl??""]),"routeKey");const counts=new Map;for(const entry of entries){const route=routeKey(entry);counts.set(route,(counts.get(route)??0)+1)}const writableScopes=getWritableScopes(loaded);return entries.filter(entry=>writableScopes.includes(entry.scope)).map(entry=>{const{model,authType,key}=entry;const uniqueRoute=counts.get(routeKey(entry))===1;let imageModel;let advisorModel;if(uniqueRoute&&isConversationModelConfiguration(model)){if(!model.baseUrl)advisorModel=`${authType}:${model.id}\0`;else{try{const url=new URL(model.baseUrl);if(["https:","http:"].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash)advisorModel=`${authType}:${model.id}\0${model.baseUrl}`}catch{}}}if(uniqueRoute&&isImageModelConfiguration(model)){imageModel=`${authType}:${model.id}\0${model.baseUrl}`}return{key,authType,modelId:model.id,name:model.name,baseUrl:model.baseUrl?publicProviderBaseUrl(model.baseUrl):void 0,envKey:typeof model.envKey==="string"?model.envKey:void 0,contextWindowSize:typeof model.generationConfig?.contextWindowSize==="number"&&Number.isInteger(model.generationConfig.contextWindowSize)&&model.generationConfig.contextWindowSize>0?model.generationConfig.contextWindowSize:void 0,canEditContextWindow:uniqueRoute,purpose:model.imageOnly===true?"image":model.voiceOnly===true?"voice":model.realtimeOnly===true?"realtime":"chat",...imageModel?{imageModel}:{},...advisorModel?{advisorModel}:{}}})}__name(listModelConfigurations,"listModelConfigurations");function updateModelContextWindow(loaded,key,contextWindowSize,assertGenerationOpen){const match=findModelConfiguration(loaded,key);if(!match)return void 0;if(getModelConfigurationKey(loaded,match.authType,match.model.id,match.model.baseUrl)!==key)return void 0;const{scope,provider,index}=match;const providers=loaded.forScope(scope).originalSettings.modelProviders??{};const model=providers[provider][index];const generationConfig={...model.generationConfig};if(contextWindowSize===null)delete generationConfig.contextWindowSize;else generationConfig.contextWindowSize=contextWindowSize;const updated={...model,generationConfig};if(Object.keys(generationConfig).length===0)delete updated.generationConfig;loaded.setValue(scope,"modelProviders",{...providers,[provider]:providers[provider].map((entry,i)=>i===index?updated:entry)},assertGenerationOpen,{throwOnWriteFailure:true});return scope==="Workspace"?"workspace":"user"}__name(updateModelContextWindow,"updateModelContextWindow");export{findModelConfiguration,findModelConfigurationForDeletion,getModelConfigurationKey,isConversationModelConfiguration,isImageModelConfiguration,listModelConfigurations,updateModelContextWindow};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-AHV4IMUX.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,ensureCrlfLineEndings,getDiffStat,needsUtf8Bom}from"./chunk-POMEWCFJ.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,ReadFileTool,getLanguageFromFilePath,logFileOperation}from"./chunk-MJEL7DIE.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-6JHMYZNS.js";import{safeLiteralReplace}from"./chunk-DBRQGEEI.js";import{BaseDeclarativeTool,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";init_esbuild_shims();var UNICODE_EQUIVALENT_MAP={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function normalizeBasicCharacters(text){if(text===""){return text}let normalized="";for(const char of text){normalized+=UNICODE_EQUIVALENT_MAP[char]??char}return normalized}__name(normalizeBasicCharacters,"normalizeBasicCharacters");var LINE_COMPARISON_PASSES=[value=>value,value=>value.trimEnd()];function normalizeLineForComparison(value){return normalizeBasicCharacters(value).trimEnd()}__name(normalizeLineForComparison,"normalizeLineForComparison");function seekSequenceWithTransform(lines,pattern,transform){if(pattern.length===0){return 0}if(pattern.length>lines.length){return null}outer:for(let i=0;i<=lines.length-pattern.length;i++){for(let p=0;p<pattern.length;p++){if(transform(lines[i+p])!==transform(pattern[p])){continue outer}}return i}return null}__name(seekSequenceWithTransform,"seekSequenceWithTransform");function buildLineIndex(text){const lines=text.split("\n");const offsets=new Array(lines.length+1);let cursor=0;for(let i=0;i<lines.length;i++){offsets[i]=cursor;cursor+=lines[i].length;if(i<lines.length-1){cursor+=1}}offsets[lines.length]=text.length;return{lines,offsets}}__name(buildLineIndex,"buildLineIndex");function sliceFromLines(text,offsets,lines,startLine,lineCount,includeTrailingNewline){if(lineCount===0){return includeTrailingNewline?"\n":""}const startIndex=offsets[startLine]??0;const lastLineIndex=startLine+lineCount-1;const lastLineStart=offsets[lastLineIndex]??0;let endIndex=lastLineStart+(lines[lastLineIndex]?.length??0);if(includeTrailingNewline){const nextLineStart=offsets[startLine+lineCount];if(nextLineStart!==void 0){endIndex=nextLineStart}else if(text.endsWith("\n")){endIndex=text.length}}return text.slice(startIndex,endIndex)}__name(sliceFromLines,"sliceFromLines");function findLineBasedMatch(haystack,needle){const{lines,offsets}=buildLineIndex(haystack);const patternLines=needle.split("\n");const endsWithNewline=needle.endsWith("\n");if(patternLines.length===0){return null}const attemptMatch=__name(candidate=>{for(const pass of LINE_COMPARISON_PASSES){const idx=seekSequenceWithTransform(lines,candidate,pass);if(idx!==null){return idx}}return seekSequenceWithTransform(lines,candidate,normalizeLineForComparison)},"attemptMatch");let matchIndex=attemptMatch(patternLines);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,patternLines.length-(endsWithNewline?1:0),endsWithNewline),removedTrailingFinalEmptyLine:false,lineBasedMatch:true}}if(patternLines.at(-1)===""){const trimmedPattern=patternLines.slice(0,-1);if(trimmedPattern.length===0){return null}matchIndex=attemptMatch(trimmedPattern);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,trimmedPattern.length,false),removedTrailingFinalEmptyLine:true,lineBasedMatch:true}}}return null}__name(findLineBasedMatch,"findLineBasedMatch");function findMatchedSlice(haystack,needle){if(needle===""){return null}const literalIndex=haystack.indexOf(needle);if(literalIndex!==-1){return{slice:haystack.slice(literalIndex,literalIndex+needle.length),removedTrailingFinalEmptyLine:false}}const normalizedHaystack=normalizeBasicCharacters(haystack);const normalizedNeedleChars=normalizeBasicCharacters(needle);const normalizedIndex=normalizedHaystack.indexOf(normalizedNeedleChars);if(normalizedIndex!==-1){return{slice:haystack.slice(normalizedIndex,normalizedIndex+needle.length),removedTrailingFinalEmptyLine:false}}return findLineBasedMatch(haystack,needle)}__name(findMatchedSlice,"findMatchedSlice");function removeTrailingNewline(text){if(text.endsWith("\r\n")){return text.slice(0,-2)}if(text.endsWith("\n")||text.endsWith("\r")){return text.slice(0,-1)}return text}__name(removeTrailingNewline,"removeTrailingNewline");function adjustNewStringForTrailingLine(newString,removedTrailingLine){return removedTrailingLine?removeTrailingNewline(newString):newString}__name(adjustNewStringForTrailingLine,"adjustNewStringForTrailingLine");var UNICODE_ESCAPE_PATTERN=/\\\\|\\u[0-9a-fA-F]{4}/g;var MAX_UNICODE_RECOVERY_CODE_UNITS=256;function decodeUnicodeEscapes(text){const decoded=text.replace(UNICODE_ESCAPE_PATTERN,escape=>{if(escape.length===2)return escape;const code=parseInt(escape.slice(2),16);return code>=128?String.fromCharCode(code):escape});return/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(decoded)?null:decoded}__name(decodeUnicodeEscapes,"decodeUnicodeEscapes");function splitsEscapeSequence(text,offset){if(text[offset-1]==="\\"&&/[\\'"/bfnrtv0]/.test(text[offset]??"")){return true}for(let start=Math.max(0,offset-5);start<offset;start++){if(text[start]==="\\"&&/^\\u[0-9a-fA-F]{4}$/.test(text.slice(start,start+6))){return true}}return false}__name(splitsEscapeSequence,"splitsEscapeSequence");function findUnicodeEscapeMatch(fileContent,oldString,newString){const decoded=decodeUnicodeEscapes(oldString);if(decoded===null||decoded.length>MAX_UNICODE_RECOVERY_CODE_UNITS||!/[\u0080-\uffff]/.test(decoded)){return null}if(decoded===oldString&&!fileContent.includes("\\u"))return null;const pattern=decoded.split("").map(char=>{const literal=char.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(char.charCodeAt(0)<128)return literal;const hex=char.charCodeAt(0).toString(16).padStart(4,"0").replace(/[a-f]/g,digit=>`[${digit}${digit.toUpperCase()}]`);return`(?:${literal}|(?<!\\\\)\\\\u${hex})`}).join("");let canonical;let literalSearchStart=0;const trailingBackslash=/(?:^|[^\\])(?:\\\\)*\\$/.test(newString);for(const match of fileContent.matchAll(new RegExp(pattern,"g"))){const end=match.index+match[0].length;if(splitsEscapeSequence(fileContent,match.index)||splitsEscapeSequence(fileContent,end)||trailingBackslash&&fileContent[end]==="\\"){return null}if(canonical!==void 0&&canonical!==match[0])return null;canonical=match[0];if(fileContent.indexOf(canonical,literalSearchStart)!==match.index){return null}literalSearchStart=match.index+canonical.length}if(canonical===void 0)return null;if(fileContent.indexOf(canonical,literalSearchStart)!==-1)return null;const escapes=Array.from(canonical.matchAll(UNICODE_ESCAPE_PATTERN),match=>match[0]).filter(escape=>escape.length===6&&parseInt(escape.slice(2),16)>=128);if(escapes.length===0){return{oldString:canonical,newString:decodeUnicodeEscapes(newString)??newString}}if(/[\u0080-\uffff]/.test(canonical))return null;if(/(?:^|[^\\])(?:\\\\)*\\[\u0080-\uffff]/.test(newString))return null;const byChar=new Map(escapes.map(escape=>[String.fromCharCode(parseInt(escape.slice(2),16)),escape]));const digits=escapes.join("").replace(/\\u/g,"");const uppercase=(digits.match(/[A-F]/g)?.length??0)>(digits.match(/[a-f]/g)?.length??0);return{oldString:canonical,newString:newString.split("").map(char=>{if(char.charCodeAt(0)<128)return char;const hex=char.charCodeAt(0).toString(16).padStart(4,"0");return byChar.get(char)??"\\u"+(uppercase?hex.toUpperCase():hex)}).join("")}}__name(findUnicodeEscapeMatch,"findUnicodeEscapeMatch");function normalizeEditStrings(fileContent,oldString,newString){if(fileContent===null||oldString===""){return{oldString,newString}}const canonicalOriginal=findMatchedSlice(fileContent,oldString);if(canonicalOriginal!==null){return{oldString:canonicalOriginal.slice,newString:adjustNewStringForTrailingLine(newString,canonicalOriginal.removedTrailingFinalEmptyLine),...canonicalOriginal.lineBasedMatch?{lineBasedMatch:true}:{}}}return findUnicodeEscapeMatch(fileContent,oldString,newString)??{oldString,newString}}__name(normalizeEditStrings,"normalizeEditStrings");function maybeAugmentOldStringForDeletion(fileContent,oldString,newString,lineBasedMatch=false){if(fileContent===null||oldString===""||newString!==""||oldString.endsWith("\n")){return oldString}const candidate=`${oldString}
3
+ import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-E4QOAV5O.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-VFFTE2PS.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-54CHQYA3.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,ensureCrlfLineEndings,getDiffStat,needsUtf8Bom}from"./chunk-ZUWLTGSR.js";import{backgroundFixHolding}from"./chunk-B5ZFH363.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{FileOperationEvent,ReadFileTool,getLanguageFromFilePath,logFileOperation}from"./chunk-MJEL7DIE.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-6JHMYZNS.js";import{safeLiteralReplace}from"./chunk-DBRQGEEI.js";import{BaseDeclarativeTool,StructuredToolError}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";init_esbuild_shims();var UNICODE_EQUIVALENT_MAP={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function normalizeBasicCharacters(text){if(text===""){return text}let normalized="";for(const char of text){normalized+=UNICODE_EQUIVALENT_MAP[char]??char}return normalized}__name(normalizeBasicCharacters,"normalizeBasicCharacters");var LINE_COMPARISON_PASSES=[value=>value,value=>value.trimEnd()];function normalizeLineForComparison(value){return normalizeBasicCharacters(value).trimEnd()}__name(normalizeLineForComparison,"normalizeLineForComparison");function seekSequenceWithTransform(lines,pattern,transform){if(pattern.length===0){return 0}if(pattern.length>lines.length){return null}outer:for(let i=0;i<=lines.length-pattern.length;i++){for(let p=0;p<pattern.length;p++){if(transform(lines[i+p])!==transform(pattern[p])){continue outer}}return i}return null}__name(seekSequenceWithTransform,"seekSequenceWithTransform");function buildLineIndex(text){const lines=text.split("\n");const offsets=new Array(lines.length+1);let cursor=0;for(let i=0;i<lines.length;i++){offsets[i]=cursor;cursor+=lines[i].length;if(i<lines.length-1){cursor+=1}}offsets[lines.length]=text.length;return{lines,offsets}}__name(buildLineIndex,"buildLineIndex");function sliceFromLines(text,offsets,lines,startLine,lineCount,includeTrailingNewline){if(lineCount===0){return includeTrailingNewline?"\n":""}const startIndex=offsets[startLine]??0;const lastLineIndex=startLine+lineCount-1;const lastLineStart=offsets[lastLineIndex]??0;let endIndex=lastLineStart+(lines[lastLineIndex]?.length??0);if(includeTrailingNewline){const nextLineStart=offsets[startLine+lineCount];if(nextLineStart!==void 0){endIndex=nextLineStart}else if(text.endsWith("\n")){endIndex=text.length}}return text.slice(startIndex,endIndex)}__name(sliceFromLines,"sliceFromLines");function findLineBasedMatch(haystack,needle){const{lines,offsets}=buildLineIndex(haystack);const patternLines=needle.split("\n");const endsWithNewline=needle.endsWith("\n");if(patternLines.length===0){return null}const attemptMatch=__name(candidate=>{for(const pass of LINE_COMPARISON_PASSES){const idx=seekSequenceWithTransform(lines,candidate,pass);if(idx!==null){return idx}}return seekSequenceWithTransform(lines,candidate,normalizeLineForComparison)},"attemptMatch");let matchIndex=attemptMatch(patternLines);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,patternLines.length-(endsWithNewline?1:0),endsWithNewline),removedTrailingFinalEmptyLine:false,lineBasedMatch:true}}if(patternLines.at(-1)===""){const trimmedPattern=patternLines.slice(0,-1);if(trimmedPattern.length===0){return null}matchIndex=attemptMatch(trimmedPattern);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,trimmedPattern.length,false),removedTrailingFinalEmptyLine:true,lineBasedMatch:true}}}return null}__name(findLineBasedMatch,"findLineBasedMatch");function findMatchedSlice(haystack,needle){if(needle===""){return null}const literalIndex=haystack.indexOf(needle);if(literalIndex!==-1){return{slice:haystack.slice(literalIndex,literalIndex+needle.length),removedTrailingFinalEmptyLine:false}}const normalizedHaystack=normalizeBasicCharacters(haystack);const normalizedNeedleChars=normalizeBasicCharacters(needle);const normalizedIndex=normalizedHaystack.indexOf(normalizedNeedleChars);if(normalizedIndex!==-1){return{slice:haystack.slice(normalizedIndex,normalizedIndex+needle.length),removedTrailingFinalEmptyLine:false}}return findLineBasedMatch(haystack,needle)}__name(findMatchedSlice,"findMatchedSlice");function removeTrailingNewline(text){if(text.endsWith("\r\n")){return text.slice(0,-2)}if(text.endsWith("\n")||text.endsWith("\r")){return text.slice(0,-1)}return text}__name(removeTrailingNewline,"removeTrailingNewline");function adjustNewStringForTrailingLine(newString,removedTrailingLine){return removedTrailingLine?removeTrailingNewline(newString):newString}__name(adjustNewStringForTrailingLine,"adjustNewStringForTrailingLine");var UNICODE_ESCAPE_PATTERN=/\\\\|\\u[0-9a-fA-F]{4}/g;var MAX_UNICODE_RECOVERY_CODE_UNITS=256;function decodeUnicodeEscapes(text){const decoded=text.replace(UNICODE_ESCAPE_PATTERN,escape=>{if(escape.length===2)return escape;const code=parseInt(escape.slice(2),16);return code>=128?String.fromCharCode(code):escape});return/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(decoded)?null:decoded}__name(decodeUnicodeEscapes,"decodeUnicodeEscapes");function splitsEscapeSequence(text,offset){if(text[offset-1]==="\\"&&/[\\'"/bfnrtv0]/.test(text[offset]??"")){return true}for(let start=Math.max(0,offset-5);start<offset;start++){if(text[start]==="\\"&&/^\\u[0-9a-fA-F]{4}$/.test(text.slice(start,start+6))){return true}}return false}__name(splitsEscapeSequence,"splitsEscapeSequence");function findUnicodeEscapeMatch(fileContent,oldString,newString){const decoded=decodeUnicodeEscapes(oldString);if(decoded===null||decoded.length>MAX_UNICODE_RECOVERY_CODE_UNITS||!/[\u0080-\uffff]/.test(decoded)){return null}if(decoded===oldString&&!fileContent.includes("\\u"))return null;const pattern=decoded.split("").map(char=>{const literal=char.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(char.charCodeAt(0)<128)return literal;const hex=char.charCodeAt(0).toString(16).padStart(4,"0").replace(/[a-f]/g,digit=>`[${digit}${digit.toUpperCase()}]`);return`(?:${literal}|(?<!\\\\)\\\\u${hex})`}).join("");let canonical;let literalSearchStart=0;const trailingBackslash=/(?:^|[^\\])(?:\\\\)*\\$/.test(newString);for(const match of fileContent.matchAll(new RegExp(pattern,"g"))){const end=match.index+match[0].length;if(splitsEscapeSequence(fileContent,match.index)||splitsEscapeSequence(fileContent,end)||trailingBackslash&&fileContent[end]==="\\"){return null}if(canonical!==void 0&&canonical!==match[0])return null;canonical=match[0];if(fileContent.indexOf(canonical,literalSearchStart)!==match.index){return null}literalSearchStart=match.index+canonical.length}if(canonical===void 0)return null;if(fileContent.indexOf(canonical,literalSearchStart)!==-1)return null;const escapes=Array.from(canonical.matchAll(UNICODE_ESCAPE_PATTERN),match=>match[0]).filter(escape=>escape.length===6&&parseInt(escape.slice(2),16)>=128);if(escapes.length===0){return{oldString:canonical,newString:decodeUnicodeEscapes(newString)??newString}}if(/[\u0080-\uffff]/.test(canonical))return null;if(/(?:^|[^\\])(?:\\\\)*\\[\u0080-\uffff]/.test(newString))return null;const byChar=new Map(escapes.map(escape=>[String.fromCharCode(parseInt(escape.slice(2),16)),escape]));const digits=escapes.join("").replace(/\\u/g,"");const uppercase=(digits.match(/[A-F]/g)?.length??0)>(digits.match(/[a-f]/g)?.length??0);return{oldString:canonical,newString:newString.split("").map(char=>{if(char.charCodeAt(0)<128)return char;const hex=char.charCodeAt(0).toString(16).padStart(4,"0");return byChar.get(char)??"\\u"+(uppercase?hex.toUpperCase():hex)}).join("")}}__name(findUnicodeEscapeMatch,"findUnicodeEscapeMatch");function normalizeEditStrings(fileContent,oldString,newString){if(fileContent===null||oldString===""){return{oldString,newString}}const canonicalOriginal=findMatchedSlice(fileContent,oldString);if(canonicalOriginal!==null){return{oldString:canonicalOriginal.slice,newString:adjustNewStringForTrailingLine(newString,canonicalOriginal.removedTrailingFinalEmptyLine),...canonicalOriginal.lineBasedMatch?{lineBasedMatch:true}:{}}}return findUnicodeEscapeMatch(fileContent,oldString,newString)??{oldString,newString}}__name(normalizeEditStrings,"normalizeEditStrings");function maybeAugmentOldStringForDeletion(fileContent,oldString,newString,lineBasedMatch=false){if(fileContent===null||oldString===""||newString!==""||oldString.endsWith("\n")){return oldString}const candidate=`${oldString}
4
4
  `;const hasCandidate=lineBasedMatch?findLineBasedMatchOffsets(fileContent,candidate).length>0:fileContent.includes(candidate);return hasCandidate?candidate:oldString}__name(maybeAugmentOldStringForDeletion,"maybeAugmentOldStringForDeletion");function countOccurrences(source,substr){if(substr===""){return 0}let count=0;let index=source.indexOf(substr);while(index!==-1){count++;index=source.indexOf(substr,index+substr.length)}return count}__name(countOccurrences,"countOccurrences");function findLineBasedMatchOffsets(source,substr){const offsets=[];if(substr===""){return offsets}let index=source.indexOf(substr);while(index!==-1){const end=index+substr.length;const startsLine=index===0||source[index-1]==="\n";const endsLine=substr.endsWith("\n")||end===source.length||source[end]==="\n";if(startsLine&&endsLine){offsets.push(index);index=source.indexOf(substr,end)}else{index=source.indexOf(substr,index+1)}}return offsets}__name(findLineBasedMatchOffsets,"findLineBasedMatchOffsets");var SNIPPET_CONTEXT_LINES=4;var SNIPPET_MAX_LINES=1e3;function extractEditSnippet(oldContent,newContent){const newLines=newContent.split("\n");const totalLines=newLines.length;if(oldContent===null){return{startLine:1,endLine:totalLines,totalLines,content:newContent}}if(oldContent===newContent||!newContent){return null}const oldLines=oldContent.split("\n");let firstDiffLine=0;const minLength=Math.min(oldLines.length,newLines.length);while(firstDiffLine<minLength){if(oldLines[firstDiffLine]!==newLines[firstDiffLine]){break}firstDiffLine++}let oldEndIndex=oldLines.length-1;let newEndIndex=newLines.length-1;while(oldEndIndex>=firstDiffLine&&newEndIndex>=firstDiffLine){if(oldLines[oldEndIndex]!==newLines[newEndIndex]){break}oldEndIndex--;newEndIndex--}const changeStart=firstDiffLine+1;const changeEnd=newEndIndex+1;if(changeEnd-changeStart>SNIPPET_MAX_LINES){return null}const snippetStart=Math.max(1,changeStart-SNIPPET_CONTEXT_LINES);const snippetEnd=Math.min(totalLines,changeEnd+SNIPPET_CONTEXT_LINES);const snippetLines=newLines.slice(snippetStart-1,snippetEnd);return{startLine:snippetStart,endLine:snippetEnd,totalLines,content:snippetLines.join("\n")}}__name(extractEditSnippet,"extractEditSnippet");var debugLogger=createDebugLogger("EDIT_PRIOR_READ");function applyReplacement(currentContent,oldString,newString,isNewFile,matchOffsets){if(isNewFile){return newString}if(currentContent===null){return oldString===""?newString:""}if(oldString===""&&!isNewFile){return currentContent}if(matchOffsets!==void 0){const pieces=[];let cursor=0;for(const offset of matchOffsets){pieces.push(currentContent.slice(cursor,offset),newString);cursor=offset+oldString.length}pieces.push(currentContent.slice(cursor));return pieces.join("")}return safeLiteralReplace(currentContent,oldString,newString)}__name(applyReplacement,"applyReplacement");var EditToolInvocation=class{constructor(config,params){this.config=config;this.params=params}static{__name(this,"EditToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}async calculateEdit(params,original,signal){const observation=original??await this.config.getFileSystemService().textFileIo?.inspect(params.file_path,signal);const sandboxFileVersion=captureRuntimeFileVersion(this.config,params.file_path);const replaceAll=params.replace_all??false;let currentContent=null;let fileExists2=observation?observation.kind==="file":await fileExists(params.file_path);let isNewFile=false;let finalNewString=params.new_string;let finalOldString=params.old_string;let occurrences=0;let error=void 0;let useBOM=false;let detectedEncoding="utf-8";let detectedLineEnding="lf";if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing");if(!decision.ok){return{currentContent:null,newContent:"",occurrences:0,error:{display:decision.displayMessage,raw:decision.rawMessage,type:decision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}if(fileExists2){try{const fileInfo=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:params.file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);currentContent=fileInfo.content.replace(/\r\n/g,"\n");fileExists2=true}catch(err){if(!isNodeError(err)||err.code!=="ENOENT"){throw err}fileExists2=false}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection",{path:params.file_path,reason:postDecision.type});return{currentContent:null,newContent:"",occurrences:0,error:{display:postDecision.displayMessage,raw:postDecision.rawMessage,type:postDecision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}const normalizedStrings=normalizeEditStrings(currentContent,finalOldString,finalNewString);finalOldString=normalizedStrings.oldString;finalNewString=normalizedStrings.newString;let matchOffsets;if(finalOldString===""&&!fileExists2){isNewFile=true}else if(!fileExists2){error={display:`File not found. Cannot apply edit. Use an empty old_string to create a new file.`,raw:`File not found: ${params.file_path}`,type:"file_not_found"}}else if(currentContent!==null){finalOldString=maybeAugmentOldStringForDeletion(currentContent,finalOldString,finalNewString,normalizedStrings.lineBasedMatch);if(normalizedStrings.lineBasedMatch){matchOffsets=findLineBasedMatchOffsets(currentContent,finalOldString)}occurrences=matchOffsets?.length??countOccurrences(currentContent,finalOldString);if(params.old_string===""){error={display:`Failed to edit. Attempted to create a file that already exists.`,raw:`File already exists, cannot create: ${params.file_path}`,type:"attempt_to_create_existing_file"}}else if(occurrences===0){error={display:`Failed to edit, could not find the string to replace.`,raw:`Failed to edit, 0 occurrences found for old_string in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,type:"edit_no_occurrence_found"}}else if(!replaceAll&&occurrences>1){error={display:`Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.`,raw:`Failed to edit. Found ${occurrences} occurrences for old_string in ${params.file_path} but replace_all was not enabled.`,type:"edit_expected_occurrence_mismatch"}}else if(finalOldString===finalNewString){error={display:`No changes to apply. The old_string and new_string are identical.`,raw:`No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,type:"edit_no_change"}}}else{error={display:`Failed to read content of file.`,raw:`Failed to read content of existing file: ${params.file_path}`,type:"read_content_failure"}}const newContent=!error?applyReplacement(currentContent,finalOldString,finalNewString,isNewFile,matchOffsets):currentContent??"";if(!error&&fileExists2&&currentContent===newContent){error={display:"No changes to apply. The new content is identical to the current content.",raw:`No changes to apply. The new content is identical to the current content in file: ${params.file_path}`,type:"edit_no_change"}}if(!error){const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,newContent,this.config.getProjectRoot());if(teamMemoryError){const preExisting=currentContent!==null&&(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,currentContent,this.config.getProjectRoot())!==null;const message=preExisting?`${teamMemoryError} Note: the secret already exists in the current file content, so removing it from your edit alone is not enough \u2014 delete the committed secret from the file.`:teamMemoryError;error={display:message,raw:message,type:"invalid_tool_params"}}}return{currentContent,newContent,sandboxFileVersion,occurrences,error,isNewFile,bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(abortSignal){let editData;try{editData=await this.calculateEdit(this.params,void 0,abortSignal)}catch(error){if(abortSignal.aborted){throw error}const errorMsg=isNodeError(error)&&error.code==="EISDIR"?`Target is a directory, not a file: ${this.params.file_path} (${error.code})`:getErrorMessage(error);throw new Error(`Error preparing edit: ${errorMsg}`)}if(editData.error){throw new StructuredToolError(editData.error.raw,editData.error.type)}const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Edit: ${shortenPath(makeRelative(this.params.file_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.file_path,fileDiff,originalContent:editData.currentContent,newContent:editData.newContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());if(this.params.old_string===""){return`Create ${shortenPath(relativePath)}`}if(this.params.old_string===this.params.new_string){return`No file changes to ${shortenPath(relativePath)}`}return shortenPath(relativePath)}async execute(signal){try{const io=this.config.getFileSystemService().textFileIo;return io?await io.withMutation(this.params.file_path,signal,mutation=>this.executeObserved(signal,mutation)):await this.executeObserved(signal)}catch(error){if(signal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(signal,mutation){let editData;try{editData=await this.calculateEdit(this.params,mutation?.original,signal)}catch(error){if(signal.aborted){throw error}const errorMsg=getErrorMessage(error);return{llmContent:`Error preparing edit: ${errorMsg}`,returnDisplay:`Error preparing edit: ${errorMsg}`,error:{message:errorMsg,type:"edit_preparation_failure"}}}if(editData.error){return{llmContent:editData.error.raw,returnDisplay:`Error: ${editData.error.display}`,error:{message:editData.error.raw,type:editData.error.type}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"editing",{expectExisting:!editData.isNewFile});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:this.params.file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!this.config.getShellExecutionSandbox?.()){this.ensureParentDirectoriesExist(this.params.file_path)}let committedStats;const write=__name(async params=>{if(mutation)committedStats=await mutation.write(params);else await writeRuntimeFile(this.config,params,editData.sandboxFileVersion,signal)},"write");if(editData.isNewFile){const userEncoding=this.config.getDefaultFileEncoding();let useBOM=false;if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(this.params.file_path)}await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:useBOM}})}else{await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:editData.bom,encoding:editData.encoding,lineEnding:editData.lineEnding}})}if(!mutation&&!this.params.modified_by_user){CommitAttributionService.getInstance().recordEdit(this.params.file_path,editData.currentContent,editData.newContent)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(this.params.file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(this.params.file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(this.params.file_path);const originallyProposedContent=this.params.ai_proposed_content||editData.newContent;const diffStat=getDiffStat(fileName,editData.currentContent??"",originallyProposedContent,editData.newContent);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const displayResult={fileDiff,fileName,filePath:this.params.file_path,originalContent:editData.currentContent,newContent:editData.newContent,diffStat};const mimetype=getSpecificMimeType(this.params.file_path);const programmingLanguage=getLanguageFromFilePath(this.params.file_path);const extension=path.extname(this.params.file_path);const operation=editData.isNewFile?"create":"update";logFileOperation(this.config,new FileOperationEvent(EditTool.Name,operation,editData.newContent.split("\n").length,mimetype,extension,programmingLanguage));const llmSuccessMessageParts=[editData.isNewFile?`Created new file: ${this.params.file_path} with provided content.`:`The file: ${this.params.file_path} has been updated.`];const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const snippetResult=extractEditSnippet(editData.currentContent,editData.newContent);if(snippetResult){const snippetText=`Showing lines ${snippetResult.startLine}-${snippetResult.endLine} of ${snippetResult.totalLines} from the edited file:
5
5
 
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{LoadedSettings,getNestedProperty,getPersistScopeForModelSelection}from"./chunk-JRIVHFCG.js";import{getHomeEnvFallbackVars}from"./chunk-3VKLOQ2P.js";import{writeWithBackupSync}from"./chunk-YFXKRGHT.js";import{preserveModelProviderPlaceholders}from"./chunk-G3COGFSZ.js";import{resolveEnvVarsInObject}from"./chunk-HW7ZRPZU.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";function findRawModelProviderEntries(settings,providerId){return["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].map(source=>settings.forScope(source).originalSettings.modelProviders).find(providers=>providers&&Object.hasOwn(providers,providerId))?.[providerId]}__name(findRawModelProviderEntries,"findRawModelProviderEntries");function getRawModelProviders(settings){return Object.fromEntries(Object.keys(settings.merged.modelProviders??{}).map(providerId=>[providerId,findRawModelProviderEntries(settings,providerId)??[]]))}__name(getRawModelProviders,"getRawModelProviders");function createLoadedSettingsAdapter(settings,scope){const persistScope=scope??getPersistScopeForModelSelection(settings);const settingsFile=settings.forScope(persistScope);let fileSnapshot;let settingsSnapshot=null;let originalSnapshot=null;return{getValue(key){return getNestedProperty(settings.merged,key)},setValue(key,value){for(const part of key.split(".")){if(part==="__proto__"||part==="constructor"||part==="prototype"){throw new Error(`Refusing to write settings key with reserved segment: ${key}`)}}const provider=key.startsWith("modelProviders.")&&key.split(".").length===2?key.slice("modelProviders.".length):void 0;if(!provider||!Array.isArray(value)){settings.setValue(persistScope,key,value);return}const sourceFor=__name(providerId=>findRawModelProviderEntries(settings,providerId),"sourceFor");const ownsBucket=Object.hasOwn(settingsFile.settings.modelProviders??{},provider);const previous=ownsBucket?settingsFile.settings.modelProviders?.[provider]:settings.merged.modelProviders?.[provider];const raw=ownsBucket?settingsFile.originalSettings.modelProviders?.[provider]:sourceFor(provider);const resolvedProviders=provider==="openai"?settings.merged.modelProviders??{}:{[provider]:previous??[]};const rawProviders=provider==="openai"?Object.fromEntries(Object.keys(resolvedProviders).map(id=>[id,sourceFor(id)??[]])):{[provider]:raw??[]};const persisted=preserveModelProviderPlaceholders(value,provider,resolvedProviders,rawProviders,settings.merged.providerProtocol);settings.setValue(persistScope,key,persisted);settingsFile.settings.modelProviders=resolveEnvVarsInObject(settingsFile.originalSettings.modelProviders,getHomeEnvFallbackVars());settings.recomputeMerged()},getModelProviders(){return settings.merged.modelProviders??{}},getModelProvidersForWrite(){const ownProviders=settingsFile.settings.modelProviders??{};const writeView=persistScope==="User"?new LoadedSettings(settings.system,settings.systemDefaults,settings.user,{...settings.workspace,settings:{},originalSettings:{}},false,new Set).merged:settings.merged;return{modelProviders:ownProviders,providerProtocol:writeView.providerProtocol,shadowedProviders:Object.keys(ownProviders).filter(providerId=>["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].find(scope2=>Object.hasOwn(settings.forScope(scope2).originalSettings.modelProviders??{},providerId))!==persistScope)}},persist(){},backup(){const contents=fs.existsSync(settingsFile.path)?fs.readFileSync(settingsFile.path,"utf8"):null;settingsSnapshot=structuredClone(settingsFile.settings);originalSnapshot=structuredClone(settingsFile.originalSettings);fileSnapshot=contents},restore(){if(fileSnapshot===void 0)return;try{if(fileSnapshot===null){fs.rmSync(settingsFile.path,{force:true})}else{writeWithBackupSync(settingsFile.path,fileSnapshot)}}finally{if(settingsSnapshot!==null){settingsFile.settings=settingsSnapshot}if(originalSnapshot!==null){settingsFile.originalSettings=originalSnapshot}settings.recomputeMerged()}},cleanupBackup(){fileSnapshot=void 0;settingsSnapshot=null;originalSnapshot=null}}}__name(createLoadedSettingsAdapter,"createLoadedSettingsAdapter");export{findRawModelProviderEntries,getRawModelProviders,createLoadedSettingsAdapter};
3
+ import{LoadedSettings,getNestedProperty,getPersistScopeForModelSelection}from"./chunk-4RJ2RRGZ.js";import{getHomeEnvFallbackVars}from"./chunk-QJ6ZTZFC.js";import{writeWithBackupSync}from"./chunk-EYECE2PH.js";import{preserveModelProviderPlaceholders}from"./chunk-E4REGDEZ.js";import{resolveEnvVarsInObject}from"./chunk-HW7ZRPZU.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";function findRawModelProviderEntries(settings,providerId){return["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].map(source=>settings.forScope(source).originalSettings.modelProviders).find(providers=>providers&&Object.hasOwn(providers,providerId))?.[providerId]}__name(findRawModelProviderEntries,"findRawModelProviderEntries");function getRawModelProviders(settings){return Object.fromEntries(Object.keys(settings.merged.modelProviders??{}).map(providerId=>[providerId,findRawModelProviderEntries(settings,providerId)??[]]))}__name(getRawModelProviders,"getRawModelProviders");function createLoadedSettingsAdapter(settings,scope){const persistScope=scope??getPersistScopeForModelSelection(settings);const settingsFile=settings.forScope(persistScope);let fileSnapshot;let settingsSnapshot=null;let originalSnapshot=null;return{getValue(key){return getNestedProperty(settings.merged,key)},setValue(key,value){for(const part of key.split(".")){if(part==="__proto__"||part==="constructor"||part==="prototype"){throw new Error(`Refusing to write settings key with reserved segment: ${key}`)}}const provider=key.startsWith("modelProviders.")&&key.split(".").length===2?key.slice("modelProviders.".length):void 0;if(!provider||!Array.isArray(value)){settings.setValue(persistScope,key,value);return}const sourceFor=__name(providerId=>findRawModelProviderEntries(settings,providerId),"sourceFor");const ownsBucket=Object.hasOwn(settingsFile.settings.modelProviders??{},provider);const previous=ownsBucket?settingsFile.settings.modelProviders?.[provider]:settings.merged.modelProviders?.[provider];const raw=ownsBucket?settingsFile.originalSettings.modelProviders?.[provider]:sourceFor(provider);const resolvedProviders=provider==="openai"?settings.merged.modelProviders??{}:{[provider]:previous??[]};const rawProviders=provider==="openai"?Object.fromEntries(Object.keys(resolvedProviders).map(id=>[id,sourceFor(id)??[]])):{[provider]:raw??[]};const persisted=preserveModelProviderPlaceholders(value,provider,resolvedProviders,rawProviders,settings.merged.providerProtocol);settings.setValue(persistScope,key,persisted);settingsFile.settings.modelProviders=resolveEnvVarsInObject(settingsFile.originalSettings.modelProviders,getHomeEnvFallbackVars());settings.recomputeMerged()},getModelProviders(){return settings.merged.modelProviders??{}},getModelProvidersForWrite(){const ownProviders=settingsFile.settings.modelProviders??{};const writeView=persistScope==="User"?new LoadedSettings(settings.system,settings.systemDefaults,settings.user,{...settings.workspace,settings:{},originalSettings:{}},false,new Set).merged:settings.merged;return{modelProviders:ownProviders,providerProtocol:writeView.providerProtocol,shadowedProviders:Object.keys(ownProviders).filter(providerId=>["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].find(scope2=>Object.hasOwn(settings.forScope(scope2).originalSettings.modelProviders??{},providerId))!==persistScope)}},persist(){},backup(){const contents=fs.existsSync(settingsFile.path)?fs.readFileSync(settingsFile.path,"utf8"):null;settingsSnapshot=structuredClone(settingsFile.settings);originalSnapshot=structuredClone(settingsFile.originalSettings);fileSnapshot=contents},restore(){if(fileSnapshot===void 0)return;try{if(fileSnapshot===null){fs.rmSync(settingsFile.path,{force:true})}else{writeWithBackupSync(settingsFile.path,fileSnapshot)}}finally{if(settingsSnapshot!==null){settingsFile.settings=settingsSnapshot}if(originalSnapshot!==null){settingsFile.originalSettings=originalSnapshot}settings.recomputeMerged()}},cleanupBackup(){fileSnapshot=void 0;settingsSnapshot=null;originalSnapshot=null}}}__name(createLoadedSettingsAdapter,"createLoadedSettingsAdapter");export{findRawModelProviderEntries,getRawModelProviders,createLoadedSettingsAdapter};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-C3ZJUOTJ.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-MCY3IS2E.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-POMEWCFJ.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
3
+ import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-TCQJO42E.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-UYI5AMPI.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-ZUWLTGSR.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{modPromptRow}from"./chunk-5KRYBTZV.js";import{collectInlineImages,extractInlineContentRuns}from"./chunk-UF6LWI5H.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-4C5BOFDC.js";import{t}from"./chunk-5YULNQF3.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-G3COGFSZ.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-POMEWCFJ.js";import{projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{parseGoalStateRecordPayloadV2}from"./chunk-7Z2ZH5CW.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.provenance==="mod_prompt"){const payload2=record.systemPayload;const text2=projectUserTranscriptForDisplay(record).displayText||extractTextFromParts(record.message?.parts);if(text2){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"notification",text:modPromptRow(payload2?.mod??"unknown",text2)})}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
3
+ import{modPromptRow}from"./chunk-5KRYBTZV.js";import{collectInlineImages,extractInlineContentRuns}from"./chunk-UF6LWI5H.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-H3U7DXIU.js";import{t}from"./chunk-AUM57JI2.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-E4REGDEZ.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-ZUWLTGSR.js";import{projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{parseGoalStateRecordPayloadV2}from"./chunk-7Z2ZH5CW.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.provenance==="mod_prompt"){const payload2=record.systemPayload;const text2=projectUserTranscriptForDisplay(record).displayText||extractTextFromParts(record.message?.parts);if(text2){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"notification",text:modPromptRow(payload2?.mod??"unknown",text2)})}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC